pi-web-ui 0.113.0 → 0.114.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -1
- package/README.md +117 -252
- package/README.zh-CN.md +145 -223
- package/README.zh-TW.md +145 -223
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +145 -20
- package/dist/gh-comment-781.md +5 -0
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2296 -1121
- package/dist/server/approval-rules.js +29 -3
- package/dist/server/ask-user-question-tool.js +8 -8
- package/dist/server/atomic-file.js +35 -14
- package/dist/server/attachment-store.js +71 -35
- package/dist/server/attachments.js +18 -8
- package/dist/server/canvas/canvas-agent-tool.js +65 -15
- package/dist/server/canvas/canvas-dispatch.js +61 -20
- package/dist/server/canvas/canvas-orchestrator.js +516 -199
- package/dist/server/canvas/canvas-scheduler.js +99 -0
- package/dist/server/canvas/canvas-store.js +107 -54
- package/dist/server/canvas/canvas-validation.js +131 -0
- package/dist/server/canvas/canvas-workspace.js +284 -0
- package/dist/server/client-id-utils.js +8 -0
- package/dist/server/client-state.js +104 -22
- package/dist/server/communicate-tool.js +76 -0
- package/dist/server/compact-context-tool.js +2 -3
- package/dist/server/compaction-instructions.js +75 -0
- package/dist/server/compaction-markers.js +7 -2
- package/dist/server/compaction-state.js +84 -0
- package/dist/server/composer-drafts.js +43 -40
- package/dist/server/context-evidence.js +346 -0
- package/dist/server/control-socket.js +6 -2
- package/dist/server/conversation-communication.js +368 -0
- package/dist/server/conversation-read-tool.js +3 -4
- package/dist/server/conversation-tool-names.js +14 -0
- package/dist/server/conversation-tool.js +57 -0
- package/dist/server/delegate-mode.js +17 -4
- package/dist/server/device-center/bot-catalog.js +88 -0
- package/dist/server/device-center/bot-execution.js +106 -0
- package/dist/server/device-center/bots.js +170 -0
- package/dist/server/device-center/collab-service.js +153 -0
- package/dist/server/device-center/collab-tool.js +184 -0
- package/dist/server/device-center/connector.js +332 -0
- package/dist/server/device-center/desktop-linux.js +372 -0
- package/dist/server/device-center/desktop-native.js +413 -0
- package/dist/server/device-center/desktop-page.js +232 -0
- package/dist/server/device-center/desktop-setup.js +30 -0
- package/dist/server/device-center/desktop.js +387 -0
- package/dist/server/device-center/device-portals.js +241 -0
- package/dist/server/device-center/execution-failure.js +70 -0
- package/dist/server/device-center/executor.js +371 -0
- package/dist/server/device-center/file-sync.js +493 -0
- package/dist/server/device-center/hub-auth.js +69 -0
- package/dist/server/device-center/hub-page.js +68 -0
- package/dist/server/device-center/hub-setup.js +214 -0
- package/dist/server/device-center/hub.js +829 -0
- package/dist/server/device-center/local-page.js +17 -0
- package/dist/server/device-center/local.js +476 -0
- package/dist/server/device-center/main.js +118 -0
- package/dist/server/device-center/native-desktop/macos.js +192 -0
- package/dist/server/device-center/native-desktop/windows.js +118 -0
- package/dist/server/device-center/path-portal.js +120 -0
- package/dist/server/device-center/relay.js +959 -0
- package/dist/server/device-center/runtime.js +253 -0
- package/dist/server/device-center/smoke-preview.js +3 -0
- package/dist/server/device-center/store.js +122 -0
- package/dist/server/device-center/task-error.js +14 -0
- package/dist/server/device-center/transfers.js +293 -0
- package/dist/server/device-center/workspaces.js +45 -0
- package/dist/server/dispatch-domain-handlers.js +83 -27
- package/dist/server/dsh/dsh-agent-service.js +277 -158
- package/dist/server/dsh/dsh-client.js +12 -2
- package/dist/server/durable/durable-agent-service.js +1 -1
- package/dist/server/evidence-tool-hooks.js +49 -0
- package/dist/server/file-save.js +95 -0
- package/dist/server/file-transfer-routes.js +97 -47
- package/dist/server/files-service.js +110 -34
- package/dist/server/goal-review-gate.js +16 -6
- package/dist/server/goal-service.js +54 -30
- package/dist/server/http-proxy.js +120 -0
- package/dist/server/index.js +236 -232
- package/dist/server/load-timing.js +31 -0
- package/dist/server/mcp-bridge.js +219 -94
- package/dist/server/mcp-hot-reload.js +31 -5
- package/dist/server/mcp-manager.js +192 -93
- package/dist/server/mcp-oauth-login.js +169 -0
- package/dist/server/mcp-oauth-ui.js +137 -0
- package/dist/server/mcp-oauth.js +395 -0
- package/dist/server/mcp-project-runtime.js +207 -0
- package/dist/server/message-window.js +74 -21
- package/dist/server/net-guard.js +122 -20
- package/dist/server/payload-limits.js +17 -0
- package/dist/server/pending-question.js +82 -0
- package/dist/server/plan-mode.js +338 -137
- package/dist/server/plugin-assets.js +8 -4
- package/dist/server/plugin-chat-attachments.js +48 -0
- package/dist/server/plugin-facilities.js +67 -220
- package/dist/server/plugin-installer.js +2 -1
- package/dist/server/plugin-removal.js +49 -0
- package/dist/server/plugin-secrets.js +179 -0
- package/dist/server/plugins.js +262 -92
- package/dist/server/preset-fields.js +49 -0
- package/dist/server/preset-plugin-dependencies.js +57 -0
- package/dist/server/preset-share.js +112 -72
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-modes.js +10 -0
- package/dist/server/remote-ssh-service.js +160 -67
- package/dist/server/request-context.js +164 -0
- package/dist/server/sandbox-data.js +655 -0
- package/dist/server/sandbox-engines.js +7 -0
- package/dist/server/sandbox-runtime-gate.js +41 -0
- package/dist/server/sandbox-service.js +139 -698
- package/dist/server/sandbox-tool.js +21 -4
- package/dist/server/scheduler-tasks.js +63 -48
- package/dist/server/serialize.js +48 -19
- package/dist/server/session-branch.js +25 -3
- package/dist/server/session-parser.js +28 -18
- package/dist/server/session-scan.js +130 -0
- package/dist/server/session-search.js +51 -37
- package/dist/server/settings-service.js +267 -111
- package/dist/server/setup-config.js +58 -0
- package/dist/server/skill-maintenance.js +112 -24
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagent-notify.js +4 -1
- package/dist/server/subagent-security-gate.js +52 -11
- package/dist/server/subagent-task.js +27 -0
- package/dist/server/subagents.js +217 -46
- package/dist/server/tabs.js +9 -1
- package/dist/server/terminals.js +467 -363
- package/dist/server/tool-guards.js +42 -6
- package/dist/server/tool-manager.js +47 -20
- package/dist/server/tool-overrides.js +13 -11
- package/dist/server/tool-prompt-overrides.js +32 -2
- package/dist/server/tool-prompts.js +1 -1
- package/dist/server/turn-timing.js +11 -0
- package/dist/server/universal/session-store.js +48 -6
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +334 -231
- package/dist/server/uploads.js +64 -5
- package/dist/server/webui-context.js +6 -6
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/dist/test-artifact.md +9 -0
- package/dist/test-preview-modal.md +11 -0
- package/dist/test-report.html +20 -0
- package/docs/device-center.md +142 -0
- package/docs/device-desktop.md +48 -0
- package/package.json +4 -1
- package/plugin-sdk/index.d.ts +45 -9
- package/plugin-sdk/ssh-host-trust.mjs +225 -0
- package/plugins/catalog.json +1 -1
- package/themes/aetheris.css +1 -107
- package/themes/ayu-light.css +5 -29
- package/themes/bases/flow-base.css +0 -6
- package/themes/bases/statusbar-flat-base.css +112 -0
- package/themes/bases/zhujian-base.css +1 -0
- package/themes/bases/zhupi-base.css +1 -0
- package/themes/catppuccin-latte.css +4 -27
- package/themes/catppuccin.css +4 -35
- package/themes/claude-code-dark.css +1 -0
- package/themes/codex.css +4 -28
- package/themes/cyberpunk.css +3 -61
- package/themes/dark-teal.css +0 -1
- package/themes/dazzle.css +3 -73
- package/themes/everforest-light.css +4 -27
- package/themes/geist.css +4 -28
- package/themes/gruvbox-light.css +4 -27
- package/themes/kanagawa-lotus.css +4 -27
- package/themes/md-preview.css +3 -213
- package/themes/mist.css +4 -24
- package/themes/nord.css +4 -35
- package/themes/one-dark.css +4 -37
- package/themes/paper.css +4 -16
- package/themes/rose-pine-dawn.css +4 -28
- package/themes/sakura.css +4 -24
- package/themes/solarized-light.css +4 -27
- package/themes/tokyo-night.css +3 -34
- package/themes/white.css +4 -26
- package/themes/zhujian-dark.css +1 -0
- package/themes/zhupi-dark.css +1 -0
- package/web/dist/.build-assets.json +1 -0
- package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
- package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
- package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
- package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
- package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
- package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
- package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
- package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
- package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
- package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
- package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
- package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
- package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
- package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
- package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
- package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
- package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
- package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
- package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
- package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
- package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
- package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
- package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
- package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
- package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
- package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
- package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
- package/web/dist/assets/es-DWMIuDU2.js +2 -0
- package/web/dist/assets/index-CPgAH5q7.js +83 -0
- package/web/dist/assets/index-Cje8iugL.js +83 -0
- package/web/dist/assets/index-DnKeiDbj.css +1 -0
- package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
- package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
- package/web/dist/assets/math-1uRJCsA9.js +257 -0
- package/web/dist/assets/math-BorAY7qD.css +1 -0
- package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
- package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
- package/web/dist/assets/theme-BqdAjEjF.js +1 -0
- package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
- package/web/dist/index.html +15 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/TerminalPanel-3wojLfLk.js +0 -3
- package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
- package/web/dist/assets/index-BwL7qBh6.css +0 -1
- package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
- package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
|
@@ -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
|
|
2
|
-
import {
|
|
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
|
-
//
|
|
178
|
-
|
|
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
|
-
|
|
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
|
|
210
|
-
|
|
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
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
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
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
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
|
-
|
|
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
|
-
|
|
232
|
-
|
|
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
|
}
|