pi-web-ui 0.99.0 → 0.101.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 (109) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/README.md +48 -45
  3. package/README.zh-CN.md +43 -40
  4. package/bin/pi-web-ui.mjs +172 -40
  5. package/dist/server/agent-formatters.js +191 -0
  6. package/dist/server/agent-service-daemon.js +1266 -0
  7. package/dist/server/agent-service.js +9851 -11892
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +130 -184
  10. package/dist/server/ask-user-question-tool.js +94 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/attachments.js +55 -0
  13. package/dist/server/bash-tool.js +83 -0
  14. package/dist/server/bg-servers.js +82 -2
  15. package/dist/server/browser-page-tool.js +207 -0
  16. package/dist/server/claim-files-tool.js +4 -4
  17. package/dist/server/client-id-utils.js +51 -0
  18. package/dist/server/client-state.js +63 -1
  19. package/dist/server/compact-context-tool.js +10 -9
  20. package/dist/server/compaction-markers.js +34 -1
  21. package/dist/server/context-budget-runner.js +43 -0
  22. package/dist/server/conversation-read-tool.js +7 -8
  23. package/dist/server/conversation-touches.js +19 -0
  24. package/dist/server/dangling-tools.js +18 -5
  25. package/dist/server/delegate-mode.js +1 -0
  26. package/dist/server/delegate-task.js +10 -14
  27. package/dist/server/dispatch-domain-handlers.js +631 -0
  28. package/dist/server/dispatch-plugin-handlers.js +300 -0
  29. package/dist/server/dsh/dsh-agent-service.js +125 -13
  30. package/dist/server/edit-soft-tool.js +10 -12
  31. package/dist/server/eval-tool.js +4 -5
  32. package/dist/server/goal-evidence.js +180 -0
  33. package/dist/server/goal-service.js +49 -9
  34. package/dist/server/hashline-engine.js +199 -32
  35. package/dist/server/index.js +212 -944
  36. package/dist/server/left-panel-running.js +115 -0
  37. package/dist/server/load-tools-tool.js +100 -0
  38. package/dist/server/lsp-tool.js +50 -28
  39. package/dist/server/marker-service.js +53 -12
  40. package/dist/server/markers/builtins/action.js +108 -0
  41. package/dist/server/markers/index.js +4 -1
  42. package/dist/server/markers-list-tool.js +34 -0
  43. package/dist/server/market-service.js +277 -0
  44. package/dist/server/mcp-bridge.js +137 -30
  45. package/dist/server/mcp-hot-reload.js +84 -27
  46. package/dist/server/mcp-manager.js +215 -0
  47. package/dist/server/message-entry-resolver.js +32 -0
  48. package/dist/server/orphan-manager.js +44 -0
  49. package/dist/server/patch-remote-catalog.js +28 -10
  50. package/dist/server/patch-tool.js +9 -8
  51. package/dist/server/persona-chain.js +63 -0
  52. package/dist/server/plan-mode.js +9 -6
  53. package/dist/server/plan-update-tool.js +96 -0
  54. package/dist/server/plugin-api-catalog.js +30 -3
  55. package/dist/server/plugin-conversation-view.js +47 -0
  56. package/dist/server/plugin-facilities.js +13 -3
  57. package/dist/server/plugin-ui-slots.js +39 -0
  58. package/dist/server/plugins.js +183 -63
  59. package/dist/server/present-files-tool.js +10 -11
  60. package/dist/server/preset-fields.js +700 -0
  61. package/dist/server/preset-share.js +1179 -0
  62. package/dist/server/process-utils.js +30 -0
  63. package/dist/server/prompt-assembler.js +80 -0
  64. package/dist/server/prompt-composer.js +23 -9
  65. package/dist/server/protocol-version.js +1 -1
  66. package/dist/server/read-tool.js +8 -10
  67. package/dist/server/resolve-global-sdk.js +80 -18
  68. package/dist/server/schedule-agent-tool.js +147 -146
  69. package/dist/server/scm-commitmsg.js +74 -0
  70. package/dist/server/sdk-origin.js +125 -37
  71. package/dist/server/serialize.js +97 -7
  72. package/dist/server/session-branch.js +367 -0
  73. package/dist/server/session-parser.js +235 -0
  74. package/dist/server/session-search.js +158 -0
  75. package/dist/server/settings-service.js +115 -84
  76. package/dist/server/skill-content-filler.js +33 -0
  77. package/dist/server/skill-tool.js +3 -4
  78. package/dist/server/subagent-handoff.js +18 -0
  79. package/dist/server/subagent-helpers.js +88 -0
  80. package/dist/server/subagents.js +15 -22
  81. package/dist/server/terminals.js +171 -91
  82. package/dist/server/tool-approval.js +3 -1
  83. package/dist/server/tool-guards.js +527 -0
  84. package/dist/server/tool-host-factories.js +217 -0
  85. package/dist/server/tool-manager.js +84 -23
  86. package/dist/server/tool-prompt-overrides.js +158 -0
  87. package/dist/server/tool-prompts.js +42 -0
  88. package/dist/server/tool-signature.js +104 -0
  89. package/dist/server/wait-subscription-scan.js +46 -1
  90. package/dist/server/workspace-snapshot.js +60 -11
  91. package/extensions/webui.ts +90 -24
  92. package/package.json +5 -3
  93. package/plugin-sdk/README.md +25 -4
  94. package/plugin-sdk/import-check.mjs +210 -0
  95. package/plugin-sdk/index.d.ts +21 -1
  96. package/plugin-sdk/index.mjs +6 -0
  97. package/plugins/catalog.json +53 -2
  98. package/themes/aetheris.css +3 -1
  99. package/themes/translucent.css +8 -1
  100. package/themes/transparent.css +9 -1
  101. package/themes/zhupi-dark.css +1 -1
  102. package/themes/zhupi.css +1 -1
  103. package/web/dist/assets/{TerminalPanel-NerrJlTS.js → TerminalPanel-DD7I5_aC.js} +2 -2
  104. package/web/dist/assets/index-CpjA1YdT.css +1 -0
  105. package/web/dist/assets/index-nKn87VuM.js +678 -0
  106. package/web/dist/index.html +2 -2
  107. package/web/dist/sw.js +1 -1
  108. package/web/dist/assets/index-BdMaGCcs.css +0 -1
  109. package/web/dist/assets/index-ByCBN4Kt.js +0 -368
@@ -0,0 +1,34 @@
1
+ /**
2
+ * markers-list-tool — 任务列表只读查询工具(todo_list)。
3
+ *
4
+ * 读操作仍走真工具;所有写操作由模型在回复正文中使用行内标记([[todo:new:...]] 等)。
5
+ * 从 agent-service.ts 抽出为独立模块。
6
+ */
7
+ import { Type } from "typebox";
8
+ import { MARKERS_LIST_TOOL_NAME } from "./tool-manager.js";
9
+ export function makeMarkersListTool(getActiveId, markerSvc) {
10
+ return {
11
+ name: MARKERS_LIST_TOOL_NAME,
12
+ promptSnippet: "list inline-marker tasks (read-only; writes use [[todo:...]])",
13
+ label: "List marker state",
14
+ description: "Read-only query of inline marker state. All WRITE operations must use inline markers ([[todo:new:...]] etc.) in the reply body — never this tool.",
15
+ parameters: Type.Object({
16
+ action: Type.Unsafe({ enum: ["list"] }),
17
+ tool: Type.Optional(Type.Literal("todo")),
18
+ includeDeleted: Type.Optional(Type.Boolean({
19
+ description: "Include deleted tasks (tombstones, todo only).",
20
+ })),
21
+ }),
22
+ execute: async (_id, params) => {
23
+ const p = params;
24
+ const convId = getActiveId();
25
+ const text = markerSvc.describe(convId, "todo", !!p.includeDeleted);
26
+ const state = markerSvc.getRawState(convId, "todo");
27
+ const visible = (state?.tasks ?? []).filter((t) => p.includeDeleted || t.status !== "deleted");
28
+ return {
29
+ content: [{ type: "text", text }],
30
+ details: { action: "list", todos: visible, nextId: state?.nextId },
31
+ };
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,277 @@
1
+ /**
2
+ * 远程市场服务 —— MCP 服务器市场 API 与 GitHub 技能仓库目录抓取
3
+ *
4
+ * 职责:
5
+ * 1. 从 Smithery 等开放 API、GitHub 官方仓库拉取公开 MCP 服务器目录;
6
+ * 2. 从 GitHub 仓库(如 anthropics/skills 等)拉取公开 Agent Skills 清单及 SKILL.md 正文;
7
+ * 3. 本地磁盘缓存与超时防抖,网络失败时不影响主程序运行。
8
+ */
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ const DEFAULT_TIMEOUT_MS = 10_000;
12
+ const CACHE_TTL_MS = 60 * 60 * 1000; // 1 小时缓存
13
+ /** 获取 GitHub Token(优先使用配置的预设分享令牌或标准环境变量) */
14
+ function getGitHubToken() {
15
+ return (process.env.PI_WEB_PRESET_TOKEN?.trim() ||
16
+ process.env.GH_TOKEN?.trim() ||
17
+ process.env.GITHUB_TOKEN?.trim() ||
18
+ undefined);
19
+ }
20
+ function fetchHeaders(customHeaders) {
21
+ const headers = {
22
+ "User-Agent": "pi-web-ui-market/1.0",
23
+ Accept: "application/json",
24
+ ...customHeaders,
25
+ };
26
+ const token = getGitHubToken();
27
+ if (token && !headers.Authorization) {
28
+ headers.Authorization = `Bearer ${token}`;
29
+ }
30
+ return headers;
31
+ }
32
+ function readCache(cacheFile) {
33
+ if (!existsSync(cacheFile))
34
+ return null;
35
+ try {
36
+ const raw = JSON.parse(readFileSync(cacheFile, "utf8"));
37
+ if (Date.now() - raw.timestamp < CACHE_TTL_MS) {
38
+ return raw.data;
39
+ }
40
+ }
41
+ catch {
42
+ /* invalid cache */
43
+ }
44
+ return null;
45
+ }
46
+ function writeCache(cacheFile, data) {
47
+ try {
48
+ mkdirSync(dirname(cacheFile), { recursive: true });
49
+ const payload = {
50
+ timestamp: Date.now(),
51
+ data,
52
+ };
53
+ writeFileSync(cacheFile, JSON.stringify(payload), "utf8");
54
+ }
55
+ catch {
56
+ /* ignore write cache failure */
57
+ }
58
+ }
59
+ /** 从公开 API 或仓库拉取 MCP 服务器列表 */
60
+ export async function fetchRemoteMcpMarket(opts) {
61
+ const source = opts.source || "smithery";
62
+ const cacheKey = `mcp-market-${source.replace(/[^a-zA-Z0-9_-]/g, "_")}-${opts.query || "all"}.json`;
63
+ const cacheFile = join(opts.dataDir, "market-cache", cacheKey);
64
+ if (!opts.refresh) {
65
+ const cached = readCache(cacheFile);
66
+ if (cached) {
67
+ return { ok: true, servers: cached, source, total: cached.length };
68
+ }
69
+ }
70
+ try {
71
+ if (source === "smithery" || source.startsWith("https://api.smithery.ai")) {
72
+ const baseUrl = source === "smithery" ? "https://api.smithery.ai/servers" : source;
73
+ const url = new URL(baseUrl);
74
+ url.searchParams.set("pageSize", "50");
75
+ if (opts.query?.trim()) {
76
+ url.searchParams.set("q", opts.query.trim());
77
+ }
78
+ const res = await fetch(url.toString(), {
79
+ headers: fetchHeaders(),
80
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
81
+ });
82
+ if (!res.ok) {
83
+ throw new Error(`Smithery API 响应错误 HTTP ${res.status}: ${res.statusText}`);
84
+ }
85
+ const json = (await res.json());
86
+ const rawServers = Array.isArray(json.servers) ? json.servers : [];
87
+ const servers = rawServers.map((item) => {
88
+ const id = item.qualifiedName || item.id || "mcp-server";
89
+ const isRemote = !!item.remote;
90
+ return {
91
+ id,
92
+ name: item.displayName || item.qualifiedName || id,
93
+ displayName: item.displayName,
94
+ description: item.description || "Model Context Protocol Server",
95
+ homepage: item.homepage || `https://smithery.ai/server/${encodeURIComponent(id)}`,
96
+ package: item.qualifiedName ? `@smithery/${item.qualifiedName}` : id,
97
+ command: isRemote ? undefined : "npx",
98
+ args: isRemote ? undefined : ["-y", `@smithery/${item.qualifiedName}`],
99
+ transport: isRemote ? "http" : "stdio",
100
+ url: isRemote ? item.deploymentUrl : undefined,
101
+ source: "smithery",
102
+ downloads: typeof item.useCount === "number" ? item.useCount : undefined,
103
+ verified: !!item.verified,
104
+ iconUrl: item.iconUrl,
105
+ };
106
+ });
107
+ writeCache(cacheFile, servers);
108
+ return { ok: true, servers, source: "smithery", total: json.pagination?.total ?? servers.length };
109
+ }
110
+ if (source === "github" || source.includes("github.com/modelcontextprotocol/servers")) {
111
+ const apiUrl = "https://api.github.com/repos/modelcontextprotocol/servers/contents/src";
112
+ const res = await fetch(apiUrl, {
113
+ headers: fetchHeaders(),
114
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
115
+ });
116
+ if (!res.ok) {
117
+ throw new Error(`GitHub API 响应错误 HTTP ${res.status}`);
118
+ }
119
+ const list = (await res.json());
120
+ const dirs = list.filter((item) => item.type === "dir" && !item.name.startsWith("."));
121
+ const servers = dirs.map((d) => ({
122
+ id: d.name,
123
+ name: d.name,
124
+ description: `Official Model Context Protocol reference server for ${d.name}`,
125
+ homepage: d.html_url,
126
+ package: `@modelcontextprotocol/server-${d.name}`,
127
+ command: "npx",
128
+ args: ["-y", `@modelcontextprotocol/server-${d.name}`],
129
+ transport: "stdio",
130
+ source: "github",
131
+ verified: true,
132
+ }));
133
+ writeCache(cacheFile, servers);
134
+ return { ok: true, servers, source: "github", total: servers.length };
135
+ }
136
+ // 自定义 URL(支持返回 JSON 格式的 servers 列表)
137
+ const customRes = await fetch(source, {
138
+ headers: fetchHeaders(),
139
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
140
+ });
141
+ if (!customRes.ok) {
142
+ throw new Error(`自定义目录响应错误 HTTP ${customRes.status}`);
143
+ }
144
+ const customData = (await customRes.json());
145
+ const customServers = Array.isArray(customData)
146
+ ? customData
147
+ : Array.isArray(customData.servers)
148
+ ? customData.servers
149
+ : [];
150
+ writeCache(cacheFile, customServers);
151
+ return { ok: true, servers: customServers, source, total: customServers.length };
152
+ }
153
+ catch (err) {
154
+ const msg = err instanceof Error ? err.message : String(err);
155
+ // 网络出错时尝试回退至缓存
156
+ const cached = readCache(cacheFile);
157
+ if (cached) {
158
+ return { ok: true, servers: cached, source, total: cached.length, error: `网络请求失败,已展示本地缓存:${msg}` };
159
+ }
160
+ return { ok: false, servers: [], source, error: msg };
161
+ }
162
+ }
163
+ /** 从 GitHub 仓库拉取 Skills 清单 */
164
+ export async function fetchRemoteSkillMarket(opts) {
165
+ const repo = (opts.repo || "anthropics/skills").trim();
166
+ const cacheKey = `skill-market-${repo.replace(/[^a-zA-Z0-9_-]/g, "_")}.json`;
167
+ const cacheFile = join(opts.dataDir, "market-cache", cacheKey);
168
+ if (!opts.refresh) {
169
+ const cached = readCache(cacheFile);
170
+ if (cached) {
171
+ return { ok: true, skills: cached, repo };
172
+ }
173
+ }
174
+ try {
175
+ // 1. 优先尝试读取 repo 下的 skills 目录;若不存在则尝试根目录
176
+ let apiUrl = `https://api.github.com/repos/${repo}/contents/skills`;
177
+ let res = await fetch(apiUrl, {
178
+ headers: fetchHeaders(),
179
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
180
+ });
181
+ if (res.status === 404) {
182
+ apiUrl = `https://api.github.com/repos/${repo}/contents`;
183
+ res = await fetch(apiUrl, {
184
+ headers: fetchHeaders(),
185
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
186
+ });
187
+ }
188
+ if (!res.ok) {
189
+ throw new Error(`GitHub 仓库 ${repo} 读取失败 HTTP ${res.status}: ${res.statusText}`);
190
+ }
191
+ const items = (await res.json());
192
+ const skillDirs = items.filter((item) => item.type === "dir" && !item.name.startsWith("."));
193
+ // 2. 并发读取每个 skill 的 SKILL.md 提取描述(按 raw github 内容读取,避开 GitHub API rate limit)
194
+ const skills = await Promise.all(skillDirs.map(async (dir) => {
195
+ const id = dir.name;
196
+ const rawUrl = `https://raw.githubusercontent.com/${repo}/main/skills/${id}/SKILL.md`;
197
+ let description = `Agent skill ${id} from ${repo}`;
198
+ try {
199
+ const rawRes = await fetch(rawUrl, {
200
+ headers: { "User-Agent": "pi-web-ui" },
201
+ signal: AbortSignal.timeout(5000),
202
+ });
203
+ if (rawRes.ok) {
204
+ const text = await rawRes.text();
205
+ const descMatch = text.match(/description:\s*(?:>|\|)?\s*([^\r\n]+)/);
206
+ if (descMatch && descMatch[1].trim()) {
207
+ description = descMatch[1].trim();
208
+ }
209
+ }
210
+ }
211
+ catch {
212
+ /* fallback to default description */
213
+ }
214
+ return {
215
+ id,
216
+ name: id,
217
+ description,
218
+ repo,
219
+ url: dir.html_url,
220
+ };
221
+ }));
222
+ writeCache(cacheFile, skills);
223
+ return { ok: true, skills, repo };
224
+ }
225
+ catch (err) {
226
+ const msg = err instanceof Error ? err.message : String(err);
227
+ const cached = readCache(cacheFile);
228
+ if (cached) {
229
+ return { ok: true, skills: cached, repo, error: `网络请求失败,已展示本地缓存:${msg}` };
230
+ }
231
+ return { ok: false, skills: [], repo, error: msg };
232
+ }
233
+ }
234
+ /** 从 GitHub 仓库读取单个技能的完整 SKILL.md 内容 */
235
+ export async function fetchRemoteSkillContent(opts) {
236
+ const { repo, skillId } = opts;
237
+ const branches = ["main", "master"];
238
+ for (const branch of branches) {
239
+ const rawUrl = `https://raw.githubusercontent.com/${repo}/${branch}/skills/${skillId}/SKILL.md`;
240
+ try {
241
+ const res = await fetch(rawUrl, {
242
+ headers: { "User-Agent": "pi-web-ui" },
243
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
244
+ });
245
+ if (res.ok) {
246
+ const content = await res.text();
247
+ return { ok: true, skillId, content };
248
+ }
249
+ }
250
+ catch {
251
+ /* try next branch */
252
+ }
253
+ }
254
+ // 根目录下直接查找
255
+ for (const branch of branches) {
256
+ const rawUrl = `https://raw.githubusercontent.com/${repo}/${branch}/${skillId}/SKILL.md`;
257
+ try {
258
+ const res = await fetch(rawUrl, {
259
+ headers: { "User-Agent": "pi-web-ui" },
260
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
261
+ });
262
+ if (res.ok) {
263
+ const content = await res.text();
264
+ return { ok: true, skillId, content };
265
+ }
266
+ }
267
+ catch {
268
+ /* try next */
269
+ }
270
+ }
271
+ return {
272
+ ok: false,
273
+ skillId,
274
+ content: "",
275
+ error: `未在仓库 ${repo} 中找到技能 ${skillId} 的 SKILL.md 文件`,
276
+ };
277
+ }
@@ -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
- for (const [name, s] of Object.entries(parsed.servers ?? {})) {
344
- if (!s || typeof s.command !== "string" || !s.command.trim())
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: s.command,
348
- args: Array.isArray(s.args) ? s.args.map(String) : [],
349
- cwd: typeof s.cwd === "string" ? s.cwd : undefined,
350
- env: s.env && typeof s.env === "object" ? s.env : undefined,
351
- protocolVersion: typeof s.protocolVersion === "string" ? s.protocolVersion : undefined,
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
- const cfg = optsOverrideOrRead(this.opts.specOverride, this.dataDir);
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
- this.log(`[mcp] 服务器「${name}」启动失败:`, err instanceof Error ? err.message : err);
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.specOverride, this.dataDir);
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(specOverride, dataDir) {
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
- return readMcpConfig(dataDir);
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
  }