pi-web-ui 0.103.3 → 0.104.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 +10 -0
- package/dist/server/agent-formatters.js +9 -1
- package/dist/server/agent-service-daemon.js +4 -3
- package/dist/server/agent-service.js +586 -44
- package/dist/server/compaction-markers.js +111 -3
- package/dist/server/delegate-mode.js +2 -0
- package/dist/server/dispatch-domain-handlers.js +25 -0
- package/dist/server/dsh/dsh-agent-service.js +265 -11
- package/dist/server/goal-review-gate.js +2 -0
- package/dist/server/index.js +1 -0
- package/dist/server/market-service.js +36 -9
- package/dist/server/mcp-agent-tool.js +164 -0
- package/dist/server/mcp-manager.js +182 -0
- package/dist/server/plan-mode.js +3 -0
- package/dist/server/plugin-api-catalog.js +24 -0
- package/dist/server/plugins.js +113 -0
- package/dist/server/preset-share.js +52 -1
- package/dist/server/remote-ssh-service.js +90 -25
- package/dist/server/sandbox-service.js +705 -0
- package/dist/server/sandbox-tool.js +365 -0
- package/dist/server/session-parser.js +48 -21
- package/dist/server/terminals.js +210 -10
- package/dist/server/tool-manager.js +24 -0
- package/dist/server/webui-context.js +6 -0
- package/dist/server/workspace-snapshot.js +51 -13
- package/package.json +1 -1
- package/plugin-sdk/index.d.ts +39 -0
- package/plugin-sdk/index.mjs +14 -0
- package/plugins/catalog.json +101 -2
- package/themes/zhujian-dark.css +711 -0
- package/themes/zhujian.css +760 -0
- package/web/dist/assets/{TerminalPanel-CAqMqC49.js → TerminalPanel-28naZdcs.js} +1 -1
- package/web/dist/assets/index-DbGGBf5I.js +680 -0
- package/web/dist/assets/index-RqIdFOsh.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-CYQdZEbx.css +0 -1
- package/web/dist/assets/index-Dt7CQ_Z6.js +0 -680
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 沙盒项目服务(Sandbox Project Service):
|
|
3
|
+
*
|
|
4
|
+
* 1. 隔离副本工作区管理(`<dataDir>/sandboxes/registry.json` + `<dataDir>/sandboxes/<id>/`):
|
|
5
|
+
* - 支持「空白沙盒」与「导入现有项目」(自动跳过 node_modules/.venv/target 等重型缓存目录与越界软链);
|
|
6
|
+
* - 支持「临时沙盒(用完即删)」与「永久沙盒(持久化保留,随时一键转正)」;
|
|
7
|
+
* - 支持一键重置(还原到初始空白或重新从源项目同步)、另存为正式项目(promote)、将修改写回源项目(applyToSource)、彻底销毁(destroy)。
|
|
8
|
+
*
|
|
9
|
+
* 2. 沙盒硬围栏(Hard Jail Gate):
|
|
10
|
+
* - 当会话处于受管沙盒目录内时,所有文件写入/编辑/补丁(write/edit/edit_soft/patch)必须严格落在
|
|
11
|
+
* `sandbox.path` 内部(含祖先目录 realpath 校验,防软链逃逸),越界直接硬拒绝(不走审批放行);
|
|
12
|
+
* - 终端命令(bash)严禁直接引用源项目路径(`sourcePath`)或越过沙盒根向外 cd;
|
|
13
|
+
* - 外部副作用工具(sftp 远端写/删/执行、mail 发信/删信)在沙盒内默认拦截。
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { copyFile, lstat, mkdir, readdir, rm, stat } from "node:fs/promises";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
19
|
+
import { normalizePathKey } from "./client-state.js";
|
|
20
|
+
import { pick } from "./i18n.js";
|
|
21
|
+
/** 导入项目进沙盒时默认跳过的重型依赖/构建缓存目录名。 */
|
|
22
|
+
export const SANDBOX_IGNORED_DIRS = new Set([
|
|
23
|
+
"node_modules",
|
|
24
|
+
".venv",
|
|
25
|
+
"venv",
|
|
26
|
+
"__pycache__",
|
|
27
|
+
".pytest_cache",
|
|
28
|
+
".mypy_cache",
|
|
29
|
+
".ruff_cache",
|
|
30
|
+
".next",
|
|
31
|
+
".nuxt",
|
|
32
|
+
".svelte-kit",
|
|
33
|
+
".turbo",
|
|
34
|
+
".parcel-cache",
|
|
35
|
+
"target",
|
|
36
|
+
".gradle",
|
|
37
|
+
".cache",
|
|
38
|
+
"coverage",
|
|
39
|
+
".nyc_output",
|
|
40
|
+
]);
|
|
41
|
+
/** 导入项目进沙盒时跳过的系统垃圾文件。 */
|
|
42
|
+
const SANDBOX_IGNORED_FILES = new Set([".DS_Store", "Thumbs.db", "desktop.ini"]);
|
|
43
|
+
/** 单次导入沙盒的最大文件数上限(防止意外导入超大目录卡死 I/O)。 */
|
|
44
|
+
const MAX_IMPORT_FILES = 15_000;
|
|
45
|
+
/** 单次导入沙盒的单文件大小上限(64 MB,超大二进制构建产物不拷入沙盒)。 */
|
|
46
|
+
const MAX_SINGLE_FILE_BYTES = 64 * 1024 * 1024;
|
|
47
|
+
function toWirePath(p) {
|
|
48
|
+
return resolve(p).replace(/\\/g, "/");
|
|
49
|
+
}
|
|
50
|
+
function toComparablePath(p) {
|
|
51
|
+
return normalizePathKey(p).replace(/\\/g, "/").replace(/\/+$/, "");
|
|
52
|
+
}
|
|
53
|
+
export function isSameOrSubpath(childAbs, parentAbs) {
|
|
54
|
+
const c = toComparablePath(childAbs);
|
|
55
|
+
const p = toComparablePath(parentAbs);
|
|
56
|
+
return c === p || c.startsWith(p + "/");
|
|
57
|
+
}
|
|
58
|
+
function isProtectedSystemOrHomeRoot(absPath) {
|
|
59
|
+
const resolved = resolve(absPath);
|
|
60
|
+
// 文件系统根(如 "/" 或 "C:\")
|
|
61
|
+
if (parseRootOnly(resolved))
|
|
62
|
+
return true;
|
|
63
|
+
const home = resolve(homedir());
|
|
64
|
+
if (normalizePathKey(resolved) === normalizePathKey(home))
|
|
65
|
+
return true;
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
function parseRootOnly(resolved) {
|
|
69
|
+
const trimmed = resolved.replace(/[\\/]+$/, "");
|
|
70
|
+
if (!trimmed)
|
|
71
|
+
return true;
|
|
72
|
+
if (/^[a-zA-Z]:$/.test(trimmed))
|
|
73
|
+
return true;
|
|
74
|
+
return dirname(resolved) === resolved;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* 解析目标路径并校验是否严格位于 `sandboxRoot` 内部(含祖先目录 realpath 校验,防软链逃逸)。
|
|
78
|
+
*/
|
|
79
|
+
export function isStrictlyInsideSandbox(targetPath, cwd, sandboxRoot) {
|
|
80
|
+
if (!targetPath || typeof targetPath !== "string")
|
|
81
|
+
return false;
|
|
82
|
+
const trimmed = targetPath.trim();
|
|
83
|
+
if (!trimmed)
|
|
84
|
+
return false;
|
|
85
|
+
const expanded = trimmed === "~"
|
|
86
|
+
? homedir()
|
|
87
|
+
: trimmed.startsWith("~/") || trimmed.startsWith("~\\")
|
|
88
|
+
? join(homedir(), trimmed.slice(2))
|
|
89
|
+
: trimmed;
|
|
90
|
+
const resolvedTarget = isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded);
|
|
91
|
+
const resolvedSandbox = resolve(sandboxRoot);
|
|
92
|
+
// 1. 词法路径必须在 sandboxRoot 之内
|
|
93
|
+
if (!isSameOrSubpath(resolvedTarget, resolvedSandbox)) {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
// 2. 真实路径(realpath)校验:沿目标路径向上找到第一个已存在的祖先目录,防止通过沙盒内软链写到外部
|
|
97
|
+
let realSandbox = resolvedSandbox;
|
|
98
|
+
try {
|
|
99
|
+
realSandbox = realpathSync(resolvedSandbox);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// 沙盒根自身若暂不可解则用词法路径
|
|
103
|
+
}
|
|
104
|
+
let cur = resolvedTarget;
|
|
105
|
+
while (true) {
|
|
106
|
+
if (existsSync(cur)) {
|
|
107
|
+
try {
|
|
108
|
+
const realCur = realpathSync(cur);
|
|
109
|
+
if (!isSameOrSubpath(realCur, realSandbox)) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
const parent = dirname(cur);
|
|
119
|
+
if (parent === cur)
|
|
120
|
+
break;
|
|
121
|
+
cur = parent;
|
|
122
|
+
}
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
/** 从 patch 工具的补丁文本中提取所有涉及的文件路径。 */
|
|
126
|
+
export function extractPatchTargetPaths(patchText) {
|
|
127
|
+
if (!patchText || typeof patchText !== "string")
|
|
128
|
+
return [];
|
|
129
|
+
const paths = [];
|
|
130
|
+
for (const rawLine of patchText.split(/\r?\n/)) {
|
|
131
|
+
const line = rawLine.trim();
|
|
132
|
+
const mHeader = line.match(/^\*\*\*\s+(?:Add File|Update File|Delete File|Move to):\s+(.+)$/);
|
|
133
|
+
if (mHeader?.[1]) {
|
|
134
|
+
paths.push(mHeader[1].trim());
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
const mUnified = line.match(/^(?:---|\+\+\+)\s+(?:[ab]\/)?([^\t\r\n]+)$/);
|
|
138
|
+
if (mUnified?.[1] && mUnified[1] !== "/dev/null") {
|
|
139
|
+
paths.push(mUnified[1].trim());
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return paths;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* 评估一次工具调用是否违反沙盒硬围栏。
|
|
146
|
+
* 返回 null = 放行;返回 SandboxDenial = 硬拒绝(不弹审批框、不受“全部允许”影响)。
|
|
147
|
+
*/
|
|
148
|
+
export function evaluateSandboxJail(sandbox, toolName, params, cwd) {
|
|
149
|
+
const p = params ?? {};
|
|
150
|
+
const sbxPath = sandbox.path;
|
|
151
|
+
// 1. 直接写文件类工具:write / edit / edit_soft
|
|
152
|
+
if (toolName === "write" || toolName === "edit" || toolName === "edit_soft") {
|
|
153
|
+
const rawPath = typeof p.path === "string" && p.path.trim()
|
|
154
|
+
? p.path.trim()
|
|
155
|
+
: typeof p.file_path === "string" && p.file_path.trim()
|
|
156
|
+
? p.file_path.trim()
|
|
157
|
+
: "";
|
|
158
|
+
if (!rawPath || !isStrictlyInsideSandbox(rawPath, cwd, sbxPath)) {
|
|
159
|
+
return {
|
|
160
|
+
reason: `【沙盒安全隔离拦截】当前项目处于隔离沙盒(${sandbox.name})中,严禁修改沙盒目录(${sbxPath})以外的文件:"${rawPath || "(空)"}"。` +
|
|
161
|
+
(sandbox.sourcePath ? ` 原项目(${sandbox.sourcePath})受只读保护,请仅在当前沙盒工作区内修改。` : ""),
|
|
162
|
+
reasonEn: `[Sandbox Isolation Blocked] Current project is in an isolated sandbox (${sandbox.name}); modifying files outside the sandbox directory (${sbxPath}) is strictly forbidden: "${rawPath || "(empty)"}".` +
|
|
163
|
+
(sandbox.sourcePath
|
|
164
|
+
? ` The source project (${sandbox.sourcePath}) is protected; only modify files inside the current sandbox workspace.`
|
|
165
|
+
: ""),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
// 2. 补丁工具:patch
|
|
171
|
+
if (toolName === "patch") {
|
|
172
|
+
const patchText = typeof p.patch === "string" ? p.patch : "";
|
|
173
|
+
const targets = extractPatchTargetPaths(patchText);
|
|
174
|
+
for (const target of targets) {
|
|
175
|
+
if (!isStrictlyInsideSandbox(target, cwd, sbxPath)) {
|
|
176
|
+
return {
|
|
177
|
+
reason: `【沙盒安全隔离拦截】补丁包含沙盒目录(${sbxPath})以外的目标路径:"${target}"。沙盒内严禁越界修改。`,
|
|
178
|
+
reasonEn: `[Sandbox Isolation Blocked] Patch contains a target path outside the sandbox directory (${sbxPath}): "${target}". Out-of-bounds modification is forbidden in sandbox mode.`,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
// 3. 终端命令:bash
|
|
185
|
+
if (toolName === "bash") {
|
|
186
|
+
const cmd = typeof p.command === "string" ? p.command : "";
|
|
187
|
+
if (!cmd.trim())
|
|
188
|
+
return null;
|
|
189
|
+
// 3a. 若为导入源项目的沙盒,严禁在命令中直接引用源项目路径(防 AI cd 回原项目改动)
|
|
190
|
+
if (sandbox.sourcePath) {
|
|
191
|
+
const srcWire = toWirePath(sandbox.sourcePath);
|
|
192
|
+
const srcNative = resolve(sandbox.sourcePath);
|
|
193
|
+
const cmdLower = process.platform === "win32" ? cmd.toLowerCase() : cmd;
|
|
194
|
+
const wireNeedle = process.platform === "win32" ? srcWire.toLowerCase() : srcWire;
|
|
195
|
+
const nativeNeedle = process.platform === "win32" ? srcNative.toLowerCase() : srcNative;
|
|
196
|
+
if ((wireNeedle.length > 3 && cmdLower.includes(wireNeedle)) ||
|
|
197
|
+
(nativeNeedle.length > 3 && cmdLower.includes(nativeNeedle))) {
|
|
198
|
+
return {
|
|
199
|
+
reason: `【沙盒安全隔离拦截】检测到命令直接引用了源项目路径(${sandbox.sourcePath})。沙盒模式下原项目受严格保护,请仅对当前沙盒目录(${sbxPath})执行操作。`,
|
|
200
|
+
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}).`,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
// 3b. 当 cwd 就是沙盒根时,拦截 `cd ..` 逃出沙盒根
|
|
205
|
+
if (normalizePathKey(cwd) === normalizePathKey(sbxPath)) {
|
|
206
|
+
if (/(?:^|[;&|\n]\s*)cd\s+\.\.(?:[\\/\s;&|]|$)/.test(cmd)) {
|
|
207
|
+
return {
|
|
208
|
+
reason: `【沙盒安全隔离拦截】当前位于沙盒根目录(${sbxPath}),禁止通过 "cd .." 跳出沙盒边界。`,
|
|
209
|
+
reasonEn: `[Sandbox Isolation Blocked] Currently at sandbox root (${sbxPath}); escaping the sandbox boundary via "cd .." is forbidden.`,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
// 4. 外部副作用工具:sftp / mail
|
|
216
|
+
if (toolName === "sftp") {
|
|
217
|
+
const act = typeof p.action === "string" ? p.action : "";
|
|
218
|
+
const isMutatingSync = act === "sync" && p.dryRun === false;
|
|
219
|
+
if (isMutatingSync || act === "write" || act === "rm" || act === "mv" || act === "mkdir" || act === "exec") {
|
|
220
|
+
return {
|
|
221
|
+
reason: `【沙盒安全隔离拦截】沙盒项目内禁止执行会修改远程服务器的 SFTP 写/执行操作(action=${act})。`,
|
|
222
|
+
reasonEn: `[Sandbox Isolation Blocked] Remote-mutating SFTP operations (action=${act}) are forbidden inside a sandbox project.`,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (toolName === "mail") {
|
|
227
|
+
const act = typeof p.action === "string" ? p.action : "";
|
|
228
|
+
if (act === "send" || (act === "manage" && p.manage_action === "delete")) {
|
|
229
|
+
return {
|
|
230
|
+
reason: `【沙盒安全隔离拦截】沙盒项目内禁止外发邮件或删除邮箱邮件(action=${act})。`,
|
|
231
|
+
reasonEn: `[Sandbox Isolation Blocked] Sending or deleting emails (action=${act}) is forbidden inside a sandbox project.`,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* 为工具包一层「沙盒硬围栏」:当 `getSandbox()` 返回非空时,对越界写操作与源项目触达直接硬拒绝。
|
|
239
|
+
*/
|
|
240
|
+
export function withSandboxJailGate(tool, getSandbox, getCwd, getLang) {
|
|
241
|
+
return {
|
|
242
|
+
...tool,
|
|
243
|
+
execute: async (toolCallId, params, signal, onUpdate, ctx) => {
|
|
244
|
+
const sbx = getSandbox();
|
|
245
|
+
if (sbx) {
|
|
246
|
+
const denied = evaluateSandboxJail(sbx, tool.name, params, getCwd());
|
|
247
|
+
if (denied) {
|
|
248
|
+
return {
|
|
249
|
+
content: [{ type: "text", text: pick(getLang(), denied.reason, denied.reasonEn) }],
|
|
250
|
+
details: { guardDenied: true, sandboxDenied: true, sandboxId: sbx.id },
|
|
251
|
+
isError: true,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return tool.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* 递归复制目录内容(安全跳过重型缓存目录与指向源目录外部的软链)。
|
|
261
|
+
*/
|
|
262
|
+
async function copyWorkspaceTree(srcRoot, destRoot, opts) {
|
|
263
|
+
const resolvedSrcRoot = resolve(srcRoot);
|
|
264
|
+
let realSrcRoot = resolvedSrcRoot;
|
|
265
|
+
try {
|
|
266
|
+
realSrcRoot = realpathSync(resolvedSrcRoot);
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
// ignore
|
|
270
|
+
}
|
|
271
|
+
const stats = { copiedFiles: 0, skippedFiles: 0 };
|
|
272
|
+
async function walk(curSrc, curDest) {
|
|
273
|
+
await mkdir(curDest, { recursive: true });
|
|
274
|
+
const entries = await readdir(curSrc, { withFileTypes: true });
|
|
275
|
+
for (const entry of entries) {
|
|
276
|
+
const name = entry.name;
|
|
277
|
+
if (SANDBOX_IGNORED_FILES.has(name) || name.startsWith(".pi-tmp")) {
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
if (SANDBOX_IGNORED_DIRS.has(name)) {
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (opts?.skipGitDir && name === ".git") {
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const srcPath = join(curSrc, name);
|
|
287
|
+
const destPath = join(curDest, name);
|
|
288
|
+
let lst;
|
|
289
|
+
try {
|
|
290
|
+
lst = await lstat(srcPath);
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
// 安全防御:跳过符号链接(避免软链逃逸或循环软链爆栈)
|
|
296
|
+
if (lst.isSymbolicLink()) {
|
|
297
|
+
stats.skippedFiles++;
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (lst.isDirectory()) {
|
|
301
|
+
// 防止把沙盒目录自身递归拷进自己
|
|
302
|
+
if (isSameOrSubpath(destRoot, srcPath)) {
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
await walk(srcPath, destPath);
|
|
306
|
+
}
|
|
307
|
+
else if (lst.isFile()) {
|
|
308
|
+
if (stats.copiedFiles >= MAX_IMPORT_FILES || lst.size > MAX_SINGLE_FILE_BYTES) {
|
|
309
|
+
stats.skippedFiles++;
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
// 确认真实路径仍在源目录内
|
|
313
|
+
try {
|
|
314
|
+
const realParent = realpathSync(dirname(srcPath));
|
|
315
|
+
if (!isSameOrSubpath(realParent, realSrcRoot)) {
|
|
316
|
+
stats.skippedFiles++;
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
stats.skippedFiles++;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
await copyFile(srcPath, destPath);
|
|
325
|
+
stats.copiedFiles++;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
await walk(resolvedSrcRoot, resolve(destRoot));
|
|
330
|
+
return stats;
|
|
331
|
+
}
|
|
332
|
+
export class SandboxManager {
|
|
333
|
+
sandboxesRoot;
|
|
334
|
+
registryPath;
|
|
335
|
+
items = new Map();
|
|
336
|
+
lastLoadedMtime = -1;
|
|
337
|
+
constructor(dataDir) {
|
|
338
|
+
this.sandboxesRoot = toWirePath(join(dataDir, "sandboxes"));
|
|
339
|
+
this.registryPath = join(dataDir, "sandboxes", "registry.json");
|
|
340
|
+
this.load();
|
|
341
|
+
}
|
|
342
|
+
ensureFresh() {
|
|
343
|
+
if (!existsSync(this.registryPath)) {
|
|
344
|
+
if (this.lastLoadedMtime !== -1) {
|
|
345
|
+
this.items.clear();
|
|
346
|
+
this.lastLoadedMtime = -1;
|
|
347
|
+
}
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
try {
|
|
351
|
+
const mtime = statSync(this.registryPath).mtimeMs;
|
|
352
|
+
if (mtime !== this.lastLoadedMtime) {
|
|
353
|
+
this.load();
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
// ignore
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
load() {
|
|
361
|
+
this.items.clear();
|
|
362
|
+
if (!existsSync(this.registryPath)) {
|
|
363
|
+
this.lastLoadedMtime = -1;
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
this.lastLoadedMtime = statSync(this.registryPath).mtimeMs;
|
|
368
|
+
const raw = JSON.parse(readFileSync(this.registryPath, "utf-8"));
|
|
369
|
+
if (!Array.isArray(raw.sandboxes))
|
|
370
|
+
return;
|
|
371
|
+
for (const item of raw.sandboxes) {
|
|
372
|
+
if (!item || typeof item.id !== "string" || typeof item.path !== "string")
|
|
373
|
+
continue;
|
|
374
|
+
const wirePath = toWirePath(item.path);
|
|
375
|
+
if (!existsSync(wirePath))
|
|
376
|
+
continue;
|
|
377
|
+
this.items.set(item.id, {
|
|
378
|
+
id: item.id,
|
|
379
|
+
name: typeof item.name === "string" && item.name.trim() ? item.name.trim() : item.id,
|
|
380
|
+
path: wirePath,
|
|
381
|
+
sourcePath: typeof item.sourcePath === "string" && item.sourcePath.trim() ? toWirePath(item.sourcePath) : undefined,
|
|
382
|
+
ephemeral: Boolean(item.ephemeral),
|
|
383
|
+
createdAt: typeof item.createdAt === "number" ? item.createdAt : Date.now(),
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
// best-effort
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
save() {
|
|
392
|
+
try {
|
|
393
|
+
mkdirSync(dirname(this.registryPath), { recursive: true });
|
|
394
|
+
const payload = {
|
|
395
|
+
version: 1,
|
|
396
|
+
sandboxes: [...this.items.values()].sort((a, b) => b.createdAt - a.createdAt),
|
|
397
|
+
};
|
|
398
|
+
writeFileSync(this.registryPath, JSON.stringify(payload, null, "\t"), "utf-8");
|
|
399
|
+
this.lastLoadedMtime = statSync(this.registryPath).mtimeMs;
|
|
400
|
+
}
|
|
401
|
+
catch {
|
|
402
|
+
// best-effort
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
/** 列出所有有效沙盒(自动剔除磁盘上已被外部删除的目录)。 */
|
|
406
|
+
list() {
|
|
407
|
+
this.ensureFresh();
|
|
408
|
+
let dirty = false;
|
|
409
|
+
for (const [id, info] of this.items) {
|
|
410
|
+
if (!existsSync(info.path)) {
|
|
411
|
+
this.items.delete(id);
|
|
412
|
+
dirty = true;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (dirty)
|
|
416
|
+
this.save();
|
|
417
|
+
return [...this.items.values()].sort((a, b) => b.createdAt - a.createdAt);
|
|
418
|
+
}
|
|
419
|
+
/** 按沙盒 id 或路径精确查找沙盒。 */
|
|
420
|
+
get(idOrPath) {
|
|
421
|
+
if (!idOrPath)
|
|
422
|
+
return undefined;
|
|
423
|
+
this.ensureFresh();
|
|
424
|
+
const byId = this.items.get(idOrPath);
|
|
425
|
+
if (byId && existsSync(byId.path))
|
|
426
|
+
return byId;
|
|
427
|
+
const key = normalizePathKey(idOrPath);
|
|
428
|
+
for (const info of this.list()) {
|
|
429
|
+
if (normalizePathKey(info.path) === key)
|
|
430
|
+
return info;
|
|
431
|
+
}
|
|
432
|
+
return undefined;
|
|
433
|
+
}
|
|
434
|
+
/** 判断给定工作目录 `cwd` 是否处于某个受管沙盒内(含沙盒的子目录),若是则返回该沙盒信息。 */
|
|
435
|
+
getByCwd(cwd) {
|
|
436
|
+
if (!cwd)
|
|
437
|
+
return undefined;
|
|
438
|
+
for (const info of this.list()) {
|
|
439
|
+
if (isSameOrSubpath(cwd, info.path)) {
|
|
440
|
+
return info;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return undefined;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* 创建一个新沙盒工作区(空白或从 `sourcePath` 导入隔离副本)。
|
|
447
|
+
*/
|
|
448
|
+
async create(opts) {
|
|
449
|
+
const rawSource = opts.sourcePath?.trim();
|
|
450
|
+
let resolvedSource;
|
|
451
|
+
if (rawSource) {
|
|
452
|
+
const expanded = rawSource === "~"
|
|
453
|
+
? homedir()
|
|
454
|
+
: rawSource.startsWith("~/") || rawSource.startsWith("~\\")
|
|
455
|
+
? join(homedir(), rawSource.slice(2))
|
|
456
|
+
: rawSource;
|
|
457
|
+
const abs = resolve(expanded);
|
|
458
|
+
if (!existsSync(abs) || !statSync(abs).isDirectory()) {
|
|
459
|
+
throw new Error(`Source directory does not exist: ${rawSource}`);
|
|
460
|
+
}
|
|
461
|
+
if (isProtectedSystemOrHomeRoot(abs)) {
|
|
462
|
+
throw new Error(`Refusing to import system root or user home directory into sandbox: ${abs}`);
|
|
463
|
+
}
|
|
464
|
+
if (isSameOrSubpath(this.sandboxesRoot, abs)) {
|
|
465
|
+
throw new Error(`Refusing to import a parent directory of sandboxes root: ${abs}`);
|
|
466
|
+
}
|
|
467
|
+
// 若选中的 source 本身已经是某个沙盒,而且该沙盒记录了原始 sourcePath,保留最外层真实路径或直接复制该沙盒内容
|
|
468
|
+
resolvedSource = toWirePath(abs);
|
|
469
|
+
}
|
|
470
|
+
const id = `sbx-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
471
|
+
const sbxDir = toWirePath(join(this.sandboxesRoot, id));
|
|
472
|
+
await mkdir(sbxDir, { recursive: true });
|
|
473
|
+
let copyStats = { copiedFiles: 0, skippedFiles: 0 };
|
|
474
|
+
if (resolvedSource) {
|
|
475
|
+
copyStats = await copyWorkspaceTree(resolvedSource, sbxDir);
|
|
476
|
+
}
|
|
477
|
+
const defaultName = resolvedSource ? `${basename(resolvedSource)} (Sandbox)` : `Sandbox ${id.slice(-4)}`;
|
|
478
|
+
const name = opts.name?.trim() || defaultName;
|
|
479
|
+
const info = {
|
|
480
|
+
id,
|
|
481
|
+
name,
|
|
482
|
+
path: sbxDir,
|
|
483
|
+
sourcePath: resolvedSource,
|
|
484
|
+
ephemeral: opts.ephemeral ?? true,
|
|
485
|
+
createdAt: Date.now(),
|
|
486
|
+
};
|
|
487
|
+
this.items.set(id, info);
|
|
488
|
+
this.save();
|
|
489
|
+
return { sandbox: info, ...copyStats };
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* 重置沙盒:清空沙盒根下所有文件;若存在 `sourcePath` 则重新从源项目同步干净副本。
|
|
493
|
+
*/
|
|
494
|
+
async reset(idOrPath) {
|
|
495
|
+
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
496
|
+
if (!info) {
|
|
497
|
+
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
498
|
+
}
|
|
499
|
+
await mkdir(info.path, { recursive: true });
|
|
500
|
+
const entries = await readdir(info.path);
|
|
501
|
+
for (const entry of entries) {
|
|
502
|
+
await rm(join(info.path, entry), { recursive: true, force: true, maxRetries: 3 });
|
|
503
|
+
}
|
|
504
|
+
let copyStats = { copiedFiles: 0, skippedFiles: 0 };
|
|
505
|
+
if (info.sourcePath && existsSync(info.sourcePath)) {
|
|
506
|
+
copyStats = await copyWorkspaceTree(info.sourcePath, info.path);
|
|
507
|
+
}
|
|
508
|
+
return { sandbox: info, ...copyStats };
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* 将临时沙盒转为永久沙盒(`ephemeral = false`)。
|
|
512
|
+
*/
|
|
513
|
+
persist(idOrPath) {
|
|
514
|
+
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
515
|
+
if (!info) {
|
|
516
|
+
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
517
|
+
}
|
|
518
|
+
const updated = { ...info, ephemeral: false };
|
|
519
|
+
this.items.set(info.id, updated);
|
|
520
|
+
this.save();
|
|
521
|
+
return updated;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* 将沙盒项目导出/转正到指定目标目录(`targetPath` 必须位于沙盒根外部,且若已存在必须为空目录)。
|
|
525
|
+
*/
|
|
526
|
+
async promote(idOrPath, targetPath) {
|
|
527
|
+
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
528
|
+
if (!info) {
|
|
529
|
+
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
530
|
+
}
|
|
531
|
+
const trimmed = targetPath.trim();
|
|
532
|
+
if (!trimmed) {
|
|
533
|
+
throw new Error("Target path is required");
|
|
534
|
+
}
|
|
535
|
+
const expanded = trimmed === "~"
|
|
536
|
+
? homedir()
|
|
537
|
+
: trimmed.startsWith("~/") || trimmed.startsWith("~\\")
|
|
538
|
+
? join(homedir(), trimmed.slice(2))
|
|
539
|
+
: trimmed;
|
|
540
|
+
const resolvedTarget = resolve(expanded);
|
|
541
|
+
if (isProtectedSystemOrHomeRoot(resolvedTarget)) {
|
|
542
|
+
throw new Error(`Refusing to export sandbox to system or home root: ${resolvedTarget}`);
|
|
543
|
+
}
|
|
544
|
+
if (isSameOrSubpath(resolvedTarget, this.sandboxesRoot)) {
|
|
545
|
+
throw new Error("Target path must be outside the managed sandboxes directory");
|
|
546
|
+
}
|
|
547
|
+
if (existsSync(resolvedTarget)) {
|
|
548
|
+
const st = await stat(resolvedTarget);
|
|
549
|
+
if (!st.isDirectory()) {
|
|
550
|
+
throw new Error(`Target path already exists and is not a directory: ${resolvedTarget}`);
|
|
551
|
+
}
|
|
552
|
+
const existing = await readdir(resolvedTarget);
|
|
553
|
+
if (existing.length > 0) {
|
|
554
|
+
throw new Error(`Target directory is not empty: ${resolvedTarget}`);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
else {
|
|
558
|
+
await mkdir(resolvedTarget, { recursive: true });
|
|
559
|
+
}
|
|
560
|
+
const stats = await copyWorkspaceTree(info.path, resolvedTarget);
|
|
561
|
+
return {
|
|
562
|
+
sandbox: info,
|
|
563
|
+
targetPath: toWirePath(resolvedTarget),
|
|
564
|
+
copiedFiles: stats.copiedFiles,
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* 将导入型沙盒中的修改写回源项目(保留源项目 `.git` 与重型依赖目录,仅同步工作区文件变更)。
|
|
569
|
+
*/
|
|
570
|
+
async applyToSource(idOrPath) {
|
|
571
|
+
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
572
|
+
if (!info) {
|
|
573
|
+
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
574
|
+
}
|
|
575
|
+
if (!info.sourcePath || !existsSync(info.sourcePath)) {
|
|
576
|
+
throw new Error("This sandbox has no valid source project to apply changes back to");
|
|
577
|
+
}
|
|
578
|
+
const stats = await copyWorkspaceTree(info.path, info.sourcePath, { skipGitDir: true });
|
|
579
|
+
return {
|
|
580
|
+
sandbox: info,
|
|
581
|
+
sourcePath: info.sourcePath,
|
|
582
|
+
copiedFiles: stats.copiedFiles,
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* 对比沙盒与源项目之间的文件增删改差异(若为空白沙盒,则所有沙盒内文件计入 added)。
|
|
587
|
+
*/
|
|
588
|
+
async diffWithSource(idOrPath) {
|
|
589
|
+
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
590
|
+
if (!info) {
|
|
591
|
+
throw new Error(`Sandbox not found: ${idOrPath}`);
|
|
592
|
+
}
|
|
593
|
+
const collectRelativeFiles = async (rootDir) => {
|
|
594
|
+
const map = new Map();
|
|
595
|
+
if (!existsSync(rootDir))
|
|
596
|
+
return map;
|
|
597
|
+
const resolvedRoot = resolve(rootDir);
|
|
598
|
+
const walk = async (curDir, relPrefix) => {
|
|
599
|
+
const entries = await readdir(curDir, { withFileTypes: true });
|
|
600
|
+
for (const entry of entries) {
|
|
601
|
+
const name = entry.name;
|
|
602
|
+
if (name === ".git" ||
|
|
603
|
+
SANDBOX_IGNORED_FILES.has(name) ||
|
|
604
|
+
name.startsWith(".pi-tmp") ||
|
|
605
|
+
SANDBOX_IGNORED_DIRS.has(name)) {
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
const fullPath = join(curDir, name);
|
|
609
|
+
const relPath = relPrefix ? `${relPrefix}/${name}` : name;
|
|
610
|
+
let lst;
|
|
611
|
+
try {
|
|
612
|
+
lst = await lstat(fullPath);
|
|
613
|
+
}
|
|
614
|
+
catch {
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
if (lst.isSymbolicLink())
|
|
618
|
+
continue;
|
|
619
|
+
if (lst.isDirectory()) {
|
|
620
|
+
await walk(fullPath, relPath);
|
|
621
|
+
}
|
|
622
|
+
else if (lst.isFile()) {
|
|
623
|
+
if (map.size < MAX_IMPORT_FILES && lst.size <= MAX_SINGLE_FILE_BYTES) {
|
|
624
|
+
map.set(relPath, { abs: fullPath, size: lst.size });
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
await walk(resolvedRoot, "");
|
|
630
|
+
return map;
|
|
631
|
+
};
|
|
632
|
+
const sbxFiles = await collectRelativeFiles(info.path);
|
|
633
|
+
if (!info.sourcePath || !existsSync(info.sourcePath)) {
|
|
634
|
+
return {
|
|
635
|
+
sandbox: info,
|
|
636
|
+
sourcePath: info.sourcePath,
|
|
637
|
+
added: [...sbxFiles.keys()].sort(),
|
|
638
|
+
modified: [],
|
|
639
|
+
deleted: [],
|
|
640
|
+
unchangedCount: 0,
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
const srcFiles = await collectRelativeFiles(info.sourcePath);
|
|
644
|
+
const added = [];
|
|
645
|
+
const modified = [];
|
|
646
|
+
const deleted = [];
|
|
647
|
+
let unchangedCount = 0;
|
|
648
|
+
for (const [rel, sbxMeta] of sbxFiles) {
|
|
649
|
+
const srcMeta = srcFiles.get(rel);
|
|
650
|
+
if (!srcMeta) {
|
|
651
|
+
added.push(rel);
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
if (sbxMeta.size !== srcMeta.size) {
|
|
655
|
+
modified.push(rel);
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
try {
|
|
659
|
+
const b1 = readFileSync(sbxMeta.abs);
|
|
660
|
+
const b2 = readFileSync(srcMeta.abs);
|
|
661
|
+
if (b1.equals(b2)) {
|
|
662
|
+
unchangedCount++;
|
|
663
|
+
}
|
|
664
|
+
else {
|
|
665
|
+
modified.push(rel);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
catch {
|
|
669
|
+
modified.push(rel);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
for (const rel of srcFiles.keys()) {
|
|
673
|
+
if (!sbxFiles.has(rel)) {
|
|
674
|
+
deleted.push(rel);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
added.sort();
|
|
678
|
+
modified.sort();
|
|
679
|
+
deleted.sort();
|
|
680
|
+
return {
|
|
681
|
+
sandbox: info,
|
|
682
|
+
sourcePath: info.sourcePath,
|
|
683
|
+
added,
|
|
684
|
+
modified,
|
|
685
|
+
deleted,
|
|
686
|
+
unchangedCount,
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* 彻底销毁沙盒:从注册表移除并递归删除沙盒磁盘目录。
|
|
691
|
+
*/
|
|
692
|
+
async destroy(idOrPath) {
|
|
693
|
+
const info = this.get(idOrPath) ?? this.getByCwd(idOrPath);
|
|
694
|
+
if (!info)
|
|
695
|
+
return undefined;
|
|
696
|
+
this.items.delete(info.id);
|
|
697
|
+
this.save();
|
|
698
|
+
// 安全校验:仅删除位于 sandboxesRoot 下的目录
|
|
699
|
+
if (isSameOrSubpath(info.path, this.sandboxesRoot) &&
|
|
700
|
+
normalizePathKey(info.path) !== normalizePathKey(this.sandboxesRoot)) {
|
|
701
|
+
await rm(info.path, { recursive: true, force: true, maxRetries: 3 }).catch(() => { });
|
|
702
|
+
}
|
|
703
|
+
return info;
|
|
704
|
+
}
|
|
705
|
+
}
|