pi-web-ui 0.88.0 → 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.
@@ -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 重算;合法插件无诊断时记空数组)。 */
@@ -1068,6 +1070,39 @@ export class PluginManager {
1068
1070
  res.end();
1069
1071
  }
1070
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
+ }
1071
1106
  broadcast(pluginId, payload) {
1072
1107
  this.deliverAll({ type: "plugin_data", pluginId, payload });
1073
1108
  }
@@ -1334,6 +1369,30 @@ export class PluginManager {
1334
1369
  }
1335
1370
  }
1336
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
+ }
1337
1396
  /** 当前全部插件注册的 AI 工具(扁平化,按插件 id 稳定排序)。 */
1338
1397
  getAgentTools() {
1339
1398
  const out = [];
@@ -1544,11 +1603,24 @@ export class PluginManager {
1544
1603
  this.deactivateEntry(id, p);
1545
1604
  }
1546
1605
  }
1547
- return found.map((f) => this.loaded.get(f.id)?.info ?? 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
+ });
1548
1614
  }
1549
1615
  /** 反激活清理:把该插件名下全部订阅/注册一次收完(工具/命令/watch/定时/
1550
1616
  * 总线/stats/流式——参考 agentToolUnsubscribers 模式,新增订阅一律走这里)。 */
1551
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
+ }
1552
1624
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
1553
1625
  for (const off of [
1554
1626
  ...(p.agentToolUnsubscribers ?? []),
@@ -1749,6 +1821,9 @@ export class PluginManager {
1749
1821
  });
1750
1822
  // 诊断随清单下发:manifest 解析 + 到目前为止的运行时诊断。
1751
1823
  this.manifestDiags.set(name, uiDiags);
1824
+ const agentTools = this.agentToolsSnapshot(name);
1825
+ if (agentTools.length)
1826
+ out[out.length - 1].agentTools = agentTools;
1752
1827
  const scanned = [...uiDiags, ...(this.runtimeDiags.get(name) ?? [])].slice(0, 100);
1753
1828
  if (scanned.length)
1754
1829
  out[out.length - 1].diagnostics = scanned;
@@ -2243,6 +2318,19 @@ export class PluginManager {
2243
2318
  httpRoutes.set(`${m} ${path}`, handler);
2244
2319
  return () => httpRoutes.delete(`${m} ${path}`);
2245
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
+ },
2246
2334
  // 包一层:插件反激活时自动注销它注册的全部 AI 工具,不留悬挂项。
2247
2335
  registerAgentTool: (tool) => {
2248
2336
  if (!can("tools"))
@@ -2948,6 +3036,57 @@ export function resolvePluginClientFile(pluginsDir, id, rest) {
2948
3036
  return null;
2949
3037
  return abs;
2950
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
+ }
2951
3090
  /**
2952
3091
  * 把插件 AI 工具定义同步进一个「会话状对象」(SDK AgentSession 的结构子集:
2953
3092
  * 内部 _customTools 数组 + _refreshToolRegistry()——refresh 会重读数组,且新