pi-web-ui 0.88.0 → 0.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +80 -1
  2. package/dist/server/agent-service.js +464 -68
  3. package/dist/server/attachments.js +39 -0
  4. package/dist/server/auth-cookie.js +23 -0
  5. package/dist/server/client-state.js +35 -0
  6. package/dist/server/composer-drafts.js +20 -2
  7. package/dist/server/conversation-read-tool.js +325 -0
  8. package/dist/server/dsh/dsh-agent-service.js +46 -11
  9. package/dist/server/file-archives.js +258 -0
  10. package/dist/server/file-transfer-routes.js +113 -0
  11. package/dist/server/files-service.js +123 -1
  12. package/dist/server/index.js +361 -14
  13. package/dist/server/marker-service.js +3 -1
  14. package/dist/server/model-admin.js +285 -36
  15. package/dist/server/plugins.js +152 -5
  16. package/dist/server/queue-utils.js +16 -0
  17. package/dist/server/schedule-agent-tool.js +240 -0
  18. package/dist/server/scheduler-tasks.js +414 -0
  19. package/dist/server/settings-service.js +76 -2
  20. package/dist/server/terminals.js +14 -1
  21. package/dist/server/tool-manager.js +16 -1
  22. package/dist/server/update-check.js +253 -19
  23. package/dist/server/webui-context.js +4 -0
  24. package/dist/server/ws-unknown-types.js +44 -0
  25. package/extensions/webui.ts +9 -2
  26. package/package.json +7 -3
  27. package/plugin-sdk/index.d.ts +4 -0
  28. package/plugin-sdk/index.mjs +9 -0
  29. package/plugins/catalog.json +11 -2
  30. package/web/dist/assets/TerminalPanel-BDbdLhpT.js +6 -0
  31. package/web/dist/assets/index-1f_DP8S3.js +380 -0
  32. package/web/dist/assets/index-DeUwDA-C.css +10 -0
  33. package/web/dist/index.html +2 -2
  34. package/web/dist/assets/TerminalPanel-CDH27dNP.js +0 -6
  35. package/web/dist/assets/index-CQg5A74_.js +0 -375
  36. package/web/dist/assets/index-DTEcxHWs.css +0 -10
@@ -12,9 +12,58 @@
12
12
  * UI 文案直接中文(服务端 notice 约定)。apiKey/headers 绝不下发浏览器。
13
13
  */
14
14
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
- import { join } from "node:path";
15
+ import { dirname, join } from "node:path";
16
16
  import { pick } from "./i18n.js";
17
17
  import { ProviderOAuthFlowManager } from "./provider-oauth-flow.js";
18
+ /** Drop provisional overlay rows once the official catalog lists the same id.
19
+ *
20
+ * Background: a hand-appended row SHADOWS the official row at compose time
21
+ * (applyModelsJson rebuilds the entry from the definition, so official
22
+ * name/vision/contextWindow/etc. are lost and only api/baseUrl are
23
+ * inherited). While pi.dev doesn't list the id the shadow is the whole
24
+ * point; once it does, the shadow becomes stale metadata. `official` maps
25
+ * provider → model id → the official row's api (undefined when unknown).
26
+ * A row graduates when the official catalog lists its id AND the row
27
+ * carries no deliberate routing of its own: no baseUrl, and either no api
28
+ * or the same api the official row uses. A row with its own baseUrl or a
29
+ * differing api is a customization, not a provisional — it stays. When an
30
+ * entry's models become empty and it carries no other keys, the whole entry
31
+ * is removed so it also leaves the "custom providers" list; entries with
32
+ * other keys (baseUrl/apiKey/headers/…) are kept. Mutates `providers` in
33
+ * place and returns what was graduated. Pure + unit-tested. */
34
+ export function graduateOverlayModels(providers, official) {
35
+ const graduated = [];
36
+ for (const [pid, entry] of Object.entries(providers)) {
37
+ if (!entry || typeof entry !== "object" || !Array.isArray(entry.models))
38
+ continue;
39
+ const officialModels = official[pid];
40
+ if (!officialModels || Object.keys(officialModels).length === 0)
41
+ continue;
42
+ const kept = [];
43
+ for (const row of entry.models) {
44
+ const r = (row ?? {});
45
+ const id = typeof r.id === "string" ? r.id.trim() : "";
46
+ const listed = id !== "" && Object.hasOwn(officialModels, id);
47
+ const officialApi = listed ? officialModels[id] : undefined;
48
+ const rowApi = typeof r.api === "string" && r.api.trim() ? r.api.trim() : undefined;
49
+ const provisional = listed && r.baseUrl == null && (rowApi === undefined || (officialApi !== undefined && rowApi === officialApi));
50
+ if (provisional) {
51
+ graduated.push({ providerId: pid, modelId: id });
52
+ continue;
53
+ }
54
+ kept.push(row);
55
+ }
56
+ if (kept.length === entry.models.length)
57
+ continue;
58
+ if (kept.length === 0 && Object.keys(entry).every((k) => k === "models")) {
59
+ delete providers[pid];
60
+ }
61
+ else {
62
+ entry.models = kept;
63
+ }
64
+ }
65
+ return graduated;
66
+ }
18
67
  /** Strip // and /* *\/ comments without touching string literals (URLs contain //). */
19
68
  function stripJsonComments(src) {
20
69
  let out = "";
@@ -1256,6 +1305,239 @@ export class ModelAdminService {
1256
1305
  return done(false, { error: err.message });
1257
1306
  }
1258
1307
  }
1308
+ /** Force-refresh BUILT-IN providers' official pi.dev catalogs, bypassing
1309
+ * the SDK's 4h freshness window (`force: true`). Without force, refresh
1310
+ * inside the window is a silent no-op against models-store.json — which
1311
+ * is why a newly-published cheap model can sit on pi.dev for hours while
1312
+ * the picker still shows the old list. Afterwards the picker + provider
1313
+ * status are repushed. Per-provider fetch failures don't fail the whole
1314
+ * run (those providers keep their cached catalog) but are surfaced in
1315
+ * the result + a warning notice. */
1316
+ async refreshBuiltinModels(reqId) {
1317
+ const done = (ok, error) => this.host.emit({ type: "refresh_builtin_result", reqId, ok, ...(error ? { error } : {}) });
1318
+ try {
1319
+ const mr = this.host.modelRuntime();
1320
+ const res = await mr.refresh({
1321
+ allowNetwork: true,
1322
+ force: true,
1323
+ signal: AbortSignal.timeout(90_000),
1324
+ });
1325
+ // Provisional overlay rows (append_builtin_model) shadow the official
1326
+ // row once pi.dev lists the id — graduate them so official
1327
+ // name/vision/limits take over. Only rows without their own
1328
+ // api/baseUrl are provisional; deliberate customizations stay.
1329
+ const graduated = this.graduateProvisionalOverlays();
1330
+ if (graduated.length > 0) {
1331
+ await mr.refresh();
1332
+ }
1333
+ this.host.invalidatePiConfig();
1334
+ await this.host.pushModels();
1335
+ await this.listProviders();
1336
+ const failures = [...res.errors.entries()].map(([pid, err]) => `${pid} (${err.message})`);
1337
+ if (failures.length > 0) {
1338
+ const detail = failures.join("; ");
1339
+ this.host.emit({
1340
+ type: "notice",
1341
+ level: "warning",
1342
+ text: `⚠️ 官方模型目录已强制刷新,但 ${failures.length} 个供应商拉取失败(沿用缓存):${detail}`,
1343
+ textEn: `⚠️ Official model catalogs force-refreshed, but ${failures.length} provider(s) failed (cached catalog kept): ${detail}`,
1344
+ });
1345
+ return done(true, detail);
1346
+ }
1347
+ this.host.emit({
1348
+ type: "notice",
1349
+ level: "info",
1350
+ text: "🔄 已强制刷新官方模型目录(绕过 4 小时缓存),模型下拉已更新",
1351
+ textEn: "🔄 Official model catalogs force-refreshed (4h cache bypassed); the model picker is up to date",
1352
+ });
1353
+ if (graduated.length > 0) {
1354
+ const names = graduated.map((g) => `${g.providerId}/${g.modelId}`).join("、");
1355
+ this.host.emit({
1356
+ type: "notice",
1357
+ level: "info",
1358
+ text: `🎓 ${names} 官方已收录,手工条目已移除并转用官方配置`,
1359
+ textEn: `${names} graduated to the official catalog; provisional rows removed`,
1360
+ });
1361
+ }
1362
+ return done(true);
1363
+ }
1364
+ catch (err) {
1365
+ this.host.emit({
1366
+ type: "notice",
1367
+ level: "error",
1368
+ text: `强制刷新官方模型目录失败:${err.message}`,
1369
+ textEn: `Failed to force-refresh official model catalogs: ${err.message}`,
1370
+ });
1371
+ return done(false, err.message);
1372
+ }
1373
+ finally {
1374
+ this.host.flushSnapshot();
1375
+ }
1376
+ }
1377
+ /** Graduate provisional overlay rows against the freshly force-refreshed
1378
+ * official catalog (models-store.json next to models.json). Persists the
1379
+ * pruned models.json only when something actually graduated; a missing
1380
+ * or unparsable store is a silent no-op (never fail the refresh). */
1381
+ graduateProvisionalOverlays() {
1382
+ let official = {};
1383
+ try {
1384
+ const storePath = join(dirname(this.modelsConfigPath()), "models-store.json");
1385
+ const stored = JSON.parse(readFileSync(storePath, "utf8"));
1386
+ for (const [pid, entry] of Object.entries(stored ?? {})) {
1387
+ if (!Array.isArray(entry?.models))
1388
+ continue;
1389
+ const byId = {};
1390
+ for (const m of entry.models) {
1391
+ if (typeof m?.id !== "string" || !m.id.trim())
1392
+ continue;
1393
+ byId[m.id.trim()] = typeof m.api === "string" ? m.api : undefined;
1394
+ }
1395
+ official[pid] = byId;
1396
+ }
1397
+ }
1398
+ catch {
1399
+ return [];
1400
+ }
1401
+ const { providers } = this.readModelsConfig();
1402
+ const graduated = graduateOverlayModels(providers, official);
1403
+ if (graduated.length === 0)
1404
+ return graduated;
1405
+ try {
1406
+ writeFileSync(this.modelsConfigPath(), JSON.stringify({ providers }, null, 2) + "\n");
1407
+ }
1408
+ catch {
1409
+ return [];
1410
+ }
1411
+ return graduated;
1412
+ }
1413
+ /** Normalize one UI-submitted model row into models.json shape (same rules
1414
+ * as save_model_config: blank optionals dropped, numbers coerced).
1415
+ * Per-model api/baseUrl overrides pass through (validated by callers —
1416
+ * toModelRow itself only trims); absent values keep being inherited
1417
+ * from sibling models at compose time. */
1418
+ static toModelRow(m) {
1419
+ return {
1420
+ id: m.id.trim(),
1421
+ ...(m.name?.trim() ? { name: m.name.trim() } : {}),
1422
+ ...(m.reasoning ? { reasoning: true } : {}),
1423
+ ...(m.input?.length ? { input: m.input } : {}),
1424
+ ...(m.contextWindow ? { contextWindow: Number(m.contextWindow) } : {}),
1425
+ ...(m.maxTokens ? { maxTokens: Number(m.maxTokens) } : {}),
1426
+ ...(m.api?.trim() ? { api: m.api.trim() } : {}),
1427
+ ...(m.baseUrl?.trim() ? { baseUrl: m.baseUrl.trim() } : {}),
1428
+ };
1429
+ }
1430
+ /** Known per-model api types (same list as the custom-provider form). */
1431
+ static MODEL_APIS = new Set([
1432
+ "openai-completions",
1433
+ "openai-responses",
1434
+ "anthropic-messages",
1435
+ "google-generative-ai",
1436
+ ]);
1437
+ /** Write models.json and hot-reload the model runtime (shared tail of
1438
+ * save_model_config / append_builtin_model). Reuses the provider
1439
+ * credential already in auth.json for the runtime, then repushes the
1440
+ * config list + the picker. Callers emit their own notice. */
1441
+ async writeModelsConfigAndReload(providers, pid) {
1442
+ mkdirSync(this.host.agentDir, { recursive: true });
1443
+ writeFileSync(this.modelsConfigPath(), JSON.stringify({ providers }, null, 2) + "\n");
1444
+ // Allow a models.json entry to reuse the provider credential already
1445
+ // stored in auth.json. Seed the shared runtime too, because older pi-ai
1446
+ // versions did not always fall back to stored credentials for a
1447
+ // newly-created custom provider. Never copy the secret into models.json.
1448
+ try {
1449
+ const auth = JSON.parse(readFileSync(join(this.host.agentDir, "auth.json"), "utf8"));
1450
+ const credential = auth[pid];
1451
+ if (credential &&
1452
+ typeof credential === "object" &&
1453
+ "key" in credential &&
1454
+ typeof credential.key === "string" &&
1455
+ credential.key.trim()) {
1456
+ await this.host.modelRuntime().setRuntimeApiKey(pid, credential.key);
1457
+ }
1458
+ }
1459
+ catch {
1460
+ // auth.json is optional; models.json can still use its own apiKey.
1461
+ }
1462
+ await this.host.modelRuntime().refresh();
1463
+ this.host.invalidatePiConfig();
1464
+ await this.listModelsConfig();
1465
+ await this.host.pushModels();
1466
+ }
1467
+ /** Append ONE model to a BUILT-IN provider's models.json overlay entry
1468
+ * (append_builtin_result). Pure overlay: when the provider has no entry
1469
+ * yet, a `{ models: [row] }` entry is created — no baseUrl/api — so
1470
+ * api/baseUrl keep being inherited from the provider's own models at
1471
+ * compose time and later official catalog refreshes never drop the row.
1472
+ * Existing entry fields are left byte-for-byte alone (append-only, even
1473
+ * safer than save_model_config's merge). Duplicate id is an idempotent
1474
+ * no-op (info notice, ok:true). The row shows up under "custom
1475
+ * providers" (same id) for edit/remove. */
1476
+ async appendBuiltinModel(providerId, model, reqId) {
1477
+ const done = (ok, error) => this.host.emit({ type: "append_builtin_result", reqId, ok, ...(error ? { error } : {}) });
1478
+ const pid = providerId.trim();
1479
+ const mid = model?.id?.trim() ?? "";
1480
+ const fail = (text, textEn) => {
1481
+ this.host.emit({ type: "notice", level: "error", text, textEn });
1482
+ return done(false, text);
1483
+ };
1484
+ try {
1485
+ if (!pid)
1486
+ return fail("请填写服务商 ID", "Enter a provider ID");
1487
+ if (!mid)
1488
+ return fail("请填写模型 ID", "Enter a model ID");
1489
+ const api = model?.api?.trim() ? model.api.trim() : undefined;
1490
+ if (api && !ModelAdminService.MODEL_APIS.has(api)) {
1491
+ return fail(`接口类型无效:${api}(仅支持 ${[...ModelAdminService.MODEL_APIS].join(" / ")},留空则自动继承)`, `Invalid api type: ${api} (supported: ${[...ModelAdminService.MODEL_APIS].join(" / ")}; leave blank to inherit)`);
1492
+ }
1493
+ const baseUrl = model?.baseUrl?.trim() ? model.baseUrl.trim() : undefined;
1494
+ if (baseUrl) {
1495
+ let url;
1496
+ try {
1497
+ url = new URL(baseUrl);
1498
+ }
1499
+ catch {
1500
+ url = undefined;
1501
+ }
1502
+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:")) {
1503
+ return fail(`接口地址无效:${baseUrl}(仅支持 http/https,留空则自动继承)`, `Invalid baseUrl: ${baseUrl} (http/https only; leave blank to inherit)`);
1504
+ }
1505
+ }
1506
+ if (!this.host.modelRuntime().getProvider(pid)) {
1507
+ return fail(`供应商 ${pid} 不存在`, `Provider ${pid} does not exist`);
1508
+ }
1509
+ const { providers } = this.readModelsConfig();
1510
+ const prev = providers[pid];
1511
+ const prevModels = Array.isArray(prev?.models) ? [...prev.models] : [];
1512
+ if (prevModels.some((m) => typeof m?.id === "string" && m.id.trim() === mid)) {
1513
+ this.host.emit({
1514
+ type: "notice",
1515
+ level: "info",
1516
+ text: `${pid} 已有模型 ${mid},无需重复添加`,
1517
+ textEn: `${pid} already has model ${mid}; nothing to add`,
1518
+ });
1519
+ return done(true);
1520
+ }
1521
+ // 手填行只带用户给的字段(通常只有 id,也许有名),api/baseUrl
1522
+ // 由 compose 时从同供应商现有模型继承——这正是纯 overlay 能工作的原因。
1523
+ const row = ModelAdminService.toModelRow({ ...model, id: mid });
1524
+ providers[pid] = { ...prev, models: [...prevModels, row] };
1525
+ await this.writeModelsConfigAndReload(providers, pid);
1526
+ this.host.emit({
1527
+ type: "notice",
1528
+ level: "info",
1529
+ text: `✅ 已给 ${pid} 添加模型 ${mid},模型下拉已更新(该条目同时列在「自定义服务商」下,可编辑/删除)`,
1530
+ textEn: `✅ Added model ${mid} to ${pid}; the picker is updated (the entry is also listed under custom providers for edit/remove)`,
1531
+ });
1532
+ return done(true);
1533
+ }
1534
+ catch (err) {
1535
+ return fail(`添加模型失败:${err.message}`, `Failed to add model: ${err.message}`);
1536
+ }
1537
+ finally {
1538
+ this.host.flushSnapshot();
1539
+ }
1540
+ }
1259
1541
  /** Upsert one provider into models.json and hot-reload the model runtime. */
1260
1542
  async saveModelConfig(providerId, config) {
1261
1543
  const pid = providerId.trim();
@@ -1268,16 +1550,7 @@ export class ModelAdminService {
1268
1550
  });
1269
1551
  return;
1270
1552
  }
1271
- const models = (config.models ?? [])
1272
- .filter((m) => m.id && m.id.trim())
1273
- .map((m) => ({
1274
- id: m.id.trim(),
1275
- ...(m.name?.trim() ? { name: m.name.trim() } : {}),
1276
- ...(m.reasoning ? { reasoning: true } : {}),
1277
- ...(m.input?.length ? { input: m.input } : {}),
1278
- ...(m.contextWindow ? { contextWindow: Number(m.contextWindow) } : {}),
1279
- ...(m.maxTokens ? { maxTokens: Number(m.maxTokens) } : {}),
1280
- }));
1553
+ const models = (config.models ?? []).filter((m) => m.id && m.id.trim()).map((m) => ModelAdminService.toModelRow(m));
1281
1554
  if (models.length === 0) {
1282
1555
  this.host.emit({
1283
1556
  type: "notice",
@@ -1292,31 +1565,7 @@ export class ModelAdminService {
1292
1565
  // 合并而不是重建:UI 认识之外的字段(provider 级 headers、模型级 api/
1293
1566
  // baseUrl/cost/compat/thinkingLevelMap)必须原样保留,见 mergeProviderConfigEntry。
1294
1567
  providers[pid] = mergeProviderConfigEntry(providers[pid], config, models);
1295
- mkdirSync(this.host.agentDir, { recursive: true });
1296
- writeFileSync(this.modelsConfigPath(), JSON.stringify({ providers }, null, 2) + "\n");
1297
- // Allow a custom models.json entry to reuse the provider credential
1298
- // already stored in auth.json. Seed the shared runtime too, because
1299
- // older pi-ai versions did not always fall back to stored credentials
1300
- // for a newly-created custom provider. Never copy the secret into
1301
- // models.json.
1302
- try {
1303
- const auth = JSON.parse(readFileSync(join(this.host.agentDir, "auth.json"), "utf8"));
1304
- const credential = auth[pid];
1305
- if (credential &&
1306
- typeof credential === "object" &&
1307
- "key" in credential &&
1308
- typeof credential.key === "string" &&
1309
- credential.key.trim()) {
1310
- await this.host.modelRuntime().setRuntimeApiKey(pid, credential.key);
1311
- }
1312
- }
1313
- catch {
1314
- // auth.json is optional; models.json can still use its own apiKey.
1315
- }
1316
- await this.host.modelRuntime().refresh();
1317
- this.host.invalidatePiConfig();
1318
- await this.listModelsConfig();
1319
- await this.host.pushModels();
1568
+ await this.writeModelsConfigAndReload(providers, pid);
1320
1569
  this.host.emit({
1321
1570
  type: "notice",
1322
1571
  level: "info",
@@ -768,6 +768,8 @@ export class PluginManager {
768
768
  onGrantsChanged = undefined;
769
769
  /** 插件运行时注册的 UI 贡献(host.ui.register/arrange),随 plugins 清单推送。 */
770
770
  uiRuntime = new Map();
771
+ /** 通用反向代理注册表:归一化前缀 → { 插件 id, 回环目标 }(index.ts 按最长前缀命中透传)。 */
772
+ proxyRoutes = new Map();
771
773
  /** manifest "ui" 基线(每次 scan 刷新;host.ui.list 与合并都读它)。 */
772
774
  uiBase = new Map();
773
775
  /** manifest 解析诊断(每次 scan 重算;合法插件无诊断时记空数组)。 */
@@ -870,7 +872,9 @@ export class PluginManager {
870
872
  try {
871
873
  this.onBgTasksChanged?.();
872
874
  }
873
- catch { }
875
+ catch {
876
+ // best-effort:可选 UI 刷新,失败忽略。
877
+ }
874
878
  return true;
875
879
  }
876
880
  return false;
@@ -1068,6 +1072,39 @@ export class PluginManager {
1068
1072
  res.end();
1069
1073
  }
1070
1074
  }
1075
+ /** 注册通用代理前缀(host.registerProxy 的本体,index.ts 只读 findProxy)。
1076
+ * 成功返回归一化前缀;前缀非法/目标非法/被其它插件占用返回 null(调用方记诊断)。 */
1077
+ registerProxy(pluginId, prefix, target) {
1078
+ const p = normalizeProxyPrefix(prefix);
1079
+ const t = normalizeProxyTarget(target);
1080
+ if (!p || !t)
1081
+ return null;
1082
+ const taken = this.proxyRoutes.get(p);
1083
+ if (taken && taken.pluginId !== pluginId)
1084
+ return null;
1085
+ this.proxyRoutes.set(p, { pluginId, host: t.host, port: t.port });
1086
+ return p;
1087
+ }
1088
+ /** 注销代理前缀(同插件才能注销自己的;返回是否真删掉了)。 */
1089
+ unregisterProxy(pluginId, prefix) {
1090
+ const p = normalizeProxyPrefix(prefix);
1091
+ if (!p)
1092
+ return false;
1093
+ if (this.proxyRoutes.get(p)?.pluginId !== pluginId)
1094
+ return false;
1095
+ return this.proxyRoutes.delete(p);
1096
+ }
1097
+ /** index.ts 转发/upgrade 共用:请求路径的最长前缀命中(无命中返回 undefined)。
1098
+ * 查表前小写化:注册前缀统一小写归一,大小写混写也命中同一条。 */
1099
+ findProxy(path) {
1100
+ const p = matchProxyPrefix(String(path ?? "").toLowerCase(), this.proxyRoutes.keys());
1101
+ if (!p)
1102
+ return undefined;
1103
+ const hit = this.proxyRoutes.get(p);
1104
+ if (!hit)
1105
+ return undefined;
1106
+ return { prefix: p, ...hit };
1107
+ }
1071
1108
  broadcast(pluginId, payload) {
1072
1109
  this.deliverAll({ type: "plugin_data", pluginId, payload });
1073
1110
  }
@@ -1334,6 +1371,30 @@ export class PluginManager {
1334
1371
  }
1335
1372
  }
1336
1373
  }
1374
+ /** 某插件的 AI 工具展示快照(设置面板用;按工具名稳定排序;无工具回 [])。
1375
+ * 纯展示字段,不含 execute。 */
1376
+ agentToolsSnapshot(pluginId) {
1377
+ const table = this.agentTools.get(pluginId);
1378
+ if (!table)
1379
+ return [];
1380
+ return [...table.values()]
1381
+ .map((t) => ({
1382
+ name: t.name,
1383
+ ...(t.label ? { label: t.label } : {}),
1384
+ ...(t.description ? { description: t.description } : {}),
1385
+ }))
1386
+ .sort((a, b) => a.name.localeCompare(b.name));
1387
+ }
1388
+ /** 全部分组快照(设置面板“按插件分组”展示用;无工具的插件不出现;按插件 id 排序)。 */
1389
+ getAgentToolsGrouped() {
1390
+ const out = [];
1391
+ for (const pid of [...this.agentTools.keys()].sort()) {
1392
+ const tools = this.agentToolsSnapshot(pid);
1393
+ if (tools.length)
1394
+ out.push({ pluginId: pid, tools });
1395
+ }
1396
+ return out;
1397
+ }
1337
1398
  /** 当前全部插件注册的 AI 工具(扁平化,按插件 id 稳定排序)。 */
1338
1399
  getAgentTools() {
1339
1400
  const out = [];
@@ -1544,11 +1605,24 @@ export class PluginManager {
1544
1605
  this.deactivateEntry(id, p);
1545
1606
  }
1546
1607
  }
1547
- return found.map((f) => this.loaded.get(f.id)?.info ?? f);
1608
+ return found.map((f) => {
1609
+ const base = this.loaded.get(f.id)?.info ?? f;
1610
+ const agentTools = this.agentToolsSnapshot(f.id);
1611
+ if (agentTools.length)
1612
+ return { ...base, agentTools };
1613
+ const { agentTools: _drop, ...rest } = base;
1614
+ return rest;
1615
+ });
1548
1616
  }
1549
1617
  /** 反激活清理:把该插件名下全部订阅/注册一次收完(工具/命令/watch/定时/
1550
1618
  * 总线/stats/流式——参考 agentToolUnsubscribers 模式,新增订阅一律走这里)。 */
1551
1619
  releaseEntry(p) {
1620
+ // 该插件注册的代理前缀随反激活一起回收(全局表按 pluginId 过滤;
1621
+ // Map 迭代中删除是良定义的:删过的条目不会再被访问到)。
1622
+ for (const [prefix, hit] of this.proxyRoutes) {
1623
+ if (hit.pluginId === p.info.id)
1624
+ this.proxyRoutes.delete(prefix);
1625
+ }
1552
1626
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
1553
1627
  for (const off of [
1554
1628
  ...(p.agentToolUnsubscribers ?? []),
@@ -1614,7 +1688,9 @@ export class PluginManager {
1614
1688
  try {
1615
1689
  t.stop?.();
1616
1690
  }
1617
- catch { }
1691
+ catch {
1692
+ // best-effort:反激活清理,单个任务失败不阻断。
1693
+ }
1618
1694
  }
1619
1695
  }
1620
1696
  this.pluginBgTasks.clear();
@@ -1749,6 +1825,9 @@ export class PluginManager {
1749
1825
  });
1750
1826
  // 诊断随清单下发:manifest 解析 + 到目前为止的运行时诊断。
1751
1827
  this.manifestDiags.set(name, uiDiags);
1828
+ const agentTools = this.agentToolsSnapshot(name);
1829
+ if (agentTools.length)
1830
+ out[out.length - 1].agentTools = agentTools;
1752
1831
  const scanned = [...uiDiags, ...(this.runtimeDiags.get(name) ?? [])].slice(0, 100);
1753
1832
  if (scanned.length)
1754
1833
  out[out.length - 1].diagnostics = scanned;
@@ -1800,7 +1879,9 @@ export class PluginManager {
1800
1879
  try {
1801
1880
  apiVersion = Number(JSON.parse(readFileSync(join(dir, "manifest.json"), "utf8")).apiVersion ?? 1) || 1;
1802
1881
  }
1803
- catch { }
1882
+ catch {
1883
+ // best-effort:无 manifest/JSON 坏 → 按 apiVersion 1 处理。
1884
+ }
1804
1885
  if (apiVersion > PLUGIN_API_VERSION) {
1805
1886
  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 });
1806
1887
  console.error(`[plugin:${info.id}] ${msg}`);
@@ -2243,6 +2324,19 @@ export class PluginManager {
2243
2324
  httpRoutes.set(`${m} ${path}`, handler);
2244
2325
  return () => httpRoutes.delete(`${m} ${path}`);
2245
2326
  },
2327
+ registerProxy: (prefix, target) => {
2328
+ if (!can("http"))
2329
+ return () => { };
2330
+ const p = self.registerProxy(info.id, String(prefix ?? ""), target);
2331
+ if (!p) {
2332
+ console.error(`[plugin:${info.id}] registerProxy: 非法前缀/目标或被占用(prefix=${String(prefix)}),忽略`);
2333
+ self.pushRuntimeDiag(info.id, `registerProxy: invalid prefix/target or taken (prefix=${String(prefix)}), ignored`);
2334
+ return () => { };
2335
+ }
2336
+ return () => {
2337
+ self.unregisterProxy(info.id, p);
2338
+ };
2339
+ },
2246
2340
  // 包一层:插件反激活时自动注销它注册的全部 AI 工具,不留悬挂项。
2247
2341
  registerAgentTool: (tool) => {
2248
2342
  if (!can("tools"))
@@ -2376,7 +2470,9 @@ export class PluginManager {
2376
2470
  try {
2377
2471
  this.onBgTasksChanged?.();
2378
2472
  }
2379
- catch { }
2473
+ catch {
2474
+ // best-effort:可选 UI 刷新,失败忽略。
2475
+ }
2380
2476
  };
2381
2477
  fire();
2382
2478
  return {
@@ -2948,6 +3044,57 @@ export function resolvePluginClientFile(pluginsDir, id, rest) {
2948
3044
  return null;
2949
3045
  return abs;
2950
3046
  }
3047
+ /** 通用代理前缀的保留字:命中即拒绝注册(宿主自用路径,代理抢了会吞掉主站功能)。 */
3048
+ export const PROXY_RESERVED_PREFIXES = [
3049
+ "/api",
3050
+ "/ws",
3051
+ "/plugins",
3052
+ "/plugins-api",
3053
+ "/assets",
3054
+ "/icons",
3055
+ "/themes",
3056
+ ];
3057
+ /** 校验并归一化代理前缀:合法返回去尾斜杠的小写形式,否则返回 null(纯函数,单测覆盖)。 */
3058
+ export function normalizeProxyPrefix(prefix) {
3059
+ if (typeof prefix !== "string")
3060
+ return null;
3061
+ let p = prefix.trim();
3062
+ if (!p.startsWith("/") || p.length < 2)
3063
+ return null;
3064
+ // 去尾斜杠("/liveserver/" → "/liveserver")
3065
+ while (p.length > 1 && p.endsWith("/"))
3066
+ p = p.slice(0, -1);
3067
+ if (!/^[A-Za-z0-9/_-]+$/.test(p) || p.includes("//"))
3068
+ return null;
3069
+ const lower = p.toLowerCase();
3070
+ for (const r of PROXY_RESERVED_PREFIXES) {
3071
+ if (lower === r || lower.startsWith(`${r}/`))
3072
+ return null;
3073
+ }
3074
+ return lower;
3075
+ }
3076
+ /** 校验代理目标:只收 127.0.0.1/localhost + 合法端口(纯函数,单测覆盖)。 */
3077
+ export function normalizeProxyTarget(target) {
3078
+ const port = typeof target === "number" ? target : target?.port;
3079
+ const hostRaw = typeof target === "number" ? "127.0.0.1" : String(target?.host ?? "127.0.0.1");
3080
+ const host = hostRaw.trim().toLowerCase();
3081
+ if (host !== "127.0.0.1" && host !== "localhost")
3082
+ return null;
3083
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
3084
+ return null;
3085
+ return { host: "127.0.0.1", port: port };
3086
+ }
3087
+ /** 在请求路径上做最长前缀匹配(边界对齐:prefix 本身或 prefix + "/" 开头才算命中)。 */
3088
+ export function matchProxyPrefix(path, prefixes) {
3089
+ let best;
3090
+ for (const p of prefixes) {
3091
+ if (path === p || path.startsWith(`${p}/`)) {
3092
+ if (!best || p.length > best.length)
3093
+ best = p;
3094
+ }
3095
+ }
3096
+ return best;
3097
+ }
2951
3098
  /**
2952
3099
  * 把插件 AI 工具定义同步进一个「会话状对象」(SDK AgentSession 的结构子集:
2953
3100
  * 内部 _customTools 数组 + _refreshToolRegistry()——refresh 会重读数组,且新
@@ -16,3 +16,19 @@ export function removeFirstOccurrence(list, text) {
16
16
  return [...list];
17
17
  return [...list.slice(0, index), ...list.slice(index + 1)];
18
18
  }
19
+ /**
20
+ * 按气泡下标移除一条排队消息(✕ 对应的是「第几个气泡」,不是「哪段文本」)。
21
+ * `index` 越界、非整数、或该位置文本与 `text` 对不上(点击与执行之间队列
22
+ * 已变化——有条消息刚送达或新入队)时,回落到 `removeFirstOccurrence` 的文本匹配,
23
+ * 保持旧客户端(只发 text)行为不变。不修改入参。
24
+ */
25
+ export function removeQueuedByIndexOrText(list, text, index) {
26
+ if (typeof index === "number" &&
27
+ Number.isInteger(index) &&
28
+ index >= 0 &&
29
+ index < list.length &&
30
+ list[index] === text) {
31
+ return [...list.slice(0, index), ...list.slice(index + 1)];
32
+ }
33
+ return removeFirstOccurrence(list, text);
34
+ }