pi-web-ui 0.113.1 → 0.114.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 +43 -1
- package/README.md +117 -246
- package/README.zh-CN.md +145 -217
- package/README.zh-TW.md +145 -217
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +47 -15
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2289 -1120
- package/dist/server/approval-rules.js +29 -3
- package/dist/server/ask-user-question-tool.js +8 -8
- package/dist/server/atomic-file.js +35 -14
- package/dist/server/attachment-store.js +71 -35
- package/dist/server/attachments.js +18 -8
- package/dist/server/canvas/canvas-agent-tool.js +65 -15
- package/dist/server/canvas/canvas-dispatch.js +61 -20
- package/dist/server/canvas/canvas-orchestrator.js +516 -199
- package/dist/server/canvas/canvas-scheduler.js +99 -0
- package/dist/server/canvas/canvas-store.js +107 -54
- package/dist/server/canvas/canvas-validation.js +131 -0
- package/dist/server/canvas/canvas-workspace.js +284 -0
- package/dist/server/client-id-utils.js +8 -0
- package/dist/server/client-state.js +104 -22
- package/dist/server/communicate-tool.js +76 -0
- package/dist/server/compact-context-tool.js +2 -3
- package/dist/server/compaction-instructions.js +75 -0
- package/dist/server/compaction-markers.js +7 -2
- package/dist/server/compaction-state.js +84 -0
- package/dist/server/composer-drafts.js +43 -40
- package/dist/server/context-evidence.js +346 -0
- package/dist/server/conversation-communication.js +368 -0
- package/dist/server/conversation-read-tool.js +3 -4
- package/dist/server/conversation-tool-names.js +14 -0
- package/dist/server/conversation-tool.js +57 -0
- package/dist/server/delegate-mode.js +17 -4
- package/dist/server/device-center/bot-catalog.js +88 -0
- package/dist/server/device-center/bot-execution.js +106 -0
- package/dist/server/device-center/bots.js +170 -0
- package/dist/server/device-center/collab-service.js +153 -0
- package/dist/server/device-center/collab-tool.js +184 -0
- package/dist/server/device-center/connector.js +332 -0
- package/dist/server/device-center/desktop-linux.js +372 -0
- package/dist/server/device-center/desktop-native.js +413 -0
- package/dist/server/device-center/desktop-page.js +232 -0
- package/dist/server/device-center/desktop-setup.js +30 -0
- package/dist/server/device-center/desktop.js +387 -0
- package/dist/server/device-center/device-portals.js +241 -0
- package/dist/server/device-center/execution-failure.js +70 -0
- package/dist/server/device-center/executor.js +371 -0
- package/dist/server/device-center/file-sync.js +493 -0
- package/dist/server/device-center/hub-auth.js +69 -0
- package/dist/server/device-center/hub-page.js +68 -0
- package/dist/server/device-center/hub-setup.js +214 -0
- package/dist/server/device-center/hub.js +829 -0
- package/dist/server/device-center/local-page.js +17 -0
- package/dist/server/device-center/local.js +476 -0
- package/dist/server/device-center/main.js +118 -0
- package/dist/server/device-center/native-desktop/macos.js +192 -0
- package/dist/server/device-center/native-desktop/windows.js +118 -0
- package/dist/server/device-center/path-portal.js +120 -0
- package/dist/server/device-center/relay.js +959 -0
- package/dist/server/device-center/runtime.js +253 -0
- package/dist/server/device-center/smoke-preview.js +3 -0
- package/dist/server/device-center/store.js +122 -0
- package/dist/server/device-center/task-error.js +14 -0
- package/dist/server/device-center/transfers.js +293 -0
- package/dist/server/device-center/workspaces.js +45 -0
- package/dist/server/dispatch-domain-handlers.js +83 -27
- package/dist/server/dsh/dsh-agent-service.js +277 -158
- package/dist/server/dsh/dsh-client.js +12 -2
- package/dist/server/durable/durable-agent-service.js +1 -1
- package/dist/server/evidence-tool-hooks.js +49 -0
- package/dist/server/file-save.js +95 -0
- package/dist/server/file-transfer-routes.js +97 -47
- package/dist/server/files-service.js +38 -26
- package/dist/server/goal-review-gate.js +16 -6
- package/dist/server/goal-service.js +54 -30
- package/dist/server/http-proxy.js +120 -0
- package/dist/server/index.js +229 -223
- package/dist/server/load-timing.js +31 -0
- package/dist/server/mcp-bridge.js +219 -94
- package/dist/server/mcp-hot-reload.js +31 -5
- package/dist/server/mcp-manager.js +192 -93
- package/dist/server/mcp-oauth-login.js +169 -0
- package/dist/server/mcp-oauth-ui.js +137 -0
- package/dist/server/mcp-oauth.js +395 -0
- package/dist/server/mcp-project-runtime.js +207 -0
- package/dist/server/message-window.js +74 -21
- package/dist/server/net-guard.js +122 -20
- package/dist/server/payload-limits.js +17 -0
- package/dist/server/pending-question.js +82 -0
- package/dist/server/plan-mode.js +338 -137
- package/dist/server/plugin-assets.js +8 -4
- package/dist/server/plugin-chat-attachments.js +48 -0
- package/dist/server/plugin-facilities.js +67 -220
- package/dist/server/plugin-installer.js +2 -1
- package/dist/server/plugin-removal.js +49 -0
- package/dist/server/plugin-secrets.js +179 -0
- package/dist/server/plugins.js +262 -92
- package/dist/server/preset-fields.js +49 -0
- package/dist/server/preset-plugin-dependencies.js +57 -0
- package/dist/server/preset-share.js +112 -72
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-modes.js +10 -0
- package/dist/server/remote-ssh-service.js +160 -67
- package/dist/server/request-context.js +164 -0
- package/dist/server/sandbox-data.js +655 -0
- package/dist/server/sandbox-engines.js +7 -0
- package/dist/server/sandbox-runtime-gate.js +41 -0
- package/dist/server/sandbox-service.js +139 -698
- package/dist/server/sandbox-tool.js +21 -4
- package/dist/server/scheduler-tasks.js +63 -48
- package/dist/server/serialize.js +48 -19
- package/dist/server/session-branch.js +25 -3
- package/dist/server/session-parser.js +28 -18
- package/dist/server/session-scan.js +130 -0
- package/dist/server/session-search.js +51 -37
- package/dist/server/settings-service.js +267 -111
- package/dist/server/setup-config.js +58 -0
- package/dist/server/skill-maintenance.js +112 -24
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagent-notify.js +4 -1
- package/dist/server/subagent-security-gate.js +52 -11
- package/dist/server/subagent-task.js +27 -0
- package/dist/server/subagents.js +217 -46
- package/dist/server/tabs.js +9 -1
- package/dist/server/terminals.js +467 -363
- package/dist/server/tool-guards.js +42 -6
- package/dist/server/tool-manager.js +47 -20
- package/dist/server/tool-overrides.js +13 -11
- package/dist/server/tool-prompt-overrides.js +32 -2
- package/dist/server/tool-prompts.js +1 -1
- package/dist/server/turn-timing.js +11 -0
- package/dist/server/universal/session-store.js +48 -6
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +334 -231
- package/dist/server/uploads.js +64 -5
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/docs/device-center.md +142 -0
- package/docs/device-desktop.md +48 -0
- package/package.json +4 -1
- package/plugin-sdk/index.d.ts +28 -6
- package/plugin-sdk/ssh-host-trust.mjs +225 -0
- package/plugins/catalog.json +1 -1
- package/themes/aetheris.css +1 -107
- package/themes/ayu-light.css +5 -29
- package/themes/bases/flow-base.css +0 -6
- package/themes/bases/statusbar-flat-base.css +112 -0
- package/themes/bases/zhujian-base.css +1 -0
- package/themes/bases/zhupi-base.css +1 -0
- package/themes/catppuccin-latte.css +4 -27
- package/themes/catppuccin.css +4 -35
- package/themes/claude-code-dark.css +1 -0
- package/themes/codex.css +4 -28
- package/themes/cyberpunk.css +3 -61
- package/themes/dark-teal.css +0 -1
- package/themes/dazzle.css +3 -73
- package/themes/everforest-light.css +4 -27
- package/themes/geist.css +4 -28
- package/themes/gruvbox-light.css +4 -27
- package/themes/kanagawa-lotus.css +4 -27
- package/themes/md-preview.css +3 -213
- package/themes/mist.css +4 -24
- package/themes/nord.css +4 -35
- package/themes/one-dark.css +4 -37
- package/themes/paper.css +4 -16
- package/themes/rose-pine-dawn.css +4 -28
- package/themes/sakura.css +4 -24
- package/themes/solarized-light.css +4 -27
- package/themes/tokyo-night.css +3 -34
- package/themes/white.css +4 -26
- package/themes/zhujian-dark.css +1 -0
- package/themes/zhupi-dark.css +1 -0
- package/web/dist/.build-assets.json +1 -0
- package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
- package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
- package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
- package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
- package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
- package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
- package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
- package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
- package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
- package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
- package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
- package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
- package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
- package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
- package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
- package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
- package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
- package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
- package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
- package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
- package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
- package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
- package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
- package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
- package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
- package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
- package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
- package/web/dist/assets/es-DWMIuDU2.js +2 -0
- package/web/dist/assets/index-CPgAH5q7.js +83 -0
- package/web/dist/assets/index-Cje8iugL.js +83 -0
- package/web/dist/assets/index-DnKeiDbj.css +1 -0
- package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
- package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
- package/web/dist/assets/math-1uRJCsA9.js +257 -0
- package/web/dist/assets/math-BorAY7qD.css +1 -0
- package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
- package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
- package/web/dist/assets/theme-BqdAjEjF.js +1 -0
- package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
- package/web/dist/index.html +15 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
- package/web/dist/assets/index-ByiO9f-N.js +0 -2008
- package/web/dist/assets/index-ycGLh4a4.css +0 -1
- package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
- package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { performance } from "node:perf_hooks";
|
|
2
|
+
const disabled = { mark() { }, finish() { } };
|
|
3
|
+
/** Opt-in diagnostics; deliberately omit transcript paths, IDs and message content. */
|
|
4
|
+
export function startLoadTiming(enabled = /^(1|true|on|yes)$/i.test(process.env.PI_WEB_LOAD_TIMING ?? ""), now = () => performance.now(), report = (record) => console.info("[load-timing]", JSON.stringify(record))) {
|
|
5
|
+
if (!enabled)
|
|
6
|
+
return disabled;
|
|
7
|
+
const start = now();
|
|
8
|
+
let previous = start;
|
|
9
|
+
let finished = false;
|
|
10
|
+
const stages = [];
|
|
11
|
+
return {
|
|
12
|
+
mark(stage) {
|
|
13
|
+
if (finished)
|
|
14
|
+
return;
|
|
15
|
+
const current = now();
|
|
16
|
+
stages.push({ stage, ms: Number((current - previous).toFixed(3)) });
|
|
17
|
+
previous = current;
|
|
18
|
+
},
|
|
19
|
+
finish(outcome) {
|
|
20
|
+
if (finished)
|
|
21
|
+
return;
|
|
22
|
+
finished = true;
|
|
23
|
+
try {
|
|
24
|
+
report({ event: "history-open", outcome, totalMs: Number((now() - start).toFixed(3)), stages });
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// Diagnostics must never change session loading behavior.
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -17,6 +17,7 @@ import { spawn } from "node:child_process";
|
|
|
17
17
|
import { existsSync, readFileSync } from "node:fs";
|
|
18
18
|
import { homedir } from "node:os";
|
|
19
19
|
import { join } from "node:path";
|
|
20
|
+
import { getMcpAccessToken, refreshMcpAccessToken } from "./mcp-oauth.js";
|
|
20
21
|
/** 展开字符串中的 ${VAR_NAME} 环境变量占位符。 */
|
|
21
22
|
export function expandEnvVars(val) {
|
|
22
23
|
return val.replace(/\$\{([^}]+)\}/g, (_, k) => process.env[k] ?? "");
|
|
@@ -68,6 +69,7 @@ let rpcSeq = 0;
|
|
|
68
69
|
*/
|
|
69
70
|
export class McpClient {
|
|
70
71
|
spec;
|
|
72
|
+
clientOpts;
|
|
71
73
|
child = null;
|
|
72
74
|
buffer = "";
|
|
73
75
|
pending = new Map();
|
|
@@ -86,16 +88,53 @@ export class McpClient {
|
|
|
86
88
|
initialized = false;
|
|
87
89
|
/** 工具列表动态更新回调(收到 notifications/tools/list_changed 时触发)。 */
|
|
88
90
|
onToolsChanged;
|
|
91
|
+
/** HTTP notifications have no pending RPC response, but still belong to this client. */
|
|
92
|
+
notificationControllers = new Set();
|
|
89
93
|
constructor(name,
|
|
90
94
|
/** 启动规格;热加载按它判断「这个服务器要不要重启」(见 McpBridge.reload)。 */
|
|
91
|
-
spec, log
|
|
95
|
+
spec, log,
|
|
96
|
+
/** OAuth:`agentDir` 指向 pi 的凭据库(`mcp-auth.json`),见 mcp-oauth.ts 与 Issue #786。 */
|
|
97
|
+
clientOpts = {}) {
|
|
92
98
|
this.spec = spec;
|
|
99
|
+
this.clientOpts = clientOpts;
|
|
93
100
|
this.name = name;
|
|
94
101
|
this.log = log ?? (() => { });
|
|
95
102
|
}
|
|
96
103
|
get isHttp() {
|
|
97
104
|
return !this.spec.command && !!this.spec.url;
|
|
98
105
|
}
|
|
106
|
+
/** 显式配置了 Authorization 头 → 用配置的静态凭据,不碰 OAuth 凭据库。 */
|
|
107
|
+
hasStaticAuthorization() {
|
|
108
|
+
const headers = this.spec.headers ?? {};
|
|
109
|
+
return Object.keys(headers).some((k) => k.toLowerCase() === "authorization");
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* 该服务器要发的 `Authorization` 值(OAuth 保护的远端服务器用),没有凭据时返回 null。
|
|
113
|
+
* `isRetry` = 上一次请求收到 401:强制刷新一次(凭据库里的 access token 可能没过期但已被吊销)。
|
|
114
|
+
*/
|
|
115
|
+
async resolveAuthHeader(isRetry, signal, staleToken) {
|
|
116
|
+
if (!this.isHttp || !this.spec.url || this.hasStaticAuthorization())
|
|
117
|
+
return null;
|
|
118
|
+
const options = { agentDir: this.clientOpts.agentDir, name: this.name, serverUrl: this.spec.url, signal };
|
|
119
|
+
try {
|
|
120
|
+
const token = isRetry
|
|
121
|
+
? await refreshMcpAccessToken({ ...options, staleToken })
|
|
122
|
+
: await getMcpAccessToken(options);
|
|
123
|
+
if (!token)
|
|
124
|
+
return null;
|
|
125
|
+
return `Bearer ${token}`;
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
signal?.throwIfAborted();
|
|
129
|
+
// 刷新失败不该让请求烂在这里:照旧发出去,由服务端的 401 给出最终结论(或失败原因)。
|
|
130
|
+
this.log(`[mcp:${this.name}] oauth:`, err instanceof Error ? err.message : err);
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** 401 的可操作错误:告诉用户这一台服务器需要登录,以及怎么登录。 */
|
|
135
|
+
signInRequiredError(detail) {
|
|
136
|
+
return new Error(`MCP_OAUTH_SIGN_IN_REQUIRED: HTTP 401: ${detail || "unauthorized"} — OAuth sign-in is missing or has expired; run \`pi mcp login ${this.name}\` and try again`);
|
|
137
|
+
}
|
|
99
138
|
/** 启动子进程或 HTTP 连接 + 握手 + 拉取工具列表。可安全重入:退出后再次调用即全新启动。 */
|
|
100
139
|
async start(timeoutMs = 8000) {
|
|
101
140
|
if (this.isHttp) {
|
|
@@ -342,6 +381,8 @@ export class McpClient {
|
|
|
342
381
|
this.shuttingDown = true;
|
|
343
382
|
this.initialized = false;
|
|
344
383
|
this.rejectAll(new Error("[mcp] client closed"));
|
|
384
|
+
for (const controller of this.notificationControllers)
|
|
385
|
+
controller.abort();
|
|
345
386
|
if (this.child) {
|
|
346
387
|
try {
|
|
347
388
|
this.child.kill();
|
|
@@ -425,8 +466,10 @@ export class McpClient {
|
|
|
425
466
|
if (signal?.aborted) {
|
|
426
467
|
throw new Error("Request aborted");
|
|
427
468
|
}
|
|
469
|
+
if (this.shuttingDown)
|
|
470
|
+
throw new Error("[mcp] client closed");
|
|
428
471
|
const onAbort = () => {
|
|
429
|
-
|
|
472
|
+
this.pending.get(outId)?.reject(new Error("Request aborted"));
|
|
430
473
|
};
|
|
431
474
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
432
475
|
const headers = {
|
|
@@ -441,7 +484,6 @@ export class McpClient {
|
|
|
441
484
|
headers[k] = expandEnvVars(v);
|
|
442
485
|
}
|
|
443
486
|
}
|
|
444
|
-
let timedOut = false;
|
|
445
487
|
let reqResolve;
|
|
446
488
|
let reqReject;
|
|
447
489
|
const reqPromise = new Promise((res, rej) => {
|
|
@@ -449,10 +491,7 @@ export class McpClient {
|
|
|
449
491
|
reqReject = rej;
|
|
450
492
|
});
|
|
451
493
|
const timer = setTimeout(() => {
|
|
452
|
-
|
|
453
|
-
this.pending.delete(outId);
|
|
454
|
-
abortController.abort();
|
|
455
|
-
reqReject(new Error(`[mcp:${this.name}] ${method} 超时 (${timeoutMs}ms)`));
|
|
494
|
+
this.pending.get(outId)?.reject(new Error(`[mcp:${this.name}] ${method} 超时 (${timeoutMs}ms)`));
|
|
456
495
|
}, timeoutMs);
|
|
457
496
|
this.pending.set(outId, {
|
|
458
497
|
resolve: (v) => {
|
|
@@ -465,6 +504,7 @@ export class McpClient {
|
|
|
465
504
|
clearTimeout(timer);
|
|
466
505
|
signal?.removeEventListener("abort", onAbort);
|
|
467
506
|
this.pending.delete(outId);
|
|
507
|
+
abortController.abort();
|
|
468
508
|
reqReject(e);
|
|
469
509
|
},
|
|
470
510
|
timer,
|
|
@@ -473,98 +513,115 @@ export class McpClient {
|
|
|
473
513
|
progressToken: outId,
|
|
474
514
|
abortController,
|
|
475
515
|
});
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
516
|
+
// Return the result promise immediately: timeout/close must settle even during auth.
|
|
517
|
+
void (async () => {
|
|
518
|
+
try {
|
|
519
|
+
const authHeader = await this.resolveAuthHeader(false, abortController.signal);
|
|
520
|
+
abortController.signal.throwIfAborted();
|
|
521
|
+
if (authHeader)
|
|
522
|
+
headers.Authorization = authHeader;
|
|
523
|
+
const body = JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
524
|
+
let res = await fetch(url, {
|
|
525
|
+
method: "POST",
|
|
526
|
+
headers,
|
|
527
|
+
body,
|
|
528
|
+
signal: abortController.signal,
|
|
529
|
+
});
|
|
530
|
+
abortController.signal.throwIfAborted();
|
|
531
|
+
// 401 → 凭据库里的 token 可能已被吊销/轮换:强制刷新一次再重试同一请求(OAuth 保护的服务器)。
|
|
532
|
+
if (res.status === 401 && !this.hasStaticAuthorization()) {
|
|
533
|
+
const retriedHeader = await this.resolveAuthHeader(true, abortController.signal, authHeader?.slice("Bearer ".length));
|
|
534
|
+
abortController.signal.throwIfAborted();
|
|
535
|
+
if (retriedHeader && retriedHeader !== authHeader) {
|
|
536
|
+
headers.Authorization = retriedHeader;
|
|
537
|
+
res = await fetch(url, {
|
|
538
|
+
method: "POST",
|
|
539
|
+
headers,
|
|
540
|
+
body,
|
|
541
|
+
signal: abortController.signal,
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
abortController.signal.throwIfAborted();
|
|
545
|
+
if (res.status === 401) {
|
|
546
|
+
const detail = await res.text().catch(() => "");
|
|
547
|
+
throw this.signInRequiredError(detail);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const newSid = res.headers.get("mcp-session-id");
|
|
551
|
+
if (newSid)
|
|
552
|
+
this.sessionId = newSid;
|
|
553
|
+
if (res.status === 202) {
|
|
496
554
|
const pending = this.pending.get(outId);
|
|
497
|
-
pending?.
|
|
498
|
-
return
|
|
555
|
+
pending?.resolve(null);
|
|
556
|
+
return;
|
|
499
557
|
}
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
const text = await res.text();
|
|
512
|
-
let parsed;
|
|
513
|
-
try {
|
|
514
|
-
parsed = JSON.parse(text);
|
|
558
|
+
if (res.status === 404 || res.status === 400) {
|
|
559
|
+
const errText = await res.text().catch(() => "");
|
|
560
|
+
abortController.signal.throwIfAborted();
|
|
561
|
+
if (res.status === 404 || /session/i.test(errText)) {
|
|
562
|
+
this.sessionId = null;
|
|
563
|
+
this.initialized = false;
|
|
564
|
+
const pending = this.pending.get(outId);
|
|
565
|
+
pending?.reject(new Error(`MCP_SESSION_EXPIRED: ${errText || "Session expired or not found"}`));
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
throw new Error(`HTTP ${res.status}: ${errText}`);
|
|
515
569
|
}
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
570
|
+
if (!res.ok) {
|
|
571
|
+
const errText = await res.text().catch(() => "");
|
|
572
|
+
throw new Error(`HTTP ${res.status}: ${errText}`);
|
|
573
|
+
}
|
|
574
|
+
const contentType = res.headers.get("content-type") || "";
|
|
575
|
+
if (contentType.includes("text/event-stream") && res.body) {
|
|
576
|
+
void this.readSseStream(res.body, outId, abortController.signal);
|
|
577
|
+
}
|
|
578
|
+
else {
|
|
579
|
+
const text = await res.text();
|
|
580
|
+
abortController.signal.throwIfAborted();
|
|
581
|
+
let parsed;
|
|
582
|
+
try {
|
|
583
|
+
parsed = JSON.parse(text);
|
|
584
|
+
}
|
|
585
|
+
catch {
|
|
586
|
+
let matched;
|
|
587
|
+
if (text.includes("data:")) {
|
|
588
|
+
for (const l of text.split("\n")) {
|
|
589
|
+
const trimmed = l.trim();
|
|
590
|
+
if (trimmed.startsWith("data:")) {
|
|
591
|
+
try {
|
|
592
|
+
const item = JSON.parse(trimmed.slice(5).trim());
|
|
593
|
+
if (item.id !== undefined && String(item.id) === outId) {
|
|
594
|
+
matched = item;
|
|
595
|
+
break;
|
|
596
|
+
}
|
|
527
597
|
}
|
|
598
|
+
catch { }
|
|
528
599
|
}
|
|
529
|
-
catch { }
|
|
530
600
|
}
|
|
531
601
|
}
|
|
602
|
+
if (matched) {
|
|
603
|
+
parsed = matched;
|
|
604
|
+
}
|
|
605
|
+
else {
|
|
606
|
+
throw new Error(`Invalid JSON response: ${text.slice(0, 200)}`);
|
|
607
|
+
}
|
|
532
608
|
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
if (pending) {
|
|
542
|
-
if (parsed.error) {
|
|
543
|
-
pending.reject(new Error(`[mcp:${this.name}] ${parsed.error.message ?? "MCP 错误"}`));
|
|
544
|
-
}
|
|
545
|
-
else {
|
|
546
|
-
pending.resolve(parsed.result);
|
|
609
|
+
const pending = this.pending.get(outId);
|
|
610
|
+
if (pending) {
|
|
611
|
+
if (parsed.error) {
|
|
612
|
+
pending.reject(new Error(`[mcp:${this.name}] ${parsed.error.message ?? "MCP 错误"}`));
|
|
613
|
+
}
|
|
614
|
+
else {
|
|
615
|
+
pending.resolve(parsed.result);
|
|
616
|
+
}
|
|
547
617
|
}
|
|
548
618
|
}
|
|
549
619
|
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
catch (err) {
|
|
553
|
-
if (timedOut) {
|
|
554
|
-
return await reqPromise;
|
|
555
|
-
}
|
|
556
|
-
if (signal?.aborted) {
|
|
557
|
-
const pending = this.pending.get(outId);
|
|
558
|
-
pending?.reject(new Error("Request aborted"));
|
|
559
|
-
return await reqPromise;
|
|
620
|
+
catch (err) {
|
|
621
|
+
this.pending.get(outId)?.reject(err instanceof Error ? err : new Error(String(err)));
|
|
560
622
|
}
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
return await reqPromise;
|
|
564
|
-
}
|
|
565
|
-
finally {
|
|
566
|
-
signal?.removeEventListener("abort", onAbort);
|
|
567
|
-
}
|
|
623
|
+
})();
|
|
624
|
+
return reqPromise;
|
|
568
625
|
}
|
|
569
626
|
async sendHttpNotification(method, params) {
|
|
570
627
|
const url = this.spec.url;
|
|
@@ -582,12 +639,23 @@ export class McpClient {
|
|
|
582
639
|
headers[k] = expandEnvVars(v);
|
|
583
640
|
}
|
|
584
641
|
}
|
|
642
|
+
if (this.shuttingDown)
|
|
643
|
+
return;
|
|
644
|
+
const controller = new AbortController();
|
|
645
|
+
this.notificationControllers.add(controller);
|
|
646
|
+
const timer = setTimeout(() => controller.abort(), 8000);
|
|
585
647
|
try {
|
|
648
|
+
const authHeader = await this.resolveAuthHeader(false, controller.signal);
|
|
649
|
+
controller.signal.throwIfAborted();
|
|
650
|
+
if (authHeader)
|
|
651
|
+
headers.Authorization = authHeader;
|
|
586
652
|
const res = await fetch(url, {
|
|
653
|
+
signal: controller.signal,
|
|
587
654
|
method: "POST",
|
|
588
655
|
headers,
|
|
589
656
|
body: JSON.stringify({ jsonrpc: "2.0", method, params }),
|
|
590
657
|
});
|
|
658
|
+
controller.signal.throwIfAborted();
|
|
591
659
|
const newSid = res.headers.get("mcp-session-id");
|
|
592
660
|
if (newSid)
|
|
593
661
|
this.sessionId = newSid;
|
|
@@ -595,6 +663,10 @@ export class McpClient {
|
|
|
595
663
|
catch (err) {
|
|
596
664
|
this.log(`[mcp:${this.name}] HTTP notification ${method} failed:`, err);
|
|
597
665
|
}
|
|
666
|
+
finally {
|
|
667
|
+
clearTimeout(timer);
|
|
668
|
+
this.notificationControllers.delete(controller);
|
|
669
|
+
}
|
|
598
670
|
}
|
|
599
671
|
async readSseStream(body, targetId, signal) {
|
|
600
672
|
const reader = body.getReader();
|
|
@@ -840,9 +912,14 @@ function sameMcpSpec(a, b) {
|
|
|
840
912
|
* 整个 MCP 管理器的工具适配:把每个 MCP 工具变成 PluginAgentTool。
|
|
841
913
|
* getAllToolsTool(name, callFn) 生成 execute → 转发到对应 McpClient.call。
|
|
842
914
|
*/
|
|
915
|
+
const mcpToolServers = new WeakMap();
|
|
916
|
+
/** Trusted provenance keyed by the bridge-owned tool object, never by its label. */
|
|
917
|
+
export function getMcpToolServer(tool) {
|
|
918
|
+
return mcpToolServers.get(tool);
|
|
919
|
+
}
|
|
843
920
|
function adaptMcpTool(serverName, mcpTool, client) {
|
|
844
921
|
const name = sanitizeToolName(mcpTool.name);
|
|
845
|
-
|
|
922
|
+
const adapted = {
|
|
846
923
|
name,
|
|
847
924
|
label: `${serverName} · ${mcpTool.name}`,
|
|
848
925
|
description: mcpTool.description ?? `Tool ${mcpTool.name} provided by MCP server "${serverName}"`,
|
|
@@ -855,6 +932,8 @@ function adaptMcpTool(serverName, mcpTool, client) {
|
|
|
855
932
|
return client.call(mcpTool.name, params ?? {}, undefined, signal);
|
|
856
933
|
},
|
|
857
934
|
};
|
|
935
|
+
mcpToolServers.set(adapted, serverName);
|
|
936
|
+
return adapted;
|
|
858
937
|
}
|
|
859
938
|
/** 从 MCP 工具 description 提取首句做 promptSnippet(≤100 字符);空描述返回 undefined。 */
|
|
860
939
|
function firstSentenceSnippet(description) {
|
|
@@ -876,6 +955,8 @@ export class McpBridge {
|
|
|
876
955
|
log;
|
|
877
956
|
opts;
|
|
878
957
|
clients = [];
|
|
958
|
+
pendingClients = new Set();
|
|
959
|
+
disposed = false;
|
|
879
960
|
tools = [];
|
|
880
961
|
serverErrors = new Map();
|
|
881
962
|
/** reload 串行化链:重入的 reload 排在前一个之后,杜绝交叠留下的孤儿进程。 */
|
|
@@ -904,6 +985,7 @@ export class McpBridge {
|
|
|
904
985
|
if (client) {
|
|
905
986
|
return {
|
|
906
987
|
status: "running",
|
|
988
|
+
...(this.serverErrors.has(name) ? { error: this.serverErrors.get(name), usingPreviousConfig: true } : {}),
|
|
907
989
|
tools: client.getTools().map((t) => ({ name: t.name, description: t.description })),
|
|
908
990
|
};
|
|
909
991
|
}
|
|
@@ -918,14 +1000,20 @@ export class McpBridge {
|
|
|
918
1000
|
}
|
|
919
1001
|
/** 读取配置并启动全部服务器(顺序 fail-fast:单个失败记日志不拖垮其它)。 */
|
|
920
1002
|
async load() {
|
|
1003
|
+
if (this.disposed)
|
|
1004
|
+
return;
|
|
921
1005
|
this.serverErrors.clear();
|
|
922
|
-
const cfg =
|
|
1006
|
+
const cfg = this.executionConfig();
|
|
923
1007
|
await Promise.all(Object.entries(cfg.servers).map(async ([name, spec]) => {
|
|
924
1008
|
if (spec.enabled === false)
|
|
925
1009
|
return;
|
|
926
1010
|
const client = await this.startOne(name, spec);
|
|
927
1011
|
if (!client)
|
|
928
1012
|
return;
|
|
1013
|
+
if (this.disposed) {
|
|
1014
|
+
client.close();
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
929
1017
|
this.clients.push(client);
|
|
930
1018
|
for (const t of client.getTools())
|
|
931
1019
|
this.tools.push(adaptMcpTool(name, t, client));
|
|
@@ -933,21 +1021,36 @@ export class McpBridge {
|
|
|
933
1021
|
}
|
|
934
1022
|
/** 启动单个服务器:失败只记日志并返回 null(load / reload 共用)。 */
|
|
935
1023
|
async startOne(name, spec) {
|
|
1024
|
+
if (this.disposed)
|
|
1025
|
+
return null;
|
|
1026
|
+
const client = new McpClient(name, spec, this.log, { agentDir: this.agentDir });
|
|
1027
|
+
this.pendingClients.add(client);
|
|
936
1028
|
try {
|
|
937
|
-
const client = new McpClient(name, spec, this.log);
|
|
938
1029
|
client.onToolsChanged = () => this.reaggregateTools();
|
|
939
1030
|
await client.start();
|
|
1031
|
+
if (this.disposed) {
|
|
1032
|
+
client.close();
|
|
1033
|
+
return null;
|
|
1034
|
+
}
|
|
940
1035
|
this.serverErrors.delete(name);
|
|
941
1036
|
return client;
|
|
942
1037
|
}
|
|
943
1038
|
catch (err) {
|
|
944
|
-
|
|
945
|
-
this.
|
|
946
|
-
|
|
1039
|
+
client.close();
|
|
1040
|
+
if (!this.disposed) {
|
|
1041
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1042
|
+
this.serverErrors.set(name, msg);
|
|
1043
|
+
this.log(`[mcp] 服务器「${name}」启动失败:`, msg);
|
|
1044
|
+
}
|
|
947
1045
|
return null;
|
|
948
1046
|
}
|
|
1047
|
+
finally {
|
|
1048
|
+
this.pendingClients.delete(client);
|
|
1049
|
+
}
|
|
949
1050
|
}
|
|
950
1051
|
reaggregateTools() {
|
|
1052
|
+
if (this.disposed)
|
|
1053
|
+
return;
|
|
951
1054
|
this.tools = [];
|
|
952
1055
|
for (const c of this.clients) {
|
|
953
1056
|
for (const t of c.getTools()) {
|
|
@@ -965,7 +1068,9 @@ export class McpBridge {
|
|
|
965
1068
|
return run;
|
|
966
1069
|
}
|
|
967
1070
|
async reloadOnce() {
|
|
968
|
-
|
|
1071
|
+
if (this.disposed)
|
|
1072
|
+
return { kept: 0, started: 0, stopped: 0, failed: 0, servers: 0, tools: 0 };
|
|
1073
|
+
const cfg = this.executionConfig();
|
|
969
1074
|
const next = new Map();
|
|
970
1075
|
let kept = 0;
|
|
971
1076
|
for (const client of this.clients) {
|
|
@@ -973,6 +1078,7 @@ export class McpBridge {
|
|
|
973
1078
|
if (!spec || spec.enabled === false || !sameMcpSpec(spec, client.spec))
|
|
974
1079
|
continue;
|
|
975
1080
|
next.set(client.name, client);
|
|
1081
|
+
this.serverErrors.delete(client.name);
|
|
976
1082
|
kept++;
|
|
977
1083
|
}
|
|
978
1084
|
let started = 0;
|
|
@@ -994,6 +1100,15 @@ export class McpBridge {
|
|
|
994
1100
|
kept++;
|
|
995
1101
|
}
|
|
996
1102
|
}));
|
|
1103
|
+
if (this.disposed) {
|
|
1104
|
+
for (const client of next.values())
|
|
1105
|
+
client.close();
|
|
1106
|
+
return { kept: 0, started: 0, stopped: 0, failed: 0, servers: 0, tools: 0 };
|
|
1107
|
+
}
|
|
1108
|
+
for (const name of this.serverErrors.keys()) {
|
|
1109
|
+
if (!cfg.servers[name] || cfg.servers[name].enabled === false)
|
|
1110
|
+
this.serverErrors.delete(name);
|
|
1111
|
+
}
|
|
997
1112
|
const stale = this.clients.filter((c) => next.get(c.name) !== c);
|
|
998
1113
|
this.clients = [...next.values()];
|
|
999
1114
|
this.tools = [];
|
|
@@ -1011,6 +1126,12 @@ export class McpBridge {
|
|
|
1011
1126
|
tools: this.tools.length,
|
|
1012
1127
|
};
|
|
1013
1128
|
}
|
|
1129
|
+
executionConfig() {
|
|
1130
|
+
const cfg = optsOverrideOrRead(this.opts, this.dataDir);
|
|
1131
|
+
if (this.opts.allowedServers)
|
|
1132
|
+
cfg.servers = Object.fromEntries(Object.entries(cfg.servers).filter(([name]) => this.opts.allowedServers.includes(name)));
|
|
1133
|
+
return cfg;
|
|
1134
|
+
}
|
|
1014
1135
|
getTools() {
|
|
1015
1136
|
return this.tools;
|
|
1016
1137
|
}
|
|
@@ -1018,6 +1139,10 @@ export class McpBridge {
|
|
|
1018
1139
|
return this.clients.length > 0;
|
|
1019
1140
|
}
|
|
1020
1141
|
dispose() {
|
|
1142
|
+
this.disposed = true;
|
|
1143
|
+
for (const c of this.pendingClients)
|
|
1144
|
+
c.close();
|
|
1145
|
+
this.pendingClients.clear();
|
|
1021
1146
|
for (const c of this.clients)
|
|
1022
1147
|
c.close();
|
|
1023
1148
|
this.clients = [];
|
|
@@ -30,6 +30,8 @@ export function createMcpHotReload(deps) {
|
|
|
30
30
|
const pollIntervalMs = deps.pollIntervalMs ?? 2000;
|
|
31
31
|
/** 上次应用到运行时的内容指纹;null = 还没播种。 */
|
|
32
32
|
let applied = null;
|
|
33
|
+
let disposed = false;
|
|
34
|
+
let applyTail = Promise.resolve();
|
|
33
35
|
let debounce = null;
|
|
34
36
|
let poller = null;
|
|
35
37
|
let watchers = [];
|
|
@@ -97,7 +99,9 @@ export function createMcpHotReload(deps) {
|
|
|
97
99
|
servers: merged,
|
|
98
100
|
};
|
|
99
101
|
}
|
|
100
|
-
async function
|
|
102
|
+
async function applyOnce() {
|
|
103
|
+
if (disposed)
|
|
104
|
+
return "unchanged";
|
|
101
105
|
const { fp, servers } = readOnce();
|
|
102
106
|
if (fp === applied)
|
|
103
107
|
return "unchanged";
|
|
@@ -108,18 +112,37 @@ export function createMcpHotReload(deps) {
|
|
|
108
112
|
deps.onNotice?.("warning", "mcp.json 解析/读取失败,已保留当前 MCP 服务器(恢复可读后会自动重载)", "Failed to parse/read mcp.json — keeping the running MCP servers (it reloads automatically once readable)");
|
|
109
113
|
return "invalid";
|
|
110
114
|
}
|
|
111
|
-
|
|
115
|
+
let summary;
|
|
116
|
+
try {
|
|
117
|
+
summary = await deps.reload();
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
applied = null;
|
|
121
|
+
throw err;
|
|
122
|
+
}
|
|
123
|
+
if (disposed)
|
|
124
|
+
return "unchanged";
|
|
112
125
|
deps.onToolsChanged?.();
|
|
113
126
|
log(`[mcp] 配置已热加载:${summary.servers} 个服务器 / ${summary.tools} 个工具` +
|
|
114
127
|
`(沿用 ${summary.kept}、启动 ${summary.started}、关闭 ${summary.stopped}、失败 ${summary.failed})`);
|
|
115
|
-
|
|
128
|
+
if (summary.failed > 0) {
|
|
129
|
+
deps.onNotice?.("warning", `MCP 配置应用失败:${summary.failed} 个服务器未能启动,已有实例已保留;请查看服务器错误详情`, `MCP configuration failed for ${summary.failed} server(s); previous instances were retained where available. Check server error details.`);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
deps.onNotice?.("info", `mcp.json 已热加载:${summary.servers} 个服务器 / ${summary.tools} 个工具`, `mcp.json reloaded: ${summary.servers} server(s) / ${summary.tools} tool(s)`);
|
|
133
|
+
}
|
|
116
134
|
return "reloaded";
|
|
117
135
|
}
|
|
136
|
+
function apply() {
|
|
137
|
+
const run = applyTail.then(applyOnce);
|
|
138
|
+
applyTail = run.catch(() => { });
|
|
139
|
+
return run;
|
|
140
|
+
}
|
|
118
141
|
function run() {
|
|
119
142
|
void apply().catch((err) => log("[mcp] 热加载失败:", err instanceof Error ? err.message : err));
|
|
120
143
|
}
|
|
121
144
|
function schedule() {
|
|
122
|
-
if (debounce)
|
|
145
|
+
if (disposed || debounce)
|
|
123
146
|
return;
|
|
124
147
|
debounce = setTimeout(() => {
|
|
125
148
|
debounce = null;
|
|
@@ -128,6 +151,8 @@ export function createMcpHotReload(deps) {
|
|
|
128
151
|
}
|
|
129
152
|
/** fs.watch 用不了(目录还不存在、网络盘、容器)→ 回落到轮询:单文件不值得上更重的机制。 */
|
|
130
153
|
function fallBackToPolling() {
|
|
154
|
+
if (disposed)
|
|
155
|
+
return;
|
|
131
156
|
for (const w of watchers) {
|
|
132
157
|
try {
|
|
133
158
|
w.close();
|
|
@@ -142,7 +167,7 @@ export function createMcpHotReload(deps) {
|
|
|
142
167
|
poller.unref();
|
|
143
168
|
}
|
|
144
169
|
function start() {
|
|
145
|
-
if (watchers.length > 0 || poller)
|
|
170
|
+
if (disposed || watchers.length > 0 || poller)
|
|
146
171
|
return;
|
|
147
172
|
// 播种:启动时 load() 已按同一份文件启动过服务器,别在第一个事件里白重载一次。
|
|
148
173
|
applied = readOnce().fp;
|
|
@@ -168,6 +193,7 @@ export function createMcpHotReload(deps) {
|
|
|
168
193
|
}
|
|
169
194
|
}
|
|
170
195
|
function dispose() {
|
|
196
|
+
disposed = true;
|
|
171
197
|
if (debounce)
|
|
172
198
|
clearTimeout(debounce);
|
|
173
199
|
debounce = null;
|