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.
Files changed (280) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +187 -316
  3. package/README.zh-CN.md +227 -299
  4. package/README.zh-TW.md +227 -299
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -0
  8. package/bin/pi-web-ui.mjs +4081 -4041
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service-daemon.js +102 -24
  12. package/dist/server/agent-service.js +2419 -1174
  13. package/dist/server/approval-rules.js +29 -3
  14. package/dist/server/ask-user-question-tool.js +8 -8
  15. package/dist/server/atomic-file.js +35 -14
  16. package/dist/server/attachment-store.js +71 -35
  17. package/dist/server/attachments.js +69 -13
  18. package/dist/server/canvas/canvas-agent-tool.js +68 -18
  19. package/dist/server/canvas/canvas-cards.js +1 -1
  20. package/dist/server/canvas/canvas-dispatch.js +61 -20
  21. package/dist/server/canvas/canvas-orchestrator.js +519 -202
  22. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  23. package/dist/server/canvas/canvas-scheduler.js +99 -0
  24. package/dist/server/canvas/canvas-store.js +107 -54
  25. package/dist/server/canvas/canvas-validation.js +131 -0
  26. package/dist/server/canvas/canvas-workspace.js +284 -0
  27. package/dist/server/client-id-utils.js +8 -0
  28. package/dist/server/client-state.js +110 -24
  29. package/dist/server/communicate-tool.js +76 -0
  30. package/dist/server/compact-context-tool.js +2 -3
  31. package/dist/server/compaction-instructions.js +75 -0
  32. package/dist/server/compaction-markers.js +7 -2
  33. package/dist/server/compaction-state.js +84 -0
  34. package/dist/server/composer-drafts.js +43 -40
  35. package/dist/server/context-evidence.js +346 -0
  36. package/dist/server/conversation-communication.js +368 -0
  37. package/dist/server/conversation-read-tool.js +3 -4
  38. package/dist/server/conversation-tool-names.js +14 -0
  39. package/dist/server/conversation-tool.js +57 -0
  40. package/dist/server/delegate-mode.js +17 -4
  41. package/dist/server/device-center/bot-catalog.js +88 -0
  42. package/dist/server/device-center/bot-execution.js +106 -0
  43. package/dist/server/device-center/bots.js +170 -0
  44. package/dist/server/device-center/collab-service.js +153 -0
  45. package/dist/server/device-center/collab-tool.js +184 -0
  46. package/dist/server/device-center/connector.js +351 -0
  47. package/dist/server/device-center/desktop-linux.js +372 -0
  48. package/dist/server/device-center/desktop-native.js +413 -0
  49. package/dist/server/device-center/desktop-page.js +232 -0
  50. package/dist/server/device-center/desktop-setup.js +30 -0
  51. package/dist/server/device-center/desktop.js +387 -0
  52. package/dist/server/device-center/device-portals.js +241 -0
  53. package/dist/server/device-center/execution-failure.js +70 -0
  54. package/dist/server/device-center/executor.js +371 -0
  55. package/dist/server/device-center/file-sync.js +493 -0
  56. package/dist/server/device-center/hub-auth.js +69 -0
  57. package/dist/server/device-center/hub-page.js +68 -0
  58. package/dist/server/device-center/hub-setup.js +214 -0
  59. package/dist/server/device-center/hub.js +830 -0
  60. package/dist/server/device-center/local-hub.js +92 -0
  61. package/dist/server/device-center/local.js +529 -0
  62. package/dist/server/device-center/main.js +118 -0
  63. package/dist/server/device-center/native-desktop/macos.js +192 -0
  64. package/dist/server/device-center/native-desktop/windows.js +118 -0
  65. package/dist/server/device-center/path-portal.js +120 -0
  66. package/dist/server/device-center/relay.js +996 -0
  67. package/dist/server/device-center/runtime.js +253 -0
  68. package/dist/server/device-center/store.js +122 -0
  69. package/dist/server/device-center/task-error.js +14 -0
  70. package/dist/server/device-center/transfers.js +293 -0
  71. package/dist/server/device-center/workspaces.js +45 -0
  72. package/dist/server/dispatch-domain-handlers.js +84 -27
  73. package/dist/server/dsh/dsh-agent-service.js +282 -159
  74. package/dist/server/dsh/dsh-client.js +12 -2
  75. package/dist/server/dsh/runtime/cordis.yml +1 -1
  76. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  77. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  78. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  79. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  80. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  81. package/dist/server/durable/durable-agent-service.js +1 -1
  82. package/dist/server/engine-probe.js +36 -6
  83. package/dist/server/eval-tool.js +135 -135
  84. package/dist/server/evidence-tool-hooks.js +49 -0
  85. package/dist/server/file-save.js +95 -0
  86. package/dist/server/file-transfer-routes.js +97 -47
  87. package/dist/server/files-service.js +38 -26
  88. package/dist/server/global-loader.js +40 -2
  89. package/dist/server/goal-review-gate.js +16 -6
  90. package/dist/server/goal-service.js +54 -30
  91. package/dist/server/http-proxy.js +120 -0
  92. package/dist/server/index.js +285 -255
  93. package/dist/server/load-timing.js +31 -0
  94. package/dist/server/mcp-bridge.js +219 -94
  95. package/dist/server/mcp-hot-reload.js +31 -5
  96. package/dist/server/mcp-manager.js +192 -93
  97. package/dist/server/mcp-oauth-login.js +169 -0
  98. package/dist/server/mcp-oauth-ui.js +137 -0
  99. package/dist/server/mcp-oauth.js +395 -0
  100. package/dist/server/mcp-project-runtime.js +207 -0
  101. package/dist/server/message-window.js +74 -21
  102. package/dist/server/net-guard.js +122 -20
  103. package/dist/server/patch-bash-process.js +125 -0
  104. package/dist/server/patch-tool.js +9 -9
  105. package/dist/server/patch-turn-end-boundary.js +3 -3
  106. package/dist/server/payload-limits.js +17 -0
  107. package/dist/server/pending-question.js +82 -0
  108. package/dist/server/persona-chain.js +8 -8
  109. package/dist/server/plan-mode.js +338 -137
  110. package/dist/server/plugin-assets.js +8 -4
  111. package/dist/server/plugin-chat-attachments.js +48 -0
  112. package/dist/server/plugin-facilities.js +67 -220
  113. package/dist/server/plugin-installer.js +2 -1
  114. package/dist/server/plugin-removal.js +49 -0
  115. package/dist/server/plugin-secrets.js +179 -0
  116. package/dist/server/plugins.js +288 -94
  117. package/dist/server/preset-fields.js +56 -0
  118. package/dist/server/preset-plugin-dependencies.js +57 -0
  119. package/dist/server/preset-share.js +113 -72
  120. package/dist/server/prompt-templates.js +106 -0
  121. package/dist/server/protocol-version.js +1 -1
  122. package/dist/server/queue-modes.js +10 -0
  123. package/dist/server/remote-ssh-service.js +199 -106
  124. package/dist/server/request-context.js +164 -0
  125. package/dist/server/resolve-global-sdk.js +2 -0
  126. package/dist/server/sandbox-data.js +655 -0
  127. package/dist/server/sandbox-engines.js +7 -0
  128. package/dist/server/sandbox-runtime-gate.js +41 -0
  129. package/dist/server/sandbox-service.js +139 -698
  130. package/dist/server/sandbox-tool.js +21 -4
  131. package/dist/server/schedule-agent-tool.js +39 -21
  132. package/dist/server/scheduler-tasks.js +106 -55
  133. package/dist/server/scm-commitmsg.js +10 -10
  134. package/dist/server/serialize.js +48 -19
  135. package/dist/server/session-branch.js +25 -3
  136. package/dist/server/session-parser.js +28 -18
  137. package/dist/server/session-scan.js +130 -0
  138. package/dist/server/session-search.js +51 -37
  139. package/dist/server/settings-service.js +273 -111
  140. package/dist/server/setup-config.js +58 -0
  141. package/dist/server/setup-page.js +620 -620
  142. package/dist/server/skill-maintenance.js +112 -24
  143. package/dist/server/subagent-helpers.js +4 -1
  144. package/dist/server/subagent-notify.js +4 -1
  145. package/dist/server/subagent-security-gate.js +52 -11
  146. package/dist/server/subagent-task.js +27 -0
  147. package/dist/server/subagents.js +217 -46
  148. package/dist/server/tabs.js +9 -1
  149. package/dist/server/terminals.js +467 -363
  150. package/dist/server/text-quote.js +9 -0
  151. package/dist/server/tool-guards.js +42 -6
  152. package/dist/server/tool-manager.js +48 -20
  153. package/dist/server/tool-overrides.js +13 -11
  154. package/dist/server/tool-prompt-overrides.js +32 -2
  155. package/dist/server/tool-prompts.js +1 -1
  156. package/dist/server/turn-timing.js +11 -0
  157. package/dist/server/universal/drivers/claude-code.js +5 -0
  158. package/dist/server/universal/drivers/codex.js +336 -0
  159. package/dist/server/universal/index.js +1 -0
  160. package/dist/server/universal/session-store.js +48 -6
  161. package/dist/server/universal/universal-attachments.js +24 -1
  162. package/dist/server/universal/universal-service.js +1 -1
  163. package/dist/server/universal/universal-session.js +357 -231
  164. package/dist/server/uploads.js +64 -5
  165. package/dist/server/vision-bridge.js +18 -18
  166. package/dist/server/worktree-service.js +32 -24
  167. package/dist/server/ws-pending-queue.js +73 -27
  168. package/docs/device-center.md +148 -0
  169. package/docs/device-desktop.md +48 -0
  170. package/docs/dsh-engine.md +493 -493
  171. package/extensions/webui.ts +335 -335
  172. package/package.json +5 -2
  173. package/plugin-sdk/README.md +174 -174
  174. package/plugin-sdk/client-utils.mjs +279 -279
  175. package/plugin-sdk/import-check.mjs +210 -210
  176. package/plugin-sdk/index.d.ts +698 -676
  177. package/plugin-sdk/index.mjs +696 -696
  178. package/plugin-sdk/package.json +13 -13
  179. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  180. package/plugins/catalog.json +11 -1
  181. package/themes/aetheris.css +501 -607
  182. package/themes/ayu-light.css +116 -140
  183. package/themes/bases/flow-base.css +1357 -1363
  184. package/themes/bases/obsidian-base.css +895 -895
  185. package/themes/bases/statusbar-flat-base.css +112 -0
  186. package/themes/bases/zhujian-base.css +688 -687
  187. package/themes/bases/zhupi-base.css +660 -659
  188. package/themes/catppuccin-latte.css +119 -142
  189. package/themes/catppuccin.css +116 -147
  190. package/themes/claude-code-dark.css +147 -146
  191. package/themes/codex.css +114 -138
  192. package/themes/cyberpunk.css +50 -108
  193. package/themes/dark-teal.css +264 -265
  194. package/themes/dazzle.css +38 -108
  195. package/themes/everforest-light.css +115 -138
  196. package/themes/flow-light.css +164 -164
  197. package/themes/flow.css +161 -161
  198. package/themes/geist.css +114 -138
  199. package/themes/gruvbox-light.css +115 -138
  200. package/themes/kanagawa-lotus.css +115 -138
  201. package/themes/md-preview.css +24 -234
  202. package/themes/mist.css +166 -186
  203. package/themes/nord.css +107 -138
  204. package/themes/one-dark.css +106 -139
  205. package/themes/paper.css +174 -186
  206. package/themes/rose-pine-dawn.css +114 -138
  207. package/themes/sakura.css +166 -186
  208. package/themes/solarized-light.css +114 -137
  209. package/themes/tokyo-night.css +115 -146
  210. package/themes/translucent.css +85 -85
  211. package/themes/transparent.css +116 -116
  212. package/themes/vs-code-dark.css +147 -147
  213. package/themes/wallpaper-flow.css +382 -382
  214. package/themes/wallpaper-obsidian.css +74 -74
  215. package/themes/white.css +164 -186
  216. package/themes/zhujian-dark.css +115 -114
  217. package/themes/zhujian.css +114 -114
  218. package/themes/zhupi-dark.css +115 -114
  219. package/themes/zhupi.css +114 -114
  220. package/web/dist/.build-assets.json +1 -0
  221. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  222. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  223. package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
  224. package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
  225. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  226. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  227. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  228. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  229. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  230. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  231. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  232. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  233. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  234. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  235. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  236. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  237. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  238. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  239. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  240. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  241. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  242. package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
  243. package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
  244. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  245. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  246. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  247. package/web/dist/assets/desktop-YguLbrX1.js +1 -0
  248. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  249. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  250. package/web/dist/assets/index-BPvpea8t.js +85 -0
  251. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  252. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  253. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  254. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  255. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  256. package/web/dist/assets/math-BorAY7qD.css +1 -0
  257. package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
  258. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  259. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  260. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  261. package/web/dist/index.html +42 -35
  262. package/web/dist/sw.js +179 -179
  263. package/web/public/sw.js +179 -179
  264. package/dist/gh-comment-781.md +0 -5
  265. package/dist/server/durable/durable-capabilities.js +0 -11
  266. package/dist/server/markers/builtins/services.js +0 -123
  267. package/dist/server/markers/builtins/todo.js +0 -189
  268. package/dist/server/markers-list-tool.js +0 -34
  269. package/dist/server/orchestrator.js +0 -109
  270. package/dist/server/system-prompt-soul.js +0 -41
  271. package/dist/server/univer-service.js +0 -448
  272. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  273. package/dist/test-artifact.md +0 -9
  274. package/dist/test-preview-modal.md +0 -11
  275. package/dist/test-report.html +0 -20
  276. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  277. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  278. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  279. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  280. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -1,12 +1,15 @@
1
- import express, {} from "express";
2
- import { mkdtemp, mkdir, open, realpath, rm, stat } from "node:fs/promises";
1
+ import {} from "express";
2
+ import { randomUUID } from "node:crypto";
3
+ import { uploadLimitBytes } from "./payload-limits.js";
4
+ import { writeRemoteUploadExclusive } from "./uploads.js";
5
+ import { mkdtemp, mkdir, open, realpath, rm, stat, link } from "node:fs/promises";
3
6
  import { join, dirname, posix } from "node:path";
4
7
  import { tmpdir } from "node:os";
5
8
  import { createArchive, extractArchive, safeDestination, safeEntryPath } from "./file-archives.js";
6
9
  import { isAbsoluteWirePath, wireToAbs, workspacePath } from "./files-service.js";
7
10
  import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveRemoteWorkspacePath, shellQuotePosix, } from "./remote-ssh-service.js";
8
11
  /** Registered behind the host's authentication middleware; shared by Pi and DSH. */
9
- export function registerFileTransferRoutes(app, getCwd, temporaryRoot = tmpdir()) {
12
+ export function registerFileTransferRoutes(app, getCwd, temporaryRoot = tmpdir(), getMaxUploadBytes = () => uploadLimitBytes({}, "folder")) {
10
13
  const busy = new Set();
11
14
  function root(req) {
12
15
  const id = typeof req.query.clientId === "string" ? req.query.clientId : "";
@@ -174,62 +177,109 @@ export function registerFileTransferRoutes(app, getCwd, temporaryRoot = tmpdir()
174
177
  busy.delete(cwd);
175
178
  }
176
179
  });
177
- // One binary file per request, sequentially sent by the browser. Avoid base64 and WS message limits.
178
- app.post("/api/file-transfer/upload", express.raw({ type: "application/octet-stream", limit: "32mb" }), async (req, res) => {
180
+ // Reserve worst-case bytes for chunked requests before consuming their body.
181
+ // Local uploads stream to disk; SFTP's buffer-only API is bounded by the same budget.
182
+ const maxInFlight = 200 * 1024 * 1024;
183
+ let uploads = 0;
184
+ let inFlight = 0;
185
+ app.post("/api/file-transfer/upload", async (req, res) => {
186
+ let reserved;
187
+ let temp;
188
+ let handle;
189
+ const controller = new AbortController();
190
+ const cancel = () => controller.abort();
191
+ res.on("close", cancel);
179
192
  try {
193
+ // Resolve all client/path inputs before reading even the first body chunk.
180
194
  const cwd = root(req);
181
- if (isRemoteWorkspaceUri(cwd)) {
182
- const sshSvc = getGlobalRemoteSshService();
183
- if (!sshSvc)
184
- throw new Error("Remote SSH service not available");
185
- const remoteDir = remotePath(cwd, typeof req.query.dir === "string" ? req.query.dir : "", true);
186
- const name = safeEntryPath(typeof req.query.name === "string" ? req.query.name : "");
187
- const remoteDest = posix.join(remoteDir, name.replace(/\\/g, "/"));
188
- if (!Buffer.isBuffer(req.body))
189
- throw new Error("Expected a binary file");
190
- if (req.query.kind === "directory") {
191
- if (req.body.length)
192
- throw new Error("Directory requests cannot contain file data");
193
- await sshSvc.sftpMkdirRecursive(cwd, remoteDest);
194
- res.json({ name });
195
- return;
196
- }
197
- const exists = await sshSvc.sftpStat(cwd, remoteDest).catch(() => null);
198
- if (exists) {
199
- const e = new Error("File already exists");
200
- e.code = "EEXIST";
201
- throw e;
202
- }
203
- await sshSvc.sftpWriteFile(cwd, remoteDest, req.body, { createParents: true });
204
- res.json({ name });
205
- return;
206
- }
207
- const dir = await realpath(path(cwd, req.query.dir));
195
+ const maxBytes = getMaxUploadBytes(String(req.query.clientId));
208
196
  const name = safeEntryPath(typeof req.query.name === "string" ? req.query.name : "");
209
- const dest = await safeDestination(dir, name);
210
- if (!Buffer.isBuffer(req.body))
197
+ const directory = req.query.kind === "directory";
198
+ const remote = isRemoteWorkspaceUri(cwd);
199
+ const ssh = remote ? getGlobalRemoteSshService() : undefined;
200
+ if (remote && !ssh)
201
+ throw new Error("Remote SSH service not available");
202
+ const dir = remote
203
+ ? remotePath(cwd, typeof req.query.dir === "string" ? req.query.dir : "", true)
204
+ : await realpath(path(cwd, req.query.dir));
205
+ const dest = remote ? posix.join(dir, name) : await safeDestination(dir, name);
206
+ if (!req.is("application/octet-stream"))
211
207
  throw new Error("Expected a binary file");
212
- if (req.query.kind === "directory") {
213
- if (req.body.length)
214
- throw new Error("Directory requests cannot contain file data");
215
- await mkdir(dest, { recursive: true });
216
- res.json({ name });
208
+ const lengthHeader = req.headers["content-length"];
209
+ const length = lengthHeader === undefined ? undefined : Number(lengthHeader);
210
+ if (length !== undefined && (!Number.isSafeInteger(length) || length < 0))
211
+ throw new Error("Invalid content length");
212
+ if (length !== undefined && length > (directory ? 0 : maxBytes)) {
213
+ res.status(413).send("Upload exceeds size limit");
214
+ return;
215
+ }
216
+ const budget = length ?? (directory ? 0 : maxBytes);
217
+ if (uploads >= 4 || inFlight + budget > maxInFlight) {
218
+ res.status(429).send("Upload capacity exhausted; retry later");
217
219
  return;
218
220
  }
219
- await mkdir(dirname(dest), { recursive: true });
220
- const handle = await open(dest, "wx", 0o600); // Folder uploads never silently overwrite existing data.
221
- try {
222
- await handle.writeFile(req.body);
221
+ uploads++;
222
+ inFlight += budget;
223
+ reserved = budget;
224
+ if (!remote && !directory) {
225
+ await mkdir(dirname(dest), { recursive: true });
226
+ // Recheck after mkdir, then stage beside the destination (same volume).
227
+ await safeDestination(dir, name);
228
+ temp = join(dirname(dest), `.pi-upload-${randomUUID()}`);
229
+ handle = await open(temp, "wx", 0o600);
223
230
  }
224
- finally {
231
+ let bytes = 0;
232
+ const chunks = [];
233
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) {
234
+ controller.signal.throwIfAborted();
235
+ const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
236
+ bytes += data.length;
237
+ if (bytes > budget || (directory && bytes > 0)) {
238
+ res.status(413).send("Upload exceeds size limit");
239
+ return;
240
+ }
241
+ if (handle)
242
+ await handle.writeFile(data);
243
+ else if (!directory)
244
+ chunks.push(data);
245
+ }
246
+ if (length !== undefined && bytes !== length)
247
+ throw new Error("Incomplete upload");
248
+ controller.signal.throwIfAborted();
249
+ if (directory) {
250
+ if (ssh)
251
+ await ssh.sftpMkdirRecursive(cwd, dest);
252
+ else
253
+ await mkdir(dest, { recursive: true });
254
+ }
255
+ else if (ssh) {
256
+ await writeRemoteUploadExclusive(ssh, cwd, dest, Buffer.concat(chunks, bytes), controller.signal);
257
+ }
258
+ else {
225
259
  await handle.close();
260
+ handle = undefined;
261
+ await safeDestination(dir, name);
262
+ controller.signal.throwIfAborted();
263
+ // link fails with EEXIST even if a competing upload won after validation.
264
+ await link(temp, dest);
226
265
  }
227
266
  res.json({ name });
228
267
  }
229
268
  catch (err) {
230
- res
231
- .status(err.code === "EEXIST" ? 409 : 400)
232
- .send(err instanceof Error ? err.message : String(err));
269
+ if (!res.headersSent && !res.destroyed)
270
+ res
271
+ .status(err.code === "EEXIST" ? 409 : 400)
272
+ .send(err instanceof Error ? err.message : String(err));
273
+ }
274
+ finally {
275
+ res.off("close", cancel);
276
+ await handle?.close().catch(() => { });
277
+ if (temp)
278
+ await rm(temp, { force: true, maxRetries: 5, retryDelay: 100 }).catch((err) => console.error("Upload cleanup failed:", err));
279
+ if (reserved !== undefined) {
280
+ uploads--;
281
+ inFlight -= reserved;
282
+ }
233
283
  }
234
284
  });
235
285
  }
@@ -5,7 +5,10 @@
5
5
  * 全部为无状态 fs 操作 + 两个自持的 watcher(当前列出目录、git dir),
6
6
  * 经 FilesHost 回调与 ClientSession 解耦。
7
7
  */
8
- import { Dirent, existsSync, mkdirSync, readFileSync, statSync, writeFileSync, watch } from "node:fs";
8
+ import { Dirent, existsSync, mkdirSync, readFileSync, statSync, watch } from "node:fs";
9
+ import { saveFilePreservingMetadata } from "./file-save.js";
10
+ import { isUploadDataTooLong, uploadLimitBytes } from "./payload-limits.js";
11
+ import { writeUploadExclusiveSync, writeRemoteUploadExclusive } from "./uploads.js";
9
12
  import { homedir } from "node:os";
10
13
  import { resolve, relative, sep, isAbsolute, posix } from "node:path";
11
14
  import { pick } from "./i18n.js";
@@ -91,17 +94,7 @@ export function absoluteParent(wire) {
91
94
  }
92
95
  /** 预览只读文件前 512KB。 */
93
96
  export const MAX_PREVIEW_BYTES = 512 * 1024;
94
- /** 右键上传单文件上限(内存中转 base64 → Buffer)。 */
95
- export const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
96
- /** 上传 cap 对应的 base64 文本长度上限(4/3 膨胀,向上取整到 4 字符边界)。 */
97
- export const MAX_UPLOAD_BASE64_CHARS = Math.ceil(MAX_UPLOAD_BYTES / 3) * 4;
98
- /** WS 入站帧上限:base64 上限 + 1MB JSON 包络余量(dirPath/name/type)。
99
- * server/index.ts 的 maxPayload 由此取值,两处上限保持对齐。 */
100
- export const WS_MAX_PAYLOAD_BYTES = MAX_UPLOAD_BASE64_CHARS + 1024 * 1024;
101
- /** base64 文本长度是否必定超 cap(解码前快拒,不分配 Buffer)。 */
102
- export function isUploadDataTooLong(dataLength, capBytes = MAX_UPLOAD_BYTES) {
103
- return dataLength > Math.ceil(capBytes / 3) * 4;
104
- }
97
+ export { MAX_UPLOAD_BYTES, MAX_UPLOAD_BASE64_CHARS, WS_MAX_PAYLOAD_BYTES, isUploadDataTooLong, } from "./payload-limits.js";
105
98
  // mac/linux: hide build & dependency noise (original behavior).
106
99
  const IGNORED_ENTRIES = new Set([
107
100
  "node_modules",
@@ -999,7 +992,7 @@ export class FilesService {
999
992
  });
1000
993
  return;
1001
994
  }
1002
- writeFileSync(abs, text, "utf8");
995
+ await saveFilePreservingMetadata(abs, text);
1003
996
  this.host.emit({
1004
997
  type: "notice",
1005
998
  level: "info",
@@ -1026,13 +1019,17 @@ export class FilesService {
1026
1019
  * malicious payload can't escape the directory. Emits notice + file_changed
1027
1020
  * for the target dir (the recursive watcher may not cover it on posix).
1028
1021
  */
1029
- async uploadFile(relDir, name, data) {
1022
+ async uploadFile(relDir, name, data, uploadId) {
1030
1023
  const root = this.host.getCwd();
1031
1024
  if (isRemoteWorkspaceUri(root)) {
1032
- await this.uploadRemoteFile(root, relDir, name, data);
1025
+ await this.uploadRemoteFile(root, relDir, name, data, uploadId);
1033
1026
  return;
1034
1027
  }
1035
- const emitErr = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
1028
+ const emitErr = (text, textEn) => {
1029
+ this.host.emit({ type: "notice", level: "error", text, textEn });
1030
+ if (typeof uploadId === "string")
1031
+ this.host.emit({ type: "file_upload_result", uploadId, ok: false, error: textEn ?? text });
1032
+ };
1036
1033
  try {
1037
1034
  const absDir = relDir ? isAbsoluteWirePath(relDir) : false;
1038
1035
  let wp;
@@ -1072,8 +1069,9 @@ export class FilesService {
1072
1069
  }
1073
1070
  uploadRel = rawRel.split(sep).join("/");
1074
1071
  }
1075
- if (isUploadDataTooLong(data.length)) {
1076
- emitErr(`文件过大:${name}(上限 ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`, `File too large: ${name} (max ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`);
1072
+ const maxBytes = this.host.getUploadMaxBytes?.() ?? uploadLimitBytes({}, "workspace");
1073
+ if (isUploadDataTooLong(data.length, maxBytes)) {
1074
+ emitErr(`文件过大:${name}(上限 ${Math.round(maxBytes / 1024 / 1024)}MB)`, `File too large: ${name} (max ${Math.round(maxBytes / 1024 / 1024)}MB)`);
1077
1075
  return;
1078
1076
  }
1079
1077
  const buf = Buffer.from(data, "base64");
@@ -1081,8 +1079,8 @@ export class FilesService {
1081
1079
  emitErr(`空文件:${name}`, `Empty file: ${name}`);
1082
1080
  return;
1083
1081
  }
1084
- if (buf.length > MAX_UPLOAD_BYTES) {
1085
- emitErr(`文件过大:${name}(上限 ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`, `File too large: ${name} (max ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`);
1082
+ if (buf.length > maxBytes) {
1083
+ emitErr(`文件过大:${name}(上限 ${Math.round(maxBytes / 1024 / 1024)}MB)`, `File too large: ${name} (max ${Math.round(maxBytes / 1024 / 1024)}MB)`);
1086
1084
  return;
1087
1085
  }
1088
1086
  mkdirSync(wp.abs, { recursive: true });
@@ -1093,7 +1091,7 @@ export class FilesService {
1093
1091
  // wx:与预检之间存在窗口(TOCTOU),并发同名上传走 EEXIST 落到 catch
1094
1092
  // 报错 —— 两个上传路径语义统一为「目标已存在拒绝」,绝不静默截断覆盖
1095
1093
  // (/api/file-transfer/upload 一直是 open(dest, "wx") 拒绝)。
1096
- writeFileSync(abs, buf, { flag: "wx" });
1094
+ writeUploadExclusiveSync(abs, buf);
1097
1095
  this.host.emit({
1098
1096
  type: "notice",
1099
1097
  level: "info",
@@ -1107,6 +1105,8 @@ export class FilesService {
1107
1105
  type: "file_changed",
1108
1106
  path: wp.rel,
1109
1107
  });
1108
+ if (typeof uploadId === "string")
1109
+ this.host.emit({ type: "file_upload_result", uploadId, ok: true });
1110
1110
  }
1111
1111
  catch (err) {
1112
1112
  emitErr(`上传文件失败:${err.message}`, `Upload failed: ${err.message}`);
@@ -1993,6 +1993,11 @@ export class FilesService {
1993
1993
  });
1994
1994
  return;
1995
1995
  }
1996
+ // Preserve the existing SFTP file object (ACLs, xattrs and symlink target).
1997
+ // Keep the established SFTP save path rather than GNU shell replacement.
1998
+ const info = await sshSvc.sftpStat(rawCwd, t.abs);
1999
+ if (!info.isFile || info.size > 2 * 1024 * 1024)
2000
+ throw new Error("Remote save target must be a regular file no larger than 2MB");
1996
2001
  await sshSvc.sftpWriteFile(rawCwd, t.abs, text);
1997
2002
  this.host.emit({
1998
2003
  type: "notice",
@@ -2011,8 +2016,12 @@ export class FilesService {
2011
2016
  });
2012
2017
  }
2013
2018
  }
2014
- async uploadRemoteFile(rawCwd, relDir, name, data) {
2015
- const emitErr = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
2019
+ async uploadRemoteFile(rawCwd, relDir, name, data, uploadId) {
2020
+ const emitErr = (text, textEn) => {
2021
+ this.host.emit({ type: "notice", level: "error", text, textEn });
2022
+ if (typeof uploadId === "string")
2023
+ this.host.emit({ type: "file_upload_result", uploadId, ok: false, error: textEn ?? text });
2024
+ };
2016
2025
  try {
2017
2026
  const sshSvc = getGlobalRemoteSshService();
2018
2027
  if (!sshSvc)
@@ -2027,12 +2036,13 @@ export class FilesService {
2027
2036
  emitErr(`文件名不合法:${name}`, `Invalid file name: ${name}`);
2028
2037
  return;
2029
2038
  }
2030
- if (isUploadDataTooLong(data.length)) {
2039
+ const maxBytes = this.host.getUploadMaxBytes?.() ?? uploadLimitBytes({}, "workspace");
2040
+ if (isUploadDataTooLong(data.length, maxBytes)) {
2031
2041
  emitErr(`文件过大:${name}`, `File too large: ${name}`);
2032
2042
  return;
2033
2043
  }
2034
2044
  const buf = Buffer.from(data, "base64");
2035
- if (buf.length === 0 || buf.length > MAX_UPLOAD_BYTES) {
2045
+ if (buf.length === 0 || buf.length > maxBytes) {
2036
2046
  emitErr(`文件大小不合法:${name}`, `Invalid file size: ${name}`);
2037
2047
  return;
2038
2048
  }
@@ -2042,7 +2052,7 @@ export class FilesService {
2042
2052
  emitErr(`已存在:${safe}`, `Already exists: ${safe}`);
2043
2053
  return;
2044
2054
  }
2045
- await sshSvc.sftpWriteFile(rawCwd, destAbs, buf, { createParents: true });
2055
+ await writeRemoteUploadExclusive(sshSvc, rawCwd, destAbs, buf);
2046
2056
  const uploadRel = dirTarget.rel ? `${dirTarget.rel}/${safe}` : safe;
2047
2057
  this.host.emit({
2048
2058
  type: "notice",
@@ -2054,6 +2064,8 @@ export class FilesService {
2054
2064
  type: "file_changed",
2055
2065
  path: dirTarget.rel,
2056
2066
  });
2067
+ if (typeof uploadId === "string")
2068
+ this.host.emit({ type: "file_upload_result", uploadId, ok: true });
2057
2069
  }
2058
2070
  catch (err) {
2059
2071
  emitErr(`上传文件失败:${err.message}`, `Upload failed: ${err.message}`);
@@ -19,6 +19,8 @@ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
19
19
  import { fileURLToPath, pathToFileURL } from "node:url";
20
20
  let cachedNpmRootG = null;
21
21
  let cachedCandidateRoots = null;
22
+ let candidateRootsCachedAt = 0;
23
+ const CANDIDATE_CACHE_TTL_MS = 5000;
22
24
  const packageRootCache = new Map();
23
25
  /**
24
26
  * 安全且带缓存地获取系统 npm 全局 root 目录。
@@ -50,9 +52,13 @@ export function getSystemNpmRootG() {
50
52
  * 覆盖:本地项目链、Node 邻近目录、fnm、nvm、pnpm、volta、yarn、bun、npm 全局 prefix 等。
51
53
  */
52
54
  export function getCandidateNodeModulesRoots(options) {
53
- if (!options?.refresh && cachedCandidateRoots !== null) {
55
+ if (!options?.refresh &&
56
+ cachedCandidateRoots !== null &&
57
+ Date.now() - candidateRootsCachedAt < CANDIDATE_CACHE_TTL_MS) {
54
58
  return cachedCandidateRoots;
55
59
  }
60
+ // A refreshed discovery must also re-query npm when its prefix changed.
61
+ cachedNpmRootG = null;
56
62
  const candidates = new Set();
57
63
  // 1. 本包内部与向上的祖先链路 node_modules
58
64
  let cur = dirname(fileURLToPath(import.meta.url));
@@ -100,7 +106,38 @@ export function getCandidateNodeModulesRoots(options) {
100
106
  candidates.add(npmGlobal);
101
107
  const env = process.env;
102
108
  const home = env.HOME || env.USERPROFILE || homedir();
103
- // 6. 版本管理器:fnm 自动嗅探
109
+ // 6. fnm 的 multishell 是临时链接;桌面/服务启动时可能完全不存在。
110
+ // 持久安装位于 FNM_DIR/node-versions/<version>/installation。
111
+ if (env.FNM_MULTISHELL_PATH) {
112
+ for (const suffix of ["node_modules", join("lib", "node_modules")]) {
113
+ const nm = join(env.FNM_MULTISHELL_PATH, suffix);
114
+ if (existsSync(nm))
115
+ candidates.add(resolve(nm));
116
+ }
117
+ }
118
+ const fnmDirs = new Set([
119
+ env.FNM_DIR,
120
+ env.APPDATA && join(env.APPDATA, "fnm"),
121
+ env.LOCALAPPDATA && join(env.LOCALAPPDATA, "fnm"),
122
+ join(env.XDG_DATA_HOME || join(home, ".local", "share"), "fnm"),
123
+ join(home, ".fnm"),
124
+ ].filter((dir) => !!dir));
125
+ for (const fnmDir of fnmDirs) {
126
+ try {
127
+ const versionsDir = join(fnmDir, "node-versions");
128
+ const versions = readdirSync(versionsDir).sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
129
+ for (const version of versions) {
130
+ for (const suffix of ["node_modules", join("lib", "node_modules")]) {
131
+ const nm = join(versionsDir, version, "installation", suffix);
132
+ if (existsSync(nm))
133
+ candidates.add(resolve(nm));
134
+ }
135
+ }
136
+ }
137
+ catch {
138
+ /* Missing or unreadable version store; continue with other managers. */
139
+ }
140
+ }
104
141
  if (process.platform === "win32") {
105
142
  const localAppData = env.LOCALAPPDATA;
106
143
  if (localAppData) {
@@ -202,6 +239,7 @@ export function getCandidateNodeModulesRoots(options) {
202
239
  candidates.add(resolve("/usr/lib/node_modules"));
203
240
  }
204
241
  cachedCandidateRoots = Array.from(candidates);
242
+ candidateRootsCachedAt = Date.now();
205
243
  return cachedCandidateRoots;
206
244
  }
207
245
  /**
@@ -16,7 +16,8 @@
16
16
  * 同样被包裹;但之后经 refreshPluginTools 动态补入已有会话的不在覆盖面。
17
17
  * 自研插件若绕过 wrapper 直接写文件同样拦不住 —— 只读是硬闸门,不是安全边界。
18
18
  */
19
- import { bashCommandIsReadOnly, SESSION_DISPATCH_TOOLS } from "./plan-mode.js";
19
+ import { bashCommandIsReadOnly, readOnlyToolCallAllowed, SESSION_DISPATCH_TOOLS } from "./plan-mode.js";
20
+ import { isReadOnlyConversationAction, isConversationTool } from "./conversation-tool-names.js";
20
21
  /** 审查回合禁写的工具:与计划/审查者模式同名单(写 / 改 / 增删 / git 写 / 形态变换)。 */
21
22
  const WRITE_TOOLS = new Set([
22
23
  // 文件写入与编辑(第一方 + SDK 内置 + 编辑器类扩展的常见名)
@@ -68,12 +69,12 @@ const WRITE_TOOLS = new Set([
68
69
  * 别的对话、排程、改模式 / 开新目标都会绕开「一轮 = 派活 + 判定」的口径。
69
70
  * 名单 = 三闸门共用的真实注册派发工具(SESSION_DISPATCH_TOOLS,#436 前是一堆
70
71
  * 幽灵名)。subagent 不在此列:上面的按 action 判定已拦掉全部写向 action,
71
- * 只读的 `conversation_read` / subagent get_result/list/templates 放行 ——
72
+ * conversation 的只读操作(read/files/status/get_result/list/templates)放行 ——
72
73
  * 审查者可以按需看执行者的转录(契约要求看实际状态,而不是信描述)。
73
74
  */
74
75
  const DISPATCH_TOOLS = SESSION_DISPATCH_TOOLS;
75
76
  /** bash 家族(要逐条判命令是否只读;与审查者模式同名单)。 */
76
- const BASH_TOOLS = new Set(["bash", "shell", "sh", "zsh", "terminal", "terminal_bash", "run_command", "exec"]);
77
+ const BASH_TOOLS = new Set(["bash", "shell", "sh", "zsh", "terminal_bash", "run_command", "exec"]);
77
78
  /** 引号感知的命令切分(按 | ; && || 换行拆段;含 $( / 反引号时整条视为一段交白名单判
78
79
  * —— 白名单必拒,方向是 fail-closed,这里的拆分只会让判定更严不会放宽)。 */
79
80
  function splitReviewSegments(cmd) {
@@ -206,11 +207,11 @@ export function goalReviewDenial(toolName, params) {
206
207
  reasonEn: "Goal review round: do not ask the user anything (this round is server-driven; dialogs go unanswered). Just review this round and reply with only the verdict JSON.",
207
208
  };
208
209
  }
209
- if (name === "subagent") {
210
+ if (isConversationTool(name)) {
210
211
  const action = typeof params === "object" && params !== null ? params.action : undefined;
211
212
  const act = typeof action === "string" ? action.trim().toLowerCase() : "";
212
- // 只读 action(get_result, list, templates)放行;其余(spawn, steer, stop, wait_all, handoff)或未传 action 均拒绝
213
- if (act === "get_result" || act === "list" || act === "templates") {
213
+ // Transcript inspection and collaboration queries are read-only; mutations and missing actions are rejected.
214
+ if (isReadOnlyConversationAction(act)) {
214
215
  return undefined;
215
216
  }
216
217
  return {
@@ -226,6 +227,15 @@ export function goalReviewDenial(toolName, params) {
226
227
  reasonEn: `Goal review round: ${name} is unavailable — the server owns the rounds. Just review this round and reply with only the verdict JSON.`,
227
228
  };
228
229
  }
230
+ if (name === "terminal") {
231
+ if (readOnlyToolCallAllowed(name, params))
232
+ return undefined;
233
+ return {
234
+ kind: "write-tool",
235
+ reason: "只读审查仅允许 terminal 的 list/read/wait。",
236
+ reasonEn: "Read-only review permits only terminal list/read/wait actions.",
237
+ };
238
+ }
229
239
  if (BASH_TOOLS.has(name)) {
230
240
  const cmd = commandOf(params);
231
241
  if (cmd.trim() === "") {