pi-web-ui 0.113.1 → 0.114.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +71 -1
- package/README.md +187 -316
- package/README.zh-CN.md +227 -299
- package/README.zh-TW.md +227 -299
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/frp-manager.mjs +1573 -1573
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +4081 -4041
- package/deploy/nginx-subpath.conf +100 -100
- package/deploy/pi-web-ui.service +36 -36
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2419 -1174
- package/dist/server/approval-rules.js +29 -3
- package/dist/server/ask-user-question-tool.js +8 -8
- package/dist/server/atomic-file.js +35 -14
- package/dist/server/attachment-store.js +71 -35
- package/dist/server/attachments.js +69 -13
- package/dist/server/canvas/canvas-agent-tool.js +68 -18
- package/dist/server/canvas/canvas-cards.js +1 -1
- package/dist/server/canvas/canvas-dispatch.js +61 -20
- package/dist/server/canvas/canvas-orchestrator.js +519 -202
- package/dist/server/canvas/canvas-scheduled-task.js +45 -0
- package/dist/server/canvas/canvas-scheduler.js +99 -0
- package/dist/server/canvas/canvas-store.js +107 -54
- package/dist/server/canvas/canvas-validation.js +131 -0
- package/dist/server/canvas/canvas-workspace.js +284 -0
- package/dist/server/client-id-utils.js +8 -0
- package/dist/server/client-state.js +110 -24
- package/dist/server/communicate-tool.js +76 -0
- package/dist/server/compact-context-tool.js +2 -3
- package/dist/server/compaction-instructions.js +75 -0
- package/dist/server/compaction-markers.js +7 -2
- package/dist/server/compaction-state.js +84 -0
- package/dist/server/composer-drafts.js +43 -40
- package/dist/server/context-evidence.js +346 -0
- package/dist/server/conversation-communication.js +368 -0
- package/dist/server/conversation-read-tool.js +3 -4
- package/dist/server/conversation-tool-names.js +14 -0
- package/dist/server/conversation-tool.js +57 -0
- package/dist/server/delegate-mode.js +17 -4
- package/dist/server/device-center/bot-catalog.js +88 -0
- package/dist/server/device-center/bot-execution.js +106 -0
- package/dist/server/device-center/bots.js +170 -0
- package/dist/server/device-center/collab-service.js +153 -0
- package/dist/server/device-center/collab-tool.js +184 -0
- package/dist/server/device-center/connector.js +351 -0
- package/dist/server/device-center/desktop-linux.js +372 -0
- package/dist/server/device-center/desktop-native.js +413 -0
- package/dist/server/device-center/desktop-page.js +232 -0
- package/dist/server/device-center/desktop-setup.js +30 -0
- package/dist/server/device-center/desktop.js +387 -0
- package/dist/server/device-center/device-portals.js +241 -0
- package/dist/server/device-center/execution-failure.js +70 -0
- package/dist/server/device-center/executor.js +371 -0
- package/dist/server/device-center/file-sync.js +493 -0
- package/dist/server/device-center/hub-auth.js +69 -0
- package/dist/server/device-center/hub-page.js +68 -0
- package/dist/server/device-center/hub-setup.js +214 -0
- package/dist/server/device-center/hub.js +830 -0
- package/dist/server/device-center/local-hub.js +92 -0
- package/dist/server/device-center/local.js +529 -0
- package/dist/server/device-center/main.js +118 -0
- package/dist/server/device-center/native-desktop/macos.js +192 -0
- package/dist/server/device-center/native-desktop/windows.js +118 -0
- package/dist/server/device-center/path-portal.js +120 -0
- package/dist/server/device-center/relay.js +996 -0
- package/dist/server/device-center/runtime.js +253 -0
- package/dist/server/device-center/store.js +122 -0
- package/dist/server/device-center/task-error.js +14 -0
- package/dist/server/device-center/transfers.js +293 -0
- package/dist/server/device-center/workspaces.js +45 -0
- package/dist/server/dispatch-domain-handlers.js +84 -27
- package/dist/server/dsh/dsh-agent-service.js +282 -159
- package/dist/server/dsh/dsh-client.js +12 -2
- package/dist/server/dsh/runtime/cordis.yml +1 -1
- package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
- package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
- package/dist/server/dsh/runtime/launcher.mjs +235 -235
- package/dist/server/dsh/runtime/override.patch.yml +89 -89
- package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
- package/dist/server/durable/durable-agent-service.js +1 -1
- package/dist/server/engine-probe.js +36 -6
- package/dist/server/eval-tool.js +135 -135
- package/dist/server/evidence-tool-hooks.js +49 -0
- package/dist/server/file-save.js +95 -0
- package/dist/server/file-transfer-routes.js +97 -47
- package/dist/server/files-service.js +38 -26
- package/dist/server/global-loader.js +40 -2
- package/dist/server/goal-review-gate.js +16 -6
- package/dist/server/goal-service.js +54 -30
- package/dist/server/http-proxy.js +120 -0
- package/dist/server/index.js +285 -255
- package/dist/server/load-timing.js +31 -0
- package/dist/server/mcp-bridge.js +219 -94
- package/dist/server/mcp-hot-reload.js +31 -5
- package/dist/server/mcp-manager.js +192 -93
- package/dist/server/mcp-oauth-login.js +169 -0
- package/dist/server/mcp-oauth-ui.js +137 -0
- package/dist/server/mcp-oauth.js +395 -0
- package/dist/server/mcp-project-runtime.js +207 -0
- package/dist/server/message-window.js +74 -21
- package/dist/server/net-guard.js +122 -20
- package/dist/server/patch-bash-process.js +125 -0
- package/dist/server/patch-tool.js +9 -9
- package/dist/server/patch-turn-end-boundary.js +3 -3
- package/dist/server/payload-limits.js +17 -0
- package/dist/server/pending-question.js +82 -0
- package/dist/server/persona-chain.js +8 -8
- package/dist/server/plan-mode.js +338 -137
- package/dist/server/plugin-assets.js +8 -4
- package/dist/server/plugin-chat-attachments.js +48 -0
- package/dist/server/plugin-facilities.js +67 -220
- package/dist/server/plugin-installer.js +2 -1
- package/dist/server/plugin-removal.js +49 -0
- package/dist/server/plugin-secrets.js +179 -0
- package/dist/server/plugins.js +288 -94
- package/dist/server/preset-fields.js +56 -0
- package/dist/server/preset-plugin-dependencies.js +57 -0
- package/dist/server/preset-share.js +113 -72
- package/dist/server/prompt-templates.js +106 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-modes.js +10 -0
- package/dist/server/remote-ssh-service.js +199 -106
- package/dist/server/request-context.js +164 -0
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/sandbox-data.js +655 -0
- package/dist/server/sandbox-engines.js +7 -0
- package/dist/server/sandbox-runtime-gate.js +41 -0
- package/dist/server/sandbox-service.js +139 -698
- package/dist/server/sandbox-tool.js +21 -4
- package/dist/server/schedule-agent-tool.js +39 -21
- package/dist/server/scheduler-tasks.js +106 -55
- package/dist/server/scm-commitmsg.js +10 -10
- package/dist/server/serialize.js +48 -19
- package/dist/server/session-branch.js +25 -3
- package/dist/server/session-parser.js +28 -18
- package/dist/server/session-scan.js +130 -0
- package/dist/server/session-search.js +51 -37
- package/dist/server/settings-service.js +273 -111
- package/dist/server/setup-config.js +58 -0
- package/dist/server/setup-page.js +620 -620
- package/dist/server/skill-maintenance.js +112 -24
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagent-notify.js +4 -1
- package/dist/server/subagent-security-gate.js +52 -11
- package/dist/server/subagent-task.js +27 -0
- package/dist/server/subagents.js +217 -46
- package/dist/server/tabs.js +9 -1
- package/dist/server/terminals.js +467 -363
- package/dist/server/text-quote.js +9 -0
- package/dist/server/tool-guards.js +42 -6
- package/dist/server/tool-manager.js +48 -20
- package/dist/server/tool-overrides.js +13 -11
- package/dist/server/tool-prompt-overrides.js +32 -2
- package/dist/server/tool-prompts.js +1 -1
- package/dist/server/turn-timing.js +11 -0
- package/dist/server/universal/drivers/claude-code.js +5 -0
- package/dist/server/universal/drivers/codex.js +336 -0
- package/dist/server/universal/index.js +1 -0
- package/dist/server/universal/session-store.js +48 -6
- package/dist/server/universal/universal-attachments.js +24 -1
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +357 -231
- package/dist/server/uploads.js +64 -5
- package/dist/server/vision-bridge.js +18 -18
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/docs/device-center.md +148 -0
- package/docs/device-desktop.md +48 -0
- package/docs/dsh-engine.md +493 -493
- package/extensions/webui.ts +335 -335
- package/package.json +5 -2
- package/plugin-sdk/README.md +174 -174
- package/plugin-sdk/client-utils.mjs +279 -279
- package/plugin-sdk/import-check.mjs +210 -210
- package/plugin-sdk/index.d.ts +698 -676
- package/plugin-sdk/index.mjs +696 -696
- package/plugin-sdk/package.json +13 -13
- package/plugin-sdk/ssh-host-trust.mjs +225 -0
- package/plugins/catalog.json +11 -1
- package/themes/aetheris.css +501 -607
- package/themes/ayu-light.css +116 -140
- package/themes/bases/flow-base.css +1357 -1363
- package/themes/bases/obsidian-base.css +895 -895
- package/themes/bases/statusbar-flat-base.css +112 -0
- package/themes/bases/zhujian-base.css +688 -687
- package/themes/bases/zhupi-base.css +660 -659
- package/themes/catppuccin-latte.css +119 -142
- package/themes/catppuccin.css +116 -147
- package/themes/claude-code-dark.css +147 -146
- package/themes/codex.css +114 -138
- package/themes/cyberpunk.css +50 -108
- package/themes/dark-teal.css +264 -265
- package/themes/dazzle.css +38 -108
- package/themes/everforest-light.css +115 -138
- package/themes/flow-light.css +164 -164
- package/themes/flow.css +161 -161
- package/themes/geist.css +114 -138
- package/themes/gruvbox-light.css +115 -138
- package/themes/kanagawa-lotus.css +115 -138
- package/themes/md-preview.css +24 -234
- package/themes/mist.css +166 -186
- package/themes/nord.css +107 -138
- package/themes/one-dark.css +106 -139
- package/themes/paper.css +174 -186
- package/themes/rose-pine-dawn.css +114 -138
- package/themes/sakura.css +166 -186
- package/themes/solarized-light.css +114 -137
- package/themes/tokyo-night.css +115 -146
- package/themes/translucent.css +85 -85
- package/themes/transparent.css +116 -116
- package/themes/vs-code-dark.css +147 -147
- package/themes/wallpaper-flow.css +382 -382
- package/themes/wallpaper-obsidian.css +74 -74
- package/themes/white.css +164 -186
- package/themes/zhujian-dark.css +115 -114
- package/themes/zhujian.css +114 -114
- package/themes/zhupi-dark.css +115 -114
- package/themes/zhupi.css +114 -114
- package/web/dist/.build-assets.json +1 -0
- package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
- package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
- package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
- package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
- package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
- package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
- package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
- package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
- package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
- package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
- package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
- package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
- package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
- package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
- package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
- package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
- package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
- package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
- package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
- package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
- package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
- package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
- package/web/dist/assets/desktop-YguLbrX1.js +1 -0
- package/web/dist/assets/es-DWMIuDU2.js +2 -0
- package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
- package/web/dist/assets/index-BPvpea8t.js +85 -0
- package/web/dist/assets/index-D6u8xH0o.js +85 -0
- package/web/dist/assets/index-DDZMv6LO.css +1 -0
- package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
- package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
- package/web/dist/assets/math-1uRJCsA9.js +257 -0
- package/web/dist/assets/math-BorAY7qD.css +1 -0
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
- package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
- package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
- package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
- package/web/dist/index.html +42 -35
- package/web/dist/sw.js +179 -179
- package/web/public/sw.js +179 -179
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
- package/web/dist/assets/index-ByiO9f-N.js +0 -2008
- package/web/dist/assets/index-ycGLh4a4.css +0 -1
- package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
- package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
|
@@ -9,15 +9,15 @@
|
|
|
9
9
|
* 2. 沙盒安全围栏(Sandbox Jail Gate):
|
|
10
10
|
* - 当会话处于受管沙盒目录内时,所有文件写入/编辑/补丁(write/edit/edit_soft/patch)必须严格落在
|
|
11
11
|
* `sandbox.path` 内部(含祖先目录 realpath 校验,防软链逃逸),越界直接硬拒绝(不走审批放行);
|
|
12
|
-
* -
|
|
13
|
-
*
|
|
14
|
-
* - 外部副作用工具(sftp 远端写/删/执行、mail 发信/删信)在沙盒内默认拦截。
|
|
12
|
+
* - 没有操作系统隔离后端时拒绝宿主 shell、解释器、终端和任意代码执行;
|
|
13
|
+
* - 仅放行来源可信且能力明确的受限文件工具,未知工具和外部副作用默认拒绝。
|
|
15
14
|
*/
|
|
16
|
-
import { existsSync,
|
|
17
|
-
import { copyFile, lstat, mkdir, readdir, rm, stat } from "node:fs/promises";
|
|
15
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
18
16
|
import { homedir } from "node:os";
|
|
19
|
-
import {
|
|
17
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
18
|
+
import * as sandboxJailFs from "node:fs";
|
|
20
19
|
import { normalizePathKey } from "./client-state.js";
|
|
20
|
+
import { isConversationTool } from "./conversation-tool-names.js";
|
|
21
21
|
import { pick } from "./i18n.js";
|
|
22
22
|
/** 导入项目进沙盒时默认跳过的重型依赖/构建缓存目录名。 */
|
|
23
23
|
export const SANDBOX_IGNORED_DIRS = new Set([
|
|
@@ -39,15 +39,6 @@ export const SANDBOX_IGNORED_DIRS = new Set([
|
|
|
39
39
|
"coverage",
|
|
40
40
|
".nyc_output",
|
|
41
41
|
]);
|
|
42
|
-
/** 导入项目进沙盒时跳过的系统垃圾文件。 */
|
|
43
|
-
const SANDBOX_IGNORED_FILES = new Set([".DS_Store", "Thumbs.db", "desktop.ini"]);
|
|
44
|
-
/** 单次导入沙盒的最大文件数上限(防止意外导入超大目录卡死 I/O)。 */
|
|
45
|
-
const MAX_IMPORT_FILES = 15_000;
|
|
46
|
-
/** 单次导入沙盒的单文件大小上限(64 MB,超大二进制构建产物不拷入沙盒)。 */
|
|
47
|
-
const MAX_SINGLE_FILE_BYTES = 64 * 1024 * 1024;
|
|
48
|
-
function toWirePath(p) {
|
|
49
|
-
return resolve(p).replace(/\\/g, "/");
|
|
50
|
-
}
|
|
51
42
|
function toComparablePath(p) {
|
|
52
43
|
return normalizePathKey(p).replace(/\\/g, "/").replace(/\/+$/, "");
|
|
53
44
|
}
|
|
@@ -56,24 +47,6 @@ export function isSameOrSubpath(childAbs, parentAbs) {
|
|
|
56
47
|
const p = toComparablePath(parentAbs);
|
|
57
48
|
return c === p || c.startsWith(p + "/");
|
|
58
49
|
}
|
|
59
|
-
function isProtectedSystemOrHomeRoot(absPath) {
|
|
60
|
-
const resolved = resolve(absPath);
|
|
61
|
-
// 文件系统根(如 "/" 或 "C:\")
|
|
62
|
-
if (parseRootOnly(resolved))
|
|
63
|
-
return true;
|
|
64
|
-
const home = resolve(homedir());
|
|
65
|
-
if (normalizePathKey(resolved) === normalizePathKey(home))
|
|
66
|
-
return true;
|
|
67
|
-
return false;
|
|
68
|
-
}
|
|
69
|
-
function parseRootOnly(resolved) {
|
|
70
|
-
const trimmed = resolved.replace(/[\\/]+$/, "");
|
|
71
|
-
if (!trimmed)
|
|
72
|
-
return true;
|
|
73
|
-
if (/^[a-zA-Z]:$/.test(trimmed))
|
|
74
|
-
return true;
|
|
75
|
-
return dirname(resolved) === resolved;
|
|
76
|
-
}
|
|
77
50
|
/**
|
|
78
51
|
* 解析目标路径并校验是否严格位于 `sandboxRoot` 内部(含祖先目录 realpath 校验,防软链逃逸)。
|
|
79
52
|
*/
|
|
@@ -95,12 +68,14 @@ export function isStrictlyInsideSandbox(targetPath, cwd, sandboxRoot) {
|
|
|
95
68
|
return false;
|
|
96
69
|
}
|
|
97
70
|
// 2. 真实路径(realpath)校验:沿目标路径向上找到第一个已存在的祖先目录,防止通过沙盒内软链写到外部
|
|
98
|
-
let realSandbox
|
|
71
|
+
let realSandbox;
|
|
99
72
|
try {
|
|
73
|
+
if (sandboxJailFs.lstatSync(resolvedSandbox).isSymbolicLink())
|
|
74
|
+
return false;
|
|
100
75
|
realSandbox = realpathSync(resolvedSandbox);
|
|
101
76
|
}
|
|
102
77
|
catch {
|
|
103
|
-
|
|
78
|
+
return false;
|
|
104
79
|
}
|
|
105
80
|
let cur = resolvedTarget;
|
|
106
81
|
while (true) {
|
|
@@ -150,177 +125,145 @@ export function extractPatchTargetPaths(patchText) {
|
|
|
150
125
|
}
|
|
151
126
|
return paths;
|
|
152
127
|
}
|
|
153
|
-
/**
|
|
154
|
-
|
|
155
|
-
|
|
128
|
+
/** Copy workspaces are not an OS execution boundary. Capabilities are opt-in. */
|
|
129
|
+
const SANDBOX_MANAGEMENT_ACTIONS = new Set([
|
|
130
|
+
"list",
|
|
131
|
+
"create",
|
|
132
|
+
"diff",
|
|
133
|
+
"reset",
|
|
134
|
+
"persist",
|
|
135
|
+
"promote",
|
|
136
|
+
"apply_to_source",
|
|
137
|
+
"destroy",
|
|
138
|
+
]);
|
|
139
|
+
/** Reject links (including dangling links), special files and Windows alternate streams.
|
|
140
|
+
* This is a preflight for trusted local file tools, not protection against a hostile
|
|
141
|
+
* process racing filesystem changes; arbitrary host execution is therefore denied.
|
|
156
142
|
*/
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
reason: `【沙盒安全隔离拦截】补丁包含沙盒目录(${sbxPath})以外的目标路径:"${target}"。沙盒内严禁越界修改。`,
|
|
187
|
-
reasonEn: `[Sandbox Isolation Blocked] Patch contains a target path outside the sandbox directory (${sbxPath}): "${target}". Out-of-bounds modification is forbidden in sandbox mode.`,
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
return null;
|
|
192
|
-
}
|
|
193
|
-
// 3. 终端命令:bash
|
|
194
|
-
if (toolName === "bash") {
|
|
195
|
-
const cmd = typeof p.command === "string" ? p.command : "";
|
|
196
|
-
if (!cmd.trim())
|
|
197
|
-
return null;
|
|
198
|
-
// 3a. 若为导入源项目的沙盒,严禁在命令中直接引用源项目路径(防 AI cd 回原项目改动)
|
|
199
|
-
if (sandbox.sourcePath) {
|
|
200
|
-
const srcWire = toWirePath(sandbox.sourcePath);
|
|
201
|
-
const srcNative = resolve(sandbox.sourcePath);
|
|
202
|
-
const cmdLower = process.platform === "win32" ? cmd.toLowerCase() : cmd;
|
|
203
|
-
const wireNeedle = process.platform === "win32" ? srcWire.toLowerCase() : srcWire;
|
|
204
|
-
const nativeNeedle = process.platform === "win32" ? srcNative.toLowerCase() : srcNative;
|
|
205
|
-
if ((wireNeedle.length > 3 && cmdLower.includes(wireNeedle)) ||
|
|
206
|
-
(nativeNeedle.length > 3 && cmdLower.includes(nativeNeedle))) {
|
|
207
|
-
return {
|
|
208
|
-
reason: `【沙盒安全隔离拦截】检测到命令直接引用了源项目路径(${sandbox.sourcePath})。沙盒模式下原项目受严格保护,请仅对当前沙盒目录(${sbxPath})执行操作。`,
|
|
209
|
-
reasonEn: `[Sandbox Isolation Blocked] Command directly references the source project path (${sandbox.sourcePath}). The original project is strictly protected in sandbox mode; operate only inside the current sandbox directory (${sbxPath}).`,
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
// 3b. 拦截通过 cd 跳出沙盒边界(裸 cd 跳 $HOME、cd ~、cd ..、或 cd 到沙盒外绝对路径,支持括号子 shell 与带引号/变量路径)
|
|
214
|
-
for (const m of cmd.matchAll(/(?:^|[;&|\n(`]\s*)cd(?:\s+([^;&|\n)`]+))?(?=$|[;&|\n)`])/g)) {
|
|
215
|
-
const rawArg = (m[1] ?? "").trim().replace(/^["']|["']$/g, "");
|
|
216
|
-
if (!rawArg ||
|
|
217
|
-
rawArg === "~" ||
|
|
218
|
-
rawArg.startsWith("~/") ||
|
|
219
|
-
rawArg.startsWith("~\\") ||
|
|
220
|
-
/^\$(?:HOME|USERPROFILE)\b|^\$\{(?:HOME|USERPROFILE)\}|^%USERPROFILE%/i.test(rawArg) ||
|
|
221
|
-
/\$(?:HOME|USERPROFILE)|\$\{(?:HOME|USERPROFILE)\}/i.test(rawArg)) {
|
|
222
|
-
return {
|
|
223
|
-
reason: `【沙盒安全隔离拦截】沙盒内禁止执行跳回用户主目录的 "cd ${rawArg || "~"}" 命令,请保持在沙盒目录(${sbxPath})内操作。`,
|
|
224
|
-
reasonEn: `[Sandbox Isolation Blocked] Escaping to the user home directory via "cd ${rawArg || "~"}" is forbidden in sandbox mode; stay within "${sbxPath}".`,
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
|
-
if (rawArg !== "-" && !rawArg.startsWith("$") && !isStrictlyInsideSandbox(rawArg, cwd, sbxPath)) {
|
|
228
|
-
return {
|
|
229
|
-
reason: `【沙盒安全隔离拦截】禁止通过 "cd ${rawArg}" 跳出沙盒根目录(${sbxPath})。`,
|
|
230
|
-
reasonEn: `[Sandbox Isolation Blocked] Escaping the sandbox root (${sbxPath}) via "cd ${rawArg}" is forbidden.`,
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
// 3c. 拦截重定向(> / >>)写入沙盒外路径(/dev/null 除外)
|
|
235
|
-
for (const m of cmd.matchAll(/(?:^|[^0-9>&])>>?\s*([^\s;&|>'"]+|"[^"]+"|'[^']+')/g)) {
|
|
236
|
-
const target = (m[1] ?? "").trim().replace(/^["']|["']$/g, "");
|
|
237
|
-
if (!target || target === "/dev/null" || target === "NUL" || target.startsWith("&"))
|
|
238
|
-
continue;
|
|
239
|
-
if (!isStrictlyInsideSandbox(target, cwd, sbxPath)) {
|
|
240
|
-
return {
|
|
241
|
-
reason: `【沙盒安全隔离拦截】禁止将输出重定向写入沙盒目录(${sbxPath})以外的路径:"${target}"。`,
|
|
242
|
-
reasonEn: `[Sandbox Isolation Blocked] Redirecting output to a path outside the sandbox directory (${sbxPath}) is forbidden: "${target}".`,
|
|
243
|
-
};
|
|
143
|
+
function sandboxJailPath(raw, cwd, root) {
|
|
144
|
+
// SDK file tools strip a leading @ and normalize Unicode spaces. Refuse
|
|
145
|
+
// alternate spellings rather than checking a different path from execution.
|
|
146
|
+
if (typeof raw !== "string" ||
|
|
147
|
+
!raw.trim() ||
|
|
148
|
+
raw !== raw.trim() ||
|
|
149
|
+
raw.startsWith("@") ||
|
|
150
|
+
/[\x00-\x1f\u00a0\u2000-\u200a\u202f\u205f\u3000]/.test(raw))
|
|
151
|
+
return false;
|
|
152
|
+
if (!isStrictlyInsideSandbox(raw, cwd, root))
|
|
153
|
+
return false;
|
|
154
|
+
const target = resolve(cwd, raw);
|
|
155
|
+
const sandboxRoot = resolve(root);
|
|
156
|
+
const suffix = target.slice(sandboxRoot.length);
|
|
157
|
+
if (suffix.includes(":"))
|
|
158
|
+
return false;
|
|
159
|
+
const safeEntry = (path) => {
|
|
160
|
+
const entry = sandboxJailFs.lstatSync(path);
|
|
161
|
+
return !entry.isSymbolicLink() && (entry.isDirectory() || (entry.isFile() && entry.nlink === 1));
|
|
162
|
+
};
|
|
163
|
+
try {
|
|
164
|
+
if (!sandboxJailFs.lstatSync(sandboxRoot).isDirectory() || sandboxJailFs.lstatSync(sandboxRoot).isSymbolicLink())
|
|
165
|
+
return false;
|
|
166
|
+
let current = sandboxRoot;
|
|
167
|
+
for (const part of suffix.split(/[\\/]/).filter(Boolean)) {
|
|
168
|
+
current = join(current, part);
|
|
169
|
+
try {
|
|
170
|
+
if (!safeEntry(current))
|
|
171
|
+
return false;
|
|
244
172
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
return {
|
|
250
|
-
reason: `【沙盒安全隔离拦截】沙盒内禁止执行宿主机系统级管理命令或全局包安装(-g/--global),以保护宿主系统环境。`,
|
|
251
|
-
reasonEn: `[Sandbox Isolation Blocked] System administration commands and global package installations (-g/--global) are forbidden in sandbox mode to protect the host environment.`,
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
// 3e. 拦截文件修改/删除命令(rm/del/mv/cp/chmod/touch/mkdir/sed -i/tee 等)指向 ..、~、$HOME 或沙盒外绝对路径
|
|
255
|
-
const mutatingCmdRe = /(?:^|[;&|\n(`]\s*)(?:rm|del|erase|rmdir|rd|mv|move|cp|copy|xcopy|robocopy|ln|mklink|chmod|chown|touch|mkdir|tee|dd|Remove-Item|Move-Item|Copy-Item|Set-Content|Add-Content|Out-File|sed\s+-[a-zA-Z]*i)\b([^;&|\n)]*)/gi;
|
|
256
|
-
for (const m of cmd.matchAll(mutatingCmdRe)) {
|
|
257
|
-
const argsTail = (m[1] ?? "").trim();
|
|
258
|
-
const tokens = argsTail.match(/(?:"[^"]*"|'[^']*'|\S+)/g) ?? [];
|
|
259
|
-
for (const rawTok of tokens) {
|
|
260
|
-
const tok = rawTok.replace(/^["']|["']$/g, "");
|
|
261
|
-
if (!tok || tok.startsWith("-") || tok === "/dev/null")
|
|
262
|
-
continue;
|
|
263
|
-
if (tok === "~" ||
|
|
264
|
-
tok.startsWith("~/") ||
|
|
265
|
-
tok.startsWith("~\\") ||
|
|
266
|
-
/^\$(?:HOME|USERPROFILE)\b|^%USERPROFILE%/i.test(tok) ||
|
|
267
|
-
tok === ".." ||
|
|
268
|
-
tok.startsWith("../") ||
|
|
269
|
-
tok.startsWith("..\\") ||
|
|
270
|
-
tok.includes("/../") ||
|
|
271
|
-
tok.includes("\\..\\")) {
|
|
272
|
-
if (!isStrictlyInsideSandbox(tok, cwd, sbxPath)) {
|
|
273
|
-
return {
|
|
274
|
-
reason: `【沙盒安全隔离拦截】检测到命令尝试操作沙盒外部或宿主系统路径("${tok}"),已被硬围栏阻断。`,
|
|
275
|
-
reasonEn: `[Sandbox Isolation Blocked] Command attempted to mutate a path outside the sandbox or on the host system ("${tok}") and was blocked.`,
|
|
276
|
-
};
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
// 绝对路径(POSIX /... 或 Windows C:\...)且不在沙盒根内
|
|
280
|
-
if ((tok.startsWith("/") && !tok.startsWith("//")) || /^[a-zA-Z]:[\\/]/.test(tok)) {
|
|
281
|
-
if (!isStrictlyInsideSandbox(tok, cwd, sbxPath)) {
|
|
282
|
-
return {
|
|
283
|
-
reason: `【沙盒安全隔离拦截】检测到命令尝试修改沙盒目录(${sbxPath})以外的系统/外部路径("${tok}"),已被硬围栏阻断。`,
|
|
284
|
-
reasonEn: `[Sandbox Isolation Blocked] Command attempted to modify an external/system path outside the sandbox ("${tok}") and was blocked.`,
|
|
285
|
-
};
|
|
286
|
-
}
|
|
287
|
-
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
if (error.code === "ENOENT")
|
|
175
|
+
break;
|
|
176
|
+
throw error;
|
|
288
177
|
}
|
|
289
178
|
}
|
|
290
|
-
return
|
|
179
|
+
return true;
|
|
291
180
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
181
|
+
catch {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
export function evaluateSandboxJail(sandbox, toolName, params, cwd, policy = {}) {
|
|
186
|
+
const deny = (detail) => ({
|
|
187
|
+
reason: "【沙盒安全隔离拦截】副本沙盒只允许可信宿主的受限文件工具与管理操作。" + detail,
|
|
188
|
+
reasonEn: "[Sandbox Isolation Blocked] Copy sandboxes only allow trusted, bounded local file tools and management operations. " +
|
|
189
|
+
detail,
|
|
190
|
+
});
|
|
191
|
+
if (!policy.trustedTool)
|
|
192
|
+
return deny("Untrusted or unknown tool implementation: " + toolName);
|
|
193
|
+
const p = params ?? {};
|
|
194
|
+
if (toolName === "sandbox") {
|
|
195
|
+
return typeof p.action === "string" && SANDBOX_MANAGEMENT_ACTIONS.has(p.action)
|
|
196
|
+
? null
|
|
197
|
+
: deny("Unknown sandbox management action.");
|
|
302
198
|
}
|
|
303
|
-
if (
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
199
|
+
if (!sandboxJailPath(".", cwd, sandbox.path))
|
|
200
|
+
return deny("Sandbox workspace is unavailable or outside its boundary.");
|
|
201
|
+
// The trusted host must validate both endpoints against the captured sandbox identity.
|
|
202
|
+
// Tool arguments cannot grant trust or select a different security boundary.
|
|
203
|
+
if (toolName === "communicate") {
|
|
204
|
+
return typeof p.action === "string" && ["read", "send", "request", "reply", "escalate"].includes(p.action)
|
|
205
|
+
? null
|
|
206
|
+
: deny("Unknown communication action.");
|
|
207
|
+
}
|
|
208
|
+
if (isConversationTool(toolName) && policy.inheritedSandboxSubagent)
|
|
209
|
+
return null;
|
|
210
|
+
if (toolName === "bash")
|
|
211
|
+
return deny("Host command execution (including scripts, eval and test/build commands) requires a secure OS-isolated backend; a workspace copy cannot isolate execution.");
|
|
212
|
+
const paths = [];
|
|
213
|
+
switch (toolName) {
|
|
214
|
+
case "read":
|
|
215
|
+
case "write":
|
|
216
|
+
case "edit":
|
|
217
|
+
case "edit_soft":
|
|
218
|
+
// Validate both aliases when present; different implementations choose different precedence.
|
|
219
|
+
if (p.path !== undefined)
|
|
220
|
+
paths.push(p.path);
|
|
221
|
+
if (p.file_path !== undefined)
|
|
222
|
+
paths.push(p.file_path);
|
|
223
|
+
break;
|
|
224
|
+
case "grep":
|
|
225
|
+
case "find":
|
|
226
|
+
// Host ownership alone does not make SDK search safe: inherited
|
|
227
|
+
// configuration (e.g. RIPGREP_CONFIG_PATH/--pre) can execute code.
|
|
228
|
+
// Reject direct wrapper calls too, until a safe search backend exists.
|
|
229
|
+
return deny("Search requires a verified safe backend without host execution or inherited executable configuration; trusted tool ownership alone is insufficient.");
|
|
230
|
+
case "patch": {
|
|
231
|
+
if (typeof p.patch !== "string" || !p.patch.trim())
|
|
232
|
+
return deny("Missing patch targets.");
|
|
233
|
+
paths.push(...extractPatchTargetPaths(p.patch));
|
|
234
|
+
// Hashline MV is an additional destination, not a section header.
|
|
235
|
+
for (const line of p.patch.split(/\r?\n/)) {
|
|
236
|
+
const move = line.trim().match(/^MV\s+([^\s]+)/i);
|
|
237
|
+
if (move)
|
|
238
|
+
paths.push(move[1]);
|
|
239
|
+
}
|
|
240
|
+
break;
|
|
310
241
|
}
|
|
242
|
+
case "present_files":
|
|
243
|
+
if (!Array.isArray(p.items))
|
|
244
|
+
return deny("Missing local file items.");
|
|
245
|
+
for (const item of p.items)
|
|
246
|
+
paths.push(item && typeof item === "object" ? item.path : undefined);
|
|
247
|
+
break;
|
|
248
|
+
default:
|
|
249
|
+
return deny("Tool capability is not allowed in a copy sandbox: " + toolName);
|
|
250
|
+
}
|
|
251
|
+
if (!paths.length || paths.some((path) => !sandboxJailPath(path, cwd, sandbox.path))) {
|
|
252
|
+
return deny("Every file target must stay inside the sandbox; links, special files, invalid paths and unsafe recursive searches are refused.");
|
|
311
253
|
}
|
|
312
254
|
return null;
|
|
313
255
|
}
|
|
314
256
|
/**
|
|
315
257
|
* 为工具包一层「沙盒硬围栏」:当 `getSandbox()` 返回非空时,对越界写操作与源项目触达直接硬拒绝。
|
|
316
258
|
*/
|
|
317
|
-
export function withSandboxJailGate(tool, getSandbox, getCwd, getLang) {
|
|
259
|
+
export function withSandboxJailGate(tool, getSandbox, getCwd, getLang, policy = {}, acquireExecution) {
|
|
318
260
|
return {
|
|
319
261
|
...tool,
|
|
320
262
|
execute: async (toolCallId, params, signal, onUpdate, ctx) => {
|
|
263
|
+
signal?.throwIfAborted();
|
|
321
264
|
const sbx = getSandbox();
|
|
322
265
|
if (sbx) {
|
|
323
|
-
const denied = evaluateSandboxJail(sbx, tool.name, params, getCwd());
|
|
266
|
+
const denied = evaluateSandboxJail(sbx, tool.name, params, getCwd(), policy);
|
|
324
267
|
if (denied) {
|
|
325
268
|
return {
|
|
326
269
|
content: [{ type: "text", text: pick(getLang(), denied.reason, denied.reasonEn) }],
|
|
@@ -329,517 +272,15 @@ export function withSandboxJailGate(tool, getSandbox, getCwd, getLang) {
|
|
|
329
272
|
};
|
|
330
273
|
}
|
|
331
274
|
}
|
|
332
|
-
|
|
333
|
-
},
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
/**
|
|
337
|
-
* 递归复制目录内容(安全跳过重型缓存目录与指向源目录外部的软链)。
|
|
338
|
-
*/
|
|
339
|
-
async function copyWorkspaceTree(srcRoot, destRoot, opts) {
|
|
340
|
-
const resolvedSrcRoot = resolve(srcRoot);
|
|
341
|
-
let realSrcRoot = resolvedSrcRoot;
|
|
342
|
-
try {
|
|
343
|
-
realSrcRoot = realpathSync(resolvedSrcRoot);
|
|
344
|
-
}
|
|
345
|
-
catch {
|
|
346
|
-
// ignore
|
|
347
|
-
}
|
|
348
|
-
const stats = { copiedFiles: 0, skippedFiles: 0 };
|
|
349
|
-
async function walk(curSrc, curDest) {
|
|
350
|
-
await mkdir(curDest, { recursive: true });
|
|
351
|
-
const entries = await readdir(curSrc, { withFileTypes: true });
|
|
352
|
-
for (const entry of entries) {
|
|
353
|
-
const name = entry.name;
|
|
354
|
-
if (SANDBOX_IGNORED_FILES.has(name) || name.startsWith(".pi-tmp")) {
|
|
355
|
-
continue;
|
|
356
|
-
}
|
|
357
|
-
if (SANDBOX_IGNORED_DIRS.has(name)) {
|
|
358
|
-
continue;
|
|
359
|
-
}
|
|
360
|
-
if (opts?.skipGitDir && name === ".git") {
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
const srcPath = join(curSrc, name);
|
|
364
|
-
const destPath = join(curDest, name);
|
|
365
|
-
let lst;
|
|
366
|
-
try {
|
|
367
|
-
lst = await lstat(srcPath);
|
|
368
|
-
}
|
|
369
|
-
catch {
|
|
370
|
-
continue;
|
|
371
|
-
}
|
|
372
|
-
// 安全防御:跳过符号链接(避免软链逃逸或循环软链爆栈)
|
|
373
|
-
if (lst.isSymbolicLink()) {
|
|
374
|
-
stats.skippedFiles++;
|
|
375
|
-
continue;
|
|
376
|
-
}
|
|
377
|
-
if (lst.isDirectory()) {
|
|
378
|
-
// 防止把沙盒目录自身递归拷进自己
|
|
379
|
-
if (isSameOrSubpath(destRoot, srcPath)) {
|
|
380
|
-
continue;
|
|
381
|
-
}
|
|
382
|
-
await walk(srcPath, destPath);
|
|
383
|
-
}
|
|
384
|
-
else if (lst.isFile()) {
|
|
385
|
-
if (stats.copiedFiles >= MAX_IMPORT_FILES || lst.size > MAX_SINGLE_FILE_BYTES) {
|
|
386
|
-
stats.skippedFiles++;
|
|
387
|
-
continue;
|
|
388
|
-
}
|
|
389
|
-
// 确认真实路径仍在源目录内
|
|
390
|
-
try {
|
|
391
|
-
const realParent = realpathSync(dirname(srcPath));
|
|
392
|
-
if (!isSameOrSubpath(realParent, realSrcRoot)) {
|
|
393
|
-
stats.skippedFiles++;
|
|
394
|
-
continue;
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
catch {
|
|
398
|
-
stats.skippedFiles++;
|
|
399
|
-
continue;
|
|
400
|
-
}
|
|
401
|
-
await copyFile(srcPath, destPath);
|
|
402
|
-
stats.copiedFiles++;
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
await walk(resolvedSrcRoot, resolve(destRoot));
|
|
407
|
-
return stats;
|
|
408
|
-
}
|
|
409
|
-
export class SandboxManager {
|
|
410
|
-
sandboxesRoot;
|
|
411
|
-
registryPath;
|
|
412
|
-
items = new Map();
|
|
413
|
-
lastLoadedMtime = -1;
|
|
414
|
-
constructor(dataDir) {
|
|
415
|
-
this.sandboxesRoot = toWirePath(join(dataDir, "sandboxes"));
|
|
416
|
-
this.registryPath = join(dataDir, "sandboxes", "registry.json");
|
|
417
|
-
this.load();
|
|
418
|
-
}
|
|
419
|
-
ensureFresh() {
|
|
420
|
-
if (!existsSync(this.registryPath)) {
|
|
421
|
-
if (this.lastLoadedMtime !== -1) {
|
|
422
|
-
this.items.clear();
|
|
423
|
-
this.lastLoadedMtime = -1;
|
|
424
|
-
}
|
|
425
|
-
return;
|
|
426
|
-
}
|
|
427
|
-
try {
|
|
428
|
-
const mtime = statSync(this.registryPath).mtimeMs;
|
|
429
|
-
if (mtime !== this.lastLoadedMtime) {
|
|
430
|
-
this.load();
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
catch {
|
|
434
|
-
// ignore
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
load() {
|
|
438
|
-
this.items.clear();
|
|
439
|
-
if (!existsSync(this.registryPath)) {
|
|
440
|
-
this.lastLoadedMtime = -1;
|
|
441
|
-
return;
|
|
442
|
-
}
|
|
443
|
-
try {
|
|
444
|
-
this.lastLoadedMtime = statSync(this.registryPath).mtimeMs;
|
|
445
|
-
const raw = JSON.parse(readFileSync(this.registryPath, "utf-8"));
|
|
446
|
-
if (!Array.isArray(raw.sandboxes))
|
|
447
|
-
return;
|
|
448
|
-
for (const item of raw.sandboxes) {
|
|
449
|
-
if (!item || typeof item.id !== "string" || typeof item.path !== "string")
|
|
450
|
-
continue;
|
|
451
|
-
const wirePath = toWirePath(item.path);
|
|
452
|
-
if (!existsSync(wirePath))
|
|
453
|
-
continue;
|
|
454
|
-
this.items.set(item.id, {
|
|
455
|
-
id: item.id,
|
|
456
|
-
name: typeof item.name === "string" && item.name.trim() ? item.name.trim() : item.id,
|
|
457
|
-
path: wirePath,
|
|
458
|
-
sourcePath: typeof item.sourcePath === "string" && item.sourcePath.trim() ? toWirePath(item.sourcePath) : undefined,
|
|
459
|
-
ephemeral: Boolean(item.ephemeral),
|
|
460
|
-
createdAt: typeof item.createdAt === "number" ? item.createdAt : Date.now(),
|
|
461
|
-
});
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
|
-
catch {
|
|
465
|
-
// best-effort
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
save() {
|
|
469
|
-
try {
|
|
470
|
-
mkdirSync(dirname(this.registryPath), { recursive: true });
|
|
471
|
-
const payload = {
|
|
472
|
-
version: 1,
|
|
473
|
-
sandboxes: [...this.items.values()].sort((a, b) => b.createdAt - a.createdAt),
|
|
474
|
-
};
|
|
475
|
-
writeFileSync(this.registryPath, JSON.stringify(payload, null, "\t"), "utf-8");
|
|
476
|
-
this.lastLoadedMtime = statSync(this.registryPath).mtimeMs;
|
|
477
|
-
}
|
|
478
|
-
catch {
|
|
479
|
-
// best-effort
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
/** 列出所有有效沙盒(自动剔除磁盘上已被外部删除的目录)。 */
|
|
483
|
-
list() {
|
|
484
|
-
this.ensureFresh();
|
|
485
|
-
let dirty = false;
|
|
486
|
-
for (const [id, info] of this.items) {
|
|
487
|
-
if (!existsSync(info.path)) {
|
|
488
|
-
this.items.delete(id);
|
|
489
|
-
dirty = true;
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
if (dirty)
|
|
493
|
-
this.save();
|
|
494
|
-
return [...this.items.values()].sort((a, b) => b.createdAt - a.createdAt);
|
|
495
|
-
}
|
|
496
|
-
/** 按沙盒 id 或路径精确查找沙盒。 */
|
|
497
|
-
get(idOrPath) {
|
|
498
|
-
if (!idOrPath)
|
|
499
|
-
return undefined;
|
|
500
|
-
this.ensureFresh();
|
|
501
|
-
const byId = this.items.get(idOrPath);
|
|
502
|
-
if (byId && existsSync(byId.path))
|
|
503
|
-
return byId;
|
|
504
|
-
const key = normalizePathKey(idOrPath);
|
|
505
|
-
for (const info of this.list()) {
|
|
506
|
-
if (normalizePathKey(info.path) === key)
|
|
507
|
-
return info;
|
|
508
|
-
}
|
|
509
|
-
return undefined;
|
|
510
|
-
}
|
|
511
|
-
/** 判断给定工作目录 `cwd` 是否处于某个受管沙盒内(含沙盒的子目录),若是则返回该沙盒信息。 */
|
|
512
|
-
getByCwd(cwd) {
|
|
513
|
-
if (!cwd)
|
|
514
|
-
return undefined;
|
|
515
|
-
for (const info of this.list()) {
|
|
516
|
-
if (isSameOrSubpath(cwd, info.path)) {
|
|
517
|
-
return info;
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
return undefined;
|
|
521
|
-
}
|
|
522
|
-
/**
|
|
523
|
-
* 创建一个新沙盒工作区(空白或从 `sourcePath` 导入隔离副本)。
|
|
524
|
-
*/
|
|
525
|
-
async create(opts) {
|
|
526
|
-
// 先同步共享注册表:每个 ClientSession/DshClientSession 各持一个管理器实例、
|
|
527
|
-
// 共享同一 registry.json——不 ensureFresh 的话并发创建会用陈旧内存覆盖写回,
|
|
528
|
-
// 丢掉其他客户端刚建的沙盒条目(getByCwd 找不到 → jail 围栏静默失效)
|
|
529
|
-
this.ensureFresh();
|
|
530
|
-
const rawSource = opts.sourcePath?.trim();
|
|
531
|
-
let resolvedSource;
|
|
532
|
-
if (rawSource) {
|
|
533
|
-
const expanded = rawSource === "~"
|
|
534
|
-
? homedir()
|
|
535
|
-
: rawSource.startsWith("~/") || rawSource.startsWith("~\\")
|
|
536
|
-
? join(homedir(), rawSource.slice(2))
|
|
537
|
-
: rawSource;
|
|
538
|
-
const abs = resolve(expanded);
|
|
539
|
-
if (!existsSync(abs) || !statSync(abs).isDirectory()) {
|
|
540
|
-
throw new Error(`Source directory does not exist: ${rawSource}`);
|
|
541
|
-
}
|
|
542
|
-
if (isProtectedSystemOrHomeRoot(abs)) {
|
|
543
|
-
throw new Error(`Refusing to import system root or user home directory into sandbox: ${abs}`);
|
|
544
|
-
}
|
|
545
|
-
if (isSameOrSubpath(this.sandboxesRoot, abs)) {
|
|
546
|
-
throw new Error(`Refusing to import a parent directory of sandboxes root: ${abs}`);
|
|
547
|
-
}
|
|
548
|
-
// 沙盒根**内部**的目录也不允许当源:会造出嵌套沙盒(源被另一沙盒的
|
|
549
|
-
// destroy/reset 抽掉、apply_to_source 把改动写进另一个沙盒)
|
|
550
|
-
if (isSameOrSubpath(abs, this.sandboxesRoot)) {
|
|
551
|
-
throw new Error(`Refusing to import a directory inside the sandboxes root: ${abs}`);
|
|
552
|
-
}
|
|
553
|
-
// 若选中的 source 本身已经是某个沙盒,而且该沙盒记录了原始 sourcePath,保留最外层真实路径或直接复制该沙盒内容
|
|
554
|
-
resolvedSource = toWirePath(abs);
|
|
555
|
-
}
|
|
556
|
-
const id = `sbx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
557
|
-
const sbxDir = toWirePath(join(this.sandboxesRoot, id));
|
|
558
|
-
await mkdir(sbxDir, { recursive: true });
|
|
559
|
-
let copyStats = { copiedFiles: 0, skippedFiles: 0 };
|
|
560
|
-
if (resolvedSource) {
|
|
561
|
-
copyStats = await copyWorkspaceTree(resolvedSource, sbxDir);
|
|
562
|
-
}
|
|
563
|
-
const defaultName = resolvedSource ? `${basename(resolvedSource)} (Sandbox)` : `Sandbox ${id.slice(-4)}`;
|
|
564
|
-
const name = opts.name?.trim() || defaultName;
|
|
565
|
-
const info = {
|
|
566
|
-
id,
|
|
567
|
-
name,
|
|
568
|
-
path: sbxDir,
|
|
569
|
-
sourcePath: resolvedSource,
|
|
570
|
-
ephemeral: opts.ephemeral ?? true,
|
|
571
|
-
createdAt: Date.now(),
|
|
572
|
-
};
|
|
573
|
-
this.items.set(id, info);
|
|
574
|
-
this.save();
|
|
575
|
-
return { sandbox: info, ...copyStats };
|
|
576
|
-
}
|
|
577
|
-
/**
|
|
578
|
-
* 重置沙盒:清空沙盒根下所有文件;若存在 `sourcePath` 则重新从源项目同步干净副本。
|
|
579
|
-
*/
|
|
580
|
-
async reset(idOrPath) {
|
|
581
|
-
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
582
|
-
if (!info) {
|
|
583
|
-
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
584
|
-
}
|
|
585
|
-
await mkdir(info.path, { recursive: true });
|
|
586
|
-
const entries = await readdir(info.path);
|
|
587
|
-
// 逐条目容错:Windows 下沙盒内进程未停(npm run dev 的 node.exe 持有句柄)
|
|
588
|
-
// 会让单个条目 EBUSY/EPERM——整体抛错会留下半清空状态;能删的先删,
|
|
589
|
-
// 全部失败才抛
|
|
590
|
-
const failures = [];
|
|
591
|
-
for (const entry of entries) {
|
|
592
|
-
try {
|
|
593
|
-
await rm(join(info.path, entry), { recursive: true, force: true, maxRetries: 3 });
|
|
594
|
-
}
|
|
595
|
-
catch {
|
|
596
|
-
failures.push(entry);
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
if (failures.length === entries.length && entries.length > 0) {
|
|
600
|
-
throw new Error(`Failed to clear sandbox contents (all ${failures.length} entries busy): ${failures.slice(0, 5).join(", ")}`);
|
|
601
|
-
}
|
|
602
|
-
if (failures.length > 0) {
|
|
603
|
-
console.warn(`[sandbox] reset: ${failures.length}/${entries.length} entries could not be removed (busy): ${failures.slice(0, 5).join(", ")}`);
|
|
604
|
-
}
|
|
605
|
-
let copyStats = { copiedFiles: 0, skippedFiles: 0 };
|
|
606
|
-
if (info.sourcePath && existsSync(info.sourcePath)) {
|
|
607
|
-
copyStats = await copyWorkspaceTree(info.sourcePath, info.path);
|
|
608
|
-
}
|
|
609
|
-
return { sandbox: info, ...copyStats };
|
|
610
|
-
}
|
|
611
|
-
/**
|
|
612
|
-
* 将临时沙盒转为永久沙盒(`ephemeral = false`)。
|
|
613
|
-
*/
|
|
614
|
-
persist(idOrPath) {
|
|
615
|
-
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
616
|
-
if (!info) {
|
|
617
|
-
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
618
|
-
}
|
|
619
|
-
const updated = { ...info, ephemeral: false };
|
|
620
|
-
this.items.set(info.id, updated);
|
|
621
|
-
this.save();
|
|
622
|
-
return updated;
|
|
623
|
-
}
|
|
624
|
-
/**
|
|
625
|
-
* 将沙盒项目导出/转正到指定目标目录(`targetPath` 必须位于沙盒根外部,且若已存在必须为空目录)。
|
|
626
|
-
*/
|
|
627
|
-
async promote(idOrPath, targetPath) {
|
|
628
|
-
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
629
|
-
if (!info) {
|
|
630
|
-
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
631
|
-
}
|
|
632
|
-
const trimmed = targetPath.trim();
|
|
633
|
-
if (!trimmed) {
|
|
634
|
-
throw new Error("Target path is required");
|
|
635
|
-
}
|
|
636
|
-
const expanded = trimmed === "~"
|
|
637
|
-
? homedir()
|
|
638
|
-
: trimmed.startsWith("~/") || trimmed.startsWith("~\\")
|
|
639
|
-
? join(homedir(), trimmed.slice(2))
|
|
640
|
-
: trimmed;
|
|
641
|
-
const resolvedTarget = resolve(expanded);
|
|
642
|
-
if (isProtectedSystemOrHomeRoot(resolvedTarget)) {
|
|
643
|
-
throw new Error(`Refusing to export sandbox to system or home root: ${resolvedTarget}`);
|
|
644
|
-
}
|
|
645
|
-
if (isSameOrSubpath(resolvedTarget, this.sandboxesRoot)) {
|
|
646
|
-
throw new Error("Target path must be outside the managed sandboxes directory");
|
|
647
|
-
}
|
|
648
|
-
if (existsSync(resolvedTarget)) {
|
|
649
|
-
const st = await stat(resolvedTarget);
|
|
650
|
-
if (!st.isDirectory()) {
|
|
651
|
-
throw new Error(`Target path already exists and is not a directory: ${resolvedTarget}`);
|
|
652
|
-
}
|
|
653
|
-
const existing = await readdir(resolvedTarget);
|
|
654
|
-
if (existing.length > 0) {
|
|
655
|
-
throw new Error(`Target directory is not empty: ${resolvedTarget}`);
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
else {
|
|
659
|
-
await mkdir(resolvedTarget, { recursive: true });
|
|
660
|
-
}
|
|
661
|
-
const stats = await copyWorkspaceTree(info.path, resolvedTarget);
|
|
662
|
-
return {
|
|
663
|
-
sandbox: info,
|
|
664
|
-
targetPath: toWirePath(resolvedTarget),
|
|
665
|
-
copiedFiles: stats.copiedFiles,
|
|
666
|
-
};
|
|
667
|
-
}
|
|
668
|
-
/**
|
|
669
|
-
* 将导入型沙盒中的修改写回源项目(保留源项目 `.git` 与重型依赖目录,同步工作区文件变更并清理已删除文件)。
|
|
670
|
-
*/
|
|
671
|
-
async applyToSource(idOrPath) {
|
|
672
|
-
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
673
|
-
if (!info) {
|
|
674
|
-
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
675
|
-
}
|
|
676
|
-
if (!info.sourcePath || !existsSync(info.sourcePath)) {
|
|
677
|
-
throw new Error("This sandbox has no valid source project to apply changes back to");
|
|
678
|
-
}
|
|
679
|
-
// 1. 先通过 diff 计算出被删除的文件列表,以便同步清理源项目中的对应文件
|
|
680
|
-
const diff = await this.diffWithSource(info.id);
|
|
681
|
-
let deletedFiles = 0;
|
|
682
|
-
for (const rel of diff.deleted) {
|
|
683
|
-
// 安全校验:严格限制在 sourcePath 内,且避开 .git 与重型忽略目录
|
|
684
|
-
if (!rel ||
|
|
685
|
-
rel === ".git" ||
|
|
686
|
-
rel.startsWith(".git/") ||
|
|
687
|
-
rel.startsWith(".git\\") ||
|
|
688
|
-
!isStrictlyInsideSandbox(rel, info.sourcePath, info.sourcePath)) {
|
|
689
|
-
continue;
|
|
690
|
-
}
|
|
691
|
-
const targetFile = join(info.sourcePath, rel);
|
|
692
|
-
if (existsSync(targetFile)) {
|
|
693
|
-
try {
|
|
694
|
-
await rm(targetFile, { force: true });
|
|
695
|
-
deletedFiles++;
|
|
696
|
-
// 尝试顺带清理变空的父目录(直到 sourcePath,不删 sourcePath 自身)
|
|
697
|
-
let parent = dirname(targetFile);
|
|
698
|
-
while (parent &&
|
|
699
|
-
isSameOrSubpath(parent, info.sourcePath) &&
|
|
700
|
-
normalizePathKey(parent) !== normalizePathKey(info.sourcePath)) {
|
|
701
|
-
const remaining = await readdir(parent).catch(() => ["non-empty"]);
|
|
702
|
-
if (remaining.length === 0) {
|
|
703
|
-
await rm(parent, { recursive: true, force: true }).catch(() => { });
|
|
704
|
-
parent = dirname(parent);
|
|
705
|
-
}
|
|
706
|
-
else {
|
|
707
|
-
break;
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
catch {
|
|
712
|
-
// 忽略单个文件清理失败
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
// 2. 将沙盒工作区的文件复制覆盖回源项目
|
|
717
|
-
const stats = await copyWorkspaceTree(info.path, info.sourcePath, { skipGitDir: true });
|
|
718
|
-
return {
|
|
719
|
-
sandbox: info,
|
|
720
|
-
sourcePath: info.sourcePath,
|
|
721
|
-
copiedFiles: stats.copiedFiles,
|
|
722
|
-
deletedFiles,
|
|
723
|
-
};
|
|
724
|
-
}
|
|
725
|
-
/**
|
|
726
|
-
* 对比沙盒与源项目之间的文件增删改差异(若为空白沙盒,则所有沙盒内文件计入 added)。
|
|
727
|
-
*/
|
|
728
|
-
async diffWithSource(idOrPath) {
|
|
729
|
-
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
730
|
-
if (!info) {
|
|
731
|
-
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
732
|
-
}
|
|
733
|
-
const collectRelativeFiles = async (rootDir) => {
|
|
734
|
-
const map = new Map();
|
|
735
|
-
if (!existsSync(rootDir))
|
|
736
|
-
return map;
|
|
737
|
-
const resolvedRoot = resolve(rootDir);
|
|
738
|
-
const walk = async (curDir, relPrefix) => {
|
|
739
|
-
const entries = await readdir(curDir, { withFileTypes: true });
|
|
740
|
-
for (const entry of entries) {
|
|
741
|
-
const name = entry.name;
|
|
742
|
-
if (name === ".git" ||
|
|
743
|
-
SANDBOX_IGNORED_FILES.has(name) ||
|
|
744
|
-
name.startsWith(".pi-tmp") ||
|
|
745
|
-
SANDBOX_IGNORED_DIRS.has(name)) {
|
|
746
|
-
continue;
|
|
747
|
-
}
|
|
748
|
-
const fullPath = join(curDir, name);
|
|
749
|
-
const relPath = relPrefix ? `${relPrefix}/${name}` : name;
|
|
750
|
-
let lst;
|
|
751
|
-
try {
|
|
752
|
-
lst = await lstat(fullPath);
|
|
753
|
-
}
|
|
754
|
-
catch {
|
|
755
|
-
continue;
|
|
756
|
-
}
|
|
757
|
-
if (lst.isSymbolicLink())
|
|
758
|
-
continue;
|
|
759
|
-
if (lst.isDirectory()) {
|
|
760
|
-
await walk(fullPath, relPath);
|
|
761
|
-
}
|
|
762
|
-
else if (lst.isFile()) {
|
|
763
|
-
if (map.size < MAX_IMPORT_FILES && lst.size <= MAX_SINGLE_FILE_BYTES) {
|
|
764
|
-
map.set(relPath, { abs: fullPath, size: lst.size });
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
};
|
|
769
|
-
await walk(resolvedRoot, "");
|
|
770
|
-
return map;
|
|
771
|
-
};
|
|
772
|
-
const sbxFiles = await collectRelativeFiles(info.path);
|
|
773
|
-
if (!info.sourcePath || !existsSync(info.sourcePath)) {
|
|
774
|
-
return {
|
|
775
|
-
sandbox: info,
|
|
776
|
-
sourcePath: info.sourcePath,
|
|
777
|
-
added: [...sbxFiles.keys()].sort(),
|
|
778
|
-
modified: [],
|
|
779
|
-
deleted: [],
|
|
780
|
-
unchangedCount: 0,
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
const srcFiles = await collectRelativeFiles(info.sourcePath);
|
|
784
|
-
const added = [];
|
|
785
|
-
const modified = [];
|
|
786
|
-
const deleted = [];
|
|
787
|
-
let unchangedCount = 0;
|
|
788
|
-
for (const [rel, sbxMeta] of sbxFiles) {
|
|
789
|
-
const srcMeta = srcFiles.get(rel);
|
|
790
|
-
if (!srcMeta) {
|
|
791
|
-
added.push(rel);
|
|
792
|
-
continue;
|
|
793
|
-
}
|
|
794
|
-
if (sbxMeta.size !== srcMeta.size) {
|
|
795
|
-
modified.push(rel);
|
|
796
|
-
continue;
|
|
797
|
-
}
|
|
275
|
+
const release = acquireExecution?.();
|
|
798
276
|
try {
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
if (b1.equals(b2)) {
|
|
802
|
-
unchangedCount++;
|
|
803
|
-
}
|
|
804
|
-
else {
|
|
805
|
-
modified.push(rel);
|
|
806
|
-
}
|
|
277
|
+
signal?.throwIfAborted();
|
|
278
|
+
return await tool.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
807
279
|
}
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
}
|
|
811
|
-
}
|
|
812
|
-
for (const rel of srcFiles.keys()) {
|
|
813
|
-
if (!sbxFiles.has(rel)) {
|
|
814
|
-
deleted.push(rel);
|
|
280
|
+
finally {
|
|
281
|
+
release?.();
|
|
815
282
|
}
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
modified.sort();
|
|
819
|
-
deleted.sort();
|
|
820
|
-
return {
|
|
821
|
-
sandbox: info,
|
|
822
|
-
sourcePath: info.sourcePath,
|
|
823
|
-
added,
|
|
824
|
-
modified,
|
|
825
|
-
deleted,
|
|
826
|
-
unchangedCount,
|
|
827
|
-
};
|
|
828
|
-
}
|
|
829
|
-
/**
|
|
830
|
-
* 彻底销毁沙盒:从注册表移除并递归删除沙盒磁盘目录。
|
|
831
|
-
*/
|
|
832
|
-
async destroy(idOrPath) {
|
|
833
|
-
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
834
|
-
if (!info)
|
|
835
|
-
return undefined;
|
|
836
|
-
this.items.delete(info.id);
|
|
837
|
-
this.save();
|
|
838
|
-
// 安全校验:仅删除位于 sandboxesRoot 下的目录
|
|
839
|
-
if (isSameOrSubpath(info.path, this.sandboxesRoot) &&
|
|
840
|
-
normalizePathKey(info.path) !== normalizePathKey(this.sandboxesRoot)) {
|
|
841
|
-
await rm(info.path, { recursive: true, force: true, maxRetries: 3 }).catch(() => { });
|
|
842
|
-
}
|
|
843
|
-
return info;
|
|
844
|
-
}
|
|
283
|
+
},
|
|
284
|
+
};
|
|
845
285
|
}
|
|
286
|
+
export { SandboxManager } from "./sandbox-data.js";
|