pi-web-ui 0.113.1 → 0.114.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/README.md +117 -246
  3. package/README.zh-CN.md +145 -217
  4. package/README.zh-TW.md +145 -217
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/pi-device-hub.mjs +9 -0
  7. package/bin/pi-web-ui.mjs +47 -15
  8. package/dist/server/agent-service-daemon.js +102 -24
  9. package/dist/server/agent-service.js +2289 -1120
  10. package/dist/server/approval-rules.js +29 -3
  11. package/dist/server/ask-user-question-tool.js +8 -8
  12. package/dist/server/atomic-file.js +35 -14
  13. package/dist/server/attachment-store.js +71 -35
  14. package/dist/server/attachments.js +18 -8
  15. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  16. package/dist/server/canvas/canvas-dispatch.js +61 -20
  17. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  18. package/dist/server/canvas/canvas-scheduler.js +99 -0
  19. package/dist/server/canvas/canvas-store.js +107 -54
  20. package/dist/server/canvas/canvas-validation.js +131 -0
  21. package/dist/server/canvas/canvas-workspace.js +284 -0
  22. package/dist/server/client-id-utils.js +8 -0
  23. package/dist/server/client-state.js +104 -22
  24. package/dist/server/communicate-tool.js +76 -0
  25. package/dist/server/compact-context-tool.js +2 -3
  26. package/dist/server/compaction-instructions.js +75 -0
  27. package/dist/server/compaction-markers.js +7 -2
  28. package/dist/server/compaction-state.js +84 -0
  29. package/dist/server/composer-drafts.js +43 -40
  30. package/dist/server/context-evidence.js +346 -0
  31. package/dist/server/conversation-communication.js +368 -0
  32. package/dist/server/conversation-read-tool.js +3 -4
  33. package/dist/server/conversation-tool-names.js +14 -0
  34. package/dist/server/conversation-tool.js +57 -0
  35. package/dist/server/delegate-mode.js +17 -4
  36. package/dist/server/device-center/bot-catalog.js +88 -0
  37. package/dist/server/device-center/bot-execution.js +106 -0
  38. package/dist/server/device-center/bots.js +170 -0
  39. package/dist/server/device-center/collab-service.js +153 -0
  40. package/dist/server/device-center/collab-tool.js +184 -0
  41. package/dist/server/device-center/connector.js +332 -0
  42. package/dist/server/device-center/desktop-linux.js +372 -0
  43. package/dist/server/device-center/desktop-native.js +413 -0
  44. package/dist/server/device-center/desktop-page.js +232 -0
  45. package/dist/server/device-center/desktop-setup.js +30 -0
  46. package/dist/server/device-center/desktop.js +387 -0
  47. package/dist/server/device-center/device-portals.js +241 -0
  48. package/dist/server/device-center/execution-failure.js +70 -0
  49. package/dist/server/device-center/executor.js +371 -0
  50. package/dist/server/device-center/file-sync.js +493 -0
  51. package/dist/server/device-center/hub-auth.js +69 -0
  52. package/dist/server/device-center/hub-page.js +68 -0
  53. package/dist/server/device-center/hub-setup.js +214 -0
  54. package/dist/server/device-center/hub.js +829 -0
  55. package/dist/server/device-center/local-page.js +17 -0
  56. package/dist/server/device-center/local.js +476 -0
  57. package/dist/server/device-center/main.js +118 -0
  58. package/dist/server/device-center/native-desktop/macos.js +192 -0
  59. package/dist/server/device-center/native-desktop/windows.js +118 -0
  60. package/dist/server/device-center/path-portal.js +120 -0
  61. package/dist/server/device-center/relay.js +959 -0
  62. package/dist/server/device-center/runtime.js +253 -0
  63. package/dist/server/device-center/smoke-preview.js +3 -0
  64. package/dist/server/device-center/store.js +122 -0
  65. package/dist/server/device-center/task-error.js +14 -0
  66. package/dist/server/device-center/transfers.js +293 -0
  67. package/dist/server/device-center/workspaces.js +45 -0
  68. package/dist/server/dispatch-domain-handlers.js +83 -27
  69. package/dist/server/dsh/dsh-agent-service.js +277 -158
  70. package/dist/server/dsh/dsh-client.js +12 -2
  71. package/dist/server/durable/durable-agent-service.js +1 -1
  72. package/dist/server/evidence-tool-hooks.js +49 -0
  73. package/dist/server/file-save.js +95 -0
  74. package/dist/server/file-transfer-routes.js +97 -47
  75. package/dist/server/files-service.js +38 -26
  76. package/dist/server/goal-review-gate.js +16 -6
  77. package/dist/server/goal-service.js +54 -30
  78. package/dist/server/http-proxy.js +120 -0
  79. package/dist/server/index.js +229 -223
  80. package/dist/server/load-timing.js +31 -0
  81. package/dist/server/mcp-bridge.js +219 -94
  82. package/dist/server/mcp-hot-reload.js +31 -5
  83. package/dist/server/mcp-manager.js +192 -93
  84. package/dist/server/mcp-oauth-login.js +169 -0
  85. package/dist/server/mcp-oauth-ui.js +137 -0
  86. package/dist/server/mcp-oauth.js +395 -0
  87. package/dist/server/mcp-project-runtime.js +207 -0
  88. package/dist/server/message-window.js +74 -21
  89. package/dist/server/net-guard.js +122 -20
  90. package/dist/server/payload-limits.js +17 -0
  91. package/dist/server/pending-question.js +82 -0
  92. package/dist/server/plan-mode.js +338 -137
  93. package/dist/server/plugin-assets.js +8 -4
  94. package/dist/server/plugin-chat-attachments.js +48 -0
  95. package/dist/server/plugin-facilities.js +67 -220
  96. package/dist/server/plugin-installer.js +2 -1
  97. package/dist/server/plugin-removal.js +49 -0
  98. package/dist/server/plugin-secrets.js +179 -0
  99. package/dist/server/plugins.js +262 -92
  100. package/dist/server/preset-fields.js +49 -0
  101. package/dist/server/preset-plugin-dependencies.js +57 -0
  102. package/dist/server/preset-share.js +112 -72
  103. package/dist/server/protocol-version.js +1 -1
  104. package/dist/server/queue-modes.js +10 -0
  105. package/dist/server/remote-ssh-service.js +160 -67
  106. package/dist/server/request-context.js +164 -0
  107. package/dist/server/sandbox-data.js +655 -0
  108. package/dist/server/sandbox-engines.js +7 -0
  109. package/dist/server/sandbox-runtime-gate.js +41 -0
  110. package/dist/server/sandbox-service.js +139 -698
  111. package/dist/server/sandbox-tool.js +21 -4
  112. package/dist/server/scheduler-tasks.js +63 -48
  113. package/dist/server/serialize.js +48 -19
  114. package/dist/server/session-branch.js +25 -3
  115. package/dist/server/session-parser.js +28 -18
  116. package/dist/server/session-scan.js +130 -0
  117. package/dist/server/session-search.js +51 -37
  118. package/dist/server/settings-service.js +267 -111
  119. package/dist/server/setup-config.js +58 -0
  120. package/dist/server/skill-maintenance.js +112 -24
  121. package/dist/server/subagent-helpers.js +4 -1
  122. package/dist/server/subagent-notify.js +4 -1
  123. package/dist/server/subagent-security-gate.js +52 -11
  124. package/dist/server/subagent-task.js +27 -0
  125. package/dist/server/subagents.js +217 -46
  126. package/dist/server/tabs.js +9 -1
  127. package/dist/server/terminals.js +467 -363
  128. package/dist/server/tool-guards.js +42 -6
  129. package/dist/server/tool-manager.js +47 -20
  130. package/dist/server/tool-overrides.js +13 -11
  131. package/dist/server/tool-prompt-overrides.js +32 -2
  132. package/dist/server/tool-prompts.js +1 -1
  133. package/dist/server/turn-timing.js +11 -0
  134. package/dist/server/universal/session-store.js +48 -6
  135. package/dist/server/universal/universal-service.js +1 -1
  136. package/dist/server/universal/universal-session.js +334 -231
  137. package/dist/server/uploads.js +64 -5
  138. package/dist/server/worktree-service.js +32 -24
  139. package/dist/server/ws-pending-queue.js +73 -27
  140. package/docs/device-center.md +142 -0
  141. package/docs/device-desktop.md +48 -0
  142. package/package.json +4 -1
  143. package/plugin-sdk/index.d.ts +28 -6
  144. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  145. package/plugins/catalog.json +1 -1
  146. package/themes/aetheris.css +1 -107
  147. package/themes/ayu-light.css +5 -29
  148. package/themes/bases/flow-base.css +0 -6
  149. package/themes/bases/statusbar-flat-base.css +112 -0
  150. package/themes/bases/zhujian-base.css +1 -0
  151. package/themes/bases/zhupi-base.css +1 -0
  152. package/themes/catppuccin-latte.css +4 -27
  153. package/themes/catppuccin.css +4 -35
  154. package/themes/claude-code-dark.css +1 -0
  155. package/themes/codex.css +4 -28
  156. package/themes/cyberpunk.css +3 -61
  157. package/themes/dark-teal.css +0 -1
  158. package/themes/dazzle.css +3 -73
  159. package/themes/everforest-light.css +4 -27
  160. package/themes/geist.css +4 -28
  161. package/themes/gruvbox-light.css +4 -27
  162. package/themes/kanagawa-lotus.css +4 -27
  163. package/themes/md-preview.css +3 -213
  164. package/themes/mist.css +4 -24
  165. package/themes/nord.css +4 -35
  166. package/themes/one-dark.css +4 -37
  167. package/themes/paper.css +4 -16
  168. package/themes/rose-pine-dawn.css +4 -28
  169. package/themes/sakura.css +4 -24
  170. package/themes/solarized-light.css +4 -27
  171. package/themes/tokyo-night.css +3 -34
  172. package/themes/white.css +4 -26
  173. package/themes/zhujian-dark.css +1 -0
  174. package/themes/zhupi-dark.css +1 -0
  175. package/web/dist/.build-assets.json +1 -0
  176. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  177. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  178. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  179. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  180. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  181. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  182. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  183. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  184. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  185. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  186. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  187. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  188. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  189. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  190. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  191. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  192. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  193. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  194. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  195. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  196. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  197. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  198. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  199. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  200. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  201. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  202. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  203. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  204. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  205. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  206. package/web/dist/assets/index-Cje8iugL.js +83 -0
  207. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  208. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  209. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  210. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  211. package/web/dist/assets/math-BorAY7qD.css +1 -0
  212. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  213. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  214. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  215. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  216. package/web/dist/index.html +15 -9
  217. package/web/dist/sw.js +1 -1
  218. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  219. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  220. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  221. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  222. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -73,6 +73,8 @@ export class DshRuntime {
73
73
  env;
74
74
  jsonrpcEntry;
75
75
  proc = null;
76
+ beforeStart;
77
+ onStopping;
76
78
  startPromise = null;
77
79
  buffer = "";
78
80
  nextId = 1;
@@ -95,6 +97,8 @@ export class DshRuntime {
95
97
  * 宿主用它重新注册一次性资源(如插件工具桥),因为重 spawn 后 ctx 是全新的。 */
96
98
  onStarted = null;
97
99
  constructor(opts) {
100
+ this.beforeStart = opts.beforeStart;
101
+ this.onStopping = opts.onStopping;
98
102
  this.cwd = resolve(opts.cwd);
99
103
  this.provider = opts.provider ?? "deepseek-official";
100
104
  this.model = opts.model ?? "deepseek-v4-flash";
@@ -169,6 +173,7 @@ export class DshRuntime {
169
173
  }
170
174
  /** 启动子进程 + initialize 握手(幂等;并发调用共享同一个启动任务)。 */
171
175
  start() {
176
+ this.beforeStart?.(this.cwd);
172
177
  if (this.disposed) {
173
178
  return Promise.reject(new DshTransportError(bilingual("client has been disposed", "客户端已销毁")));
174
179
  }
@@ -458,6 +463,7 @@ export class DshRuntime {
458
463
  }
459
464
  /** 优雅关闭:shutdown 握手 → stdin EOF → SIGTERM → SIGKILL 阶梯。 */
460
465
  async close() {
466
+ this.onStopping?.();
461
467
  if (this.disposed)
462
468
  return;
463
469
  this.disposed = true;
@@ -519,6 +525,7 @@ export class DshRuntime {
519
525
  * win32: taskkill /pid X /T /F;posix: SIGKILL(-pid)(detached 进程组)。
520
526
  */
521
527
  async kill() {
528
+ this.onStopping?.();
522
529
  const proc = this.proc;
523
530
  this.debug("kill", { pid: proc?.pid });
524
531
  this.closed = true;
@@ -600,7 +607,8 @@ export class DshRuntime {
600
607
  }
601
608
  }
602
609
  /** 换模型:关掉当前运行时(若活着),下次 start() 用新 model 重新 spawn。 */
603
- async restart(newModel, newProvider) {
610
+ async restart(newModel, newProvider, cwd) {
611
+ this.beforeStart?.(cwd ? resolve(cwd) : this.cwd);
604
612
  const wasAlive = this.alive;
605
613
  this.debug("restart", { newModel, newProvider, wasAlive });
606
614
  if (wasAlive) {
@@ -614,6 +622,8 @@ export class DshRuntime {
614
622
  this.modelProvider = newModel.slice(0, newModel.indexOf("/"));
615
623
  }
616
624
  }
625
+ if (cwd)
626
+ this.cwd = resolve(cwd);
617
627
  if (newProvider) {
618
628
  if (newProvider === "deepseek-official") {
619
629
  this.provider = newProvider;
@@ -623,7 +633,7 @@ export class DshRuntime {
623
633
  }
624
634
  }
625
635
  this.initialized = false;
626
- if (wasAlive)
636
+ if (wasAlive || cwd)
627
637
  await this.start();
628
638
  }
629
639
  /** stderr 尾部(诊断用)。 */
@@ -27,7 +27,7 @@ export class DurableAgentService {
27
27
  this.cwd = opts.cwd;
28
28
  this.dataDir = opts.dataDir;
29
29
  this.agentDir = opts.agentDir;
30
- this.store = new UniversalSessionStore(opts.dataDir);
30
+ this.store = new UniversalSessionStore(opts.dataDir, "durable");
31
31
  this.stateStore = opts.stateStore;
32
32
  }
33
33
  async attach(clientId, send) {
@@ -0,0 +1,49 @@
1
+ import { join } from "node:path";
2
+ const installed = new WeakMap();
3
+ const PREFIX = "context-evidence:";
4
+ /** Resolve evidence before SDK permission hooks; leave all file access to the reader. */
5
+ export function installEvidenceToolHooks(session) {
6
+ if (!session || typeof session !== "object")
7
+ return false;
8
+ const target = session;
9
+ const original = target._beforeToolCall;
10
+ if (typeof original !== "function" || original.length !== 2)
11
+ return false;
12
+ if (installed.get(target) === original)
13
+ return true;
14
+ if (typeof target.sessionManager?.getSessionFile !== "function")
15
+ return false;
16
+ const wrapper = function (context, parentId) {
17
+ if (context.toolCall.name === "read" && context.args && typeof context.args === "object") {
18
+ const args = context.args;
19
+ const values = [args.path, args.file_path];
20
+ const references = values.filter((value) => typeof value === "string" && value.startsWith(PREFIX));
21
+ if (references.length) {
22
+ context.signal?.throwIfAborted();
23
+ const reference = references[0];
24
+ const match = /^context-evidence:([a-f0-9]{64})$/.exec(reference);
25
+ const isIndex = reference === `${PREFIX}index`;
26
+ if ((!isIndex && (!match || reference.length !== PREFIX.length + 64)) ||
27
+ values.some((value) => value !== undefined && value !== reference)) {
28
+ throw new Error("Invalid or conflicting evidence reference");
29
+ }
30
+ const sessionFile = target.sessionManager.getSessionFile();
31
+ if (!sessionFile)
32
+ throw new Error("Evidence requires a persisted session");
33
+ // SDK validated args must be detached from the immutable transcript block.
34
+ if (args === context.toolCall.arguments) {
35
+ throw new Error("Evidence arguments must not alias tool call history");
36
+ }
37
+ context.signal?.throwIfAborted();
38
+ const directory = `${sessionFile}.evidence`;
39
+ const path = isIndex ? directory : join(directory, `${match[1]}.txt`);
40
+ args.path = path;
41
+ args.file_path = path;
42
+ }
43
+ }
44
+ return original.call(this, context, parentId);
45
+ };
46
+ target._beforeToolCall = wrapper;
47
+ installed.set(target, wrapper);
48
+ return true;
49
+ }
@@ -0,0 +1,95 @@
1
+ import { execFile } from "node:child_process";
2
+ import { access, mkdtemp, open, realpath, rename, rm, stat } from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ const run = promisify(execFile);
7
+ const timeout = 30_000;
8
+ const attributes = "--preserve=mode,ownership,timestamps,xattr";
9
+ /** Save an existing regular file without truncating it or silently discarding
10
+ * platform metadata. All preparation happens on the target volume. Native
11
+ * metadata/replace failures are fatal; there is no direct-write fallback.
12
+ * This provides atomic visibility, not a guarantee against power loss.
13
+ */
14
+ export async function saveFilePreservingMetadata(path, text) {
15
+ const target = await realpath(path); // Keep symlinks, replace their actual target.
16
+ const before = await stat(target);
17
+ if (!before.isFile())
18
+ throw new Error("Save target is not a regular file");
19
+ if (before.nlink > 1)
20
+ throw new Error("Cannot atomically save a file with multiple hard links");
21
+ await access(target, constants.W_OK);
22
+ if (!["win32", "linux", "darwin", "freebsd"].includes(process.platform))
23
+ throw new Error(`Metadata-preserving saves are unsupported on ${process.platform}`);
24
+ const stageDir = await mkdtemp(join(dirname(target), ".pi-save-"));
25
+ const staged = join(stageDir, "content");
26
+ const backup = join(stageDir, "original");
27
+ let committed = false;
28
+ try {
29
+ if (process.platform !== "win32") {
30
+ await run("cp", process.platform === "linux" ? [attributes, "--", target, staged] : ["-p", target, staged], {
31
+ timeout,
32
+ });
33
+ }
34
+ const handle = await open(staged, process.platform === "win32" ? "wx" : "r+", 0o600);
35
+ try {
36
+ await handle.writeFile(text, "utf8");
37
+ await handle.truncate(Buffer.byteLength(text, "utf8"));
38
+ await handle.sync();
39
+ }
40
+ finally {
41
+ await handle.close();
42
+ }
43
+ if (process.platform === "linux") {
44
+ // Writing can clear security xattrs/set-id bits. Reapply explicitly:
45
+ // unlike --preserve=all, failure to preserve a named attribute is fatal.
46
+ await run("cp", ["--attributes-only", attributes, "--", target, staged], { timeout });
47
+ const metadataHandle = await open(staged, "r");
48
+ try {
49
+ await metadataHandle.sync();
50
+ }
51
+ finally {
52
+ await metadataHandle.close();
53
+ }
54
+ }
55
+ const current = await stat(target);
56
+ if (current.dev !== before.dev ||
57
+ current.ino !== before.ino ||
58
+ current.nlink > 1 ||
59
+ current.size !== before.size ||
60
+ current.mtimeMs !== before.mtimeMs ||
61
+ current.ctimeMs !== before.ctimeMs)
62
+ throw new Error("Save target changed while preparing replacement; retry saving");
63
+ if (process.platform === "win32") {
64
+ // Constant script + environment paths: filenames never become PowerShell
65
+ // code. Start one process per explicit save, without a shell/profile.
66
+ const script = "$ErrorActionPreference='Stop'; try { [IO.File]::Replace($env:PI_SAVE_SOURCE,$env:PI_SAVE_TARGET,$env:PI_SAVE_BACKUP,$false) } catch { [Console]::Error.WriteLine($_.Exception.ToString()); exit 1 }";
67
+ await run("powershell.exe", [
68
+ "-NoLogo",
69
+ "-NoProfile",
70
+ "-NonInteractive",
71
+ "-EncodedCommand",
72
+ Buffer.from(script, "utf16le").toString("base64"),
73
+ ], {
74
+ timeout,
75
+ windowsHide: true,
76
+ env: { ...process.env, PI_SAVE_SOURCE: staged, PI_SAVE_TARGET: target, PI_SAVE_BACKUP: backup },
77
+ });
78
+ }
79
+ else
80
+ await rename(staged, target);
81
+ committed = true;
82
+ }
83
+ catch (error) {
84
+ // ReplaceFile can fail part-way through a metadata merge. Never delete
85
+ // its recovery backup on error; expose its stable path to the caller.
86
+ if (await stat(backup).then(() => true, () => false))
87
+ throw new Error(`Save failed; recovery file retained at ${backup}`, { cause: error });
88
+ throw error;
89
+ }
90
+ finally {
91
+ const hasBackup = await stat(backup).then(() => true, () => false);
92
+ if (committed || !hasBackup)
93
+ await rm(stageDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
94
+ }
95
+ }
@@ -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}`);
@@ -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() === "") {