pi-web-ui 0.113.0 → 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 +69 -1
- package/README.md +117 -252
- package/README.zh-CN.md +145 -223
- package/README.zh-TW.md +145 -223
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +145 -20
- package/dist/gh-comment-781.md +5 -0
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2296 -1121
- 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/control-socket.js +6 -2
- 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 +110 -34
- 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 +236 -232
- 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/webui-context.js +6 -6
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/dist/test-artifact.md +9 -0
- package/dist/test-preview-modal.md +11 -0
- package/dist/test-report.html +20 -0
- 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 +45 -9
- 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-3wojLfLk.js +0 -3
- package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
- package/web/dist/assets/index-BwL7qBh6.css +0 -1
- package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
- package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
package/dist/server/index.js
CHANGED
|
@@ -16,12 +16,15 @@
|
|
|
16
16
|
* all share one conversation list per project.
|
|
17
17
|
* PI_CODING_AGENT_DIR pi config dir (auth/models/skills) — passed to the SDK
|
|
18
18
|
*/
|
|
19
|
+
import { botExecutionMessageAllowed } from "./device-center/bot-execution.js";
|
|
19
20
|
// MUST be imported before the SDK is loaded so on-disk patches apply cleanly.
|
|
20
21
|
import "./patch-remote-catalog.js";
|
|
21
22
|
import "./patch-turn-end-boundary.js";
|
|
22
23
|
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
23
24
|
import { readFile, stat } from "node:fs/promises";
|
|
24
|
-
import { createServer
|
|
25
|
+
import { createServer } from "node:http";
|
|
26
|
+
import { proxyHttp } from "./http-proxy.js";
|
|
27
|
+
import { saveSetupConfig } from "./setup-config.js";
|
|
25
28
|
import { createConnection } from "node:net";
|
|
26
29
|
import { basename, delimiter, join, resolve, sep } from "node:path";
|
|
27
30
|
import { homedir } from "node:os";
|
|
@@ -34,11 +37,11 @@ import { sdkCopies, sdkOriginNote } from "./sdk-origin.js";
|
|
|
34
37
|
import { PROTOCOL_VERSION } from "./protocol-version.js";
|
|
35
38
|
import { AgentService, workspacePath, QuiesceRejectedError, ClientSession } from "./agent-service.js";
|
|
36
39
|
import { ClientStateStore } from "./client-state.js";
|
|
37
|
-
import {
|
|
40
|
+
import { isAbsoluteWirePath, wireToAbs } from "./files-service.js";
|
|
41
|
+
import { WS_MAX_PAYLOAD_BYTES } from "./payload-limits.js";
|
|
38
42
|
import { httpHostAllowed, isLoopbackHost, hostWithoutPort } from "./host-guard.js";
|
|
39
43
|
import { registerFileTransferRoutes } from "./file-transfer-routes.js";
|
|
40
|
-
import { initAttachmentStore,
|
|
41
|
-
import { isAudioFile, previewKind } from "./text-sniff.js";
|
|
44
|
+
import { initAttachmentStore, findAttachment } from "./attachment-store.js";
|
|
42
45
|
import { isOfficeFile, OFFICE_MAX_FILE_BYTES, unzipFiles } from "./office-parse.js";
|
|
43
46
|
import { startControlServer } from "./control-socket.js";
|
|
44
47
|
import { scheduleUploadCleanup } from "./uploads.js";
|
|
@@ -50,13 +53,18 @@ import { parseTabs, tabsRefusal } from "./tabs.js";
|
|
|
50
53
|
import { recordUnknownWsType } from "./ws-unknown-types.js";
|
|
51
54
|
import { MessageWindowTap, readMessageWindowConfig } from "./message-window.js";
|
|
52
55
|
import { validateClientId } from "./ws-client-id.js";
|
|
53
|
-
import { PendingCommandQueue } from "./ws-pending-queue.js";
|
|
56
|
+
import { PendingCommandQueue, MAX_PRE_HELLO_WS_BYTES, isClientMessageEnvelope, isClientMessageWithinByteLimit, } from "./ws-pending-queue.js";
|
|
54
57
|
import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, resolveSystemDefaultLocale, unloadServerStrings, } from "./locales.js";
|
|
55
58
|
import { PluginManager, resolvePluginClientFile, resolvePluginSharedFile, } from "./plugins.js";
|
|
56
59
|
import { confirmPluginInstall, PluginInstaller } from "./plugin-installer.js";
|
|
57
60
|
import { syncPluginCatalog } from "./plugin-catalog-sync.js";
|
|
58
|
-
import {
|
|
59
|
-
import {
|
|
61
|
+
import { McpProjectRuntimeRegistry } from "./mcp-project-runtime.js";
|
|
62
|
+
import { installLocalDeviceCenter } from "./device-center/local.js";
|
|
63
|
+
import { createDeviceConnector } from "./device-center/connector.js";
|
|
64
|
+
import { createDeviceRuntime } from "./device-center/runtime.js";
|
|
65
|
+
import { createLocalBotRegistry } from "./device-center/bots.js";
|
|
66
|
+
import { setDeviceCollabService } from "./device-center/collab-tool.js";
|
|
67
|
+
import { createDeviceDesktop } from "./device-center/desktop.js";
|
|
60
68
|
import { createHostMetricsSampler } from "./host-metrics.js";
|
|
61
69
|
import { SchedulerStore } from "./scheduler-tasks.js";
|
|
62
70
|
import { initHttpProxy } from "./http-proxy.js";
|
|
@@ -209,7 +217,10 @@ function buildId() {
|
|
|
209
217
|
if (buildIdCache === null) {
|
|
210
218
|
try {
|
|
211
219
|
const html = readFileSync(join(webDistPath(), "index.html"), "utf8");
|
|
212
|
-
buildIdCache =
|
|
220
|
+
buildIdCache =
|
|
221
|
+
html.match(/<meta\s+name="pi-web-build-id"\s+content="([^"]+)"/)?.[1] ??
|
|
222
|
+
html.match(/(?:\/|\.\/)assets\/index-([A-Za-z0-9_-]+)\.js/)?.[1] ??
|
|
223
|
+
"";
|
|
213
224
|
}
|
|
214
225
|
catch {
|
|
215
226
|
buildIdCache = "";
|
|
@@ -361,84 +372,23 @@ app.get("/api/setup/status", setupGate, (_req, res) => {
|
|
|
361
372
|
});
|
|
362
373
|
});
|
|
363
374
|
app.post("/api/setup/save", setupGate, (req, res) => {
|
|
364
|
-
const
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
let tokenChanged = false;
|
|
368
|
-
if (typeof body.token === "string") {
|
|
369
|
-
const t = body.token.trim();
|
|
370
|
-
if (t)
|
|
371
|
-
next.token = t;
|
|
372
|
-
else
|
|
373
|
-
delete next.token;
|
|
374
|
-
tokenChanged = t !== AUTH_TOKEN;
|
|
375
|
-
AUTH_TOKEN = t;
|
|
376
|
-
}
|
|
377
|
-
const setStr = (key, v, valid, what) => {
|
|
378
|
-
if (v === undefined)
|
|
379
|
-
return true;
|
|
380
|
-
if (typeof v !== "string") {
|
|
381
|
-
res.status(400).json({ ok: false, error: `${what} 必须是字符串` });
|
|
382
|
-
return false;
|
|
383
|
-
}
|
|
384
|
-
const s = v.trim();
|
|
385
|
-
if (s && !valid(s)) {
|
|
386
|
-
res.status(400).json({ ok: false, error: `${what} 格式不合法:${s}` });
|
|
387
|
-
return false;
|
|
388
|
-
}
|
|
389
|
-
if (s)
|
|
390
|
-
next[key] = s;
|
|
391
|
-
else
|
|
392
|
-
delete next[key];
|
|
393
|
-
return true;
|
|
394
|
-
};
|
|
395
|
-
if (!setStr("host", body.host, (s) => /^[A-Za-z0-9.:_-]+$/.test(s) && s.length <= 253, "host"))
|
|
396
|
-
return;
|
|
397
|
-
if (!setStr("allowHosts", body.allowHosts, (s) => /^[A-Za-z0-9.,:_\-\s]+$/.test(s), "allowHosts"))
|
|
398
|
-
return;
|
|
399
|
-
if (!setStr("allowOrigins", body.allowOrigins, (s) => s.length <= 2000, "allowOrigins"))
|
|
400
|
-
return;
|
|
401
|
-
if (body.port !== undefined && body.port !== "" && body.port !== null) {
|
|
402
|
-
const p = Number(body.port);
|
|
403
|
-
if (!Number.isInteger(p) || p <= 0 || p > 65535) {
|
|
404
|
-
res.status(400).json({ ok: false, error: `port 必须是 1-65535:${String(body.port)}` });
|
|
405
|
-
return;
|
|
406
|
-
}
|
|
407
|
-
next.port = p;
|
|
408
|
-
}
|
|
409
|
-
else if (body.port === "") {
|
|
410
|
-
delete next.port;
|
|
411
|
-
}
|
|
412
|
-
try {
|
|
413
|
-
saveServerFileConfig(DATA_DIR, next);
|
|
414
|
-
}
|
|
415
|
-
catch (err) {
|
|
416
|
-
res.status(500).json({ ok: false, error: `写入配置失败:${err.message}` });
|
|
375
|
+
const result = saveSetupConfig(req.body, loadServerFileConfig(DATA_DIR), { token: AUTH_TOKEN, host: HOST, port: PORT, allowHosts: ALLOW_HOSTS, allowOrigins: ALLOW_ORIGINS }, (next) => saveServerFileConfig(DATA_DIR, next));
|
|
376
|
+
if (!result.ok) {
|
|
377
|
+
res.status(result.status).json({ ok: false, error: result.error });
|
|
417
378
|
return;
|
|
418
379
|
}
|
|
419
|
-
|
|
420
|
-
.split(",")
|
|
421
|
-
.map((x) => x.trim().toLowerCase())
|
|
422
|
-
.filter(Boolean)
|
|
423
|
-
.join(",");
|
|
424
|
-
const restartRequired = (typeof body.host === "string" && body.host.trim() !== HOST) ||
|
|
425
|
-
(body.port !== undefined && body.port !== "" && body.port !== null && Number(body.port) !== PORT) ||
|
|
426
|
-
(typeof body.allowHosts === "string" && norm(body.allowHosts) !== ALLOW_HOSTS.join(",")) ||
|
|
427
|
-
(typeof body.allowOrigins === "string" && norm(body.allowOrigins) !== ALLOW_ORIGINS.join(","));
|
|
428
|
-
// 如果设置了新 token,直接给当前回环浏览器下发匹配的 cookie,避免保存后直接 401
|
|
380
|
+
AUTH_TOKEN = result.nextToken;
|
|
429
381
|
if (AUTH_TOKEN) {
|
|
430
|
-
|
|
431
|
-
res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, secure));
|
|
382
|
+
res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, isTlsRequest(req)));
|
|
432
383
|
}
|
|
433
|
-
else if (
|
|
434
|
-
// 清除了 token,同时清理旧 cookie
|
|
384
|
+
else if (result.tokenApplied) {
|
|
435
385
|
res.setHeader("Set-Cookie", [buildPiWebTokenCookie("", 0, false), buildPiWebTokenCookie("", 0, true)]);
|
|
436
386
|
}
|
|
437
387
|
res.json({
|
|
438
388
|
ok: true,
|
|
439
|
-
tokenApplied:
|
|
440
|
-
restartRequired,
|
|
441
|
-
saved:
|
|
389
|
+
tokenApplied: result.tokenApplied,
|
|
390
|
+
restartRequired: result.restartRequired,
|
|
391
|
+
saved: result.saved,
|
|
442
392
|
});
|
|
443
393
|
});
|
|
444
394
|
/** 从请求中提取候选 token:头 / 查询参数 / cookie(浏览器导航场景靠 cookie 续命)。 */
|
|
@@ -511,9 +461,29 @@ function splatParam(req) {
|
|
|
511
461
|
return v.join("/");
|
|
512
462
|
return String(v ?? "");
|
|
513
463
|
}
|
|
464
|
+
/** Preview capabilities authorize only a currently registered live-preview proxy.
|
|
465
|
+
* Forward here, never call next(): capability paths cannot reach any host API. */
|
|
466
|
+
function livePreviewCapability(req) {
|
|
467
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
468
|
+
return undefined;
|
|
469
|
+
const candidate = /^\/__live-preview\/[a-f0-9]{64}(?=\/|$)/.exec(req.path)?.[0];
|
|
470
|
+
if (!candidate)
|
|
471
|
+
return undefined;
|
|
472
|
+
const hit = pluginMgr.findProxy(req.path);
|
|
473
|
+
if (!hit || hit.pluginId !== "live-preview" || !/^\/__live-preview\/[a-f0-9]{64}$/.test(hit.prefix))
|
|
474
|
+
return undefined;
|
|
475
|
+
if (!timingSafeEqual(createHash("sha256").update(candidate).digest(), createHash("sha256").update(hit.prefix).digest()))
|
|
476
|
+
return undefined;
|
|
477
|
+
return hit;
|
|
478
|
+
}
|
|
514
479
|
// 常挂载:本地 /setup 页支持运行时设置/清除口令(AUTH_TOKEN 是 let,热旋转)。
|
|
515
480
|
// 无口令时直接放行,保持原有行为不变。
|
|
516
481
|
app.use((req, res, next) => {
|
|
482
|
+
const preview = livePreviewCapability(req);
|
|
483
|
+
if (preview) {
|
|
484
|
+
proxyHttp(preview, req, res);
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
517
487
|
if (!AUTH_TOKEN) {
|
|
518
488
|
next();
|
|
519
489
|
return;
|
|
@@ -600,7 +570,7 @@ const ORIGIN = launchOrigin();
|
|
|
600
570
|
const SERVICE_INFO = toServiceInfo(ORIGIN);
|
|
601
571
|
/** PI_WEB_TABS: the tabs this instance offers. null = all of them, as before. */
|
|
602
572
|
const TABS = parseTabs();
|
|
603
|
-
registerFileTransferRoutes(app, (clientId) => service.get(clientId)?.cwd);
|
|
573
|
+
registerFileTransferRoutes(app, (clientId) => service.get(clientId)?.cwd, undefined, (clientId) => (sharedStateStore.getSettingsSnapshot(clientId).folderUploadMaxMb ?? 32) * 1024 * 1024);
|
|
604
574
|
app.get("/api/health", (_req, res) => {
|
|
605
575
|
// 审查 #352:该端点对未鉴权开放(监控探针需要),故只保留版本/引擎与 SDK
|
|
606
576
|
// 副本诊断信息,不再暴露 cwd(工作区路径披露)与 pid(指纹/信息收集面)。
|
|
@@ -616,6 +586,13 @@ app.get("/api/health", (_req, res) => {
|
|
|
616
586
|
faviconColor: process.env.PI_WEB_FAVICON_COLOR?.trim() || undefined,
|
|
617
587
|
});
|
|
618
588
|
});
|
|
589
|
+
/** Every inline file response is untrusted active content, regardless of MIME.
|
|
590
|
+
* This runs before local/remote dispatch and covers HEAD, Range and 304 too. */
|
|
591
|
+
app.use(["/api/file", "/api/attachment/:hash", "/api/preview"], (req, res, next) => {
|
|
592
|
+
res.setHeader("Content-Security-Policy", req.query.allowJs === "1" ? "sandbox allow-scripts" : "sandbox");
|
|
593
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
594
|
+
next();
|
|
595
|
+
});
|
|
619
596
|
/**
|
|
620
597
|
* 基于 SHA-256 内容寻址的附件静态服务:
|
|
621
598
|
* 永久强缓存(immutable),支持图片和文件读取。
|
|
@@ -623,24 +600,22 @@ app.get("/api/health", (_req, res) => {
|
|
|
623
600
|
app.get("/api/attachment/:hash", async (req, res) => {
|
|
624
601
|
try {
|
|
625
602
|
const hash = String(req.params.hash ?? "").trim();
|
|
626
|
-
const hit = await
|
|
603
|
+
const hit = await findAttachment(hash);
|
|
627
604
|
if (!hit) {
|
|
628
605
|
res.status(404).end("attachment not found");
|
|
629
606
|
return;
|
|
630
607
|
}
|
|
631
608
|
res.setHeader("Content-Type", hit.mimeType);
|
|
632
|
-
res.setHeader("Content-Length", hit.buffer.length);
|
|
633
609
|
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
}
|
|
643
|
-
res.end(hit.buffer);
|
|
610
|
+
// Hash-located attachments may reside under a hidden dataDir (e.g. .pi-web).
|
|
611
|
+
res.sendFile(hit.filePath, { dotfiles: "allow" }, (err) => {
|
|
612
|
+
if (!err)
|
|
613
|
+
return;
|
|
614
|
+
if (!res.headersSent)
|
|
615
|
+
res.status(err.statusCode ?? 500).end();
|
|
616
|
+
else
|
|
617
|
+
res.destroy(err);
|
|
618
|
+
});
|
|
644
619
|
}
|
|
645
620
|
catch (err) {
|
|
646
621
|
res.status(500).end(err.message);
|
|
@@ -670,7 +645,7 @@ app.get("/api/file", async (req, res) => {
|
|
|
670
645
|
const cs = cid ? service.get(cid) : undefined;
|
|
671
646
|
const root = cs?.cwd ?? CWD;
|
|
672
647
|
if (isRemoteWorkspaceUri(root)) {
|
|
673
|
-
await serveRemoteWorkspaceFile(req, res, root, raw, { isDownload: req.query.download === "1", allowAllTypes:
|
|
648
|
+
await serveRemoteWorkspaceFile(req, res, root, raw, { isDownload: req.query.download === "1", allowAllTypes: true }, remoteSshService);
|
|
674
649
|
return;
|
|
675
650
|
}
|
|
676
651
|
const absWire = isAbsoluteWirePath(raw);
|
|
@@ -687,18 +662,7 @@ app.get("/api/file", async (req, res) => {
|
|
|
687
662
|
abs = wp.abs;
|
|
688
663
|
}
|
|
689
664
|
const name = basename(abs);
|
|
690
|
-
const kind = previewKind(name);
|
|
691
665
|
const isDownload = req.query.download === "1";
|
|
692
|
-
// HTML files preview through a sandboxed <iframe> in the file modal
|
|
693
|
-
// (FilePreview.tsx). They are text as far as previewKind goes, so
|
|
694
|
-
// allowlist them explicitly here.
|
|
695
|
-
const lower = name.toLowerCase();
|
|
696
|
-
const isHtmlPreview = lower.endsWith(".html") || lower.endsWith(".htm") || lower.endsWith(".xhtml");
|
|
697
|
-
const isAudioPreview = isAudioFile(name);
|
|
698
|
-
if (!isDownload && kind !== "image" && kind !== "video" && !isHtmlPreview && !isAudioPreview) {
|
|
699
|
-
res.status(400).end("not a previewable media file");
|
|
700
|
-
return;
|
|
701
|
-
}
|
|
702
666
|
const st = await stat(abs);
|
|
703
667
|
if (!st.isFile()) {
|
|
704
668
|
res.status(400).end("not a file");
|
|
@@ -715,26 +679,6 @@ app.get("/api/file", async (req, res) => {
|
|
|
715
679
|
res.download(abs, name, { dotfiles: "allow" });
|
|
716
680
|
}
|
|
717
681
|
else {
|
|
718
|
-
if (isHtmlPreview) {
|
|
719
|
-
// Sandbox even a top-level navigation to this URL: a workspace
|
|
720
|
-
// HTML file must never get our origin (it could otherwise read
|
|
721
|
-
// the token cookie). The modal iframe carries its own sandbox
|
|
722
|
-
// attribute as well (defense in depth).
|
|
723
|
-
//
|
|
724
|
-
// ?allowJs=1 is the explicit per-file opt-in from the preview
|
|
725
|
-
// modal ("启用脚本"): scripts run, but still in an opaque
|
|
726
|
-
// origin — no DOM/cookie/storage access to our app, no forms,
|
|
727
|
-
// no top-navigation. NEVER add allow-same-origin here.
|
|
728
|
-
const allowJs = req.query.allowJs === "1";
|
|
729
|
-
res.setHeader("Content-Security-Policy", allowJs ? "sandbox allow-scripts" : "sandbox");
|
|
730
|
-
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
731
|
-
}
|
|
732
|
-
else if (lower.endsWith(".svg")) {
|
|
733
|
-
// 与 /api/attachment 同理:SVG 文档形态的 <script> 沙箱化
|
|
734
|
-
// (审查 #352 P0-1),<img> 内嵌用法不受影响。
|
|
735
|
-
res.setHeader("Content-Security-Policy", "sandbox");
|
|
736
|
-
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
737
|
-
}
|
|
738
682
|
res.sendFile(abs, { dotfiles: "allow" });
|
|
739
683
|
}
|
|
740
684
|
}
|
|
@@ -871,22 +815,11 @@ app.get("/api/preview/*splat", async (req, res) => {
|
|
|
871
815
|
}
|
|
872
816
|
abs = wp.abs;
|
|
873
817
|
}
|
|
874
|
-
const name = basename(abs);
|
|
875
818
|
const st = await stat(abs);
|
|
876
819
|
if (!st.isFile()) {
|
|
877
820
|
res.status(400).end("not a file");
|
|
878
821
|
return;
|
|
879
822
|
}
|
|
880
|
-
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
881
|
-
const lower = name.toLowerCase();
|
|
882
|
-
if (lower.endsWith(".html") || lower.endsWith(".htm") || lower.endsWith(".xhtml")) {
|
|
883
|
-
const allowJs = req.query.allowJs === "1";
|
|
884
|
-
res.setHeader("Content-Security-Policy", allowJs ? "sandbox allow-scripts" : "sandbox");
|
|
885
|
-
}
|
|
886
|
-
else if (lower.endsWith(".svg")) {
|
|
887
|
-
// 与 /api/attachment 同理:SVG 文档形态的 <script> 沙箱化(审查 #352 P0-1)。
|
|
888
|
-
res.setHeader("Content-Security-Policy", "sandbox");
|
|
889
|
-
}
|
|
890
823
|
res.sendFile(abs, { dotfiles: "allow" });
|
|
891
824
|
}
|
|
892
825
|
catch {
|
|
@@ -1008,69 +941,17 @@ const PLUGINS_DIR = join(DATA_DIR, "plugins");
|
|
|
1008
941
|
app.all(["/plugins-api/:id/*splat", "/plugins-api/:id"], (req, res) => {
|
|
1009
942
|
// 多段子路径的 splat 是数组(见 splatParam),拼回 "/" 后再交插件路由。
|
|
1010
943
|
const rest = splatParam(req);
|
|
1011
|
-
|
|
944
|
+
const cid = typeof req.query.clientId === "string" ? req.query.clientId : "";
|
|
945
|
+
const cs = cid ? service.get(cid) : undefined;
|
|
946
|
+
if (cid && !cs) {
|
|
947
|
+
res.status(400).json({ error: "Unknown client workspace" });
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
pluginMgr.handleHttp(String(req.params.id ?? ""), req.method, rest, req, res, cs ? { cwd: cs.cwd, roots: cs.workspaceRoots } : undefined);
|
|
1012
951
|
});
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
fwd = `/${fwd}`;
|
|
1017
|
-
return fwd || "/";
|
|
1018
|
-
}
|
|
1019
|
-
function proxyHttp(hit, req, res) {
|
|
1020
|
-
const fwdPath = proxyForwardPath(hit, req.url ?? "/");
|
|
1021
|
-
const headers = {};
|
|
1022
|
-
for (const [k, v] of Object.entries(req.headers)) {
|
|
1023
|
-
if (v === undefined)
|
|
1024
|
-
continue;
|
|
1025
|
-
if (k.toLowerCase() === "host")
|
|
1026
|
-
continue;
|
|
1027
|
-
if (k.toLowerCase() === "content-length" && req.method !== "GET" && req.method !== "HEAD")
|
|
1028
|
-
continue;
|
|
1029
|
-
headers[k] = v;
|
|
1030
|
-
}
|
|
1031
|
-
// 内页拼 SSE/资源绝对地址用(子路径反代下 import.meta 推导不到前缀,靠这个头)。
|
|
1032
|
-
headers["x-pi-proxy-prefix"] = hit.prefix;
|
|
1033
|
-
let body;
|
|
1034
|
-
if (req.method !== "GET" && req.method !== "HEAD" && req.body !== undefined) {
|
|
1035
|
-
const b = req.body;
|
|
1036
|
-
if (Buffer.isBuffer(b))
|
|
1037
|
-
body = b;
|
|
1038
|
-
else if (typeof b === "string")
|
|
1039
|
-
body = Buffer.from(b);
|
|
1040
|
-
else if (b !== undefined) {
|
|
1041
|
-
body = Buffer.from(JSON.stringify(b));
|
|
1042
|
-
if (!headers["content-type"])
|
|
1043
|
-
headers["content-type"] = "application/json";
|
|
1044
|
-
}
|
|
1045
|
-
if (body)
|
|
1046
|
-
headers["content-length"] = String(body.length);
|
|
1047
|
-
}
|
|
1048
|
-
const up = proxyRequest({ host: hit.host, port: hit.port, method: req.method, path: fwdPath, headers, timeout: 30000 }, (upRes) => {
|
|
1049
|
-
const out = {};
|
|
1050
|
-
for (const [k, v] of Object.entries(upRes.headers)) {
|
|
1051
|
-
if (v === undefined)
|
|
1052
|
-
continue;
|
|
1053
|
-
const lk = k.toLowerCase();
|
|
1054
|
-
if (lk === "connection" || lk === "keep-alive" || lk === "transfer-encoding" || lk === "upgrade")
|
|
1055
|
-
continue;
|
|
1056
|
-
out[k] = v;
|
|
1057
|
-
}
|
|
1058
|
-
res.writeHead(upRes.statusCode ?? 502, out);
|
|
1059
|
-
upRes.pipe(res);
|
|
1060
|
-
});
|
|
1061
|
-
up.on("timeout", () => up.destroy(new Error("proxy timeout")));
|
|
1062
|
-
up.on("error", (err) => {
|
|
1063
|
-
console.error(`[proxy:${hit.prefix}] → 127.0.0.1:${hit.port}${fwdPath} failed:`, err);
|
|
1064
|
-
if (!res.headersSent)
|
|
1065
|
-
res.status(502).end("proxy target unreachable");
|
|
1066
|
-
else
|
|
1067
|
-
res.end();
|
|
1068
|
-
});
|
|
1069
|
-
if (body)
|
|
1070
|
-
up.end(body);
|
|
1071
|
-
else
|
|
1072
|
-
req.pipe(up);
|
|
1073
|
-
}
|
|
952
|
+
/** 通用插件代理(host.registerProxy 注册的前缀落到这里):去前缀后原样透传到
|
|
953
|
+
* 127.0.0.1:port——相对路径/Range/SSE 天然可用。PI_WEB_TOKEN 鉴权已在上方覆盖。
|
|
954
|
+
* 必须站在静态资源与 SPA catch-all 之前,否则子路径被 index.html 吞掉。 */
|
|
1074
955
|
app.use((req, res, next) => {
|
|
1075
956
|
const hit = pluginMgr.findProxy(req.path);
|
|
1076
957
|
if (!hit) {
|
|
@@ -1129,6 +1010,61 @@ app.get("/plugins-shared/*splat", (req, res) => {
|
|
|
1129
1010
|
});
|
|
1130
1011
|
/** Set in the env of the replacement child spawned by a self-update restart. */
|
|
1131
1012
|
const RESTART_CHILD_ENV = "PI_WEB_RESTART_CHILD";
|
|
1013
|
+
// Local-only device enrollment stays behind host authentication and ahead of the SPA fallback.
|
|
1014
|
+
const deviceDesktop = createDeviceDesktop({ app, dataDir: DATA_DIR, authorize: (req) => !AUTH_TOKEN || tokenOk(req) });
|
|
1015
|
+
const deviceBots = await createLocalBotRegistry(DATA_DIR);
|
|
1016
|
+
const deviceCenter = await installLocalDeviceCenter({
|
|
1017
|
+
app,
|
|
1018
|
+
dataDir: DATA_DIR,
|
|
1019
|
+
bots: deviceBots,
|
|
1020
|
+
botCatalog: {
|
|
1021
|
+
defaultCwd: CWD,
|
|
1022
|
+
dataDir: DATA_DIR,
|
|
1023
|
+
models: async (signal) => {
|
|
1024
|
+
signal.throwIfAborted();
|
|
1025
|
+
const models = (await piServiceInstance?.pluginClient()?.listLocalBotModels()) ?? [];
|
|
1026
|
+
signal.throwIfAborted();
|
|
1027
|
+
return models;
|
|
1028
|
+
},
|
|
1029
|
+
projects: () => sharedStateStore.getRecentProjects(""),
|
|
1030
|
+
defaultModel: () => sharedStateStore.getDefaultModel("pi"),
|
|
1031
|
+
peekMcpBridge: (cwd) => mcpProjects.peekBridge(cwd),
|
|
1032
|
+
},
|
|
1033
|
+
async connect(config, syncBots) {
|
|
1034
|
+
const localOrigin = `http://127.0.0.1:${PORT}`;
|
|
1035
|
+
const runtime = createDeviceRuntime({
|
|
1036
|
+
config,
|
|
1037
|
+
localOrigin,
|
|
1038
|
+
localAuthToken: AUTH_TOKEN,
|
|
1039
|
+
dataDir: DATA_DIR,
|
|
1040
|
+
bots: deviceBots,
|
|
1041
|
+
});
|
|
1042
|
+
setDeviceCollabService(runtime.collabService);
|
|
1043
|
+
const connector = createDeviceConnector({
|
|
1044
|
+
hubUrl: config.hubUrl,
|
|
1045
|
+
deviceId: config.deviceId,
|
|
1046
|
+
credential: config.credential,
|
|
1047
|
+
localOrigin,
|
|
1048
|
+
localAuthToken: AUTH_TOKEN,
|
|
1049
|
+
onTask: runtime.onTask,
|
|
1050
|
+
onConnect: syncBots,
|
|
1051
|
+
onCommand: runtime.onCommand,
|
|
1052
|
+
onDisconnect: () => {
|
|
1053
|
+
void runtime
|
|
1054
|
+
.onDisconnect()
|
|
1055
|
+
.catch(() => console.warn("[device-center] Task stop was not confirmed; project remains locked"));
|
|
1056
|
+
},
|
|
1057
|
+
});
|
|
1058
|
+
return {
|
|
1059
|
+
isConnected: connector.isOnline,
|
|
1060
|
+
async close() {
|
|
1061
|
+
setDeviceCollabService(undefined);
|
|
1062
|
+
connector.close();
|
|
1063
|
+
await runtime.close();
|
|
1064
|
+
},
|
|
1065
|
+
};
|
|
1066
|
+
},
|
|
1067
|
+
});
|
|
1132
1068
|
const webDist = join(pkgRoot, "web", "dist");
|
|
1133
1069
|
/** webDist accessor for buildId() (declared above webDist's const). */
|
|
1134
1070
|
function webDistPath() {
|
|
@@ -1257,6 +1193,8 @@ function originAllowed(req) {
|
|
|
1257
1193
|
return false;
|
|
1258
1194
|
}
|
|
1259
1195
|
httpServer.on("upgrade", (req, socket, head) => {
|
|
1196
|
+
if (deviceDesktop.handleUpgrade(req, socket, head))
|
|
1197
|
+
return;
|
|
1260
1198
|
let pathname = "/";
|
|
1261
1199
|
try {
|
|
1262
1200
|
pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
@@ -1619,10 +1557,14 @@ const service = {
|
|
|
1619
1557
|
}
|
|
1620
1558
|
return Promise.resolve();
|
|
1621
1559
|
},
|
|
1622
|
-
|
|
1560
|
+
navigateQuestion(targetId, id) {
|
|
1561
|
+
const targetSvc = ensureEngine(resolveClientEngine(targetId));
|
|
1562
|
+
return targetSvc.navigateQuestion?.(targetId, id) ?? Promise.resolve();
|
|
1563
|
+
},
|
|
1564
|
+
answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason) {
|
|
1623
1565
|
const targetSvc = ensureEngine(resolveClientEngine(targetId));
|
|
1624
1566
|
if (typeof targetSvc.answerElsewhereQuestion === "function") {
|
|
1625
|
-
return targetSvc.answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled);
|
|
1567
|
+
return targetSvc.answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason);
|
|
1626
1568
|
}
|
|
1627
1569
|
return Promise.resolve();
|
|
1628
1570
|
},
|
|
@@ -1977,30 +1919,23 @@ function pushNoticeToAll(level, text, textEn) {
|
|
|
1977
1919
|
}
|
|
1978
1920
|
// MCP 工具桥:读取配置启动外部 MCP 服务器(stdio / HTTP streamable-http),把它们的
|
|
1979
1921
|
// 工具并入与插件工具相同的 customTools 管线;单服务器失败不炸进程。
|
|
1980
|
-
const
|
|
1981
|
-
agentDir: getAgentDir(),
|
|
1982
|
-
cwd: CWD,
|
|
1983
|
-
onToolsChanged: () => service.applyPluginAgentTools(),
|
|
1984
|
-
});
|
|
1985
|
-
ClientSession.mcpBridge = mcpBridge;
|
|
1986
|
-
pluginMgr.mcpBridge = mcpBridge;
|
|
1987
|
-
// mcp.json 热加载:保存文件即生效,改完不必再重启服务。两半都在这里收口 —— reload 换入
|
|
1988
|
-
// 新的服务器集合(只重启规格真变了的),applyPluginAgentTools 把新工具推给已有会话。
|
|
1989
|
-
const mcpHotReload = createMcpHotReload({
|
|
1922
|
+
const mcpProjects = new McpProjectRuntimeRegistry({
|
|
1990
1923
|
dataDir: DATA_DIR,
|
|
1924
|
+
isProjectInUse: (cwd) => {
|
|
1925
|
+
const key = (value) => (process.platform === "win32" ? resolve(value).toLowerCase() : resolve(value));
|
|
1926
|
+
return activeEngines().some((svc) => svc.mcpProjectCwds?.().some((project) => key(project) === key(cwd)));
|
|
1927
|
+
},
|
|
1991
1928
|
agentDir: getAgentDir(),
|
|
1992
|
-
|
|
1993
|
-
reload: () => mcpBridge.reload(),
|
|
1994
|
-
onToolsChanged: () => service.applyPluginAgentTools(),
|
|
1995
|
-
onNotice: (level, text, textEn) => pushNoticeToAll(level, text, textEn),
|
|
1996
|
-
log: (...a) => console.log(...a),
|
|
1997
|
-
});
|
|
1998
|
-
void mcpBridge.load().then(() => {
|
|
1999
|
-
if (mcpBridge.getTools().length)
|
|
1929
|
+
onToolsChanged: (cwd) => {
|
|
2000
1930
|
service.applyPluginAgentTools();
|
|
2001
|
-
|
|
2002
|
-
|
|
1931
|
+
for (const svc of activeEngines())
|
|
1932
|
+
svc.refreshMcpProject?.(cwd);
|
|
1933
|
+
},
|
|
1934
|
+
onNotice: (_cwd, level, text, textEn) => pushNoticeToAll(level, text, textEn),
|
|
1935
|
+
log: (...a) => console.log("[mcp]", ...a),
|
|
2003
1936
|
});
|
|
1937
|
+
ClientSession.mcpProjects = mcpProjects;
|
|
1938
|
+
pluginMgr.mcpProjects = mcpProjects;
|
|
2004
1939
|
// 插件与宿主钩子统一挂载器:无论引擎在启动时预热还是运行期按需懒加载,都一致注入全部回调。
|
|
2005
1940
|
wireEngineHooks = (svc) => {
|
|
2006
1941
|
svc.onToolEvent = (ev) => pluginMgr.emitToolEvent(ev);
|
|
@@ -2011,7 +1946,7 @@ wireEngineHooks = (svc) => {
|
|
|
2011
1946
|
svc.onRunEvent = (ev) => pluginMgr.emitRunEvent(ev);
|
|
2012
1947
|
svc.onConversationChanged = () => pluginMgr.emitConversationChanged();
|
|
2013
1948
|
svc.onClientModelChanged = (snap) => pluginMgr.emitClientModelChanged(snap);
|
|
2014
|
-
svc.pluginToolsProvider = () => [...pluginMgr.getAgentTools(), ...
|
|
1949
|
+
svc.pluginToolsProvider = (cwd) => [...pluginMgr.getAgentTools(), ...(cwd ? mcpProjects.getTools(cwd) : [])];
|
|
2015
1950
|
svc.pluginCommandsProvider = () => pluginMgr.listCommands();
|
|
2016
1951
|
svc.pluginBgTasksProvider = () => pluginMgr.bgTasks();
|
|
2017
1952
|
svc.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
|
|
@@ -2132,6 +2067,11 @@ pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
|
|
|
2132
2067
|
// runAborter:有现成 abort 路径(interruptRun,卡住/空转强制重置语义继承)。
|
|
2133
2068
|
pm.runAborter = async (id) => {
|
|
2134
2069
|
try {
|
|
2070
|
+
if (id.startsWith("pr-")) {
|
|
2071
|
+
if (!piServiceInstance)
|
|
2072
|
+
return { ok: false, error: "not supported" };
|
|
2073
|
+
return await piServiceInstance.abortPluginRun(id);
|
|
2074
|
+
}
|
|
2135
2075
|
const cs = pickClient();
|
|
2136
2076
|
if (!cs || typeof cs.abortForPlugins !== "function")
|
|
2137
2077
|
return { ok: false, error: "not supported" };
|
|
@@ -2244,10 +2184,15 @@ wss.on("connection", (ws) => {
|
|
|
2244
2184
|
service.noteSocketOpen();
|
|
2245
2185
|
let clientId = null;
|
|
2246
2186
|
let closed = false;
|
|
2187
|
+
const helloTimer = setTimeout(() => {
|
|
2188
|
+
if (!clientId)
|
|
2189
|
+
ws.close(1008, "Handshake timed out");
|
|
2190
|
+
}, 15_000);
|
|
2191
|
+
helloTimer.unref?.();
|
|
2247
2192
|
/** 最近一份全量 snapshot 的估算字节数(UTF-16 ×2),供背压相对阈值用(issue #11)。 */
|
|
2248
2193
|
let lastSnapshotBytes = 0;
|
|
2249
2194
|
/** Commands received while the session is still being created — replayed after attach.
|
|
2250
|
-
*
|
|
2195
|
+
* 按条数和累计字节限制;超限关闭连接,避免静默丢弃已接收的命令。 */
|
|
2251
2196
|
const pending = new PendingCommandQueue();
|
|
2252
2197
|
/** attach 完成(含插件链 + 首快照)前一律排队(见 hello 分支的 replayQueued):
|
|
2253
2198
|
* ready 先行后,ready 只代表传输通,插件命令目录/首快照都还没好,直接分发
|
|
@@ -2313,7 +2258,13 @@ wss.on("connection", (ws) => {
|
|
|
2313
2258
|
// Plugins broadcast to every open socket; unregister on close below.
|
|
2314
2259
|
// Plugins broadcast to every open socket; unregister on close below. The
|
|
2315
2260
|
// cid getter lets plugins target THIS socket via host.sendTo(clientId).
|
|
2316
|
-
const removePluginSender = pluginMgr.addSender(
|
|
2261
|
+
const removePluginSender = pluginMgr.addSender((msg) => {
|
|
2262
|
+
// Task sockets receive only their executor/session events. Global plugin
|
|
2263
|
+
// notices have no session attribution and must not abort unrelated tasks.
|
|
2264
|
+
if (!clientId || clientId.startsWith("device-task-"))
|
|
2265
|
+
return;
|
|
2266
|
+
send(msg);
|
|
2267
|
+
}, () => clientId);
|
|
2317
2268
|
/** DOM 授权落盘 + notice 反馈(两步握手的 grant 与单步 revoke 共用收尾)。
|
|
2318
2269
|
* cs 缺席(未 attach 完成)时只落盘不提示——消息本来就会在 attach 前排队。 */
|
|
2319
2270
|
const applyDomConsent = (pluginId, granted) => {
|
|
@@ -2537,9 +2488,10 @@ wss.on("connection", (ws) => {
|
|
|
2537
2488
|
});
|
|
2538
2489
|
}
|
|
2539
2490
|
};
|
|
2540
|
-
const dispatch = (msg) => {
|
|
2491
|
+
const dispatch = (msg, wireBytes) => {
|
|
2541
2492
|
if (!clientId) {
|
|
2542
|
-
pending.push(msg)
|
|
2493
|
+
if (!pending.push(msg, wireBytes))
|
|
2494
|
+
ws.close(1009, "Pending command budget exceeded");
|
|
2543
2495
|
return;
|
|
2544
2496
|
}
|
|
2545
2497
|
// switch_engine 为宿主级控制消息:豁免 cs 初始化与 attachDone 门禁,确保任何异常状态下都能自由切回!
|
|
@@ -2561,7 +2513,8 @@ wss.on("connection", (ws) => {
|
|
|
2561
2513
|
const cs = service.get(clientId);
|
|
2562
2514
|
if (!cs || !attachDone) {
|
|
2563
2515
|
// Session not ready yet (hello processing / plugin chain) — hold the command.
|
|
2564
|
-
pending.push(msg)
|
|
2516
|
+
if (!pending.push(msg, wireBytes))
|
|
2517
|
+
ws.close(1009, "Pending command budget exceeded");
|
|
2565
2518
|
return;
|
|
2566
2519
|
}
|
|
2567
2520
|
// 历史窗口按需加载:连接级窗口化直接服务(四个引擎通吃,不依赖引擎实现)。
|
|
@@ -2573,6 +2526,7 @@ wss.on("connection", (ws) => {
|
|
|
2573
2526
|
conversationId: msg.conversationId,
|
|
2574
2527
|
beforeId: msg.beforeId,
|
|
2575
2528
|
before: msg.before,
|
|
2529
|
+
historyGeneration: msg.historyGeneration,
|
|
2576
2530
|
});
|
|
2577
2531
|
if (!handled && cs) {
|
|
2578
2532
|
const activeId = typeof cs.activeConversationId === "function" ? cs.activeConversationId() : undefined;
|
|
@@ -2586,6 +2540,7 @@ wss.on("connection", (ws) => {
|
|
|
2586
2540
|
conversationId: convId,
|
|
2587
2541
|
beforeId: msg.beforeId,
|
|
2588
2542
|
before: msg.before,
|
|
2543
|
+
historyGeneration: msg.historyGeneration,
|
|
2589
2544
|
});
|
|
2590
2545
|
}
|
|
2591
2546
|
if (!handled && (!msg.conversationId || msg.conversationId === activeId)) {
|
|
@@ -2616,7 +2571,7 @@ wss.on("connection", (ws) => {
|
|
|
2616
2571
|
return;
|
|
2617
2572
|
if (handleTerminalMessage(msg, cs))
|
|
2618
2573
|
return;
|
|
2619
|
-
if (handleSessionLifecycleMessage(msg, cs))
|
|
2574
|
+
if (handleSessionLifecycleMessage(msg, cs, send))
|
|
2620
2575
|
return;
|
|
2621
2576
|
if (handlePlanAndGoalMessage(msg, cs))
|
|
2622
2577
|
return;
|
|
@@ -2624,7 +2579,7 @@ wss.on("connection", (ws) => {
|
|
|
2624
2579
|
return;
|
|
2625
2580
|
if (handleRemoteSshMessage(msg, remoteSshService, send))
|
|
2626
2581
|
return;
|
|
2627
|
-
if (handleSettingsMessage(msg, cs))
|
|
2582
|
+
if (handleSettingsMessage(msg, cs, send))
|
|
2628
2583
|
return;
|
|
2629
2584
|
if (handleCanvasMessage(msg, DATA_DIR, canvasOrchestrator, send, { runBase: cs.cwd }))
|
|
2630
2585
|
return;
|
|
@@ -2652,6 +2607,20 @@ wss.on("connection", (ws) => {
|
|
|
2652
2607
|
return;
|
|
2653
2608
|
switch (msg.type) {
|
|
2654
2609
|
case "prompt": {
|
|
2610
|
+
// No await between identity validation and prompt(): engines capture
|
|
2611
|
+
// their conversation synchronously at entry.
|
|
2612
|
+
if (msg.targetConversationId !== undefined &&
|
|
2613
|
+
(typeof msg.targetConversationId !== "string" ||
|
|
2614
|
+
!msg.targetConversationId ||
|
|
2615
|
+
cs.activeConversationId?.() !== msg.targetConversationId)) {
|
|
2616
|
+
send({
|
|
2617
|
+
type: "notice",
|
|
2618
|
+
level: "warning",
|
|
2619
|
+
text: "发送已取消:目标对话已改变,请重新发送。",
|
|
2620
|
+
textEn: "Prompt canceled: the target conversation changed. Please send again.",
|
|
2621
|
+
});
|
|
2622
|
+
break;
|
|
2623
|
+
}
|
|
2655
2624
|
const hasAttach = Boolean(msg.attachments && msg.attachments.length > 0);
|
|
2656
2625
|
if (!msg.text?.trim() && !hasAttach) {
|
|
2657
2626
|
send({
|
|
@@ -2723,6 +2692,10 @@ wss.on("connection", (ws) => {
|
|
|
2723
2692
|
});
|
|
2724
2693
|
}
|
|
2725
2694
|
break;
|
|
2695
|
+
case "navigate_question":
|
|
2696
|
+
if (typeof service.navigateQuestion === "function")
|
|
2697
|
+
void service.navigateQuestion(clientId, msg.id);
|
|
2698
|
+
break;
|
|
2726
2699
|
case "peek_elsewhere_question":
|
|
2727
2700
|
if (typeof service.peekElsewhereQuestion === "function") {
|
|
2728
2701
|
void service.peekElsewhereQuestion(clientId, msg.owner, msg.id);
|
|
@@ -2834,14 +2807,38 @@ wss.on("connection", (ws) => {
|
|
|
2834
2807
|
ws.on("message", (data) => {
|
|
2835
2808
|
tracked.isAlive = true;
|
|
2836
2809
|
tracked.missedPings = 0;
|
|
2837
|
-
|
|
2810
|
+
const wireBytes = Array.isArray(data) ? data.reduce((n, chunk) => n + chunk.length, 0) : data.byteLength;
|
|
2811
|
+
if (!clientId && wireBytes > MAX_PRE_HELLO_WS_BYTES) {
|
|
2812
|
+
ws.close(1009, "Handshake message too large");
|
|
2813
|
+
return;
|
|
2814
|
+
}
|
|
2815
|
+
let parsed;
|
|
2816
|
+
try {
|
|
2817
|
+
parsed = JSON.parse(data.toString());
|
|
2818
|
+
}
|
|
2819
|
+
catch {
|
|
2820
|
+
return;
|
|
2821
|
+
}
|
|
2822
|
+
if (!isClientMessageEnvelope(parsed))
|
|
2823
|
+
return;
|
|
2824
|
+
if (!isClientMessageWithinByteLimit(parsed.type, wireBytes, !!clientId)) {
|
|
2825
|
+
ws.close(1009, "Message budget exceeded");
|
|
2826
|
+
return;
|
|
2827
|
+
}
|
|
2828
|
+
const msg = parsed;
|
|
2838
2829
|
try {
|
|
2839
|
-
|
|
2830
|
+
const botClientId = clientId ?? (msg.type === "hello" ? msg.clientId : undefined);
|
|
2831
|
+
if (botClientId && !botExecutionMessageAllowed(botClientId, msg.type)) {
|
|
2832
|
+
ws.close(1008, "Bot control command denied");
|
|
2833
|
+
return;
|
|
2834
|
+
}
|
|
2840
2835
|
}
|
|
2841
2836
|
catch {
|
|
2837
|
+
ws.close(1008, "Invalid Bot execution capability");
|
|
2842
2838
|
return;
|
|
2843
2839
|
}
|
|
2844
2840
|
if (msg.type === "hello") {
|
|
2841
|
+
clearTimeout(helloTimer);
|
|
2845
2842
|
// 重放守卫:一条连接只允许 attach 一次。clientId 已赋值说明 hello 处理过
|
|
2846
2843
|
//(或进行中),再来的 hello 幂等回一条 ready 即可——否则重复 hello 会把
|
|
2847
2844
|
// service.attach 整个再跑一遍:重型 ClientSession 重复创建 + 旧 send sink
|
|
@@ -3033,9 +3030,10 @@ wss.on("connection", (ws) => {
|
|
|
3033
3030
|
});
|
|
3034
3031
|
return;
|
|
3035
3032
|
}
|
|
3036
|
-
dispatch(msg);
|
|
3033
|
+
dispatch(msg, wireBytes);
|
|
3037
3034
|
});
|
|
3038
3035
|
ws.on("close", () => {
|
|
3036
|
+
clearTimeout(helloTimer);
|
|
3039
3037
|
service.noteSocketClose();
|
|
3040
3038
|
closed = true;
|
|
3041
3039
|
pending.clear();
|
|
@@ -3157,7 +3155,12 @@ if (!bootCatalogDisabled) {
|
|
|
3157
3155
|
}
|
|
3158
3156
|
// Local control socket (status / quiesce / unquiesce) — same data dir the
|
|
3159
3157
|
// CLI uses, so `pi-web-ui server status|quiesce|unquiesce` just works.
|
|
3160
|
-
const stopControl = startControlServer({
|
|
3158
|
+
const stopControl = startControlServer({
|
|
3159
|
+
service,
|
|
3160
|
+
dataDir: DATA_DIR,
|
|
3161
|
+
port: PORT,
|
|
3162
|
+
authToken: () => AUTH_TOKEN,
|
|
3163
|
+
});
|
|
3161
3164
|
/**
|
|
3162
3165
|
* Graceful shutdown budget (issue #172): disposeAll() can hang forever on a
|
|
3163
3166
|
* stuck session runtime / PTY / pending handle, and the process would then
|
|
@@ -3220,12 +3223,13 @@ async function shutdown(signal = "SIGINT") {
|
|
|
3220
3223
|
let code = 0;
|
|
3221
3224
|
try {
|
|
3222
3225
|
clearInterval(heartbeatTimer);
|
|
3226
|
+
await deviceCenter.close();
|
|
3227
|
+
await deviceDesktop.close();
|
|
3223
3228
|
stopControl();
|
|
3224
3229
|
scheduler.stop();
|
|
3225
3230
|
pluginMgr.dispose();
|
|
3226
3231
|
pluginInstaller.dispose();
|
|
3227
|
-
|
|
3228
|
-
mcpBridge.dispose();
|
|
3232
|
+
await mcpProjects.dispose();
|
|
3229
3233
|
await globalLspPool.shutdownAll();
|
|
3230
3234
|
await service.disposeAll();
|
|
3231
3235
|
// Don't let dead browsers hold the exit open: half-open WebSocket /
|