pi-web-ui 0.110.0 → 0.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +92 -7
  3. package/dist/server/agent-formatters.js +10 -6
  4. package/dist/server/agent-service-daemon.js +27 -9
  5. package/dist/server/agent-service.js +1442 -489
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/attachments.js +114 -31
  11. package/dist/server/canvas/canvas-agent-tool.js +593 -0
  12. package/dist/server/canvas/canvas-cards.js +144 -0
  13. package/dist/server/canvas/canvas-dispatch.js +155 -0
  14. package/dist/server/canvas/canvas-orchestrator.js +1094 -0
  15. package/dist/server/canvas/canvas-store.js +260 -0
  16. package/dist/server/client-id-utils.js +2 -2
  17. package/dist/server/client-state.js +52 -0
  18. package/dist/server/context-budget.js +6 -3
  19. package/dist/server/delegate-mode.js +6 -3
  20. package/dist/server/delegate-task.js +18 -3
  21. package/dist/server/dispatch-domain-handlers.js +3 -0
  22. package/dist/server/dsh/dsh-agent-service.js +357 -20
  23. package/dist/server/dsh/dsh-client.js +10 -1
  24. package/dist/server/dsh/dsh-serialize.js +1 -1
  25. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  26. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  27. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  28. package/dist/server/durable/durable-agent-service.js +3 -0
  29. package/dist/server/durable/durable-driver.js +75 -9
  30. package/dist/server/durable/durable-loader.js +1 -14
  31. package/dist/server/durable/durable-models.js +107 -0
  32. package/dist/server/durable/index.js +0 -4
  33. package/dist/server/engine-probe.js +76 -37
  34. package/dist/server/eval-tool.js +28 -3
  35. package/dist/server/file-transfer-routes.js +8 -2
  36. package/dist/server/files-service.js +10 -2
  37. package/dist/server/goal-service.js +7 -0
  38. package/dist/server/index.js +480 -59
  39. package/dist/server/json-utils.js +57 -0
  40. package/dist/server/marker-service.js +11 -1
  41. package/dist/server/markers/marker.js +45 -4
  42. package/dist/server/markers/registry.js +31 -0
  43. package/dist/server/message-window.js +44 -8
  44. package/dist/server/model-admin.js +68 -106
  45. package/dist/server/model-resolver.js +66 -44
  46. package/dist/server/office-parse.js +394 -7
  47. package/dist/server/plan-manager.js +3 -6
  48. package/dist/server/plugin-api-catalog.js +7 -0
  49. package/dist/server/plugin-assets.js +238 -0
  50. package/dist/server/plugin-facilities.js +22 -0
  51. package/dist/server/plugin-ui-slots.js +1 -0
  52. package/dist/server/plugins.js +296 -25
  53. package/dist/server/preset-fields.js +60 -2
  54. package/dist/server/preset-share.js +8 -2
  55. package/dist/server/prompt-assembler.js +9 -2
  56. package/dist/server/prompt-composer.js +84 -44
  57. package/dist/server/protocol-version.js +1 -1
  58. package/dist/server/queue-utils.js +156 -0
  59. package/dist/server/remote-ssh-service.js +16 -4
  60. package/dist/server/sdk-builtin-extensions.js +85 -0
  61. package/dist/server/server-config.js +66 -0
  62. package/dist/server/session-parser.js +49 -13
  63. package/dist/server/session-search.js +4 -3
  64. package/dist/server/settings-service.js +56 -7
  65. package/dist/server/soft-cap.js +8 -6
  66. package/dist/server/subagent-helpers.js +22 -1
  67. package/dist/server/subagent-notify.js +93 -0
  68. package/dist/server/subagent-security-gate.js +282 -0
  69. package/dist/server/subagent-templates.js +8 -0
  70. package/dist/server/subagents.js +144 -17
  71. package/dist/server/terminals.js +196 -8
  72. package/dist/server/text-quote.js +61 -0
  73. package/dist/server/tool-approval.js +63 -4
  74. package/dist/server/tool-guards.js +208 -0
  75. package/dist/server/tool-host-factories.js +46 -10
  76. package/dist/server/tool-manager.js +30 -0
  77. package/dist/server/tool-overrides.js +21 -11
  78. package/dist/server/univer-service.js +448 -0
  79. package/dist/server/universal/driver-base.js +8 -0
  80. package/dist/server/universal/drivers/claude-code.js +39 -5
  81. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  82. package/dist/server/universal/index.js +0 -1
  83. package/dist/server/universal/universal-attachments.js +5 -0
  84. package/dist/server/universal/universal-service.js +5 -0
  85. package/dist/server/universal/universal-session.js +114 -21
  86. package/dist/server/update-check.js +90 -5
  87. package/dist/server/workspace-snapshot.js +33 -2
  88. package/dist/server/worktree-service.js +189 -1
  89. package/docs/dsh-engine.md +493 -0
  90. package/package.json +5 -4
  91. package/plugin-sdk/client-utils.mjs +192 -5
  92. package/plugin-sdk/index.d.ts +80 -1
  93. package/plugin-sdk/index.mjs +99 -0
  94. package/plugin-sdk/package.json +5 -1
  95. package/plugins/catalog.json +33 -0
  96. package/themes/aetheris.css +114 -0
  97. package/themes/bases/obsidian-base.css +216 -0
  98. package/themes/md-preview.css +113 -0
  99. package/themes/wallpaper-flow.css +182 -0
  100. package/web/dist/assets/{TerminalPanel-BHjM6pzY.js → TerminalPanel-Dqr1dK28.js} +2 -2
  101. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  102. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  103. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  104. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  105. package/web/dist/index.html +13 -4
  106. package/web/dist/sw.js +1 -1
  107. package/web/dist/assets/es-DIDZppIF.js +0 -2
  108. package/web/dist/assets/index-DwInT7-a.css +0 -1
  109. package/web/dist/assets/index-GfVFIgIL.js +0 -693
  110. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -20,12 +20,12 @@
20
20
  import "./patch-remote-catalog.js";
21
21
  import "./patch-turn-end-boundary.js";
22
22
  import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
23
- import { stat } from "node:fs/promises";
23
+ import { readFile, stat } from "node:fs/promises";
24
24
  import { createServer, request as proxyRequest } from "node:http";
25
25
  import { createConnection } from "node:net";
26
26
  import { basename, delimiter, join, resolve, sep } from "node:path";
27
27
  import { homedir } from "node:os";
28
- import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
28
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
29
29
  import express from "express";
30
30
  import compression from "compression";
31
31
  import { WebSocket, WebSocketServer } from "ws";
@@ -35,10 +35,11 @@ import { PROTOCOL_VERSION } from "./protocol-version.js";
35
35
  import { AgentService, workspacePath, QuiesceRejectedError, ClientSession } from "./agent-service.js";
36
36
  import { ClientStateStore } from "./client-state.js";
37
37
  import { WS_MAX_PAYLOAD_BYTES, isAbsoluteWirePath, wireToAbs } from "./files-service.js";
38
- import { httpHostAllowed } from "./host-guard.js";
38
+ import { httpHostAllowed, isLoopbackHost, hostWithoutPort } from "./host-guard.js";
39
39
  import { registerFileTransferRoutes } from "./file-transfer-routes.js";
40
40
  import { initAttachmentStore, readAttachment } from "./attachment-store.js";
41
41
  import { isAudioFile, previewKind } from "./text-sniff.js";
42
+ import { isOfficeFile, OFFICE_MAX_FILE_BYTES, unzipFiles } from "./office-parse.js";
42
43
  import { startControlServer } from "./control-socket.js";
43
44
  import { scheduleUploadCleanup } from "./uploads.js";
44
45
  import { ensureWindowsBash, windowsBashDir } from "./ensure-bash.js";
@@ -51,7 +52,7 @@ import { MessageWindowTap, readMessageWindowConfig } from "./message-window.js";
51
52
  import { validateClientId } from "./ws-client-id.js";
52
53
  import { PendingCommandQueue } from "./ws-pending-queue.js";
53
54
  import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, resolveSystemDefaultLocale, unloadServerStrings, } from "./locales.js";
54
- import { PluginManager, resolvePluginClientFile, } from "./plugins.js";
55
+ import { PluginManager, resolvePluginClientFile, resolvePluginSharedFile, } from "./plugins.js";
55
56
  import { confirmPluginInstall, PluginInstaller } from "./plugin-installer.js";
56
57
  import { syncPluginCatalog } from "./plugin-catalog-sync.js";
57
58
  import { McpBridge } from "./mcp-bridge.js";
@@ -61,10 +62,14 @@ import { SchedulerStore } from "./scheduler-tasks.js";
61
62
  import { initHttpProxy } from "./http-proxy.js";
62
63
  import { globalLspPool } from "./lsp-tool.js";
63
64
  import { buildPiWebTokenCookie, decodeCookieToken, isTlsRequest } from "./auth-cookie.js";
65
+ import { isLoopbackAddress, loadServerFileConfig, saveServerFileConfig, tokenWarning } from "./server-config.js";
64
66
  import { getAppVersion, getPkgRoot } from "./pkg-info.js";
65
67
  import { handleFileMessage, handleScmMessage, handleBgServerMessage, handlePresetAndDshMessage, handleModelAndProviderMessage, handleTerminalMessage, handleSessionLifecycleMessage, handlePlanAndGoalMessage, handleScheduleMessage, handleSettingsMessage, handleInteractiveResponseMessage, handleRemoteSshMessage, } from "./dispatch-domain-handlers.js";
66
68
  import { RemoteSshService, isRemoteWorkspaceUri, serveRemoteWorkspaceFile, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
67
69
  import { handlePluginMessage } from "./dispatch-plugin-handlers.js";
70
+ import { CanvasOrchestrator } from "./canvas/canvas-orchestrator.js";
71
+ import { setCanvasBroadcaster, setCanvasRuntime } from "./canvas/canvas-agent-tool.js";
72
+ import { handleCanvasMessage } from "./canvas/canvas-dispatch.js";
68
73
  /** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
69
74
  * `npm_lifecycle_*` into every child). Anything this server spawns — shells,
70
75
  * `pi update` — would otherwise inherit `npm_config_allow_scripts`, which npm
@@ -93,14 +98,6 @@ function cliFlag(name) {
93
98
  }
94
99
  return undefined;
95
100
  }
96
- const PORT = Number(cliFlag("--port") ?? process.env.PI_WEB_PORT ?? 8787);
97
- // #506:直启路径与 bin 层对齐做端口校验——`--port abc` / `PI_WEB_PORT=abc` 之前会
98
- // listen(NaN) 被 Node 当 0 绑到随机端口,且日志打印 http://localhost:NaN。
99
- if (!Number.isInteger(PORT) || PORT <= 0 || PORT > 65535) {
100
- console.error(`无效端口: ${cliFlag("--port") ?? process.env.PI_WEB_PORT} (--port / PI_WEB_PORT)`);
101
- console.error(`Invalid port: ${cliFlag("--port") ?? process.env.PI_WEB_PORT} (--port / PI_WEB_PORT)`);
102
- process.exit(1);
103
- }
104
101
  const CWD = resolve(cliFlag("--cwd") ?? process.env.PI_WEB_CWD ?? process.cwd());
105
102
  const DATA_DIR = resolve(cliFlag("--data-dir") ?? process.env.PI_WEB_DATA_DIR ?? join(homedir(), ".pi-web"));
106
103
  // The data dir is where the control socket, client state, plugins, themes and
@@ -121,6 +118,16 @@ try {
121
118
  catch (err) {
122
119
  console.warn(`[cwd] 无法创建工作区目录 ${CWD}: ${err.message}`);
123
120
  }
121
+ /** 本地 setup 页持久化:<dataDir>/server-config.json(命令行 > 环境变量 > 本文件 > 默认)。 */
122
+ const FILE_CFG = loadServerFileConfig(DATA_DIR);
123
+ const PORT = Number(cliFlag("--port") ?? process.env.PI_WEB_PORT ?? FILE_CFG.port ?? 8787);
124
+ // #506:直启路径与 bin 层对齐做端口校验——`--port abc` / `PI_WEB_PORT=abc` 之前会
125
+ // listen(NaN) 被 Node 当 0 绑到随机端口,且日志打印 http://localhost:NaN。
126
+ if (!Number.isInteger(PORT) || PORT <= 0 || PORT > 65535) {
127
+ console.error(`无效端口: ${cliFlag("--port") ?? process.env.PI_WEB_PORT} (--port / PI_WEB_PORT)`);
128
+ console.error(`Invalid port: ${cliFlag("--port") ?? process.env.PI_WEB_PORT} (--port / PI_WEB_PORT)`);
129
+ process.exit(1);
130
+ }
124
131
  // issue #295:工作区直接就是家目录时,SDK 初始化期的同步目录扫描会落在 $HOME 上
125
132
  // (iCloud 占位符/外部卷坏挂载 → scandir/open 内核挂起 → 事件循环假死,hello 后无
126
133
  // ready)。新装服务默认已是 ~/pi-web-ui(见 bin/pi-web-ui.mjs serviceOptions);
@@ -150,24 +157,33 @@ function readDevNoCacheSetting() {
150
157
  /** Bind address. Default is loopback ONLY — the service is a local personal
151
158
  * tool and should not be reachable from the network unless explicitly asked
152
159
  * (e.g. PI_WEB_HOST=0.0.0.0 for LAN access / Docker port mapping). */
153
- const HOST = cliFlag("--host") ?? process.env.PI_WEB_HOST ?? "127.0.0.1";
160
+ const HOST = cliFlag("--host") ?? process.env.PI_WEB_HOST ?? FILE_CFG.host ?? "127.0.0.1";
154
161
  /** Optional strict hostname allowlist (comma-separated) — only used when set.
155
162
  * Origin / Host same-authority matching happens regardless. */
156
- const ALLOW_HOSTS = (process.env.PI_WEB_ALLOW_HOSTS ?? "")
163
+ const ALLOW_HOSTS = (process.env.PI_WEB_ALLOW_HOSTS ?? FILE_CFG.allowHosts ?? "")
157
164
  .split(",")
158
165
  .map((s) => s.trim().toLowerCase())
159
166
  .filter(Boolean);
160
167
  /** Optional extra Origins allowed through the same-authority check (comma-
161
168
  * separated, e.g. reverse-proxy setups where the browser origin differs
162
169
  * from the Host the backend sees). */
163
- const ALLOW_ORIGINS = (process.env.PI_WEB_ALLOW_ORIGINS ?? "")
170
+ const ALLOW_ORIGINS = (process.env.PI_WEB_ALLOW_ORIGINS ?? FILE_CFG.allowOrigins ?? "")
164
171
  .split(",")
165
172
  .map((s) => s.trim().toLowerCase())
166
173
  .filter(Boolean);
167
174
  /** 可选共享口令(PI_WEB_TOKEN):设置后所有 HTTP/WS 请求必须携带——
168
175
  * Authorization: Bearer / X-PI-Token 头、?token= 查询参数或 pi_web_token cookie
169
176
  * 任一匹配即可;供 0.0.0.0 / 反代等暴露场景兜底,未设置则行为不变。 */
170
- const AUTH_TOKEN = process.env.PI_WEB_TOKEN?.trim() ?? "";
177
+ let AUTH_TOKEN = (process.env.PI_WEB_TOKEN ?? FILE_CFG.token ?? "").trim();
178
+ /** 显式允许非回环地址无 Token 全开放运行(PI_WEB_INSECURE_NO_AUTH=1 / PI_WEB_ALLOW_INSECURE_NO_AUTH=1)。
179
+ * 默认为 false。未显式开启时,监听非回环地址将自动生成随机高强度 Token 实现零信任自愈保护。 */
180
+ const ALLOW_INSECURE_NO_AUTH = /^(1|true|yes)$/i.test(process.env.PI_WEB_INSECURE_NO_AUTH ?? process.env.PI_WEB_ALLOW_INSECURE_NO_AUTH ?? "");
181
+ /** 零信任自愈口令:非回环监听且未配置口令时自动生成,启动日志中输出带 token 的一键登录链接。 */
182
+ let autoGeneratedToken = "";
183
+ if (!isLoopbackHost(HOST) && !AUTH_TOKEN && !ALLOW_INSECURE_NO_AUTH) {
184
+ autoGeneratedToken = randomBytes(24).toString("hex");
185
+ AUTH_TOKEN = autoGeneratedToken;
186
+ }
171
187
  /** 语言包下载根(语言包仓库的 raw 文件地址;版本 tag 优先、main 兜底,见 locales.ts)。 */
172
188
  const LOCALE_BASE_URL = process.env.PI_WEB_LOCALE_BASE_URL?.trim() || "https://raw.githubusercontent.com/xing-shuyin/pi-web-ui";
173
189
  /**
@@ -231,6 +247,175 @@ app.use((req, res, next) => {
231
247
  next();
232
248
  });
233
249
  app.use(express.json({ limit: "10mb" }));
250
+ /**
251
+ * 只能本地访问的配置页(/setup + /api/setup/*)。
252
+ *
253
+ * - 挂在 token 鉴权中间件之前:忘记口令时正是要靠它重设。
254
+ * - 回环地址硬门禁:非 127/8、::1 进来直接 403(反代/局域网打不到)。
255
+ * - token 修改热生效;host/port/allowlist 写文件后需重启服务。
256
+ */
257
+ export function setupGate(req, res, next) {
258
+ // 1. 回环 IP 门禁:TCP 连接必须来自本机
259
+ if (!isLoopbackAddress(req.socket?.remoteAddress)) {
260
+ res.status(403).end("setup page is only available from localhost");
261
+ return;
262
+ }
263
+ // 2. 严禁反代转发:x-forwarded-for / x-real-ip 说明请求来自反代(即使反代在本机回环端口)
264
+ if (req.headers["x-forwarded-for"] || req.headers["x-real-ip"]) {
265
+ res.status(403).end("setup page cannot be accessed through a reverse proxy");
266
+ return;
267
+ }
268
+ // 3. Host 头必须是回环地址(防 DNS rebinding)
269
+ const hostHeader = typeof req.headers.host === "string" ? req.headers.host : "";
270
+ const host = hostWithoutPort(hostHeader);
271
+ if (!host || !isLoopbackHost(host)) {
272
+ res.status(403).end("setup page Host header must be localhost");
273
+ return;
274
+ }
275
+ // 4. Origin 头防跨站(CSRF):若浏览器带了 Origin,必须是回环域
276
+ const origin = typeof req.headers.origin === "string" ? req.headers.origin : "";
277
+ if (origin) {
278
+ try {
279
+ const u = new URL(origin);
280
+ if (!isLoopbackHost(u.hostname)) {
281
+ res.status(403).end("cross-origin setup request rejected");
282
+ return;
283
+ }
284
+ }
285
+ catch {
286
+ res.status(403).end("invalid origin");
287
+ return;
288
+ }
289
+ }
290
+ next();
291
+ }
292
+ const SETUP_PAGE = `<!doctype html><html lang="zh"><head><meta charset="utf-8">
293
+ <meta name="viewport" content="width=device-width,initial-scale=1">
294
+ <title>pi-web-ui 本地配置</title>
295
+ <style>body{font-family:system-ui,sans-serif;max-width:560px;margin:40px auto;padding:0 16px;
296
+ background:#16181d;color:#e6e6e6}label{display:block;margin:14px 0 4px;color:#9aa}input{width:100%;
297
+ box-sizing:border-box;padding:8px;border-radius:6px;border:1px solid #444;background:#222;color:#eee}
298
+ button{margin-top:18px;padding:9px 22px;border:0;border-radius:6px;background:#4c8dff;color:#fff;
299
+ font-size:15px;cursor:pointer}.hint{color:#9aa;font-size:13px;margin-top:4px}#msg{margin-top:14px;
300
+ white-space:pre-wrap}.warn{color:#e0a63c}.ok{color:#6fbf73}.err{color:#e06c6c}</style></head><body>
301
+ <h2>pi-web-ui 本地配置</h2>
302
+ <p class="hint">本页只能在本机打开(回环地址)。token 修改立即生效;监听地址 / 端口 /
303
+ 白名单保存后需重启服务(<code>pi-web-ui server restart</code>)。命令行旗标与环境变量
304
+ 的优先级高于这里的保存值。</p>
305
+ <label>访问口令 token(留空 = 清除)</label><input id="token" type="password" autocomplete="new-password">
306
+ <div class="hint" id="twarn"></div>
307
+ <label>监听地址 host(127.0.0.1 仅本机,0.0.0.0 允许局域网)</label><input id="host">
308
+ <label>端口 port</label><input id="port" inputmode="numeric">
309
+ <label>Host 白名单(逗号分隔,空 = 关闭严格模式)</label><input id="allowHosts">
310
+ <label>额外 Origin 白名单(反代场景,逗号分隔)</label><input id="allowOrigins">
311
+ <div><button id="save">保存</button></div>
312
+ <div id="msg"></div>
313
+ <script>
314
+ const $=id=>document.getElementById(id);
315
+ const msg=(t,c)=>{const m=$("msg");m.className=c||"";m.textContent=t;};
316
+ fetch("/api/setup/status").then(r=>{if(!r.ok)throw new Error(r.status+" "+r.statusText);return r.json();})
317
+ .then(s=>{$("host").value=s.host||"";$("port").value=s.port||"";
318
+ $("allowHosts").value=s.allowHosts||"";$("allowOrigins").value=s.allowOrigins||"";
319
+ $("twarn").textContent=s.tokenSet?("已设置口令"+(s.tokenWarning?":"+s.tokenWarning:"")):"当前未设置口令(本机直连无需口令)";})
320
+ .catch(e=>msg("读取状态失败:"+e.message,"err"));
321
+ $("save").onclick=()=>{msg("保存中…","");
322
+ fetch("/api/setup/save",{method:"POST",headers:{"Content-Type":"application/json"},
323
+ body:JSON.stringify({token:$("token").value,host:$("host").value,port:$("port").value,
324
+ allowHosts:$("allowHosts").value,allowOrigins:$("allowOrigins").value})})
325
+ .then(r=>r.json().then(j=>({st:r.status,j})))
326
+ .then(({st,j})=>{if(!j.ok){msg("保存失败:"+(j.error||st),"err");return;}
327
+ msg((j.restartRequired?"已保存,token 已生效;host/port/白名单需重启服务后生效。"
328
+ :"已保存并生效。")+"\n"+JSON.stringify(j.saved,null,2),"ok");$("token").value="";})
329
+ .catch(e=>msg("请求失败:"+e.message,"err"});};
330
+ </script></body></html>`;
331
+ app.get("/setup", setupGate, (_req, res) => {
332
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
333
+ res.end(SETUP_PAGE);
334
+ });
335
+ app.get("/api/setup/status", setupGate, (_req, res) => {
336
+ res.json({
337
+ ok: true,
338
+ tokenSet: AUTH_TOKEN.length > 0,
339
+ tokenWarning: AUTH_TOKEN ? tokenWarning(AUTH_TOKEN) : "",
340
+ host: HOST,
341
+ port: PORT,
342
+ allowHosts: ALLOW_HOSTS.join(","),
343
+ allowOrigins: ALLOW_ORIGINS.join(","),
344
+ configFile: `${DATA_DIR}/server-config.json`,
345
+ });
346
+ });
347
+ app.post("/api/setup/save", setupGate, (req, res) => {
348
+ const body = (req.body ?? {});
349
+ const prev = loadServerFileConfig(DATA_DIR);
350
+ const next = { ...prev };
351
+ let tokenChanged = false;
352
+ if (typeof body.token === "string") {
353
+ const t = body.token.trim();
354
+ if (t)
355
+ next.token = t;
356
+ else
357
+ delete next.token;
358
+ tokenChanged = t !== AUTH_TOKEN;
359
+ AUTH_TOKEN = t;
360
+ }
361
+ const setStr = (key, v, valid, what) => {
362
+ if (v === undefined)
363
+ return true;
364
+ if (typeof v !== "string") {
365
+ res.status(400).json({ ok: false, error: `${what} 必须是字符串` });
366
+ return false;
367
+ }
368
+ const s = v.trim();
369
+ if (s && !valid(s)) {
370
+ res.status(400).json({ ok: false, error: `${what} 格式不合法:${s}` });
371
+ return false;
372
+ }
373
+ if (s)
374
+ next[key] = s;
375
+ else
376
+ delete next[key];
377
+ return true;
378
+ };
379
+ if (!setStr("host", body.host, (s) => /^[A-Za-z0-9.:_-]+$/.test(s) && s.length <= 253, "host"))
380
+ return;
381
+ if (!setStr("allowHosts", body.allowHosts, (s) => /^[A-Za-z0-9.,:_\-\s]+$/.test(s), "allowHosts"))
382
+ return;
383
+ if (!setStr("allowOrigins", body.allowOrigins, (s) => s.length <= 2000, "allowOrigins"))
384
+ return;
385
+ if (body.port !== undefined && body.port !== "" && body.port !== null) {
386
+ const p = Number(body.port);
387
+ if (!Number.isInteger(p) || p <= 0 || p > 65535) {
388
+ res.status(400).json({ ok: false, error: `port 必须是 1-65535:${String(body.port)}` });
389
+ return;
390
+ }
391
+ next.port = p;
392
+ }
393
+ else if (body.port === "") {
394
+ delete next.port;
395
+ }
396
+ try {
397
+ saveServerFileConfig(DATA_DIR, next);
398
+ }
399
+ catch (err) {
400
+ res.status(500).json({ ok: false, error: `写入配置失败:${err.message}` });
401
+ return;
402
+ }
403
+ const norm = (s) => s
404
+ .split(",")
405
+ .map((x) => x.trim().toLowerCase())
406
+ .filter(Boolean)
407
+ .join(",");
408
+ const restartRequired = (typeof body.host === "string" && body.host.trim() !== HOST) ||
409
+ (body.port !== undefined && body.port !== "" && body.port !== null && Number(body.port) !== PORT) ||
410
+ (typeof body.allowHosts === "string" && norm(body.allowHosts) !== ALLOW_HOSTS.join(",")) ||
411
+ (typeof body.allowOrigins === "string" && norm(body.allowOrigins) !== ALLOW_ORIGINS.join(","));
412
+ res.json({
413
+ ok: true,
414
+ tokenApplied: tokenChanged,
415
+ restartRequired,
416
+ saved: next,
417
+ });
418
+ });
234
419
  /** 从请求中提取候选 token:头 / 查询参数 / cookie(浏览器导航场景靠 cookie 续命)。 */
235
420
  function requestTokens(req) {
236
421
  const out = [];
@@ -301,44 +486,48 @@ function splatParam(req) {
301
486
  return v.join("/");
302
487
  return String(v ?? "");
303
488
  }
304
- if (AUTH_TOKEN) {
489
+ // 常挂载:本地 /setup 页支持运行时设置/清除口令(AUTH_TOKEN 是 let,热旋转)。
490
+ // 无口令时直接放行,保持原有行为不变。
491
+ app.use((req, res, next) => {
492
+ if (!AUTH_TOKEN) {
493
+ next();
494
+ return;
495
+ }
305
496
  // /api/health 保持开放:无敏感信息,容器/监控探针需要它。
306
497
  // 但绝不能因命中 /api/health 就反射下发真实 token cookie(安全漏洞:issue #45)。
307
- app.use((req, res, next) => {
308
- const ok = tokenOk(req);
309
- const cookie = cookieToken(req);
310
- // 浏览器经 ?token= 首次进入后下发 HttpOnly cookie,后续导航/资源请求免带参数。
311
- // 重要:只要请求携带着有效 token(query/header/cookie 任一匹配)就把 cookie 刷新为
312
- // 当前 AUTH_TOKEN——服务端重启改了 PI_WEB_TOKEN 后,旧 cookie 经一次正确的
313
- // ?token= 进入即被重新同步,无需用户清缓存(issue #71)。
314
- // Secure 只在 TLS 连接上加:常加会让明文 HTTP(默认 loopback)收不到 cookie。
315
- const secure = isTlsRequest(req);
316
- if (ok) {
317
- // cookieToken 已解码成原文(issue #261),所以直接和原始口令比 ——
318
- // 以前拿 `encodeURIComponent(AUTH_TOKEN)` 比,含 `=` / 非 ASCII 的口令
319
- // 永远不相等(于是每个请求都重发 cookie,且带 cookie 的请求反而 401)。
320
- if (!sameSecret(cookie)) {
321
- res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, secure));
322
- }
323
- }
324
- else if (cookie) {
325
- // 请求带的 cookie 已是失效旧值(服务端口令已更换)——立即让其过期,
326
- // 避免浏览器被残留 cookie 卡死一年(本来也不该再信任它鉴权)。
327
- // Secure 与非 Secure 在浏览器里是两个独立 cookie:只清一种会因种植时的
328
- // 协议不同而残留,所以两种属性组合各发一遍(HTTP 下 Secure 那条被忽略,无害)。
329
- res.setHeader("Set-Cookie", [buildPiWebTokenCookie("", 0, false), buildPiWebTokenCookie("", 0, true)]);
330
- }
331
- if (req.path === "/api/health" || ok) {
332
- next();
333
- return;
334
- }
335
- res
336
- .status(401)
337
- .send(cookie
338
- ? "unauthorized: PI_WEB_TOKEN required — 服务端口令已变更?已清除旧 token cookie,请用当前 ?token= 重新进入"
339
- : "unauthorized: PI_WEB_TOKEN required (?token=…)");
340
- });
341
- }
498
+ const ok = tokenOk(req);
499
+ const cookie = cookieToken(req);
500
+ // 浏览器经 ?token= 首次进入后下发 HttpOnly cookie,后续导航/资源请求免带参数。
501
+ // 重要:只要请求携带着有效 token(query/header/cookie 任一匹配)就把 cookie 刷新为
502
+ // 当前 AUTH_TOKEN——服务端重启改了 PI_WEB_TOKEN 后,旧 cookie 经一次正确的
503
+ // ?token= 进入即被重新同步,无需用户清缓存(issue #71)。
504
+ // Secure 只在 TLS 连接上加:常加会让明文 HTTP(默认 loopback)收不到 cookie。
505
+ const secure = isTlsRequest(req);
506
+ if (ok) {
507
+ // cookieToken 已解码成原文(issue #261),所以直接和原始口令比 ——
508
+ // 以前拿 `encodeURIComponent(AUTH_TOKEN)` 比,含 `=` / 非 ASCII 的口令
509
+ // 永远不相等(于是每个请求都重发 cookie,且带 cookie 的请求反而 401)。
510
+ if (!sameSecret(cookie)) {
511
+ res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, secure));
512
+ }
513
+ }
514
+ else if (cookie) {
515
+ // 请求带的 cookie 已是失效旧值(服务端口令已更换)——立即让其过期,
516
+ // 避免浏览器被残留 cookie 卡死一年(本来也不该再信任它鉴权)。
517
+ // Secure 与非 Secure 在浏览器里是两个独立 cookie:只清一种会因种植时的
518
+ // 协议不同而残留,所以两种属性组合各发一遍(HTTP 下 Secure 那条被忽略,无害)。
519
+ res.setHeader("Set-Cookie", [buildPiWebTokenCookie("", 0, false), buildPiWebTokenCookie("", 0, true)]);
520
+ }
521
+ if (req.path === "/api/health" || ok) {
522
+ next();
523
+ return;
524
+ }
525
+ res
526
+ .status(401)
527
+ .send(cookie
528
+ ? "unauthorized: PI_WEB_TOKEN required — 服务端口令已变更?已清除旧 token cookie,请用当前 ?token= 重新进入"
529
+ : "unauthorized: PI_WEB_TOKEN required (?token=…)");
530
+ });
342
531
  /** 共享客户端持久化存储:双引擎(pi + dsh)共用同一份内存缓存与落盘通道,避免互相覆盖。 */
343
532
  const sharedStateStore = new ClientStateStore(join(DATA_DIR, "client-state.json"));
344
533
  /** 启动参数显式指定的引擎(--engine pi|dsh|claude|durable 或 PI_WEB_ENGINE)。未显式传则优先读持久化默认引擎。 */
@@ -390,6 +579,7 @@ registerFileTransferRoutes(app, (clientId) => service.get(clientId)?.cwd);
390
579
  app.get("/api/health", (_req, res) => {
391
580
  // 审查 #352:该端点对未鉴权开放(监控探针需要),故只保留版本/引擎与 SDK
392
581
  // 副本诊断信息,不再暴露 cwd(工作区路径披露)与 pid(指纹/信息收集面)。
582
+ // issue #763: 支持多实例区分的环境变量 (PI_WEB_INSTANCE_NAME / PI_WEB_FAVICON_COLOR)。
393
583
  res.json({
394
584
  ok: true,
395
585
  piVersion: VERSION,
@@ -397,6 +587,8 @@ app.get("/api/health", (_req, res) => {
397
587
  // 用户就不用猜「为什么升了全局 SDK 不生效」。(纯新增字段,piVersion 语义不变。)
398
588
  piSdkCopies: sdkCopies(),
399
589
  engine: currentDefaultEngine,
590
+ instanceName: process.env.PI_WEB_INSTANCE_NAME?.trim() || undefined,
591
+ faviconColor: process.env.PI_WEB_FAVICON_COLOR?.trim() || undefined,
400
592
  });
401
593
  });
402
594
  /**
@@ -525,6 +717,77 @@ app.get("/api/file", async (req, res) => {
525
717
  res.status(404).end("not found");
526
718
  }
527
719
  });
720
+ /**
721
+ * PPTX 等 Office 内部媒体流式下发路由。
722
+ * /api/office-media?path=<workspace-rel-path>&media=<image-name>&clientId=…
723
+ */
724
+ app.get("/api/office-media", async (req, res) => {
725
+ try {
726
+ const rawPath = typeof req.query.path === "string" ? req.query.path : "";
727
+ const media = typeof req.query.media === "string" ? req.query.media : "";
728
+ if (!rawPath || !media) {
729
+ res.status(400).end("missing path or media");
730
+ return;
731
+ }
732
+ if (!/^image\d+\.(png|jpe?g|webp|gif|svg|bmp)$/i.test(media)) {
733
+ res.status(400).end("invalid media name");
734
+ return;
735
+ }
736
+ const cid = typeof req.query.clientId === "string" ? req.query.clientId : "";
737
+ const cs = cid ? service.get(cid) : undefined;
738
+ const root = cs?.cwd ?? CWD;
739
+ const absWire = isAbsoluteWirePath(rawPath);
740
+ let abs;
741
+ if (absWire) {
742
+ abs = wireToAbs(rawPath);
743
+ }
744
+ else {
745
+ const wp = workspacePath(root, rawPath);
746
+ if (!wp) {
747
+ res.status(400).end("path outside workspace");
748
+ return;
749
+ }
750
+ abs = wp.abs;
751
+ }
752
+ if (!isOfficeFile(abs)) {
753
+ res.status(400).end("not an office file");
754
+ return;
755
+ }
756
+ const st = await stat(abs);
757
+ if (!st.isFile() || st.size > OFFICE_MAX_FILE_BYTES) {
758
+ res.status(400).end("file not found or too large");
759
+ return;
760
+ }
761
+ const data = await readFile(abs);
762
+ const zipFiles = unzipFiles(data, [`ppt/media/${media}`]);
763
+ const imgBuf = zipFiles.get(`ppt/media/${media}`);
764
+ if (!imgBuf) {
765
+ res.status(404).end("media not found");
766
+ return;
767
+ }
768
+ const ext = media.split(".").pop()?.toLowerCase() ?? "";
769
+ const mimeMap = {
770
+ png: "image/png",
771
+ jpg: "image/jpeg",
772
+ jpeg: "image/jpeg",
773
+ webp: "image/webp",
774
+ gif: "image/gif",
775
+ svg: "image/svg+xml",
776
+ bmp: "image/bmp",
777
+ };
778
+ res.setHeader("Content-Type", mimeMap[ext] || "application/octet-stream");
779
+ res.setHeader("Cache-Control", "public, max-age=86400, immutable");
780
+ if (ext === "svg") {
781
+ // 与 /api/attachment 和 /api/file 同理:SVG 文档形态的 <script> 沙箱化(审查 #352 P0-1)
782
+ res.setHeader("Content-Security-Policy", "sandbox");
783
+ res.setHeader("X-Content-Type-Options", "nosniff");
784
+ }
785
+ res.send(imgBuf);
786
+ }
787
+ catch {
788
+ res.status(404).end("not found");
789
+ }
790
+ });
528
791
  /**
529
792
  * Directory-mapped preview: serves a workspace file at a URL that mirrors its
530
793
  * directory location, so an HTML preview's RELATIVE subresources
@@ -818,6 +1081,27 @@ app.get("/plugins/:id/client/*splat", (req, res) => {
818
1081
  .end("not found");
819
1082
  });
820
1083
  });
1084
+ // 插件公共客户端依赖共享库(@pi-web-ui/plugin-sdk/client 等):
1085
+ // 静态托管在 /plugins-shared/*,配合前端 Import Maps 免去各插件重复打包。
1086
+ const PLUGIN_SHARED_DIR = join(pkgRoot, "plugin-sdk");
1087
+ app.get("/plugins-shared/*splat", (req, res) => {
1088
+ const rest = splatParam(req);
1089
+ const abs = resolvePluginSharedFile(PLUGIN_SHARED_DIR, rest);
1090
+ if (!abs || !existsSync(abs)) {
1091
+ res.status(404).end("shared module not found");
1092
+ return;
1093
+ }
1094
+ if (/\.(mjs|js)$/.test(abs)) {
1095
+ res.setHeader("Content-Type", "text/javascript; charset=utf-8");
1096
+ }
1097
+ res.setHeader("Cache-Control", "no-cache");
1098
+ res.sendFile(abs, { dotfiles: "allow" }, (err) => {
1099
+ if (err && !res.headersSent)
1100
+ res
1101
+ .status(err.statusCode === 404 ? 404 : 500)
1102
+ .end("not found");
1103
+ });
1104
+ });
821
1105
  /** Set in the env of the replacement child spawned by a self-update restart. */
822
1106
  const RESTART_CHILD_ENV = "PI_WEB_RESTART_CHILD";
823
1107
  const webDist = join(pkgRoot, "web", "dist");
@@ -1285,6 +1569,10 @@ const service = {
1285
1569
  for (const s of activeEngines())
1286
1570
  s.applyPluginCommandCatalog();
1287
1571
  },
1572
+ applyPluginMarkers() {
1573
+ for (const s of activeEngines())
1574
+ s.applyPluginMarkers?.();
1575
+ },
1288
1576
  refreshBackgroundServers() {
1289
1577
  for (const s of activeEngines())
1290
1578
  s.refreshBackgroundServers();
@@ -1465,6 +1753,41 @@ async function confirmPluginInstallHelper(items) {
1465
1753
  // 远程 SSH 连接管理、环境探针与目录浏览服务
1466
1754
  const remoteSshService = new RemoteSshService(DATA_DIR);
1467
1755
  setGlobalRemoteSshService(remoteSshService);
1756
+ // 多引擎多模型多目录画布协作调度器 (Canvas Studio)
1757
+ const canvasOrchestrator = new CanvasOrchestrator(CWD, DATA_DIR, (eng) => ensureEngine(eng));
1758
+ setCanvasRuntime(canvasOrchestrator);
1759
+ // AI 工具改图广播:与 orchestrator 同一个 WS 广播,开着的画布实时刷新(免刷新)。
1760
+ const broadcastCanvas = (msg) => {
1761
+ const payload = JSON.stringify(msg);
1762
+ for (const client of wss.clients) {
1763
+ if (client.readyState !== WebSocket.OPEN)
1764
+ continue;
1765
+ if (client.bufferedAmount > BROADCAST_BACKPRESSURE_MAX_BYTES)
1766
+ continue;
1767
+ try {
1768
+ client.send(payload);
1769
+ }
1770
+ catch {
1771
+ /* 客户端断开连接忽略 */
1772
+ }
1773
+ }
1774
+ };
1775
+ setCanvasBroadcaster((msg) => broadcastCanvas(msg));
1776
+ canvasOrchestrator.setBroadcaster((msg) => {
1777
+ const payload = JSON.stringify(msg);
1778
+ for (const client of wss.clients) {
1779
+ if (client.readyState !== WebSocket.OPEN)
1780
+ continue;
1781
+ if (client.bufferedAmount > BROADCAST_BACKPRESSURE_MAX_BYTES)
1782
+ continue;
1783
+ try {
1784
+ client.send(payload);
1785
+ }
1786
+ catch {
1787
+ /* 客户端断开连接忽略 */
1788
+ }
1789
+ }
1790
+ });
1468
1791
  // 内置定时任务(issue #184):全局 <dataDir>/scheduler-tasks.json,TTL 与
1469
1792
  // client-state 同级;Agent 工具建的任务优先唤醒发起对话(issue #193:
1470
1793
  // wakeConversation steer 投递,不切用户当前对话),原对话不在先回落同项目
@@ -1688,6 +2011,8 @@ pluginMgr.onAgentToolsChanged = () => {
1688
2011
  };
1689
2012
  // 插件扩展点:插件斜杠命令(registerCommand)→ 命令选择器目录 + prompt 拦截执行。
1690
2013
  pluginMgr.onCommandsChanged = () => service.applyPluginCommandCatalog();
2014
+ // 插件扩展点:插件内联标记(registerMarker)→ 刷新客户端 markers 与设置状态。
2015
+ pluginMgr.onMarkersChanged = () => service.applyPluginMarkers?.();
1691
2016
  // 插件扩展点:插件常驻后台任务(registerBackgroundTask)→ 并入「后台任务」面板。
1692
2017
  pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
1693
2018
  // ---------------------------------------------------------------------------
@@ -1791,13 +2116,17 @@ pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
1791
2116
  }
1792
2117
  };
1793
2118
  // llmProvider:插件直调模型(孤立无工具的一次性补全,不建对话)。
1794
- // 标准 pi 引擎走 service.completeForPlugins;DSH/未知引擎回 {ok:false},绝不抛错。
2119
+ // 双引擎适配层:支持 pi 与 dsh 引擎。
1795
2120
  pm.llmProvider = async (pluginId, req) => {
1796
2121
  try {
1797
- // SAFETY: Only invoked after the optional method is checked; request fields are narrowed below.
2122
+ for (const s of activeEngines()) {
2123
+ if (s && typeof s.completeForPlugins === "function") {
2124
+ return await s.completeForPlugins(pluginId, (req ?? {}));
2125
+ }
2126
+ }
1798
2127
  const svc = ensureEngine("pi");
1799
2128
  if (typeof svc.completeForPlugins !== "function")
1800
- return { ok: false, error: "当前引擎不支持 LLM 直调(仅标准 pi 引擎)" };
2129
+ return { ok: false, error: "当前引擎不支持 LLM 直调" };
1801
2130
  return await svc.completeForPlugins(pluginId, (req ?? {}));
1802
2131
  }
1803
2132
  catch (err) {
@@ -1898,6 +2227,8 @@ wss.on("connection", (ws) => {
1898
2227
  * ready 先行后,ready 只代表传输通,插件命令目录/首快照都还没好,直接分发
1899
2228
  * 会撞「未知命令」/ rev 链断裂。 */
1900
2229
  let attachDone = false;
2230
+ /** attach 代际(#699):hello/switch 每次发起 attach 前 +1,慢 attach 落定时代际过期则只 detach 清理,绝不 flush/replay。 */
2231
+ let attachGen = 0;
1901
2232
  /** 背压丢快照后的延迟重发定时器(去重:一次只排一个)。 */
1902
2233
  let snapshotRetryTimer = null;
1903
2234
  // 协议层错误(非法帧/未 masked 帧等):不注册 handler 会作为 uncaught
@@ -2026,6 +2357,7 @@ wss.on("connection", (ws) => {
2026
2357
  }
2027
2358
  const cid = clientId;
2028
2359
  const nextSvc = ensureEngine(targetEngine);
2360
+ const switchGen = ++attachGen;
2029
2361
  nextSvc
2030
2362
  .attach(cid, send)
2031
2363
  .then((newCs) => {
@@ -2033,6 +2365,11 @@ wss.on("connection", (ws) => {
2033
2365
  nextSvc.detach(cid, send);
2034
2366
  return;
2035
2367
  }
2368
+ if (switchGen !== attachGen) {
2369
+ // 期间又有新的 switch/hello attach:本会话已是孤儿,只清理不接管(#699)
2370
+ nextSvc.detach(cid, send);
2371
+ return;
2372
+ }
2036
2373
  nextSvc.applyPluginCommandCatalog();
2037
2374
  newCs.flushSnapshot(true);
2038
2375
  newCs.pushSettings();
@@ -2072,9 +2409,14 @@ wss.on("connection", (ws) => {
2072
2409
  .catch((err) => {
2073
2410
  // 切换失败时事务回滚:原样切回 prevEngine,避免状态悬挂
2074
2411
  setClientEngine(cid, prevEngine);
2412
+ const rollbackGen = ++attachGen;
2075
2413
  ensureEngine(prevEngine)
2076
2414
  .attach(cid, send)
2077
2415
  .then((rollbackCs) => {
2416
+ if (closed || rollbackGen !== attachGen) {
2417
+ ensureEngine(prevEngine).detach(cid, send);
2418
+ return;
2419
+ }
2078
2420
  rollbackCs.flushSnapshot(true);
2079
2421
  attachDone = true;
2080
2422
  for (const m of pending.drain())
@@ -2199,7 +2541,31 @@ wss.on("connection", (ws) => {
2199
2541
  // 历史窗口按需加载:连接级窗口化直接服务(四个引擎通吃,不依赖引擎实现)。
2200
2542
  // 放在引擎分发之前:它不是引擎能力,窗口化关闭时静默无回执(前端保持现状)。
2201
2543
  if (msg.type === "load_earlier_messages") {
2202
- windowTap.loadEarlier(msg.count, msg.all);
2544
+ let handled = windowTap.loadEarlier({
2545
+ count: msg.count,
2546
+ all: msg.all,
2547
+ conversationId: msg.conversationId,
2548
+ beforeId: msg.beforeId,
2549
+ before: msg.before,
2550
+ });
2551
+ if (!handled && cs) {
2552
+ const activeId = typeof cs.activeConversationId === "function" ? cs.activeConversationId() : undefined;
2553
+ const convId = msg.conversationId || activeId;
2554
+ const full = convId ? cs.getMessagesOfConversation?.(convId) : undefined;
2555
+ if (convId && full && full.length > 0) {
2556
+ windowTap.rehydrate(convId, full, msg.before);
2557
+ handled = windowTap.loadEarlier({
2558
+ count: msg.count,
2559
+ all: msg.all,
2560
+ conversationId: convId,
2561
+ beforeId: msg.beforeId,
2562
+ before: msg.before,
2563
+ });
2564
+ }
2565
+ if (!handled && (!msg.conversationId || msg.conversationId === activeId)) {
2566
+ cs.flushSnapshot(true);
2567
+ }
2568
+ }
2203
2569
  return;
2204
2570
  }
2205
2571
  // Managed instances do not install software on themselves, and tabs this
@@ -2234,6 +2600,8 @@ wss.on("connection", (ws) => {
2234
2600
  return;
2235
2601
  if (handleSettingsMessage(msg, cs))
2236
2602
  return;
2603
+ if (handleCanvasMessage(msg, DATA_DIR, canvasOrchestrator, send, { runBase: cs.cwd }))
2604
+ return;
2237
2605
  if (handleInteractiveResponseMessage(msg, cs, service, clientId, send))
2238
2606
  return;
2239
2607
  if (handlePluginMessage(msg, {
@@ -2274,7 +2642,7 @@ wss.on("connection", (ws) => {
2274
2642
  case "queue_remove":
2275
2643
  // #491:removeQueued 是 async——dispatch 是 fire-and-forget,缺 void 时
2276
2644
  // 内部抛错即 unhandledRejection,而全仓没有兜底 handler,Node ≥15 直接崩进程。
2277
- void cs.removeQueued(msg.kind, msg.text, msg.index);
2645
+ void cs.removeQueued(msg.kind, msg.text, msg.index, msg.id);
2278
2646
  break;
2279
2647
  case "draft_update":
2280
2648
  cs.saveDraft?.(msg.sessionId, msg.text, msg.ts);
@@ -2476,6 +2844,22 @@ wss.on("connection", (ws) => {
2476
2844
  if (!closed)
2477
2845
  send({ type: "engines_status", engines });
2478
2846
  });
2847
+ if (autoGeneratedToken) {
2848
+ send({
2849
+ type: "notice",
2850
+ level: "info",
2851
+ text: `零信任保护:服务监听在非回环地址 (${HOST}),已自动生成临时访问 Token 并生效。`,
2852
+ textEn: `Zero-Trust: Server is bound to non-loopback (${HOST}); an ephemeral access token was auto-generated.`,
2853
+ });
2854
+ }
2855
+ else if (!isLoopbackHost(HOST) && !AUTH_TOKEN && ALLOW_INSECURE_NO_AUTH) {
2856
+ send({
2857
+ type: "notice",
2858
+ level: "warning",
2859
+ text: `安全告警:服务监听在非回环地址 (${HOST}) 且开启了免密模式,局域网设备可在未授权状态下访问与执行命令!`,
2860
+ textEn: `Security Warning: Server is bound to non-loopback (${HOST}) in insecure mode; any device on the network can access without authentication!`,
2861
+ });
2862
+ }
2479
2863
  }
2480
2864
  // attach 慢提示:本体继续等,不取消;完成后照常走快照流程。
2481
2865
  const slowTimer = setTimeout(() => {
@@ -2488,12 +2872,19 @@ wss.on("connection", (ws) => {
2488
2872
  textEn: "Session init is taking a while (possibly scanning the workspace) — hang on…",
2489
2873
  });
2490
2874
  }, ATTACH_SLOW_NOTICE_MS);
2491
- service
2875
+ const helloSvc = ensureEngine(resolveClientEngine(cid));
2876
+ const helloGen = ++attachGen;
2877
+ helloSvc
2492
2878
  .attach(cid, send)
2493
2879
  .then((cs) => {
2494
2880
  clearTimeout(slowTimer);
2495
2881
  if (closed) {
2496
- service.detach(cid, send);
2882
+ helloSvc.detach(cid, send);
2883
+ return;
2884
+ }
2885
+ if (helloGen !== attachGen) {
2886
+ // hello 慢 attach 落定前用户已 switch_engine:旧引擎会话成孤儿,只清理(#699)
2887
+ helloSvc.detach(cid, send);
2497
2888
  return;
2498
2889
  }
2499
2890
  // Plugin catalog: re-scan + activate new dirs on every attach so
@@ -2670,6 +3061,36 @@ httpServer.listen(PORT, HOST, () => {
2670
3061
  console.log(` pi SDK note : ${sdkNote}`);
2671
3062
  }
2672
3063
  console.log(` bind : ${HOST}:${PORT}`);
3064
+ console.log(` setup : http://127.0.0.1:${PORT}/setup (仅本机:配 token/监听/白名单)`);
3065
+ if (autoGeneratedToken) {
3066
+ console.log("");
3067
+ console.log(" ╔═══════════════════════════════════════════════════════════════════════════════╗");
3068
+ console.log(" ║ 🛡️ 零信任自愈保护已生效 (Zero-Trust Auto-Remediation) ║");
3069
+ console.log(" ║ 检测到服务监听在非回环地址且未配置口令,系统已自动生成临时访问 Token: ║");
3070
+ console.log(` ║ Token: ${autoGeneratedToken.padEnd(68)} ║`);
3071
+ console.log(" ║ ║");
3072
+ console.log(" ║ 请使用以下带凭据的链接访问 Web 界面(浏览器将自动保存 HttpOnly Cookie): ║");
3073
+ const link = `http://${HOST === "0.0.0.0" ? "127.0.0.1" : HOST}:${PORT}/?token=${autoGeneratedToken}`;
3074
+ console.log(` ║ 👉 ${link.padEnd(73)} ║`);
3075
+ console.log(" ║ ║");
3076
+ console.log(" ║ 若确实需要在局域网完全免密公开,可设置 PI_WEB_INSECURE_NO_AUTH=1 启动。 ║");
3077
+ console.log(" ╚═══════════════════════════════════════════════════════════════════════════════╝");
3078
+ }
3079
+ else if (!isLoopbackHost(HOST) && !AUTH_TOKEN && ALLOW_INSECURE_NO_AUTH) {
3080
+ const requireAuth = /^(1|true|yes)$/i.test(process.env.PI_WEB_REQUIRE_AUTH ?? "");
3081
+ if (requireAuth) {
3082
+ console.error("");
3083
+ console.error(` [FATAL] PI_WEB_REQUIRE_AUTH is enabled, but server is bound to non-loopback host (${HOST}) without PI_WEB_TOKEN.`);
3084
+ console.error(" Please set PI_WEB_TOKEN or bind to 127.0.0.1.");
3085
+ console.error("");
3086
+ process.exit(1);
3087
+ }
3088
+ console.warn("");
3089
+ console.warn(" ─────────────────────────────────────────────────────────────────────────────");
3090
+ console.warn(` ⚠️ 【安全告警】服务监听在非回环地址 (${HOST}:${PORT}) 且显式开启了全开放免密模式 (PI_WEB_INSECURE_NO_AUTH=1)!`);
3091
+ console.warn(" 局域网(或公网路由)任意设备均可在未授权状态下访问 Web 界面并执行系统命令!");
3092
+ console.warn(" ─────────────────────────────────────────────────────────────────────────────");
3093
+ }
2673
3094
  console.log("");
2674
3095
  });
2675
3096
  // 上传文件保留期清理:启动扫一次 + 每 6 小时一次(best-effort,见 uploads.ts)