pi-web-ui 0.113.1 → 0.114.1
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 +71 -1
- package/README.md +187 -316
- package/README.zh-CN.md +227 -299
- package/README.zh-TW.md +227 -299
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/frp-manager.mjs +1573 -1573
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +4081 -4041
- package/deploy/nginx-subpath.conf +100 -100
- package/deploy/pi-web-ui.service +36 -36
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2419 -1174
- 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 +69 -13
- package/dist/server/canvas/canvas-agent-tool.js +68 -18
- package/dist/server/canvas/canvas-cards.js +1 -1
- package/dist/server/canvas/canvas-dispatch.js +61 -20
- package/dist/server/canvas/canvas-orchestrator.js +519 -202
- package/dist/server/canvas/canvas-scheduled-task.js +45 -0
- 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 +110 -24
- 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 +351 -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 +830 -0
- package/dist/server/device-center/local-hub.js +92 -0
- package/dist/server/device-center/local.js +529 -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 +996 -0
- package/dist/server/device-center/runtime.js +253 -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 +84 -27
- package/dist/server/dsh/dsh-agent-service.js +282 -159
- package/dist/server/dsh/dsh-client.js +12 -2
- package/dist/server/dsh/runtime/cordis.yml +1 -1
- package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
- package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
- package/dist/server/dsh/runtime/launcher.mjs +235 -235
- package/dist/server/dsh/runtime/override.patch.yml +89 -89
- package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
- package/dist/server/durable/durable-agent-service.js +1 -1
- package/dist/server/engine-probe.js +36 -6
- package/dist/server/eval-tool.js +135 -135
- 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/global-loader.js +40 -2
- 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 +285 -255
- 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/patch-bash-process.js +125 -0
- package/dist/server/patch-tool.js +9 -9
- package/dist/server/patch-turn-end-boundary.js +3 -3
- package/dist/server/payload-limits.js +17 -0
- package/dist/server/pending-question.js +82 -0
- package/dist/server/persona-chain.js +8 -8
- 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 +288 -94
- package/dist/server/preset-fields.js +56 -0
- package/dist/server/preset-plugin-dependencies.js +57 -0
- package/dist/server/preset-share.js +113 -72
- package/dist/server/prompt-templates.js +106 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-modes.js +10 -0
- package/dist/server/remote-ssh-service.js +199 -106
- package/dist/server/request-context.js +164 -0
- package/dist/server/resolve-global-sdk.js +2 -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/schedule-agent-tool.js +39 -21
- package/dist/server/scheduler-tasks.js +106 -55
- package/dist/server/scm-commitmsg.js +10 -10
- 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 +273 -111
- package/dist/server/setup-config.js +58 -0
- package/dist/server/setup-page.js +620 -620
- 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/text-quote.js +9 -0
- package/dist/server/tool-guards.js +42 -6
- package/dist/server/tool-manager.js +48 -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/drivers/claude-code.js +5 -0
- package/dist/server/universal/drivers/codex.js +336 -0
- package/dist/server/universal/index.js +1 -0
- package/dist/server/universal/session-store.js +48 -6
- package/dist/server/universal/universal-attachments.js +24 -1
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +357 -231
- package/dist/server/uploads.js +64 -5
- package/dist/server/vision-bridge.js +18 -18
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/docs/device-center.md +148 -0
- package/docs/device-desktop.md +48 -0
- package/docs/dsh-engine.md +493 -493
- package/extensions/webui.ts +335 -335
- package/package.json +5 -2
- package/plugin-sdk/README.md +174 -174
- package/plugin-sdk/client-utils.mjs +279 -279
- package/plugin-sdk/import-check.mjs +210 -210
- package/plugin-sdk/index.d.ts +698 -676
- package/plugin-sdk/index.mjs +696 -696
- package/plugin-sdk/package.json +13 -13
- package/plugin-sdk/ssh-host-trust.mjs +225 -0
- package/plugins/catalog.json +11 -1
- package/themes/aetheris.css +501 -607
- package/themes/ayu-light.css +116 -140
- package/themes/bases/flow-base.css +1357 -1363
- package/themes/bases/obsidian-base.css +895 -895
- package/themes/bases/statusbar-flat-base.css +112 -0
- package/themes/bases/zhujian-base.css +688 -687
- package/themes/bases/zhupi-base.css +660 -659
- package/themes/catppuccin-latte.css +119 -142
- package/themes/catppuccin.css +116 -147
- package/themes/claude-code-dark.css +147 -146
- package/themes/codex.css +114 -138
- package/themes/cyberpunk.css +50 -108
- package/themes/dark-teal.css +264 -265
- package/themes/dazzle.css +38 -108
- package/themes/everforest-light.css +115 -138
- package/themes/flow-light.css +164 -164
- package/themes/flow.css +161 -161
- package/themes/geist.css +114 -138
- package/themes/gruvbox-light.css +115 -138
- package/themes/kanagawa-lotus.css +115 -138
- package/themes/md-preview.css +24 -234
- package/themes/mist.css +166 -186
- package/themes/nord.css +107 -138
- package/themes/one-dark.css +106 -139
- package/themes/paper.css +174 -186
- package/themes/rose-pine-dawn.css +114 -138
- package/themes/sakura.css +166 -186
- package/themes/solarized-light.css +114 -137
- package/themes/tokyo-night.css +115 -146
- package/themes/translucent.css +85 -85
- package/themes/transparent.css +116 -116
- package/themes/vs-code-dark.css +147 -147
- package/themes/wallpaper-flow.css +382 -382
- package/themes/wallpaper-obsidian.css +74 -74
- package/themes/white.css +164 -186
- package/themes/zhujian-dark.css +115 -114
- package/themes/zhujian.css +114 -114
- package/themes/zhupi-dark.css +115 -114
- package/themes/zhupi.css +114 -114
- package/web/dist/.build-assets.json +1 -0
- package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
- package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
- package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
- package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
- package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
- package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
- package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
- package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
- package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
- package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
- package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
- package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
- package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
- package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
- package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
- package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
- package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
- package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
- package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
- package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
- package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
- package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
- package/web/dist/assets/desktop-YguLbrX1.js +1 -0
- package/web/dist/assets/es-DWMIuDU2.js +2 -0
- package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
- package/web/dist/assets/index-BPvpea8t.js +85 -0
- package/web/dist/assets/index-D6u8xH0o.js +85 -0
- package/web/dist/assets/index-DDZMv6LO.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-BRBg6zmQ.js +1 -0
- package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
- package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
- package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
- package/web/dist/index.html +42 -35
- package/web/dist/sw.js +179 -179
- package/web/public/sw.js +179 -179
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- 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
package/dist/server/index.js
CHANGED
|
@@ -16,12 +16,16 @@
|
|
|
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";
|
|
24
|
+
import { registerPromptTemplateRoutes } from "./prompt-templates.js";
|
|
23
25
|
import { readFile, stat } from "node:fs/promises";
|
|
24
|
-
import { createServer
|
|
26
|
+
import { createServer } from "node:http";
|
|
27
|
+
import { proxyHttp } from "./http-proxy.js";
|
|
28
|
+
import { saveSetupConfig } from "./setup-config.js";
|
|
25
29
|
import { createConnection } from "node:net";
|
|
26
30
|
import { basename, delimiter, join, resolve, sep } from "node:path";
|
|
27
31
|
import { homedir } from "node:os";
|
|
@@ -34,10 +38,11 @@ import { sdkCopies, sdkOriginNote } from "./sdk-origin.js";
|
|
|
34
38
|
import { PROTOCOL_VERSION } from "./protocol-version.js";
|
|
35
39
|
import { AgentService, workspacePath, QuiesceRejectedError, ClientSession } from "./agent-service.js";
|
|
36
40
|
import { ClientStateStore } from "./client-state.js";
|
|
37
|
-
import {
|
|
41
|
+
import { isAbsoluteWirePath, wireToAbs } from "./files-service.js";
|
|
42
|
+
import { WS_MAX_PAYLOAD_BYTES } from "./payload-limits.js";
|
|
38
43
|
import { httpHostAllowed, isLoopbackHost, hostWithoutPort } from "./host-guard.js";
|
|
39
44
|
import { registerFileTransferRoutes } from "./file-transfer-routes.js";
|
|
40
|
-
import { initAttachmentStore,
|
|
45
|
+
import { initAttachmentStore, findAttachment } from "./attachment-store.js";
|
|
41
46
|
import { isOfficeFile, OFFICE_MAX_FILE_BYTES, unzipFiles } from "./office-parse.js";
|
|
42
47
|
import { startControlServer } from "./control-socket.js";
|
|
43
48
|
import { scheduleUploadCleanup } from "./uploads.js";
|
|
@@ -49,13 +54,18 @@ import { parseTabs, tabsRefusal } from "./tabs.js";
|
|
|
49
54
|
import { recordUnknownWsType } from "./ws-unknown-types.js";
|
|
50
55
|
import { MessageWindowTap, readMessageWindowConfig } from "./message-window.js";
|
|
51
56
|
import { validateClientId } from "./ws-client-id.js";
|
|
52
|
-
import { PendingCommandQueue } from "./ws-pending-queue.js";
|
|
57
|
+
import { PendingCommandQueue, MAX_PRE_HELLO_WS_BYTES, isClientMessageEnvelope, isClientMessageWithinByteLimit, } from "./ws-pending-queue.js";
|
|
53
58
|
import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, resolveSystemDefaultLocale, unloadServerStrings, } from "./locales.js";
|
|
54
59
|
import { PluginManager, resolvePluginClientFile, resolvePluginSharedFile, } from "./plugins.js";
|
|
55
60
|
import { confirmPluginInstall, PluginInstaller } from "./plugin-installer.js";
|
|
56
61
|
import { syncPluginCatalog } from "./plugin-catalog-sync.js";
|
|
57
|
-
import {
|
|
58
|
-
import {
|
|
62
|
+
import { McpProjectRuntimeRegistry } from "./mcp-project-runtime.js";
|
|
63
|
+
import { installLocalDeviceCenter } from "./device-center/local.js";
|
|
64
|
+
import { createDeviceConnector } from "./device-center/connector.js";
|
|
65
|
+
import { createDeviceRuntime } from "./device-center/runtime.js";
|
|
66
|
+
import { createLocalBotRegistry } from "./device-center/bots.js";
|
|
67
|
+
import { setDeviceCollabService } from "./device-center/collab-tool.js";
|
|
68
|
+
import { createDeviceDesktop } from "./device-center/desktop.js";
|
|
59
69
|
import { createHostMetricsSampler } from "./host-metrics.js";
|
|
60
70
|
import { SchedulerStore } from "./scheduler-tasks.js";
|
|
61
71
|
import { initHttpProxy } from "./http-proxy.js";
|
|
@@ -68,6 +78,7 @@ import { handleFileMessage, handleScmMessage, handleBgServerMessage, handlePrese
|
|
|
68
78
|
import { RemoteSshService, isRemoteWorkspaceUri, serveRemoteWorkspaceFile, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
|
|
69
79
|
import { handlePluginMessage } from "./dispatch-plugin-handlers.js";
|
|
70
80
|
import { CanvasOrchestrator } from "./canvas/canvas-orchestrator.js";
|
|
81
|
+
import { executeScheduledCanvas, validateScheduledCanvas } from "./canvas/canvas-scheduled-task.js";
|
|
71
82
|
import { setCanvasBroadcaster, setCanvasRuntime } from "./canvas/canvas-agent-tool.js";
|
|
72
83
|
import { handleCanvasMessage } from "./canvas/canvas-dispatch.js";
|
|
73
84
|
/** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
|
|
@@ -208,7 +219,10 @@ function buildId() {
|
|
|
208
219
|
if (buildIdCache === null) {
|
|
209
220
|
try {
|
|
210
221
|
const html = readFileSync(join(webDistPath(), "index.html"), "utf8");
|
|
211
|
-
buildIdCache =
|
|
222
|
+
buildIdCache =
|
|
223
|
+
html.match(/<meta\s+name="pi-web-build-id"\s+content="([^"]+)"/)?.[1] ??
|
|
224
|
+
html.match(/(?:\/|\.\/)assets\/index-([A-Za-z0-9_-]+)\.js/)?.[1] ??
|
|
225
|
+
"";
|
|
212
226
|
}
|
|
213
227
|
catch {
|
|
214
228
|
buildIdCache = "";
|
|
@@ -360,84 +374,23 @@ app.get("/api/setup/status", setupGate, (_req, res) => {
|
|
|
360
374
|
});
|
|
361
375
|
});
|
|
362
376
|
app.post("/api/setup/save", setupGate, (req, res) => {
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
let tokenChanged = false;
|
|
367
|
-
if (typeof body.token === "string") {
|
|
368
|
-
const t = body.token.trim();
|
|
369
|
-
if (t)
|
|
370
|
-
next.token = t;
|
|
371
|
-
else
|
|
372
|
-
delete next.token;
|
|
373
|
-
tokenChanged = t !== AUTH_TOKEN;
|
|
374
|
-
AUTH_TOKEN = t;
|
|
375
|
-
}
|
|
376
|
-
const setStr = (key, v, valid, what) => {
|
|
377
|
-
if (v === undefined)
|
|
378
|
-
return true;
|
|
379
|
-
if (typeof v !== "string") {
|
|
380
|
-
res.status(400).json({ ok: false, error: `${what} 必须是字符串` });
|
|
381
|
-
return false;
|
|
382
|
-
}
|
|
383
|
-
const s = v.trim();
|
|
384
|
-
if (s && !valid(s)) {
|
|
385
|
-
res.status(400).json({ ok: false, error: `${what} 格式不合法:${s}` });
|
|
386
|
-
return false;
|
|
387
|
-
}
|
|
388
|
-
if (s)
|
|
389
|
-
next[key] = s;
|
|
390
|
-
else
|
|
391
|
-
delete next[key];
|
|
392
|
-
return true;
|
|
393
|
-
};
|
|
394
|
-
if (!setStr("host", body.host, (s) => /^[A-Za-z0-9.:_-]+$/.test(s) && s.length <= 253, "host"))
|
|
395
|
-
return;
|
|
396
|
-
if (!setStr("allowHosts", body.allowHosts, (s) => /^[A-Za-z0-9.,:_\-\s]+$/.test(s), "allowHosts"))
|
|
397
|
-
return;
|
|
398
|
-
if (!setStr("allowOrigins", body.allowOrigins, (s) => s.length <= 2000, "allowOrigins"))
|
|
377
|
+
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));
|
|
378
|
+
if (!result.ok) {
|
|
379
|
+
res.status(result.status).json({ ok: false, error: result.error });
|
|
399
380
|
return;
|
|
400
|
-
if (body.port !== undefined && body.port !== "" && body.port !== null) {
|
|
401
|
-
const p = Number(body.port);
|
|
402
|
-
if (!Number.isInteger(p) || p <= 0 || p > 65535) {
|
|
403
|
-
res.status(400).json({ ok: false, error: `port 必须是 1-65535:${String(body.port)}` });
|
|
404
|
-
return;
|
|
405
|
-
}
|
|
406
|
-
next.port = p;
|
|
407
|
-
}
|
|
408
|
-
else if (body.port === "") {
|
|
409
|
-
delete next.port;
|
|
410
381
|
}
|
|
411
|
-
|
|
412
|
-
saveServerFileConfig(DATA_DIR, next);
|
|
413
|
-
}
|
|
414
|
-
catch (err) {
|
|
415
|
-
res.status(500).json({ ok: false, error: `写入配置失败:${err.message}` });
|
|
416
|
-
return;
|
|
417
|
-
}
|
|
418
|
-
const norm = (s) => s
|
|
419
|
-
.split(",")
|
|
420
|
-
.map((x) => x.trim().toLowerCase())
|
|
421
|
-
.filter(Boolean)
|
|
422
|
-
.join(",");
|
|
423
|
-
const restartRequired = (typeof body.host === "string" && body.host.trim() !== HOST) ||
|
|
424
|
-
(body.port !== undefined && body.port !== "" && body.port !== null && Number(body.port) !== PORT) ||
|
|
425
|
-
(typeof body.allowHosts === "string" && norm(body.allowHosts) !== ALLOW_HOSTS.join(",")) ||
|
|
426
|
-
(typeof body.allowOrigins === "string" && norm(body.allowOrigins) !== ALLOW_ORIGINS.join(","));
|
|
427
|
-
// 如果设置了新 token,直接给当前回环浏览器下发匹配的 cookie,避免保存后直接 401
|
|
382
|
+
AUTH_TOKEN = result.nextToken;
|
|
428
383
|
if (AUTH_TOKEN) {
|
|
429
|
-
|
|
430
|
-
res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, secure));
|
|
384
|
+
res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, isTlsRequest(req)));
|
|
431
385
|
}
|
|
432
|
-
else if (
|
|
433
|
-
// 清除了 token,同时清理旧 cookie
|
|
386
|
+
else if (result.tokenApplied) {
|
|
434
387
|
res.setHeader("Set-Cookie", [buildPiWebTokenCookie("", 0, false), buildPiWebTokenCookie("", 0, true)]);
|
|
435
388
|
}
|
|
436
389
|
res.json({
|
|
437
390
|
ok: true,
|
|
438
|
-
tokenApplied:
|
|
439
|
-
restartRequired,
|
|
440
|
-
saved:
|
|
391
|
+
tokenApplied: result.tokenApplied,
|
|
392
|
+
restartRequired: result.restartRequired,
|
|
393
|
+
saved: result.saved,
|
|
441
394
|
});
|
|
442
395
|
});
|
|
443
396
|
/** 从请求中提取候选 token:头 / 查询参数 / cookie(浏览器导航场景靠 cookie 续命)。 */
|
|
@@ -510,9 +463,29 @@ function splatParam(req) {
|
|
|
510
463
|
return v.join("/");
|
|
511
464
|
return String(v ?? "");
|
|
512
465
|
}
|
|
466
|
+
/** Preview capabilities authorize only a currently registered live-preview proxy.
|
|
467
|
+
* Forward here, never call next(): capability paths cannot reach any host API. */
|
|
468
|
+
function livePreviewCapability(req) {
|
|
469
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
470
|
+
return undefined;
|
|
471
|
+
const candidate = /^\/__live-preview\/[a-f0-9]{64}(?=\/|$)/.exec(req.path)?.[0];
|
|
472
|
+
if (!candidate)
|
|
473
|
+
return undefined;
|
|
474
|
+
const hit = pluginMgr.findProxy(req.path);
|
|
475
|
+
if (!hit || hit.pluginId !== "live-preview" || !/^\/__live-preview\/[a-f0-9]{64}$/.test(hit.prefix))
|
|
476
|
+
return undefined;
|
|
477
|
+
if (!timingSafeEqual(createHash("sha256").update(candidate).digest(), createHash("sha256").update(hit.prefix).digest()))
|
|
478
|
+
return undefined;
|
|
479
|
+
return hit;
|
|
480
|
+
}
|
|
513
481
|
// 常挂载:本地 /setup 页支持运行时设置/清除口令(AUTH_TOKEN 是 let,热旋转)。
|
|
514
482
|
// 无口令时直接放行,保持原有行为不变。
|
|
515
483
|
app.use((req, res, next) => {
|
|
484
|
+
const preview = livePreviewCapability(req);
|
|
485
|
+
if (preview) {
|
|
486
|
+
proxyHttp(preview, req, res);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
516
489
|
if (!AUTH_TOKEN) {
|
|
517
490
|
next();
|
|
518
491
|
return;
|
|
@@ -554,17 +527,20 @@ app.use((req, res, next) => {
|
|
|
554
527
|
});
|
|
555
528
|
/** 共享客户端持久化存储:双引擎(pi + dsh)共用同一份内存缓存与落盘通道,避免互相覆盖。 */
|
|
556
529
|
const sharedStateStore = new ClientStateStore(join(DATA_DIR, "client-state.json"));
|
|
557
|
-
|
|
530
|
+
registerPromptTemplateRoutes(app, DATA_DIR);
|
|
531
|
+
/** 启动参数显式指定的引擎(--engine pi|dsh|codex|claude|durable 或 PI_WEB_ENGINE)。未显式传则优先读持久化默认引擎。 */
|
|
558
532
|
const EXPLICIT_ENGINE_ARG = cliFlag("--engine") ?? process.env.PI_WEB_ENGINE;
|
|
559
|
-
let currentDefaultEngine = EXPLICIT_ENGINE_ARG === "
|
|
560
|
-
? "
|
|
561
|
-
: EXPLICIT_ENGINE_ARG === "
|
|
562
|
-
? "
|
|
563
|
-
: EXPLICIT_ENGINE_ARG === "
|
|
564
|
-
? "
|
|
565
|
-
: EXPLICIT_ENGINE_ARG === "
|
|
566
|
-
? "
|
|
567
|
-
:
|
|
533
|
+
let currentDefaultEngine = EXPLICIT_ENGINE_ARG === "codex"
|
|
534
|
+
? "codex"
|
|
535
|
+
: EXPLICIT_ENGINE_ARG === "durable"
|
|
536
|
+
? "durable"
|
|
537
|
+
: EXPLICIT_ENGINE_ARG === "claude"
|
|
538
|
+
? "claude"
|
|
539
|
+
: EXPLICIT_ENGINE_ARG === "dsh"
|
|
540
|
+
? "dsh"
|
|
541
|
+
: EXPLICIT_ENGINE_ARG === "pi"
|
|
542
|
+
? "pi"
|
|
543
|
+
: (sharedStateStore.getDefaultEngine() ?? "pi");
|
|
568
544
|
/** 默认引擎标识(兼容 /api/health 等读取)。 */
|
|
569
545
|
/** 每个客户端(浏览器标签页 clientId)当前激活的引擎。支持多标签页同时跑不同引擎 + 零重启热切。 */
|
|
570
546
|
const clientEngines = new Map();
|
|
@@ -599,7 +575,7 @@ const ORIGIN = launchOrigin();
|
|
|
599
575
|
const SERVICE_INFO = toServiceInfo(ORIGIN);
|
|
600
576
|
/** PI_WEB_TABS: the tabs this instance offers. null = all of them, as before. */
|
|
601
577
|
const TABS = parseTabs();
|
|
602
|
-
registerFileTransferRoutes(app, (clientId) => service.get(clientId)?.cwd);
|
|
578
|
+
registerFileTransferRoutes(app, (clientId) => service.get(clientId)?.cwd, undefined, (clientId) => (sharedStateStore.getSettingsSnapshot(clientId).folderUploadMaxMb ?? 32) * 1024 * 1024);
|
|
603
579
|
app.get("/api/health", (_req, res) => {
|
|
604
580
|
// 审查 #352:该端点对未鉴权开放(监控探针需要),故只保留版本/引擎与 SDK
|
|
605
581
|
// 副本诊断信息,不再暴露 cwd(工作区路径披露)与 pid(指纹/信息收集面)。
|
|
@@ -615,6 +591,13 @@ app.get("/api/health", (_req, res) => {
|
|
|
615
591
|
faviconColor: process.env.PI_WEB_FAVICON_COLOR?.trim() || undefined,
|
|
616
592
|
});
|
|
617
593
|
});
|
|
594
|
+
/** Every inline file response is untrusted active content, regardless of MIME.
|
|
595
|
+
* This runs before local/remote dispatch and covers HEAD, Range and 304 too. */
|
|
596
|
+
app.use(["/api/file", "/api/attachment/:hash", "/api/preview"], (req, res, next) => {
|
|
597
|
+
res.setHeader("Content-Security-Policy", req.query.allowJs === "1" ? "sandbox allow-scripts" : "sandbox");
|
|
598
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
599
|
+
next();
|
|
600
|
+
});
|
|
618
601
|
/**
|
|
619
602
|
* 基于 SHA-256 内容寻址的附件静态服务:
|
|
620
603
|
* 永久强缓存(immutable),支持图片和文件读取。
|
|
@@ -622,24 +605,22 @@ app.get("/api/health", (_req, res) => {
|
|
|
622
605
|
app.get("/api/attachment/:hash", async (req, res) => {
|
|
623
606
|
try {
|
|
624
607
|
const hash = String(req.params.hash ?? "").trim();
|
|
625
|
-
const hit = await
|
|
608
|
+
const hit = await findAttachment(hash);
|
|
626
609
|
if (!hit) {
|
|
627
610
|
res.status(404).end("attachment not found");
|
|
628
611
|
return;
|
|
629
612
|
}
|
|
630
613
|
res.setHeader("Content-Type", hit.mimeType);
|
|
631
|
-
res.setHeader("Content-Length", hit.buffer.length);
|
|
632
614
|
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
}
|
|
642
|
-
res.end(hit.buffer);
|
|
615
|
+
// Hash-located attachments may reside under a hidden dataDir (e.g. .pi-web).
|
|
616
|
+
res.sendFile(hit.filePath, { dotfiles: "allow" }, (err) => {
|
|
617
|
+
if (!err)
|
|
618
|
+
return;
|
|
619
|
+
if (!res.headersSent)
|
|
620
|
+
res.status(err.statusCode ?? 500).end();
|
|
621
|
+
else
|
|
622
|
+
res.destroy(err);
|
|
623
|
+
});
|
|
643
624
|
}
|
|
644
625
|
catch (err) {
|
|
645
626
|
res.status(500).end(err.message);
|
|
@@ -687,11 +668,6 @@ app.get("/api/file", async (req, res) => {
|
|
|
687
668
|
}
|
|
688
669
|
const name = basename(abs);
|
|
689
670
|
const isDownload = req.query.download === "1";
|
|
690
|
-
// HTML files preview through a sandboxed <iframe> in the file modal
|
|
691
|
-
// (FilePreview.tsx). They are text as far as previewKind goes, so
|
|
692
|
-
// allowlist them explicitly here.
|
|
693
|
-
const lower = name.toLowerCase();
|
|
694
|
-
const isHtmlPreview = lower.endsWith(".html") || lower.endsWith(".htm") || lower.endsWith(".xhtml");
|
|
695
671
|
const st = await stat(abs);
|
|
696
672
|
if (!st.isFile()) {
|
|
697
673
|
res.status(400).end("not a file");
|
|
@@ -708,26 +684,6 @@ app.get("/api/file", async (req, res) => {
|
|
|
708
684
|
res.download(abs, name, { dotfiles: "allow" });
|
|
709
685
|
}
|
|
710
686
|
else {
|
|
711
|
-
if (isHtmlPreview) {
|
|
712
|
-
// Sandbox even a top-level navigation to this URL: a workspace
|
|
713
|
-
// HTML file must never get our origin (it could otherwise read
|
|
714
|
-
// the token cookie). The modal iframe carries its own sandbox
|
|
715
|
-
// attribute as well (defense in depth).
|
|
716
|
-
//
|
|
717
|
-
// ?allowJs=1 is the explicit per-file opt-in from the preview
|
|
718
|
-
// modal ("启用脚本"): scripts run, but still in an opaque
|
|
719
|
-
// origin — no DOM/cookie/storage access to our app, no forms,
|
|
720
|
-
// no top-navigation. NEVER add allow-same-origin here.
|
|
721
|
-
const allowJs = req.query.allowJs === "1";
|
|
722
|
-
res.setHeader("Content-Security-Policy", allowJs ? "sandbox allow-scripts" : "sandbox");
|
|
723
|
-
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
724
|
-
}
|
|
725
|
-
else if (lower.endsWith(".svg")) {
|
|
726
|
-
// 与 /api/attachment 同理:SVG 文档形态的 <script> 沙箱化
|
|
727
|
-
// (审查 #352 P0-1),<img> 内嵌用法不受影响。
|
|
728
|
-
res.setHeader("Content-Security-Policy", "sandbox");
|
|
729
|
-
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
730
|
-
}
|
|
731
687
|
res.sendFile(abs, { dotfiles: "allow" });
|
|
732
688
|
}
|
|
733
689
|
}
|
|
@@ -864,22 +820,11 @@ app.get("/api/preview/*splat", async (req, res) => {
|
|
|
864
820
|
}
|
|
865
821
|
abs = wp.abs;
|
|
866
822
|
}
|
|
867
|
-
const name = basename(abs);
|
|
868
823
|
const st = await stat(abs);
|
|
869
824
|
if (!st.isFile()) {
|
|
870
825
|
res.status(400).end("not a file");
|
|
871
826
|
return;
|
|
872
827
|
}
|
|
873
|
-
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
874
|
-
const lower = name.toLowerCase();
|
|
875
|
-
if (lower.endsWith(".html") || lower.endsWith(".htm") || lower.endsWith(".xhtml")) {
|
|
876
|
-
const allowJs = req.query.allowJs === "1";
|
|
877
|
-
res.setHeader("Content-Security-Policy", allowJs ? "sandbox allow-scripts" : "sandbox");
|
|
878
|
-
}
|
|
879
|
-
else if (lower.endsWith(".svg")) {
|
|
880
|
-
// 与 /api/attachment 同理:SVG 文档形态的 <script> 沙箱化(审查 #352 P0-1)。
|
|
881
|
-
res.setHeader("Content-Security-Policy", "sandbox");
|
|
882
|
-
}
|
|
883
828
|
res.sendFile(abs, { dotfiles: "allow" });
|
|
884
829
|
}
|
|
885
830
|
catch {
|
|
@@ -1001,69 +946,17 @@ const PLUGINS_DIR = join(DATA_DIR, "plugins");
|
|
|
1001
946
|
app.all(["/plugins-api/:id/*splat", "/plugins-api/:id"], (req, res) => {
|
|
1002
947
|
// 多段子路径的 splat 是数组(见 splatParam),拼回 "/" 后再交插件路由。
|
|
1003
948
|
const rest = splatParam(req);
|
|
1004
|
-
|
|
949
|
+
const cid = typeof req.query.clientId === "string" ? req.query.clientId : "";
|
|
950
|
+
const cs = cid ? service.get(cid) : undefined;
|
|
951
|
+
if (cid && !cs) {
|
|
952
|
+
res.status(400).json({ error: "Unknown client workspace" });
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
pluginMgr.handleHttp(String(req.params.id ?? ""), req.method, rest, req, res, cs ? { cwd: cs.cwd, roots: cs.workspaceRoots } : undefined);
|
|
1005
956
|
});
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
fwd = `/${fwd}`;
|
|
1010
|
-
return fwd || "/";
|
|
1011
|
-
}
|
|
1012
|
-
function proxyHttp(hit, req, res) {
|
|
1013
|
-
const fwdPath = proxyForwardPath(hit, req.url ?? "/");
|
|
1014
|
-
const headers = {};
|
|
1015
|
-
for (const [k, v] of Object.entries(req.headers)) {
|
|
1016
|
-
if (v === undefined)
|
|
1017
|
-
continue;
|
|
1018
|
-
if (k.toLowerCase() === "host")
|
|
1019
|
-
continue;
|
|
1020
|
-
if (k.toLowerCase() === "content-length" && req.method !== "GET" && req.method !== "HEAD")
|
|
1021
|
-
continue;
|
|
1022
|
-
headers[k] = v;
|
|
1023
|
-
}
|
|
1024
|
-
// 内页拼 SSE/资源绝对地址用(子路径反代下 import.meta 推导不到前缀,靠这个头)。
|
|
1025
|
-
headers["x-pi-proxy-prefix"] = hit.prefix;
|
|
1026
|
-
let body;
|
|
1027
|
-
if (req.method !== "GET" && req.method !== "HEAD" && req.body !== undefined) {
|
|
1028
|
-
const b = req.body;
|
|
1029
|
-
if (Buffer.isBuffer(b))
|
|
1030
|
-
body = b;
|
|
1031
|
-
else if (typeof b === "string")
|
|
1032
|
-
body = Buffer.from(b);
|
|
1033
|
-
else if (b !== undefined) {
|
|
1034
|
-
body = Buffer.from(JSON.stringify(b));
|
|
1035
|
-
if (!headers["content-type"])
|
|
1036
|
-
headers["content-type"] = "application/json";
|
|
1037
|
-
}
|
|
1038
|
-
if (body)
|
|
1039
|
-
headers["content-length"] = String(body.length);
|
|
1040
|
-
}
|
|
1041
|
-
const up = proxyRequest({ host: hit.host, port: hit.port, method: req.method, path: fwdPath, headers, timeout: 30000 }, (upRes) => {
|
|
1042
|
-
const out = {};
|
|
1043
|
-
for (const [k, v] of Object.entries(upRes.headers)) {
|
|
1044
|
-
if (v === undefined)
|
|
1045
|
-
continue;
|
|
1046
|
-
const lk = k.toLowerCase();
|
|
1047
|
-
if (lk === "connection" || lk === "keep-alive" || lk === "transfer-encoding" || lk === "upgrade")
|
|
1048
|
-
continue;
|
|
1049
|
-
out[k] = v;
|
|
1050
|
-
}
|
|
1051
|
-
res.writeHead(upRes.statusCode ?? 502, out);
|
|
1052
|
-
upRes.pipe(res);
|
|
1053
|
-
});
|
|
1054
|
-
up.on("timeout", () => up.destroy(new Error("proxy timeout")));
|
|
1055
|
-
up.on("error", (err) => {
|
|
1056
|
-
console.error(`[proxy:${hit.prefix}] → 127.0.0.1:${hit.port}${fwdPath} failed:`, err);
|
|
1057
|
-
if (!res.headersSent)
|
|
1058
|
-
res.status(502).end("proxy target unreachable");
|
|
1059
|
-
else
|
|
1060
|
-
res.end();
|
|
1061
|
-
});
|
|
1062
|
-
if (body)
|
|
1063
|
-
up.end(body);
|
|
1064
|
-
else
|
|
1065
|
-
req.pipe(up);
|
|
1066
|
-
}
|
|
957
|
+
/** 通用插件代理(host.registerProxy 注册的前缀落到这里):去前缀后原样透传到
|
|
958
|
+
* 127.0.0.1:port——相对路径/Range/SSE 天然可用。PI_WEB_TOKEN 鉴权已在上方覆盖。
|
|
959
|
+
* 必须站在静态资源与 SPA catch-all 之前,否则子路径被 index.html 吞掉。 */
|
|
1067
960
|
app.use((req, res, next) => {
|
|
1068
961
|
const hit = pluginMgr.findProxy(req.path);
|
|
1069
962
|
if (!hit) {
|
|
@@ -1122,6 +1015,61 @@ app.get("/plugins-shared/*splat", (req, res) => {
|
|
|
1122
1015
|
});
|
|
1123
1016
|
/** Set in the env of the replacement child spawned by a self-update restart. */
|
|
1124
1017
|
const RESTART_CHILD_ENV = "PI_WEB_RESTART_CHILD";
|
|
1018
|
+
// Local-only device enrollment stays behind host authentication and ahead of the SPA fallback.
|
|
1019
|
+
const deviceDesktop = createDeviceDesktop({ app, dataDir: DATA_DIR, authorize: (req) => !AUTH_TOKEN || tokenOk(req) });
|
|
1020
|
+
const deviceBots = await createLocalBotRegistry(DATA_DIR);
|
|
1021
|
+
const deviceCenter = await installLocalDeviceCenter({
|
|
1022
|
+
app,
|
|
1023
|
+
dataDir: DATA_DIR,
|
|
1024
|
+
bots: deviceBots,
|
|
1025
|
+
botCatalog: {
|
|
1026
|
+
defaultCwd: CWD,
|
|
1027
|
+
dataDir: DATA_DIR,
|
|
1028
|
+
models: async (signal) => {
|
|
1029
|
+
signal.throwIfAborted();
|
|
1030
|
+
const models = (await piServiceInstance?.pluginClient()?.listLocalBotModels()) ?? [];
|
|
1031
|
+
signal.throwIfAborted();
|
|
1032
|
+
return models;
|
|
1033
|
+
},
|
|
1034
|
+
projects: () => sharedStateStore.getRecentProjects(""),
|
|
1035
|
+
defaultModel: () => sharedStateStore.getDefaultModel("pi"),
|
|
1036
|
+
peekMcpBridge: (cwd) => mcpProjects.peekBridge(cwd),
|
|
1037
|
+
},
|
|
1038
|
+
async connect(config, syncBots) {
|
|
1039
|
+
const localOrigin = `http://127.0.0.1:${PORT}`;
|
|
1040
|
+
const runtime = createDeviceRuntime({
|
|
1041
|
+
config,
|
|
1042
|
+
localOrigin,
|
|
1043
|
+
localAuthToken: AUTH_TOKEN,
|
|
1044
|
+
dataDir: DATA_DIR,
|
|
1045
|
+
bots: deviceBots,
|
|
1046
|
+
});
|
|
1047
|
+
setDeviceCollabService(runtime.collabService);
|
|
1048
|
+
const connector = createDeviceConnector({
|
|
1049
|
+
hubUrl: config.hubUrl,
|
|
1050
|
+
deviceId: config.deviceId,
|
|
1051
|
+
credential: config.credential,
|
|
1052
|
+
localOrigin,
|
|
1053
|
+
localAuthToken: AUTH_TOKEN,
|
|
1054
|
+
onTask: runtime.onTask,
|
|
1055
|
+
onConnect: syncBots,
|
|
1056
|
+
onCommand: runtime.onCommand,
|
|
1057
|
+
onDisconnect: () => {
|
|
1058
|
+
void runtime
|
|
1059
|
+
.onDisconnect()
|
|
1060
|
+
.catch(() => console.warn("[device-center] Task stop was not confirmed; project remains locked"));
|
|
1061
|
+
},
|
|
1062
|
+
});
|
|
1063
|
+
return {
|
|
1064
|
+
isConnected: connector.isOnline,
|
|
1065
|
+
async close() {
|
|
1066
|
+
setDeviceCollabService(undefined);
|
|
1067
|
+
connector.close();
|
|
1068
|
+
await runtime.close();
|
|
1069
|
+
},
|
|
1070
|
+
};
|
|
1071
|
+
},
|
|
1072
|
+
});
|
|
1125
1073
|
const webDist = join(pkgRoot, "web", "dist");
|
|
1126
1074
|
/** webDist accessor for buildId() (declared above webDist's const). */
|
|
1127
1075
|
function webDistPath() {
|
|
@@ -1250,6 +1198,8 @@ function originAllowed(req) {
|
|
|
1250
1198
|
return false;
|
|
1251
1199
|
}
|
|
1252
1200
|
httpServer.on("upgrade", (req, socket, head) => {
|
|
1201
|
+
if (deviceDesktop.handleUpgrade(req, socket, head))
|
|
1202
|
+
return;
|
|
1253
1203
|
let pathname = "/";
|
|
1254
1204
|
try {
|
|
1255
1205
|
pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
@@ -1408,12 +1358,13 @@ heartbeatTimer.unref?.();
|
|
|
1408
1358
|
// PI_WEB_ENGINE=durable 时使用 Pi Durable 引擎(server/durable/),
|
|
1409
1359
|
// 默认 pi 引擎。同一 wire 协议,前端无感知(ready/health 携带 engine 字段)。
|
|
1410
1360
|
import { DshAgentService } from "./dsh/dsh-agent-service.js";
|
|
1411
|
-
import { UniversalAgentService, ClaudeCodeDriver, probeClaudeCode } from "./universal/index.js";
|
|
1361
|
+
import { UniversalAgentService, ClaudeCodeDriver, probeClaudeCode, CodexDriver } from "./universal/index.js";
|
|
1412
1362
|
import { DurableAgentService } from "./durable/index.js";
|
|
1413
1363
|
import { probeAllEngines, probeEngine, getCachedEngineStatuses, updateEngineBackground, isEngineUpdating, ENGINE_PACKAGES, } from "./engine-probe.js";
|
|
1414
1364
|
let piServiceInstance = null;
|
|
1415
1365
|
let dshServiceInstance = null;
|
|
1416
1366
|
let claudeServiceInstance = null;
|
|
1367
|
+
let codexServiceInstance = null;
|
|
1417
1368
|
let durableServiceInstance = null;
|
|
1418
1369
|
let wireEngineHooks = null;
|
|
1419
1370
|
let sharedSocketCount = 0;
|
|
@@ -1426,11 +1377,31 @@ function activeEngines() {
|
|
|
1426
1377
|
list.push(dshServiceInstance);
|
|
1427
1378
|
if (claudeServiceInstance)
|
|
1428
1379
|
list.push(claudeServiceInstance);
|
|
1380
|
+
if (codexServiceInstance)
|
|
1381
|
+
list.push(codexServiceInstance);
|
|
1429
1382
|
if (durableServiceInstance)
|
|
1430
1383
|
list.push(durableServiceInstance);
|
|
1431
1384
|
return list;
|
|
1432
1385
|
}
|
|
1433
1386
|
function ensureEngine(engine) {
|
|
1387
|
+
if (engine === "codex") {
|
|
1388
|
+
if (!codexServiceInstance) {
|
|
1389
|
+
codexServiceInstance = new UniversalAgentService({
|
|
1390
|
+
cwd: CWD,
|
|
1391
|
+
dataDir: DATA_DIR,
|
|
1392
|
+
agentDir: getAgentDir(),
|
|
1393
|
+
stateStore: sharedStateStore,
|
|
1394
|
+
engine: "codex",
|
|
1395
|
+
driverFactory: (cwd) => new CodexDriver(cwd),
|
|
1396
|
+
});
|
|
1397
|
+
for (let i = 0; i < sharedSocketCount; i++)
|
|
1398
|
+
codexServiceInstance.noteSocketOpen();
|
|
1399
|
+
if (sharedQuiesced)
|
|
1400
|
+
codexServiceInstance.quiesce();
|
|
1401
|
+
wireEngineHooks?.(codexServiceInstance);
|
|
1402
|
+
}
|
|
1403
|
+
return codexServiceInstance;
|
|
1404
|
+
}
|
|
1434
1405
|
if (engine === "durable") {
|
|
1435
1406
|
if (!durableServiceInstance) {
|
|
1436
1407
|
durableServiceInstance = new DurableAgentService({
|
|
@@ -1612,10 +1583,14 @@ const service = {
|
|
|
1612
1583
|
}
|
|
1613
1584
|
return Promise.resolve();
|
|
1614
1585
|
},
|
|
1615
|
-
|
|
1586
|
+
navigateQuestion(targetId, id) {
|
|
1587
|
+
const targetSvc = ensureEngine(resolveClientEngine(targetId));
|
|
1588
|
+
return targetSvc.navigateQuestion?.(targetId, id) ?? Promise.resolve();
|
|
1589
|
+
},
|
|
1590
|
+
answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason) {
|
|
1616
1591
|
const targetSvc = ensureEngine(resolveClientEngine(targetId));
|
|
1617
1592
|
if (typeof targetSvc.answerElsewhereQuestion === "function") {
|
|
1618
|
-
return targetSvc.answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled);
|
|
1593
|
+
return targetSvc.answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason);
|
|
1619
1594
|
}
|
|
1620
1595
|
return Promise.resolve();
|
|
1621
1596
|
},
|
|
@@ -1814,7 +1789,11 @@ canvasOrchestrator.setBroadcaster((msg) => {
|
|
|
1814
1789
|
// 客户端(chatFromScheduler);单次任务触发后自动删除。DSH 引擎无这俩方法时
|
|
1815
1790
|
// executor 回 not-supported(历史里记失败,不炸进程)。
|
|
1816
1791
|
const scheduler = new SchedulerStore(DATA_DIR, {
|
|
1792
|
+
validateTask: (task) => validateScheduledCanvas(DATA_DIR, task),
|
|
1817
1793
|
executor: async (task) => {
|
|
1794
|
+
if (task.target === "canvas") {
|
|
1795
|
+
return executeScheduledCanvas(DATA_DIR, canvasOrchestrator, task);
|
|
1796
|
+
}
|
|
1818
1797
|
let result;
|
|
1819
1798
|
try {
|
|
1820
1799
|
const svc = ensureEngine("pi");
|
|
@@ -1905,15 +1884,6 @@ const scheduler = new SchedulerStore(DATA_DIR, {
|
|
|
1905
1884
|
catch (err) {
|
|
1906
1885
|
result = { ok: false, error: err.message };
|
|
1907
1886
|
}
|
|
1908
|
-
// 单次任务:触发一次后自动删除(历史随任务一起走,成败已由上面的 notify 播报)。
|
|
1909
|
-
if (task.oneShot) {
|
|
1910
|
-
try {
|
|
1911
|
-
scheduler.remove(task.id);
|
|
1912
|
-
}
|
|
1913
|
-
catch {
|
|
1914
|
-
// 删除失败不影响已记录的执行结果
|
|
1915
|
-
}
|
|
1916
|
-
}
|
|
1917
1887
|
return result;
|
|
1918
1888
|
},
|
|
1919
1889
|
onChange: () => pushSchedulerTasks(),
|
|
@@ -1970,30 +1940,23 @@ function pushNoticeToAll(level, text, textEn) {
|
|
|
1970
1940
|
}
|
|
1971
1941
|
// MCP 工具桥:读取配置启动外部 MCP 服务器(stdio / HTTP streamable-http),把它们的
|
|
1972
1942
|
// 工具并入与插件工具相同的 customTools 管线;单服务器失败不炸进程。
|
|
1973
|
-
const
|
|
1974
|
-
agentDir: getAgentDir(),
|
|
1975
|
-
cwd: CWD,
|
|
1976
|
-
onToolsChanged: () => service.applyPluginAgentTools(),
|
|
1977
|
-
});
|
|
1978
|
-
ClientSession.mcpBridge = mcpBridge;
|
|
1979
|
-
pluginMgr.mcpBridge = mcpBridge;
|
|
1980
|
-
// mcp.json 热加载:保存文件即生效,改完不必再重启服务。两半都在这里收口 —— reload 换入
|
|
1981
|
-
// 新的服务器集合(只重启规格真变了的),applyPluginAgentTools 把新工具推给已有会话。
|
|
1982
|
-
const mcpHotReload = createMcpHotReload({
|
|
1943
|
+
const mcpProjects = new McpProjectRuntimeRegistry({
|
|
1983
1944
|
dataDir: DATA_DIR,
|
|
1945
|
+
isProjectInUse: (cwd) => {
|
|
1946
|
+
const key = (value) => (process.platform === "win32" ? resolve(value).toLowerCase() : resolve(value));
|
|
1947
|
+
return activeEngines().some((svc) => svc.mcpProjectCwds?.().some((project) => key(project) === key(cwd)));
|
|
1948
|
+
},
|
|
1984
1949
|
agentDir: getAgentDir(),
|
|
1985
|
-
|
|
1986
|
-
reload: () => mcpBridge.reload(),
|
|
1987
|
-
onToolsChanged: () => service.applyPluginAgentTools(),
|
|
1988
|
-
onNotice: (level, text, textEn) => pushNoticeToAll(level, text, textEn),
|
|
1989
|
-
log: (...a) => console.log(...a),
|
|
1990
|
-
});
|
|
1991
|
-
void mcpBridge.load().then(() => {
|
|
1992
|
-
if (mcpBridge.getTools().length)
|
|
1950
|
+
onToolsChanged: (cwd) => {
|
|
1993
1951
|
service.applyPluginAgentTools();
|
|
1994
|
-
|
|
1995
|
-
|
|
1952
|
+
for (const svc of activeEngines())
|
|
1953
|
+
svc.refreshMcpProject?.(cwd);
|
|
1954
|
+
},
|
|
1955
|
+
onNotice: (_cwd, level, text, textEn) => pushNoticeToAll(level, text, textEn),
|
|
1956
|
+
log: (...a) => console.log("[mcp]", ...a),
|
|
1996
1957
|
});
|
|
1958
|
+
ClientSession.mcpProjects = mcpProjects;
|
|
1959
|
+
pluginMgr.mcpProjects = mcpProjects;
|
|
1997
1960
|
// 插件与宿主钩子统一挂载器:无论引擎在启动时预热还是运行期按需懒加载,都一致注入全部回调。
|
|
1998
1961
|
wireEngineHooks = (svc) => {
|
|
1999
1962
|
svc.onToolEvent = (ev) => pluginMgr.emitToolEvent(ev);
|
|
@@ -2004,7 +1967,7 @@ wireEngineHooks = (svc) => {
|
|
|
2004
1967
|
svc.onRunEvent = (ev) => pluginMgr.emitRunEvent(ev);
|
|
2005
1968
|
svc.onConversationChanged = () => pluginMgr.emitConversationChanged();
|
|
2006
1969
|
svc.onClientModelChanged = (snap) => pluginMgr.emitClientModelChanged(snap);
|
|
2007
|
-
svc.pluginToolsProvider = () => [...pluginMgr.getAgentTools(), ...
|
|
1970
|
+
svc.pluginToolsProvider = (cwd) => [...pluginMgr.getAgentTools(), ...(cwd ? mcpProjects.getTools(cwd) : [])];
|
|
2008
1971
|
svc.pluginCommandsProvider = () => pluginMgr.listCommands();
|
|
2009
1972
|
svc.pluginBgTasksProvider = () => pluginMgr.bgTasks();
|
|
2010
1973
|
svc.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
|
|
@@ -2125,6 +2088,11 @@ pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
|
|
|
2125
2088
|
// runAborter:有现成 abort 路径(interruptRun,卡住/空转强制重置语义继承)。
|
|
2126
2089
|
pm.runAborter = async (id) => {
|
|
2127
2090
|
try {
|
|
2091
|
+
if (id.startsWith("pr-")) {
|
|
2092
|
+
if (!piServiceInstance)
|
|
2093
|
+
return { ok: false, error: "not supported" };
|
|
2094
|
+
return await piServiceInstance.abortPluginRun(id);
|
|
2095
|
+
}
|
|
2128
2096
|
const cs = pickClient();
|
|
2129
2097
|
if (!cs || typeof cs.abortForPlugins !== "function")
|
|
2130
2098
|
return { ok: false, error: "not supported" };
|
|
@@ -2237,10 +2205,15 @@ wss.on("connection", (ws) => {
|
|
|
2237
2205
|
service.noteSocketOpen();
|
|
2238
2206
|
let clientId = null;
|
|
2239
2207
|
let closed = false;
|
|
2208
|
+
const helloTimer = setTimeout(() => {
|
|
2209
|
+
if (!clientId)
|
|
2210
|
+
ws.close(1008, "Handshake timed out");
|
|
2211
|
+
}, 15_000);
|
|
2212
|
+
helloTimer.unref?.();
|
|
2240
2213
|
/** 最近一份全量 snapshot 的估算字节数(UTF-16 ×2),供背压相对阈值用(issue #11)。 */
|
|
2241
2214
|
let lastSnapshotBytes = 0;
|
|
2242
2215
|
/** Commands received while the session is still being created — replayed after attach.
|
|
2243
|
-
*
|
|
2216
|
+
* 按条数和累计字节限制;超限关闭连接,避免静默丢弃已接收的命令。 */
|
|
2244
2217
|
const pending = new PendingCommandQueue();
|
|
2245
2218
|
/** attach 完成(含插件链 + 首快照)前一律排队(见 hello 分支的 replayQueued):
|
|
2246
2219
|
* ready 先行后,ready 只代表传输通,插件命令目录/首快照都还没好,直接分发
|
|
@@ -2306,7 +2279,13 @@ wss.on("connection", (ws) => {
|
|
|
2306
2279
|
// Plugins broadcast to every open socket; unregister on close below.
|
|
2307
2280
|
// Plugins broadcast to every open socket; unregister on close below. The
|
|
2308
2281
|
// cid getter lets plugins target THIS socket via host.sendTo(clientId).
|
|
2309
|
-
const removePluginSender = pluginMgr.addSender(
|
|
2282
|
+
const removePluginSender = pluginMgr.addSender((msg) => {
|
|
2283
|
+
// Task sockets receive only their executor/session events. Global plugin
|
|
2284
|
+
// notices have no session attribution and must not abort unrelated tasks.
|
|
2285
|
+
if (!clientId || clientId.startsWith("device-task-"))
|
|
2286
|
+
return;
|
|
2287
|
+
send(msg);
|
|
2288
|
+
}, () => clientId);
|
|
2310
2289
|
/** DOM 授权落盘 + notice 反馈(两步握手的 grant 与单步 revoke 共用收尾)。
|
|
2311
2290
|
* cs 缺席(未 attach 完成)时只落盘不提示——消息本来就会在 attach 前排队。 */
|
|
2312
2291
|
const applyDomConsent = (pluginId, granted) => {
|
|
@@ -2324,21 +2303,23 @@ wss.on("connection", (ws) => {
|
|
|
2324
2303
|
.catch(() => { });
|
|
2325
2304
|
};
|
|
2326
2305
|
const handleSwitchEngine = async (msg) => {
|
|
2327
|
-
const targetEngine = msg.engine === "
|
|
2328
|
-
? "
|
|
2329
|
-
: msg.engine === "
|
|
2330
|
-
? "
|
|
2331
|
-
: msg.engine === "
|
|
2332
|
-
? "
|
|
2333
|
-
: msg.engine === "
|
|
2334
|
-
? "
|
|
2335
|
-
:
|
|
2306
|
+
const targetEngine = msg.engine === "codex"
|
|
2307
|
+
? "codex"
|
|
2308
|
+
: msg.engine === "durable"
|
|
2309
|
+
? "durable"
|
|
2310
|
+
: msg.engine === "claude"
|
|
2311
|
+
? "claude"
|
|
2312
|
+
: msg.engine === "dsh"
|
|
2313
|
+
? "dsh"
|
|
2314
|
+
: msg.engine === "pi"
|
|
2315
|
+
? "pi"
|
|
2316
|
+
: null;
|
|
2336
2317
|
if (!targetEngine) {
|
|
2337
2318
|
send({
|
|
2338
2319
|
type: "notice",
|
|
2339
2320
|
level: "error",
|
|
2340
|
-
text: `无效的引擎类型:${String(msg.engine)}(仅支持 pi / dsh / claude / durable)`,
|
|
2341
|
-
textEn: `Invalid engine "${String(msg.engine)}" (supported: pi, dsh, claude, durable)`,
|
|
2321
|
+
text: `无效的引擎类型:${String(msg.engine)}(仅支持 pi / dsh / codex / claude / durable)`,
|
|
2322
|
+
textEn: `Invalid engine "${String(msg.engine)}" (supported: pi, dsh, codex, claude, durable)`,
|
|
2342
2323
|
});
|
|
2343
2324
|
return;
|
|
2344
2325
|
}
|
|
@@ -2482,6 +2463,7 @@ wss.on("connection", (ws) => {
|
|
|
2482
2463
|
pi: { zh: "Pi", en: "Pi" },
|
|
2483
2464
|
dsh: { zh: "DSH", en: "DSH" },
|
|
2484
2465
|
claude: { zh: "Claude Code", en: "Claude Code" },
|
|
2466
|
+
codex: { zh: "Codex", en: "Codex" },
|
|
2485
2467
|
durable: { zh: "Pi Durable", en: "Pi Durable" },
|
|
2486
2468
|
};
|
|
2487
2469
|
const displayName = engineDisplayNames[targetEngine] ?? {
|
|
@@ -2530,9 +2512,10 @@ wss.on("connection", (ws) => {
|
|
|
2530
2512
|
});
|
|
2531
2513
|
}
|
|
2532
2514
|
};
|
|
2533
|
-
const dispatch = (msg) => {
|
|
2515
|
+
const dispatch = (msg, wireBytes) => {
|
|
2534
2516
|
if (!clientId) {
|
|
2535
|
-
pending.push(msg)
|
|
2517
|
+
if (!pending.push(msg, wireBytes))
|
|
2518
|
+
ws.close(1009, "Pending command budget exceeded");
|
|
2536
2519
|
return;
|
|
2537
2520
|
}
|
|
2538
2521
|
// switch_engine 为宿主级控制消息:豁免 cs 初始化与 attachDone 门禁,确保任何异常状态下都能自由切回!
|
|
@@ -2554,7 +2537,8 @@ wss.on("connection", (ws) => {
|
|
|
2554
2537
|
const cs = service.get(clientId);
|
|
2555
2538
|
if (!cs || !attachDone) {
|
|
2556
2539
|
// Session not ready yet (hello processing / plugin chain) — hold the command.
|
|
2557
|
-
pending.push(msg)
|
|
2540
|
+
if (!pending.push(msg, wireBytes))
|
|
2541
|
+
ws.close(1009, "Pending command budget exceeded");
|
|
2558
2542
|
return;
|
|
2559
2543
|
}
|
|
2560
2544
|
// 历史窗口按需加载:连接级窗口化直接服务(四个引擎通吃,不依赖引擎实现)。
|
|
@@ -2566,6 +2550,7 @@ wss.on("connection", (ws) => {
|
|
|
2566
2550
|
conversationId: msg.conversationId,
|
|
2567
2551
|
beforeId: msg.beforeId,
|
|
2568
2552
|
before: msg.before,
|
|
2553
|
+
historyGeneration: msg.historyGeneration,
|
|
2569
2554
|
});
|
|
2570
2555
|
if (!handled && cs) {
|
|
2571
2556
|
const activeId = typeof cs.activeConversationId === "function" ? cs.activeConversationId() : undefined;
|
|
@@ -2579,6 +2564,7 @@ wss.on("connection", (ws) => {
|
|
|
2579
2564
|
conversationId: convId,
|
|
2580
2565
|
beforeId: msg.beforeId,
|
|
2581
2566
|
before: msg.before,
|
|
2567
|
+
historyGeneration: msg.historyGeneration,
|
|
2582
2568
|
});
|
|
2583
2569
|
}
|
|
2584
2570
|
if (!handled && (!msg.conversationId || msg.conversationId === activeId)) {
|
|
@@ -2609,7 +2595,7 @@ wss.on("connection", (ws) => {
|
|
|
2609
2595
|
return;
|
|
2610
2596
|
if (handleTerminalMessage(msg, cs))
|
|
2611
2597
|
return;
|
|
2612
|
-
if (handleSessionLifecycleMessage(msg, cs))
|
|
2598
|
+
if (handleSessionLifecycleMessage(msg, cs, send))
|
|
2613
2599
|
return;
|
|
2614
2600
|
if (handlePlanAndGoalMessage(msg, cs))
|
|
2615
2601
|
return;
|
|
@@ -2617,7 +2603,7 @@ wss.on("connection", (ws) => {
|
|
|
2617
2603
|
return;
|
|
2618
2604
|
if (handleRemoteSshMessage(msg, remoteSshService, send))
|
|
2619
2605
|
return;
|
|
2620
|
-
if (handleSettingsMessage(msg, cs))
|
|
2606
|
+
if (handleSettingsMessage(msg, cs, send))
|
|
2621
2607
|
return;
|
|
2622
2608
|
if (handleCanvasMessage(msg, DATA_DIR, canvasOrchestrator, send, { runBase: cs.cwd }))
|
|
2623
2609
|
return;
|
|
@@ -2645,6 +2631,20 @@ wss.on("connection", (ws) => {
|
|
|
2645
2631
|
return;
|
|
2646
2632
|
switch (msg.type) {
|
|
2647
2633
|
case "prompt": {
|
|
2634
|
+
// No await between identity validation and prompt(): engines capture
|
|
2635
|
+
// their conversation synchronously at entry.
|
|
2636
|
+
if (msg.targetConversationId !== undefined &&
|
|
2637
|
+
(typeof msg.targetConversationId !== "string" ||
|
|
2638
|
+
!msg.targetConversationId ||
|
|
2639
|
+
cs.activeConversationId?.() !== msg.targetConversationId)) {
|
|
2640
|
+
send({
|
|
2641
|
+
type: "notice",
|
|
2642
|
+
level: "warning",
|
|
2643
|
+
text: "发送已取消:目标对话已改变,请重新发送。",
|
|
2644
|
+
textEn: "Prompt canceled: the target conversation changed. Please send again.",
|
|
2645
|
+
});
|
|
2646
|
+
break;
|
|
2647
|
+
}
|
|
2648
2648
|
const hasAttach = Boolean(msg.attachments && msg.attachments.length > 0);
|
|
2649
2649
|
if (!msg.text?.trim() && !hasAttach) {
|
|
2650
2650
|
send({
|
|
@@ -2670,7 +2670,7 @@ wss.on("connection", (ws) => {
|
|
|
2670
2670
|
void cs.abort();
|
|
2671
2671
|
break;
|
|
2672
2672
|
case "abort_bash":
|
|
2673
|
-
void cs.abortBash();
|
|
2673
|
+
void cs.abortBash(msg.conversationId);
|
|
2674
2674
|
break;
|
|
2675
2675
|
case "retry_last":
|
|
2676
2676
|
void cs.retryLast();
|
|
@@ -2716,6 +2716,10 @@ wss.on("connection", (ws) => {
|
|
|
2716
2716
|
});
|
|
2717
2717
|
}
|
|
2718
2718
|
break;
|
|
2719
|
+
case "navigate_question":
|
|
2720
|
+
if (typeof service.navigateQuestion === "function")
|
|
2721
|
+
void service.navigateQuestion(clientId, msg.id);
|
|
2722
|
+
break;
|
|
2719
2723
|
case "peek_elsewhere_question":
|
|
2720
2724
|
if (typeof service.peekElsewhereQuestion === "function") {
|
|
2721
2725
|
void service.peekElsewhereQuestion(clientId, msg.owner, msg.id);
|
|
@@ -2827,14 +2831,38 @@ wss.on("connection", (ws) => {
|
|
|
2827
2831
|
ws.on("message", (data) => {
|
|
2828
2832
|
tracked.isAlive = true;
|
|
2829
2833
|
tracked.missedPings = 0;
|
|
2830
|
-
|
|
2834
|
+
const wireBytes = Array.isArray(data) ? data.reduce((n, chunk) => n + chunk.length, 0) : data.byteLength;
|
|
2835
|
+
if (!clientId && wireBytes > MAX_PRE_HELLO_WS_BYTES) {
|
|
2836
|
+
ws.close(1009, "Handshake message too large");
|
|
2837
|
+
return;
|
|
2838
|
+
}
|
|
2839
|
+
let parsed;
|
|
2840
|
+
try {
|
|
2841
|
+
parsed = JSON.parse(data.toString());
|
|
2842
|
+
}
|
|
2843
|
+
catch {
|
|
2844
|
+
return;
|
|
2845
|
+
}
|
|
2846
|
+
if (!isClientMessageEnvelope(parsed))
|
|
2847
|
+
return;
|
|
2848
|
+
if (!isClientMessageWithinByteLimit(parsed.type, wireBytes, !!clientId)) {
|
|
2849
|
+
ws.close(1009, "Message budget exceeded");
|
|
2850
|
+
return;
|
|
2851
|
+
}
|
|
2852
|
+
const msg = parsed;
|
|
2831
2853
|
try {
|
|
2832
|
-
|
|
2854
|
+
const botClientId = clientId ?? (msg.type === "hello" ? msg.clientId : undefined);
|
|
2855
|
+
if (botClientId && !botExecutionMessageAllowed(botClientId, msg.type)) {
|
|
2856
|
+
ws.close(1008, "Bot control command denied");
|
|
2857
|
+
return;
|
|
2858
|
+
}
|
|
2833
2859
|
}
|
|
2834
2860
|
catch {
|
|
2861
|
+
ws.close(1008, "Invalid Bot execution capability");
|
|
2835
2862
|
return;
|
|
2836
2863
|
}
|
|
2837
2864
|
if (msg.type === "hello") {
|
|
2865
|
+
clearTimeout(helloTimer);
|
|
2838
2866
|
// 重放守卫:一条连接只允许 attach 一次。clientId 已赋值说明 hello 处理过
|
|
2839
2867
|
//(或进行中),再来的 hello 幂等回一条 ready 即可——否则重复 hello 会把
|
|
2840
2868
|
// service.attach 整个再跑一遍:重型 ClientSession 重复创建 + 旧 send sink
|
|
@@ -3026,9 +3054,10 @@ wss.on("connection", (ws) => {
|
|
|
3026
3054
|
});
|
|
3027
3055
|
return;
|
|
3028
3056
|
}
|
|
3029
|
-
dispatch(msg);
|
|
3057
|
+
dispatch(msg, wireBytes);
|
|
3030
3058
|
});
|
|
3031
3059
|
ws.on("close", () => {
|
|
3060
|
+
clearTimeout(helloTimer);
|
|
3032
3061
|
service.noteSocketClose();
|
|
3033
3062
|
closed = true;
|
|
3034
3063
|
pending.clear();
|
|
@@ -3218,12 +3247,13 @@ async function shutdown(signal = "SIGINT") {
|
|
|
3218
3247
|
let code = 0;
|
|
3219
3248
|
try {
|
|
3220
3249
|
clearInterval(heartbeatTimer);
|
|
3250
|
+
await deviceCenter.close();
|
|
3251
|
+
await deviceDesktop.close();
|
|
3221
3252
|
stopControl();
|
|
3222
3253
|
scheduler.stop();
|
|
3223
3254
|
pluginMgr.dispose();
|
|
3224
3255
|
pluginInstaller.dispose();
|
|
3225
|
-
|
|
3226
|
-
mcpBridge.dispose();
|
|
3256
|
+
await mcpProjects.dispose();
|
|
3227
3257
|
await globalLspPool.shutdownAll();
|
|
3228
3258
|
await service.disposeAll();
|
|
3229
3259
|
// Don't let dead browsers hold the exit open: half-open WebSocket /
|