pi-web-ui 0.100.0 → 0.102.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 +53 -1
- package/README.md +46 -44
- package/README.zh-CN.md +41 -39
- package/bin/pi-web-ui.mjs +17 -19
- package/dist/server/agent-formatters.js +191 -0
- package/dist/server/agent-service-daemon.js +1266 -0
- package/dist/server/agent-service.js +9884 -12815
- package/dist/server/approval-default-rules.js +158 -0
- package/dist/server/approval-rules.js +41 -167
- package/dist/server/ask-user-question-tool.js +104 -0
- package/dist/server/attachment-store.js +38 -1
- package/dist/server/bash-tool.js +83 -0
- package/dist/server/browser-page-tool.js +207 -0
- package/dist/server/client-id-utils.js +51 -0
- package/dist/server/client-state.js +38 -2
- package/dist/server/compaction-markers.js +34 -1
- package/dist/server/context-budget-runner.js +43 -0
- package/dist/server/dangling-tools.js +18 -5
- package/dist/server/delegate-mode.js +1 -0
- package/dist/server/dispatch-domain-handlers.js +631 -0
- package/dist/server/dispatch-plugin-handlers.js +300 -0
- package/dist/server/dsh/dsh-agent-service.js +30 -5
- package/dist/server/dsh/runtime/goal-rpc.mjs +5 -1
- package/dist/server/goal-evidence.js +9 -2
- package/dist/server/goal-service.js +1 -1
- package/dist/server/hashline-engine.js +1 -1
- package/dist/server/index.js +191 -969
- package/dist/server/left-panel-running.js +115 -0
- package/dist/server/lsp-tool.js +40 -12
- package/dist/server/markers-list-tool.js +34 -0
- package/dist/server/market-service.js +277 -0
- package/dist/server/mcp-bridge.js +137 -30
- package/dist/server/mcp-hot-reload.js +84 -27
- package/dist/server/mcp-manager.js +215 -0
- package/dist/server/message-entry-resolver.js +32 -0
- package/dist/server/orphan-manager.js +44 -0
- package/dist/server/persona-chain.js +63 -0
- package/dist/server/plan-mode.js +2 -0
- package/dist/server/plan-update-tool.js +96 -0
- package/dist/server/plugin-api-catalog.js +20 -0
- package/dist/server/plugin-facilities.js +13 -3
- package/dist/server/plugin-installer.js +6 -1
- package/dist/server/plugin-ui-slots.js +39 -0
- package/dist/server/plugins.js +72 -38
- package/dist/server/preset-fields.js +35 -0
- package/dist/server/preset-share.js +9 -0
- package/dist/server/process-utils.js +30 -0
- package/dist/server/prompt-assembler.js +80 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/scm-commitmsg.js +74 -0
- package/dist/server/serialize.js +97 -7
- package/dist/server/session-branch.js +367 -0
- package/dist/server/session-parser.js +235 -0
- package/dist/server/session-search.js +158 -0
- package/dist/server/settings-service.js +28 -1
- package/dist/server/skill-content-filler.js +33 -0
- package/dist/server/subagent-handoff.js +18 -0
- package/dist/server/subagent-helpers.js +88 -0
- package/dist/server/terminals.js +155 -58
- package/dist/server/tool-guards.js +527 -0
- package/dist/server/tool-host-factories.js +217 -0
- package/dist/server/tool-manager.js +30 -5
- package/dist/server/wait-subscription-scan.js +46 -1
- package/dist/server/workspace-snapshot.js +18 -0
- package/extensions/webui.ts +90 -24
- package/package.json +1 -1
- package/plugin-sdk/README.md +17 -0
- package/plugin-sdk/index.d.ts +17 -0
- package/plugin-sdk/index.mjs +5 -0
- package/plugins/catalog.json +20 -0
- package/themes/aetheris.css +3 -1
- package/themes/translucent.css +8 -1
- package/themes/transparent.css +9 -1
- package/themes/zhupi-dark.css +3 -14
- package/themes/zhupi.css +2 -16
- package/web/dist/assets/{TerminalPanel-C3I1Mc-C.js → TerminalPanel-CYGOzbPT.js} +1 -1
- package/web/dist/assets/index-CP71PHb6.js +680 -0
- package/web/dist/assets/index-ytRwL6j0.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-B-E2EM_0.css +0 -1
- package/web/dist/assets/index-BYumAaGi.js +0 -379
|
@@ -14,8 +14,24 @@
|
|
|
14
14
|
* { "servers": { "gitserv": { "command": "node", "args": ["mcp.js"], "cwd": "/x" } } }
|
|
15
15
|
*/
|
|
16
16
|
import { spawn } from "node:child_process";
|
|
17
|
-
import { readFileSync } from "node:fs";
|
|
17
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
18
|
+
import { homedir } from "node:os";
|
|
18
19
|
import { join } from "node:path";
|
|
20
|
+
/** 获取全局 MCP 配置文件路径 */
|
|
21
|
+
export function getGlobalMcpPath(agentDir, dataDir) {
|
|
22
|
+
const defaultAgentDir = agentDir || process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
23
|
+
const agentPath = join(defaultAgentDir, "mcp.json");
|
|
24
|
+
if (existsSync(agentPath))
|
|
25
|
+
return agentPath;
|
|
26
|
+
if (dataDir && existsSync(join(dataDir, "mcp.json")))
|
|
27
|
+
return join(dataDir, "mcp.json");
|
|
28
|
+
return agentPath;
|
|
29
|
+
}
|
|
30
|
+
/** 获取项目级 MCP 配置文件路径 */
|
|
31
|
+
export function getProjectMcpPath(cwd) {
|
|
32
|
+
const activeCwd = cwd || process.cwd();
|
|
33
|
+
return join(activeCwd, ".pi", "mcp.json");
|
|
34
|
+
}
|
|
19
35
|
const PROTOCOL_VERSION = "2025-03-26"; // 广泛支持的工具版本
|
|
20
36
|
/** 单行(一条 JSON-RPC 消息)的长度上限(1MB):失控服务器一行永不换行会顶爆内存。 */
|
|
21
37
|
const MCP_MAX_LINE_CHARS = 1024 * 1024;
|
|
@@ -56,6 +72,12 @@ export class McpClient {
|
|
|
56
72
|
if (this.child)
|
|
57
73
|
return;
|
|
58
74
|
const { command, args = [], cwd, env } = this.spec;
|
|
75
|
+
if (!command) {
|
|
76
|
+
if (this.spec.url) {
|
|
77
|
+
throw new Error(`远程 HTTP MCP 服务器(${this.spec.url})暂不支持 stdio 直接直连`);
|
|
78
|
+
}
|
|
79
|
+
throw new Error("MCP 服务器规格未声明 command 启动命令");
|
|
80
|
+
}
|
|
59
81
|
this.log(`[mcp:${this.name}] starting: ${command} ${args.join(" ")}`);
|
|
60
82
|
this.buffer = "";
|
|
61
83
|
const child = spawn(command, args, {
|
|
@@ -340,15 +362,29 @@ export function parseMcpConfig(text) {
|
|
|
340
362
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
341
363
|
return null;
|
|
342
364
|
const servers = {};
|
|
343
|
-
|
|
344
|
-
|
|
365
|
+
const raw = parsed.mcpServers ??
|
|
366
|
+
parsed.servers ??
|
|
367
|
+
{};
|
|
368
|
+
for (const [name, s] of Object.entries(raw)) {
|
|
369
|
+
if (!s || typeof s !== "object")
|
|
370
|
+
continue;
|
|
371
|
+
const entry = s;
|
|
372
|
+
const cmd = typeof entry.command === "string" && entry.command.trim() ? entry.command.trim() : undefined;
|
|
373
|
+
const url = typeof entry.url === "string" && entry.url.trim() ? entry.url.trim() : undefined;
|
|
374
|
+
if (!cmd && !url && entry.enabled === undefined)
|
|
345
375
|
continue;
|
|
346
376
|
servers[name] = {
|
|
347
|
-
command:
|
|
348
|
-
args: Array.isArray(
|
|
349
|
-
cwd: typeof
|
|
350
|
-
env:
|
|
351
|
-
|
|
377
|
+
command: cmd,
|
|
378
|
+
args: Array.isArray(entry.args) ? entry.args.map(String) : [],
|
|
379
|
+
cwd: typeof entry.cwd === "string" ? entry.cwd : undefined,
|
|
380
|
+
env: entry.env && typeof entry.env === "object" ? entry.env : undefined,
|
|
381
|
+
url,
|
|
382
|
+
headers: entry.headers && typeof entry.headers === "object" ? entry.headers : undefined,
|
|
383
|
+
type: typeof entry.type === "string" ? entry.type : undefined,
|
|
384
|
+
timeout: typeof entry.timeout === "number" ? entry.timeout : undefined,
|
|
385
|
+
enabled: typeof entry.enabled === "boolean" ? entry.enabled : true,
|
|
386
|
+
description: typeof entry.description === "string" ? entry.description : undefined,
|
|
387
|
+
protocolVersion: typeof entry.protocolVersion === "string" ? entry.protocolVersion : undefined,
|
|
352
388
|
};
|
|
353
389
|
}
|
|
354
390
|
return { servers };
|
|
@@ -371,11 +407,20 @@ export function mcpServerSnapshot(spec) {
|
|
|
371
407
|
const env = {};
|
|
372
408
|
for (const k of Object.keys(spec.env ?? {}).sort())
|
|
373
409
|
env[k] = spec.env[k];
|
|
410
|
+
const headers = {};
|
|
411
|
+
for (const k of Object.keys(spec.headers ?? {}).sort())
|
|
412
|
+
headers[k] = spec.headers[k];
|
|
374
413
|
return {
|
|
375
|
-
command: spec.command,
|
|
414
|
+
command: spec.command ?? null,
|
|
376
415
|
args: spec.args ?? [],
|
|
377
416
|
cwd: spec.cwd ?? null,
|
|
378
417
|
env,
|
|
418
|
+
url: spec.url ?? null,
|
|
419
|
+
headers,
|
|
420
|
+
type: spec.type ?? null,
|
|
421
|
+
timeout: spec.timeout ?? null,
|
|
422
|
+
enabled: spec.enabled !== false,
|
|
423
|
+
description: spec.description ?? null,
|
|
379
424
|
protocolVersion: spec.protocolVersion ?? null,
|
|
380
425
|
};
|
|
381
426
|
}
|
|
@@ -424,17 +469,52 @@ export class McpBridge {
|
|
|
424
469
|
opts;
|
|
425
470
|
clients = [];
|
|
426
471
|
tools = [];
|
|
472
|
+
serverErrors = new Map();
|
|
427
473
|
/** reload 串行化链:重入的 reload 排在前一个之后,杜绝交叠留下的孤儿进程。 */
|
|
428
474
|
reloadChain = Promise.resolve();
|
|
475
|
+
agentDir;
|
|
476
|
+
cwd;
|
|
429
477
|
constructor(dataDir, log = () => { }, opts = {}) {
|
|
430
478
|
this.dataDir = dataDir;
|
|
431
479
|
this.log = log;
|
|
432
480
|
this.opts = opts;
|
|
481
|
+
this.agentDir = opts.agentDir;
|
|
482
|
+
this.cwd = opts.cwd;
|
|
483
|
+
}
|
|
484
|
+
setCwd(newCwd) {
|
|
485
|
+
this.cwd = newCwd;
|
|
486
|
+
this.opts.cwd = newCwd;
|
|
487
|
+
}
|
|
488
|
+
getCwd() {
|
|
489
|
+
return this.cwd;
|
|
490
|
+
}
|
|
491
|
+
getAgentDir() {
|
|
492
|
+
return this.agentDir;
|
|
493
|
+
}
|
|
494
|
+
getServerStatus(name) {
|
|
495
|
+
const client = this.clients.find((c) => c.name === name);
|
|
496
|
+
if (client) {
|
|
497
|
+
return {
|
|
498
|
+
status: "running",
|
|
499
|
+
tools: client.getTools().map((t) => ({ name: t.name, description: t.description })),
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
if (this.serverErrors.has(name)) {
|
|
503
|
+
return {
|
|
504
|
+
status: "error",
|
|
505
|
+
error: this.serverErrors.get(name),
|
|
506
|
+
tools: [],
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
return { status: "stopped", tools: [] };
|
|
433
510
|
}
|
|
434
511
|
/** 读取配置并启动全部服务器(顺序 fail-fast:单个失败记日志不拖垮其它)。 */
|
|
435
512
|
async load() {
|
|
436
|
-
|
|
513
|
+
this.serverErrors.clear();
|
|
514
|
+
const cfg = optsOverrideOrRead(this.opts, this.dataDir);
|
|
437
515
|
await Promise.all(Object.entries(cfg.servers).map(async ([name, spec]) => {
|
|
516
|
+
if (spec.enabled === false)
|
|
517
|
+
return;
|
|
438
518
|
const client = await this.startOne(name, spec);
|
|
439
519
|
if (!client)
|
|
440
520
|
return;
|
|
@@ -448,27 +528,18 @@ export class McpBridge {
|
|
|
448
528
|
try {
|
|
449
529
|
const client = new McpClient(name, spec, this.log);
|
|
450
530
|
await client.start();
|
|
531
|
+
this.serverErrors.delete(name);
|
|
451
532
|
return client;
|
|
452
533
|
}
|
|
453
534
|
catch (err) {
|
|
454
|
-
|
|
535
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
536
|
+
this.serverErrors.set(name, msg);
|
|
537
|
+
this.log(`[mcp] 服务器「${name}」启动失败:`, msg);
|
|
455
538
|
return null;
|
|
456
539
|
}
|
|
457
540
|
}
|
|
458
541
|
/**
|
|
459
542
|
* 按磁盘上的最新配置**整体换入**服务器集合(`mcp.json` 热加载用),可重复调用。
|
|
460
|
-
*
|
|
461
|
-
* 并发互斥:watch + 轮询 + 手动 apply 可能同时触发 reload,两个 reload 交叠跑
|
|
462
|
-
* 会各自 startOne/close —— 同一服务器起两个子进程、或把别人刚换入的实例当
|
|
463
|
-
* stale 关掉(孤儿/误杀)。这里用一条 promise 链把重入排成队,每个 reload
|
|
464
|
-
* 看到的是前一个完成后的最新状态;热加载的防抖窗口之外再兜一道。
|
|
465
|
-
*
|
|
466
|
-
* 三步的顺序都有讲究:
|
|
467
|
-
* 1. 规格没变的服务器**沿用原实例** —— 改一个服务器不该连带重启其它服务器(子进程、
|
|
468
|
-
* 浏览器会话、在途调用全都不动);
|
|
469
|
-
* 2. 新增/变更的**先启动成功才换入**,失败则沿用旧实例 —— 配置写坏不等于把还能用的
|
|
470
|
-
* 工具一起下线;
|
|
471
|
-
* 3. 最后才 close 掉被移除/被替换的旧实例,并按新集合重建工具表。
|
|
472
543
|
*/
|
|
473
544
|
async reload() {
|
|
474
545
|
const run = this.reloadChain.then(() => this.reloadOnce(), () => this.reloadOnce());
|
|
@@ -476,12 +547,12 @@ export class McpBridge {
|
|
|
476
547
|
return run;
|
|
477
548
|
}
|
|
478
549
|
async reloadOnce() {
|
|
479
|
-
const cfg = optsOverrideOrRead(this.opts
|
|
550
|
+
const cfg = optsOverrideOrRead(this.opts, this.dataDir);
|
|
480
551
|
const next = new Map();
|
|
481
552
|
let kept = 0;
|
|
482
553
|
for (const client of this.clients) {
|
|
483
554
|
const spec = cfg.servers[client.name];
|
|
484
|
-
if (!spec || !sameMcpSpec(spec, client.spec))
|
|
555
|
+
if (!spec || spec.enabled === false || !sameMcpSpec(spec, client.spec))
|
|
485
556
|
continue;
|
|
486
557
|
next.set(client.name, client);
|
|
487
558
|
kept++;
|
|
@@ -489,7 +560,7 @@ export class McpBridge {
|
|
|
489
560
|
let started = 0;
|
|
490
561
|
let failed = 0;
|
|
491
562
|
await Promise.all(Object.entries(cfg.servers)
|
|
492
|
-
.filter(([name]) => !next.has(name))
|
|
563
|
+
.filter(([name, s]) => s.enabled !== false && !next.has(name))
|
|
493
564
|
.map(async ([name, spec]) => {
|
|
494
565
|
const previous = this.clients.find((c) => c.name === name);
|
|
495
566
|
const fresh = await this.startOne(name, spec);
|
|
@@ -533,14 +604,50 @@ export class McpBridge {
|
|
|
533
604
|
c.close();
|
|
534
605
|
this.clients = [];
|
|
535
606
|
this.tools = [];
|
|
607
|
+
this.serverErrors.clear();
|
|
536
608
|
}
|
|
537
609
|
}
|
|
538
|
-
function optsOverrideOrRead(
|
|
539
|
-
if (specOverride && specOverride.length > 0) {
|
|
610
|
+
function optsOverrideOrRead(opts, dataDir) {
|
|
611
|
+
if (opts?.specOverride && opts.specOverride.length > 0) {
|
|
540
612
|
const servers = {};
|
|
541
|
-
for (const o of specOverride)
|
|
613
|
+
for (const o of opts.specOverride)
|
|
542
614
|
servers[o.name] = o.spec;
|
|
543
615
|
return { servers };
|
|
544
616
|
}
|
|
545
|
-
|
|
617
|
+
// 1. 全局配置:agentDir 或 dataDir 兜底
|
|
618
|
+
const globalPath = getGlobalMcpPath(opts?.agentDir, dataDir);
|
|
619
|
+
let globalCfg = readMcpConfigByPath(globalPath);
|
|
620
|
+
if (Object.keys(globalCfg.servers).length === 0 && dataDir) {
|
|
621
|
+
const dataDirCfg = readMcpConfig(dataDir);
|
|
622
|
+
if (Object.keys(dataDirCfg.servers).length > 0) {
|
|
623
|
+
globalCfg = dataDirCfg;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
// 2. 项目级配置:cwd/.pi/mcp.json
|
|
627
|
+
let projectCfg = { servers: {} };
|
|
628
|
+
if (opts?.cwd) {
|
|
629
|
+
const projectPath = getProjectMcpPath(opts.cwd);
|
|
630
|
+
projectCfg = readMcpConfigByPath(projectPath);
|
|
631
|
+
}
|
|
632
|
+
// 3. 项目级覆盖全局
|
|
633
|
+
const merged = { ...globalCfg.servers };
|
|
634
|
+
for (const [name, projSpec] of Object.entries(projectCfg.servers)) {
|
|
635
|
+
if (!projSpec.command && !projSpec.url && projSpec.enabled !== undefined && merged[name]) {
|
|
636
|
+
merged[name] = { ...merged[name], enabled: projSpec.enabled };
|
|
637
|
+
}
|
|
638
|
+
else {
|
|
639
|
+
merged[name] = projSpec;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
return { servers: merged };
|
|
643
|
+
}
|
|
644
|
+
function readMcpConfigByPath(filePath) {
|
|
645
|
+
if (!existsSync(filePath))
|
|
646
|
+
return { servers: {} };
|
|
647
|
+
try {
|
|
648
|
+
return parseMcpConfig(readFileSync(filePath, "utf8")) ?? { servers: {} };
|
|
649
|
+
}
|
|
650
|
+
catch {
|
|
651
|
+
return { servers: {} };
|
|
652
|
+
}
|
|
546
653
|
}
|
|
@@ -14,15 +14,17 @@
|
|
|
14
14
|
* MCP 服务器,照常应用。
|
|
15
15
|
*/
|
|
16
16
|
import { readFileSync, watch } from "node:fs";
|
|
17
|
-
import { join } from "node:path";
|
|
18
|
-
import { mcpServerSnapshot, parseMcpConfig } from "./mcp-bridge.js";
|
|
17
|
+
import { dirname, join } from "node:path";
|
|
18
|
+
import { getGlobalMcpPath, getProjectMcpPath, mcpServerSnapshot, parseMcpConfig, } from "./mcp-bridge.js";
|
|
19
19
|
/** 规范化指纹:只含影响行为的字段、服务器顺序无关 —— 「内容变了吗」的判据。 */
|
|
20
20
|
function fingerprint(servers) {
|
|
21
21
|
const names = Object.keys(servers).sort();
|
|
22
22
|
return JSON.stringify(names.map((n) => [n, mcpServerSnapshot(servers[n])]));
|
|
23
23
|
}
|
|
24
24
|
export function createMcpHotReload(deps) {
|
|
25
|
-
const
|
|
25
|
+
const globalFile = getGlobalMcpPath(deps.agentDir, deps.dataDir);
|
|
26
|
+
const projectFile = deps.cwd ? getProjectMcpPath(deps.cwd) : undefined;
|
|
27
|
+
const legacyFile = join(deps.dataDir, "mcp.json");
|
|
26
28
|
const log = deps.log ?? (() => { });
|
|
27
29
|
const debounceMs = deps.debounceMs ?? 300;
|
|
28
30
|
const pollIntervalMs = deps.pollIntervalMs ?? 2000;
|
|
@@ -30,22 +32,17 @@ export function createMcpHotReload(deps) {
|
|
|
30
32
|
let applied = null;
|
|
31
33
|
let debounce = null;
|
|
32
34
|
let poller = null;
|
|
33
|
-
let
|
|
34
|
-
|
|
35
|
-
function readOnce() {
|
|
35
|
+
let watchers = [];
|
|
36
|
+
function readOneFile(file) {
|
|
36
37
|
let raw;
|
|
37
38
|
try {
|
|
38
39
|
raw = readFileSync(file, "utf8");
|
|
39
40
|
}
|
|
40
41
|
catch (err) {
|
|
41
|
-
// 不变量 3 只覆盖「文件不在」:删掉 mcp.json = 关掉全部 MCP 服务器。
|
|
42
|
-
// #497:EBUSY/EACCES 等临时读失败(OneDrive/杀毒独占、权限误改)既不是
|
|
43
|
-
// 坏配置也不是删除意图——按坏配置口径走(servers: null → 保留在跑的
|
|
44
|
-
// 服务器 + 一次性提示),否则会把在跑的 MCP 服务器全杀还报「成功 0 个」。
|
|
45
42
|
const code = err?.code;
|
|
46
43
|
if (code === "ENOENT")
|
|
47
44
|
return { fp: "empty", servers: {} };
|
|
48
|
-
log(`[mcp]
|
|
45
|
+
log(`[mcp] ${file} 读取失败(${code ?? String(err)}),按坏配置处理:保留在跑的 MCP 服务器`);
|
|
49
46
|
return { fp: `unreadable:${code ?? "unknown"}`, servers: null };
|
|
50
47
|
}
|
|
51
48
|
const parsed = parseMcpConfig(raw);
|
|
@@ -53,6 +50,48 @@ export function createMcpHotReload(deps) {
|
|
|
53
50
|
return { fp: `invalid:${raw}`, servers: null };
|
|
54
51
|
return { fp: `ok:${fingerprint(parsed.servers)}`, servers: parsed.servers };
|
|
55
52
|
}
|
|
53
|
+
/** 读全部配置文件(全局 + 项目)并合并指纹 */
|
|
54
|
+
function readOnce() {
|
|
55
|
+
const g = readOneFile(globalFile);
|
|
56
|
+
let globalServers = g.servers;
|
|
57
|
+
let gFp = g.fp;
|
|
58
|
+
if (g.fp === "empty" && legacyFile !== globalFile) {
|
|
59
|
+
const leg = readOneFile(legacyFile);
|
|
60
|
+
if (leg.servers) {
|
|
61
|
+
globalServers = leg.servers;
|
|
62
|
+
gFp = leg.fp;
|
|
63
|
+
}
|
|
64
|
+
else if (leg.fp.startsWith("unreadable:") || leg.fp.startsWith("invalid:")) {
|
|
65
|
+
return leg;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
else if (!g.servers && (g.fp.startsWith("unreadable:") || g.fp.startsWith("invalid:"))) {
|
|
69
|
+
return g;
|
|
70
|
+
}
|
|
71
|
+
let pFp = "none";
|
|
72
|
+
let projServers = {};
|
|
73
|
+
if (projectFile) {
|
|
74
|
+
const p = readOneFile(projectFile);
|
|
75
|
+
if (!p.servers && (p.fp.startsWith("unreadable:") || p.fp.startsWith("invalid:"))) {
|
|
76
|
+
return p;
|
|
77
|
+
}
|
|
78
|
+
projServers = p.servers;
|
|
79
|
+
pFp = p.fp;
|
|
80
|
+
}
|
|
81
|
+
const merged = { ...globalServers };
|
|
82
|
+
for (const [name, ps] of Object.entries(projServers || {})) {
|
|
83
|
+
if (!ps.command && !ps.url && ps.enabled !== undefined && merged[name]) {
|
|
84
|
+
merged[name] = { ...merged[name], enabled: ps.enabled };
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
merged[name] = ps;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
fp: `g:${gFp}|p:${pFp}`,
|
|
92
|
+
servers: merged,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
56
95
|
async function apply() {
|
|
57
96
|
const { fp, servers } = readOnce();
|
|
58
97
|
if (fp === applied)
|
|
@@ -84,8 +123,13 @@ export function createMcpHotReload(deps) {
|
|
|
84
123
|
}
|
|
85
124
|
/** fs.watch 用不了(目录还不存在、网络盘、容器)→ 回落到轮询:单文件不值得上更重的机制。 */
|
|
86
125
|
function fallBackToPolling() {
|
|
87
|
-
|
|
88
|
-
|
|
126
|
+
for (const w of watchers) {
|
|
127
|
+
try {
|
|
128
|
+
w.close();
|
|
129
|
+
}
|
|
130
|
+
catch { }
|
|
131
|
+
}
|
|
132
|
+
watchers = [];
|
|
89
133
|
if (poller)
|
|
90
134
|
return;
|
|
91
135
|
log(`[mcp] 目录监视不可用,mcp.json 热加载回落到 ${pollIntervalMs}ms 轮询`);
|
|
@@ -93,21 +137,29 @@ export function createMcpHotReload(deps) {
|
|
|
93
137
|
poller.unref();
|
|
94
138
|
}
|
|
95
139
|
function start() {
|
|
96
|
-
if (
|
|
140
|
+
if (watchers.length > 0 || poller)
|
|
97
141
|
return;
|
|
98
142
|
// 播种:启动时 load() 已按同一份文件启动过服务器,别在第一个事件里白重载一次。
|
|
99
143
|
applied = readOnce().fp;
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
144
|
+
const dirsToWatch = new Set();
|
|
145
|
+
dirsToWatch.add(deps.dataDir);
|
|
146
|
+
if (globalFile)
|
|
147
|
+
dirsToWatch.add(dirname(globalFile));
|
|
148
|
+
if (projectFile)
|
|
149
|
+
dirsToWatch.add(dirname(projectFile));
|
|
150
|
+
for (const dir of dirsToWatch) {
|
|
151
|
+
try {
|
|
152
|
+
const w = watch(dir, { persistent: false }, (_event, filename) => {
|
|
153
|
+
if (typeof filename === "string" && filename && filename !== "mcp.json")
|
|
154
|
+
return;
|
|
155
|
+
schedule();
|
|
156
|
+
});
|
|
157
|
+
w.on("error", () => fallBackToPolling());
|
|
158
|
+
watchers.push(w);
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
fallBackToPolling();
|
|
162
|
+
}
|
|
111
163
|
}
|
|
112
164
|
}
|
|
113
165
|
function dispose() {
|
|
@@ -117,8 +169,13 @@ export function createMcpHotReload(deps) {
|
|
|
117
169
|
if (poller)
|
|
118
170
|
clearInterval(poller);
|
|
119
171
|
poller = null;
|
|
120
|
-
|
|
121
|
-
|
|
172
|
+
for (const w of watchers) {
|
|
173
|
+
try {
|
|
174
|
+
w.close();
|
|
175
|
+
}
|
|
176
|
+
catch { }
|
|
177
|
+
}
|
|
178
|
+
watchers = [];
|
|
122
179
|
}
|
|
123
180
|
return { apply, start, dispose };
|
|
124
181
|
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP 服务器管理服务
|
|
3
|
+
*
|
|
4
|
+
* 负责 Pi 全局 (~/.pi/agent/mcp.json 或兼容 ~/.pi-web/mcp.json)
|
|
5
|
+
* 与工作区项目级 (.pi/mcp.json) MCP 服务器配置的读写、合并与生命周期。
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
import { getGlobalMcpPath, getProjectMcpPath, parseMcpConfig, } from "./mcp-bridge.js";
|
|
10
|
+
export { getGlobalMcpPath, getProjectMcpPath };
|
|
11
|
+
/** 读取指定文件的 MCP 服务器配置 */
|
|
12
|
+
export function readMcpConfigFile(filePath) {
|
|
13
|
+
if (!existsSync(filePath)) {
|
|
14
|
+
return { servers: {}, raw: null, legacy: false, exists: false };
|
|
15
|
+
}
|
|
16
|
+
try {
|
|
17
|
+
const text = readFileSync(filePath, "utf8");
|
|
18
|
+
let raw = null;
|
|
19
|
+
try {
|
|
20
|
+
const parsed = JSON.parse(text);
|
|
21
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
22
|
+
raw = parsed;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
/* invalid json */
|
|
27
|
+
}
|
|
28
|
+
const legacy = !!raw && raw.servers !== undefined && raw.mcpServers === undefined;
|
|
29
|
+
const parsedConfig = parseMcpConfig(text);
|
|
30
|
+
return {
|
|
31
|
+
servers: parsedConfig ? parsedConfig.servers : {},
|
|
32
|
+
raw,
|
|
33
|
+
legacy,
|
|
34
|
+
exists: true,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return { servers: {}, raw: null, legacy: false, exists: true };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** 写入指定文件的 MCP 服务器配置(保留除服务器清单以外的其它字段) */
|
|
42
|
+
export function writeMcpConfigFile(filePath, servers, preferLegacy = false) {
|
|
43
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
44
|
+
let raw = {};
|
|
45
|
+
if (existsSync(filePath)) {
|
|
46
|
+
try {
|
|
47
|
+
const text = readFileSync(filePath, "utf8");
|
|
48
|
+
const parsed = JSON.parse(text);
|
|
49
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
50
|
+
raw = parsed;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
/* ignore corrupt file, rewrite cleanly */
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const legacy = raw.servers !== undefined && raw.mcpServers === undefined ? true : preferLegacy;
|
|
58
|
+
const next = { ...raw };
|
|
59
|
+
if (legacy) {
|
|
60
|
+
delete next.mcpServers;
|
|
61
|
+
next.servers = servers;
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
delete next.servers;
|
|
65
|
+
next.mcpServers = servers;
|
|
66
|
+
}
|
|
67
|
+
writeFileSync(filePath, JSON.stringify(next, null, 2) + "\n", "utf8");
|
|
68
|
+
}
|
|
69
|
+
/** 校验 MCP 服务器名称合法性(字母、数字、下划线、短横线) */
|
|
70
|
+
export function isValidMcpServerName(name) {
|
|
71
|
+
return /^[a-zA-Z0-9_-]+$/.test(name.trim());
|
|
72
|
+
}
|
|
73
|
+
/** 汇总查询全局与项目级配置列表,并结合 McpBridge 运行时状态组装 UiMcpServer 数组 */
|
|
74
|
+
export function listAllMcpServers(opts) {
|
|
75
|
+
const globalPath = getGlobalMcpPath(opts.agentDir, opts.dataDir);
|
|
76
|
+
const projectPath = getProjectMcpPath(opts.cwd);
|
|
77
|
+
const globalCfg = readMcpConfigFile(globalPath);
|
|
78
|
+
const projectCfg = readMcpConfigFile(projectPath);
|
|
79
|
+
const result = [];
|
|
80
|
+
// 全局服务器
|
|
81
|
+
for (const [name, spec] of Object.entries(globalCfg.servers)) {
|
|
82
|
+
const status = getRuntimeStatus(name, spec, opts.bridge);
|
|
83
|
+
result.push({
|
|
84
|
+
name,
|
|
85
|
+
scope: "global",
|
|
86
|
+
command: spec.command,
|
|
87
|
+
args: spec.args,
|
|
88
|
+
cwd: spec.cwd,
|
|
89
|
+
env: spec.env,
|
|
90
|
+
url: spec.url,
|
|
91
|
+
headers: spec.headers,
|
|
92
|
+
type: spec.type,
|
|
93
|
+
timeout: spec.timeout,
|
|
94
|
+
protocolVersion: spec.protocolVersion,
|
|
95
|
+
enabled: spec.enabled !== false,
|
|
96
|
+
description: spec.description,
|
|
97
|
+
status: status.status,
|
|
98
|
+
error: status.error,
|
|
99
|
+
tools: status.tools,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
// 项目级服务器
|
|
103
|
+
for (const [name, spec] of Object.entries(projectCfg.servers)) {
|
|
104
|
+
const status = getRuntimeStatus(name, spec, opts.bridge);
|
|
105
|
+
result.push({
|
|
106
|
+
name,
|
|
107
|
+
scope: "project",
|
|
108
|
+
command: spec.command,
|
|
109
|
+
args: spec.args,
|
|
110
|
+
cwd: spec.cwd,
|
|
111
|
+
env: spec.env,
|
|
112
|
+
url: spec.url,
|
|
113
|
+
headers: spec.headers,
|
|
114
|
+
type: spec.type,
|
|
115
|
+
timeout: spec.timeout,
|
|
116
|
+
protocolVersion: spec.protocolVersion,
|
|
117
|
+
enabled: spec.enabled !== false,
|
|
118
|
+
description: spec.description,
|
|
119
|
+
status: status.status,
|
|
120
|
+
error: status.error,
|
|
121
|
+
tools: status.tools,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
return { servers: result, globalPath, projectPath };
|
|
125
|
+
}
|
|
126
|
+
function getRuntimeStatus(name, spec, bridge) {
|
|
127
|
+
if (spec.enabled === false) {
|
|
128
|
+
return { status: "stopped", tools: [] };
|
|
129
|
+
}
|
|
130
|
+
if (!bridge) {
|
|
131
|
+
return { status: "stopped", tools: [] };
|
|
132
|
+
}
|
|
133
|
+
return bridge.getServerStatus(name);
|
|
134
|
+
}
|
|
135
|
+
/** 保存或更新 MCP 服务器 */
|
|
136
|
+
export function saveMcpServer(opts) {
|
|
137
|
+
const name = opts.server.name.trim();
|
|
138
|
+
if (!isValidMcpServerName(name)) {
|
|
139
|
+
return { ok: false, error: "服务器名称仅允许包含英文字母、数字、下划线及中划线" };
|
|
140
|
+
}
|
|
141
|
+
const targetScope = opts.server.scope;
|
|
142
|
+
const globalPath = getGlobalMcpPath(opts.agentDir, opts.dataDir);
|
|
143
|
+
const projectPath = getProjectMcpPath(opts.cwd);
|
|
144
|
+
const targetPath = targetScope === "global" ? globalPath : projectPath;
|
|
145
|
+
// 若存在旧名称或作用域移动,从原作用域文件中移除
|
|
146
|
+
if (opts.prevName && opts.prevScope) {
|
|
147
|
+
const prevCleanName = opts.prevName.trim();
|
|
148
|
+
if (prevCleanName !== name || opts.prevScope !== targetScope) {
|
|
149
|
+
const oldPath = opts.prevScope === "global" ? globalPath : projectPath;
|
|
150
|
+
const oldCfg = readMcpConfigFile(oldPath);
|
|
151
|
+
if (oldCfg.servers[prevCleanName]) {
|
|
152
|
+
delete oldCfg.servers[prevCleanName];
|
|
153
|
+
writeMcpConfigFile(oldPath, oldCfg.servers, oldCfg.legacy);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const targetCfg = readMcpConfigFile(targetPath);
|
|
158
|
+
const spec = {
|
|
159
|
+
command: opts.server.command?.trim() || undefined,
|
|
160
|
+
args: Array.isArray(opts.server.args) && opts.server.args.length > 0 ? opts.server.args.map(String) : undefined,
|
|
161
|
+
cwd: opts.server.cwd?.trim() || undefined,
|
|
162
|
+
env: opts.server.env && Object.keys(opts.server.env).length > 0
|
|
163
|
+
? opts.server.env
|
|
164
|
+
: undefined,
|
|
165
|
+
url: opts.server.url?.trim() || undefined,
|
|
166
|
+
headers: opts.server.headers && Object.keys(opts.server.headers).length > 0
|
|
167
|
+
? opts.server.headers
|
|
168
|
+
: undefined,
|
|
169
|
+
type: opts.server.type,
|
|
170
|
+
timeout: typeof opts.server.timeout === "number" ? opts.server.timeout : undefined,
|
|
171
|
+
protocolVersion: opts.server.protocolVersion?.trim() || undefined,
|
|
172
|
+
enabled: opts.server.enabled !== false,
|
|
173
|
+
description: opts.server.description?.trim() || undefined,
|
|
174
|
+
};
|
|
175
|
+
targetCfg.servers[name] = spec;
|
|
176
|
+
writeMcpConfigFile(targetPath, targetCfg.servers, targetCfg.legacy);
|
|
177
|
+
return { ok: true };
|
|
178
|
+
}
|
|
179
|
+
/** 删除指定作用域下的 MCP 服务器 */
|
|
180
|
+
export function deleteMcpServer(opts) {
|
|
181
|
+
const name = opts.name.trim();
|
|
182
|
+
const globalPath = getGlobalMcpPath(opts.agentDir, opts.dataDir);
|
|
183
|
+
const projectPath = getProjectMcpPath(opts.cwd);
|
|
184
|
+
const targetPath = opts.scope === "global" ? globalPath : projectPath;
|
|
185
|
+
const targetCfg = readMcpConfigFile(targetPath);
|
|
186
|
+
if (!targetCfg.servers[name]) {
|
|
187
|
+
return { ok: false, error: `服务器 ${name} 在 ${opts.scope === "global" ? "全局" : "项目"} 配置中不存在` };
|
|
188
|
+
}
|
|
189
|
+
delete targetCfg.servers[name];
|
|
190
|
+
writeMcpConfigFile(targetPath, targetCfg.servers, targetCfg.legacy);
|
|
191
|
+
return { ok: true };
|
|
192
|
+
}
|
|
193
|
+
/** 切换指定作用域下的 MCP 服务器启用/停用状态 */
|
|
194
|
+
export function toggleMcpServer(opts) {
|
|
195
|
+
const name = opts.name.trim();
|
|
196
|
+
const globalPath = getGlobalMcpPath(opts.agentDir, opts.dataDir);
|
|
197
|
+
const projectPath = getProjectMcpPath(opts.cwd);
|
|
198
|
+
const targetPath = opts.scope === "global" ? globalPath : projectPath;
|
|
199
|
+
const targetCfg = readMcpConfigFile(targetPath);
|
|
200
|
+
if (targetCfg.servers[name]) {
|
|
201
|
+
targetCfg.servers[name].enabled = opts.enabled;
|
|
202
|
+
writeMcpConfigFile(targetPath, targetCfg.servers, targetCfg.legacy);
|
|
203
|
+
return { ok: true };
|
|
204
|
+
}
|
|
205
|
+
// 若在项目级切换全局服务器的启用状态(项目级覆盖):写入仅带 enabled 的配置项
|
|
206
|
+
if (opts.scope === "project") {
|
|
207
|
+
const globalCfg = readMcpConfigFile(globalPath);
|
|
208
|
+
if (globalCfg.servers[name]) {
|
|
209
|
+
targetCfg.servers[name] = { enabled: opts.enabled };
|
|
210
|
+
writeMcpConfigFile(targetPath, targetCfg.servers, targetCfg.legacy);
|
|
211
|
+
return { ok: true };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return { ok: false, error: `服务器 ${name} 不存在` };
|
|
215
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { findEntryByUiId } from "./serialize.js";
|
|
2
|
+
/**
|
|
3
|
+
* 将前端渲染的用户消息 ID(u-<timestamp>-<seq>)解析为底层 SessionEntry 的唯一 ID。
|
|
4
|
+
* seq 用于解决同一毫秒内发出的多条用户消息(例如附件 aside 消息)。
|
|
5
|
+
*/
|
|
6
|
+
export function resolveUserMessageEntryId(contextEntries, messageId) {
|
|
7
|
+
const m = /^u-(\d+)(?:-(\d+))?$/.exec(messageId);
|
|
8
|
+
if (!m)
|
|
9
|
+
return null;
|
|
10
|
+
const ts = Number(m[1]);
|
|
11
|
+
const seq = m[2] ? Number(m[2]) : 1;
|
|
12
|
+
let count = 0;
|
|
13
|
+
for (const entry of contextEntries) {
|
|
14
|
+
if (entry.type !== "message")
|
|
15
|
+
continue;
|
|
16
|
+
const msg = entry.message;
|
|
17
|
+
if (!msg || msg.role !== "user" || msg.timestamp !== ts)
|
|
18
|
+
continue;
|
|
19
|
+
count += 1;
|
|
20
|
+
if (count === seq)
|
|
21
|
+
return entry.id;
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* 将任意渲染的消息 ID 解析为当前会话分支的 SessionEntry 节点。
|
|
27
|
+
* 优先在上下文条目中比对 UI ID,未命中时通过 fallback 查整棵历史树。
|
|
28
|
+
*/
|
|
29
|
+
export function resolveConversationMessageEntry(contextEntries, messageId, seqOf, fallbackGetEntry) {
|
|
30
|
+
const found = findEntryByUiId(contextEntries, messageId, seqOf);
|
|
31
|
+
return found ?? fallbackGetEntry?.(messageId) ?? null;
|
|
32
|
+
}
|