@ai-hero/sandcastle 0.13.0 → 0.14.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/README.md +3 -3
- package/dist/{SandboxProvider-YCL97qco.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +5 -41
- package/dist/{chunk-XCYK7I45.js → chunk-4BB7DNPW.js} +3 -3
- package/dist/chunk-4BB7DNPW.js.map +1 -0
- package/dist/chunk-4GZMUHVO.js +60 -0
- package/dist/chunk-4GZMUHVO.js.map +1 -0
- package/dist/{chunk-A4C2FG74.js → chunk-7JUTKCHL.js} +43 -42
- package/dist/chunk-7JUTKCHL.js.map +1 -0
- package/dist/chunk-7PHPLDVS.js +284 -0
- package/dist/chunk-7PHPLDVS.js.map +1 -0
- package/dist/{chunk-NMQ5Z6YG.js → chunk-BXLS4HRY.js} +15 -4
- package/dist/chunk-BXLS4HRY.js.map +1 -0
- package/dist/chunk-EM4QNWKF.js +3161 -0
- package/dist/chunk-EM4QNWKF.js.map +1 -0
- package/dist/chunk-EXYXBRCX.js +60 -0
- package/dist/chunk-EXYXBRCX.js.map +1 -0
- package/dist/{chunk-LWNC4UTZ.js → chunk-JEQ4IVQM.js} +1520 -5375
- package/dist/chunk-JEQ4IVQM.js.map +1 -0
- package/dist/{chunk-XCWKLDH4.js → chunk-L3BU47F6.js} +3 -3
- package/dist/{chunk-XCWKLDH4.js.map → chunk-L3BU47F6.js.map} +1 -1
- package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
- package/dist/chunk-PTJEKJPQ.js.map +1 -0
- package/dist/chunk-SAQXFLO2.js +1268 -0
- package/dist/chunk-SAQXFLO2.js.map +1 -0
- package/dist/{chunk-767EAJVT.js → chunk-TBVRAXYF.js} +3 -3
- package/dist/{chunk-767EAJVT.js.map → chunk-TBVRAXYF.js.map} +1 -1
- package/dist/{chunk-J5J5YJ5S.js → chunk-VUOXFCWO.js} +3 -3
- package/dist/{chunk-J5J5YJ5S.js.map → chunk-VUOXFCWO.js.map} +1 -1
- package/dist/{chunk-U42XXICG.js → chunk-WYOGXC72.js} +47 -82
- package/dist/chunk-WYOGXC72.js.map +1 -0
- package/dist/chunk-YDQW5IOY.js +799 -0
- package/dist/chunk-YDQW5IOY.js.map +1 -0
- package/dist/index.d.ts +51 -4
- package/dist/index.js +892 -2018
- package/dist/index.js.map +1 -1
- package/dist/main.js +322 -251
- package/dist/main.js.map +1 -1
- package/dist/sandboxes/bwrap.d.ts +1 -1
- package/dist/sandboxes/bwrap.js +9 -14
- package/dist/sandboxes/bwrap.js.map +1 -1
- package/dist/sandboxes/daytona.d.ts +1 -1
- package/dist/sandboxes/daytona.js +183 -136
- package/dist/sandboxes/daytona.js.map +1 -1
- package/dist/sandboxes/docker.d.ts +23 -1
- package/dist/sandboxes/docker.js +7 -3
- package/dist/sandboxes/e2b.d.ts +41 -0
- package/dist/sandboxes/e2b.js +202 -0
- package/dist/sandboxes/e2b.js.map +1 -0
- package/dist/sandboxes/modal.d.ts +78 -0
- package/dist/sandboxes/modal.js +171 -0
- package/dist/sandboxes/modal.js.map +1 -0
- package/dist/sandboxes/no-sandbox.d.ts +1 -1
- package/dist/sandboxes/no-sandbox.js +1 -1
- package/dist/sandboxes/podman.d.ts +27 -4
- package/dist/sandboxes/podman.js +19 -43
- package/dist/sandboxes/podman.js.map +1 -1
- package/dist/sandboxes/seatbelt.d.ts +2 -2
- package/dist/sandboxes/seatbelt.js +10 -7
- package/dist/sandboxes/seatbelt.js.map +1 -1
- package/dist/sandboxes/sprites.d.ts +54 -0
- package/dist/sandboxes/sprites.js +219 -0
- package/dist/sandboxes/sprites.js.map +1 -0
- package/dist/sandboxes/vercel.d.ts +10 -1
- package/dist/sandboxes/vercel.js +74 -46
- package/dist/sandboxes/vercel.js.map +1 -1
- package/dist/templates/parallel-planner/main.mts +43 -21
- package/dist/templates/parallel-planner-with-review/main.mts +55 -27
- package/dist/templates/sequential-reviewer/main.mts +1 -1
- package/package.json +36 -4
- package/dist/chunk-4EIVTSOZ.js +0 -93
- package/dist/chunk-4EIVTSOZ.js.map +0 -1
- package/dist/chunk-7N7AMUYA.js.map +0 -1
- package/dist/chunk-A4C2FG74.js.map +0 -1
- package/dist/chunk-LWNC4UTZ.js.map +0 -1
- package/dist/chunk-NMQ5Z6YG.js.map +0 -1
- package/dist/chunk-U42XXICG.js.map +0 -1
- package/dist/chunk-XCYK7I45.js.map +0 -1
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { CopyError, ExecError, WorktreeError } from './chunk-YDQW5IOY.js';
|
|
3
|
+
import { Effect_exports } from './chunk-JEQ4IVQM.js';
|
|
4
|
+
import { statSync, rm, existsSync } from 'fs';
|
|
5
|
+
import { join, dirname, isAbsolute, resolve } from 'path';
|
|
6
|
+
import { tmpdir, homedir } from 'os';
|
|
7
|
+
import { mkdtemp, writeFile } from 'fs/promises';
|
|
8
|
+
|
|
9
|
+
createRequire(import.meta.url);
|
|
10
|
+
var PARENT_GIT_SANDBOX_DIR = "/.sandcastle-parent-git";
|
|
11
|
+
var parseGitdirPath = (gitdirPath) => {
|
|
12
|
+
const normalized = gitdirPath.replaceAll("\\", "/").replace(/\/+$/u, "");
|
|
13
|
+
const segments = normalized.split("/");
|
|
14
|
+
const worktreeName = segments.pop() ?? "";
|
|
15
|
+
segments.pop();
|
|
16
|
+
const parentGitDir = segments.join("/");
|
|
17
|
+
return { worktreeName, parentGitDir };
|
|
18
|
+
};
|
|
19
|
+
var readWorktreeGitdir = (gitEntryPath, fileAccess) => Effect_exports.gen(function* () {
|
|
20
|
+
const { readFile, statFile } = fileAccess;
|
|
21
|
+
const gitEntryType = yield* Effect_exports.tryPromise({
|
|
22
|
+
try: () => statFile(gitEntryPath),
|
|
23
|
+
catch: () => null
|
|
24
|
+
}).pipe(Effect_exports.catchAll(() => Effect_exports.succeed(null)));
|
|
25
|
+
if (gitEntryType === null || gitEntryType === "directory") {
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
const content = yield* Effect_exports.tryPromise({
|
|
29
|
+
try: () => readFile(gitEntryPath),
|
|
30
|
+
catch: () => null
|
|
31
|
+
}).pipe(
|
|
32
|
+
Effect_exports.map((s) => s.trim()),
|
|
33
|
+
Effect_exports.catchAll(() => Effect_exports.succeed(null))
|
|
34
|
+
);
|
|
35
|
+
if (content === null) {
|
|
36
|
+
return void 0;
|
|
37
|
+
}
|
|
38
|
+
return /^gitdir:\s*(?<gitdir>.+)$/u.exec(content)?.groups?.gitdir;
|
|
39
|
+
});
|
|
40
|
+
var writeGitOverride = (correctedGitdir) => Effect_exports.gen(function* () {
|
|
41
|
+
const tempDir = yield* Effect_exports.tryPromise({
|
|
42
|
+
try: () => mkdtemp(join(tmpdir(), "sandcastle-git-")),
|
|
43
|
+
catch: (e) => new WorktreeError({
|
|
44
|
+
message: `Failed to create temp dir for git override: ${e instanceof Error ? e.message : String(e)}`
|
|
45
|
+
})
|
|
46
|
+
});
|
|
47
|
+
const tempGitFile = join(tempDir, "git-override");
|
|
48
|
+
yield* Effect_exports.tryPromise({
|
|
49
|
+
try: () => writeFile(tempGitFile, `gitdir: ${correctedGitdir}
|
|
50
|
+
`),
|
|
51
|
+
catch: (e) => new WorktreeError({
|
|
52
|
+
message: `Failed to write git override file: ${e instanceof Error ? e.message : String(e)}`
|
|
53
|
+
})
|
|
54
|
+
}).pipe(
|
|
55
|
+
Effect_exports.tapError(
|
|
56
|
+
() => removeMountTempDirs([
|
|
57
|
+
{ hostPath: tempGitFile, sandboxPath: "", tempDir }
|
|
58
|
+
])
|
|
59
|
+
)
|
|
60
|
+
);
|
|
61
|
+
return { hostPath: tempGitFile, tempDir };
|
|
62
|
+
});
|
|
63
|
+
var overlayGitMounts = (gitMounts, paths) => {
|
|
64
|
+
const normalizedParentGitDir = paths.parentGitDir.replaceAll("\\", "/");
|
|
65
|
+
const gitFileHostPath = paths.gitEntryPath.replaceAll("\\", "/");
|
|
66
|
+
const correctedMounts = [];
|
|
67
|
+
let replacedGitFile = false;
|
|
68
|
+
for (const m of gitMounts) {
|
|
69
|
+
const normalizedHostPath = m.hostPath.replaceAll("\\", "/");
|
|
70
|
+
if (normalizedHostPath === normalizedParentGitDir) {
|
|
71
|
+
correctedMounts.push({ ...m, sandboxPath: PARENT_GIT_SANDBOX_DIR });
|
|
72
|
+
} else if (normalizedHostPath === gitFileHostPath) {
|
|
73
|
+
correctedMounts.push({ ...m, ...paths.overrideMount });
|
|
74
|
+
replacedGitFile = true;
|
|
75
|
+
} else {
|
|
76
|
+
correctedMounts.push(m);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (!replacedGitFile) {
|
|
80
|
+
correctedMounts.push(paths.overrideMount);
|
|
81
|
+
}
|
|
82
|
+
return correctedMounts;
|
|
83
|
+
};
|
|
84
|
+
var removeMountTempDirs = (mounts) => Effect_exports.forEach(
|
|
85
|
+
mounts.flatMap((m) => m.tempDir === void 0 ? [] : [m.tempDir]),
|
|
86
|
+
(dir) => (
|
|
87
|
+
// A dir that can't be removed is left behind; nothing depends on it.
|
|
88
|
+
Effect_exports.async((resume) => {
|
|
89
|
+
rm(dir, { recursive: true, force: true }, (error) => {
|
|
90
|
+
resume(Effect_exports.succeed(error));
|
|
91
|
+
});
|
|
92
|
+
})
|
|
93
|
+
),
|
|
94
|
+
{ discard: true }
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
// src/sandboxService.ts
|
|
98
|
+
var getCopyIn = (handle) => {
|
|
99
|
+
if ("copyIn" in handle) {
|
|
100
|
+
return (hostPath, sandboxPath) => Effect_exports.tryPromise({
|
|
101
|
+
try: () => handle.copyIn(hostPath, sandboxPath),
|
|
102
|
+
catch: (e) => new CopyError({
|
|
103
|
+
message: `copyIn failed: ${e instanceof Error ? e.message : String(e)}`
|
|
104
|
+
})
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
if ("copyFileIn" in handle) {
|
|
108
|
+
return (hostPath, sandboxPath) => Effect_exports.tryPromise({
|
|
109
|
+
try: () => handle.copyFileIn(hostPath, sandboxPath),
|
|
110
|
+
catch: (e) => new CopyError({
|
|
111
|
+
message: `copyFileIn failed: ${e instanceof Error ? e.message : String(e)}`
|
|
112
|
+
})
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return () => Effect_exports.fail(
|
|
116
|
+
new CopyError({
|
|
117
|
+
message: "copyIn is not supported for this sandbox provider"
|
|
118
|
+
})
|
|
119
|
+
);
|
|
120
|
+
};
|
|
121
|
+
var makeSandboxFromHandle = (handle) => ({
|
|
122
|
+
exec: (command, options) => Effect_exports.tryPromise({
|
|
123
|
+
try: () => handle.exec(command, options),
|
|
124
|
+
catch: (e) => new ExecError({
|
|
125
|
+
command,
|
|
126
|
+
message: `exec failed: ${e instanceof Error ? e.message : String(e)}`
|
|
127
|
+
})
|
|
128
|
+
}),
|
|
129
|
+
copyIn: getCopyIn(handle),
|
|
130
|
+
copyFileOut: "copyFileOut" in handle ? (sandboxPath, hostPath) => Effect_exports.tryPromise({
|
|
131
|
+
try: () => handle.copyFileOut(sandboxPath, hostPath),
|
|
132
|
+
catch: (e) => new CopyError({
|
|
133
|
+
message: `copyFileOut failed: ${e instanceof Error ? e.message : String(e)}`
|
|
134
|
+
})
|
|
135
|
+
}) : () => Effect_exports.fail(
|
|
136
|
+
new CopyError({
|
|
137
|
+
message: "copyFileOut is not supported for this sandbox provider"
|
|
138
|
+
})
|
|
139
|
+
)
|
|
140
|
+
});
|
|
141
|
+
var SANDBOX_REPO_DIR = "/home/agent/workspace";
|
|
142
|
+
|
|
143
|
+
// src/mountPaths.ts
|
|
144
|
+
var expandTilde = (p, homeDirPath) => {
|
|
145
|
+
const home = homeDirPath ?? homedir();
|
|
146
|
+
if (p === "~") {
|
|
147
|
+
return home;
|
|
148
|
+
}
|
|
149
|
+
if (p.startsWith("~/") || p.startsWith("~\\")) {
|
|
150
|
+
return `${home}/${p.slice(2)}`;
|
|
151
|
+
}
|
|
152
|
+
return p;
|
|
153
|
+
};
|
|
154
|
+
var resolveHostPath = (hostPath) => {
|
|
155
|
+
const expanded = expandTilde(hostPath);
|
|
156
|
+
return isAbsolute(expanded) ? expanded : resolve(process.cwd(), expanded);
|
|
157
|
+
};
|
|
158
|
+
var resolveSandboxPath = (sandboxPath, sandboxHomedir) => {
|
|
159
|
+
const hasTilde = sandboxPath === "~" || sandboxPath.startsWith("~/") || sandboxPath.startsWith("~\\");
|
|
160
|
+
if (hasTilde && sandboxHomedir === void 0) {
|
|
161
|
+
throw new Error(
|
|
162
|
+
`sandboxPath "${sandboxPath}" contains a tilde but the provider has no sandboxHomedir set`
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
const expanded = hasTilde ? expandTilde(sandboxPath, sandboxHomedir) : sandboxPath;
|
|
166
|
+
return isAbsolute(expanded) ? expanded : resolve(SANDBOX_REPO_DIR, expanded);
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
// src/mountUtils.ts
|
|
170
|
+
var defaultImageName = (repoDir) => {
|
|
171
|
+
const dirName = repoDir.replace(/[\\/]+$/u, "").split(/[\\/]/u).pop() ?? "local";
|
|
172
|
+
const sanitized = dirName.toLowerCase().replaceAll(/[^a-z0-9_.-]/gu, (char) => "-".repeat(char.length));
|
|
173
|
+
return `sandcastle:${sanitized || "local"}`;
|
|
174
|
+
};
|
|
175
|
+
var resolveUserMounts = (mounts, sandboxHomedir) => mounts.map((m) => {
|
|
176
|
+
const resolvedHostPath = resolveHostPath(m.hostPath);
|
|
177
|
+
if (!existsSync(resolvedHostPath)) {
|
|
178
|
+
throw new Error(
|
|
179
|
+
`Mount hostPath does not exist: ${m.hostPath}${m.hostPath === resolvedHostPath ? "" : ` (resolved to ${resolvedHostPath})`}`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
hostPath: resolvedHostPath,
|
|
184
|
+
sandboxPath: resolveSandboxPath(m.sandboxPath, sandboxHomedir),
|
|
185
|
+
...m.readonly === true ? { readonly: true } : {}
|
|
186
|
+
};
|
|
187
|
+
});
|
|
188
|
+
var normalizeMounts = (mounts, repo, platform = process.platform) => {
|
|
189
|
+
if (platform !== "win32") {
|
|
190
|
+
return mounts;
|
|
191
|
+
}
|
|
192
|
+
const { worktreeHostPath, sandboxRepoDir } = repo;
|
|
193
|
+
const normalizedWorktree = worktreeHostPath.replaceAll("\\", "/");
|
|
194
|
+
return mounts.map((m) => {
|
|
195
|
+
const hostPath = m.hostPath.replaceAll("\\", "/");
|
|
196
|
+
let { sandboxPath } = m;
|
|
197
|
+
if (/^[A-Za-z]:[/\\]/u.test(sandboxPath) || sandboxPath.includes("\\")) {
|
|
198
|
+
const normalizedSandboxPath = sandboxPath.replaceAll("\\", "/");
|
|
199
|
+
if (normalizedSandboxPath.startsWith(`${normalizedWorktree}/`)) {
|
|
200
|
+
const relativeSuffix = normalizedSandboxPath.slice(
|
|
201
|
+
normalizedWorktree.length
|
|
202
|
+
);
|
|
203
|
+
sandboxPath = sandboxRepoDir + relativeSuffix;
|
|
204
|
+
} else if (normalizedSandboxPath === normalizedWorktree) {
|
|
205
|
+
sandboxPath = sandboxRepoDir;
|
|
206
|
+
} else {
|
|
207
|
+
sandboxPath = normalizedSandboxPath;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return { ...m, hostPath, sandboxPath };
|
|
211
|
+
});
|
|
212
|
+
};
|
|
213
|
+
var patchGitMountsForWindows = (gitMounts, worktreeHostPath, sandboxRepoDir, readFile, statFile, platform = process.platform) => Effect_exports.gen(function* () {
|
|
214
|
+
if (platform !== "win32") {
|
|
215
|
+
return gitMounts;
|
|
216
|
+
}
|
|
217
|
+
const gitEntryPath = join(worktreeHostPath, ".git");
|
|
218
|
+
const gitdirPath = yield* readWorktreeGitdir(gitEntryPath, {
|
|
219
|
+
readFile: readFile ?? defaultReadFile,
|
|
220
|
+
statFile: statFile ?? defaultStatFile
|
|
221
|
+
});
|
|
222
|
+
if (gitdirPath === void 0) {
|
|
223
|
+
return gitMounts;
|
|
224
|
+
}
|
|
225
|
+
const { parentGitDir, worktreeName } = parseGitdirPath(gitdirPath);
|
|
226
|
+
const override = yield* writeGitOverride(
|
|
227
|
+
`${PARENT_GIT_SANDBOX_DIR}/worktrees/${worktreeName}`
|
|
228
|
+
);
|
|
229
|
+
return overlayGitMounts(gitMounts, {
|
|
230
|
+
parentGitDir,
|
|
231
|
+
gitEntryPath,
|
|
232
|
+
overrideMount: {
|
|
233
|
+
...override,
|
|
234
|
+
sandboxPath: `${sandboxRepoDir}/.git`,
|
|
235
|
+
readonly: true
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
var defaultReadFile = async (p) => {
|
|
240
|
+
const { readFile: rf } = await import('fs/promises');
|
|
241
|
+
return rf(p, "utf8");
|
|
242
|
+
};
|
|
243
|
+
var defaultStatFile = async (p) => {
|
|
244
|
+
const { stat } = await import('fs/promises');
|
|
245
|
+
const s = await stat(p);
|
|
246
|
+
return s.isDirectory() ? "directory" : "file";
|
|
247
|
+
};
|
|
248
|
+
var formatVolumeMount = (mount, selinuxLabel) => {
|
|
249
|
+
const base = `${mount.hostPath}:${mount.sandboxPath}`;
|
|
250
|
+
const options = [
|
|
251
|
+
mount.readonly === true ? "ro" : void 0,
|
|
252
|
+
selinuxLabel === false ? void 0 : selinuxLabel
|
|
253
|
+
].filter((option) => option !== void 0).join(",");
|
|
254
|
+
return options ? `${base}:${options}` : base;
|
|
255
|
+
};
|
|
256
|
+
var processFileMountParents = (mounts, sandboxHomedir, statFn = statSync) => {
|
|
257
|
+
const parentDirs = /* @__PURE__ */ new Set();
|
|
258
|
+
for (const mount of mounts) {
|
|
259
|
+
let isFile;
|
|
260
|
+
try {
|
|
261
|
+
isFile = statFn(mount.hostPath).isFile();
|
|
262
|
+
} catch {
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
if (!isFile) {
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const parentDir = dirname(mount.sandboxPath);
|
|
269
|
+
if (parentDir === sandboxHomedir) {
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
if (!parentDir.startsWith(`${sandboxHomedir}/`)) {
|
|
273
|
+
throw new Error(
|
|
274
|
+
`Cannot mount file to '${mount.sandboxPath}': parent directory '${parentDir}' is outside the sandbox home directory ('${sandboxHomedir}'). Mount the parent directory instead, or rebuild the image with '${parentDir}' pre-created.`
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
parentDirs.add(parentDir);
|
|
278
|
+
}
|
|
279
|
+
return [...parentDirs];
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
export { SANDBOX_REPO_DIR, defaultImageName, formatVolumeMount, makeSandboxFromHandle, normalizeMounts, patchGitMountsForWindows, processFileMountParents, removeMountTempDirs, resolveUserMounts };
|
|
283
|
+
//# sourceMappingURL=chunk-7PHPLDVS.js.map
|
|
284
|
+
//# sourceMappingURL=chunk-7PHPLDVS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/gitMountOverride.ts","../src/sandboxService.ts","../src/mountPaths.ts","../src/mountUtils.ts"],"names":["rmCallback","join"],"mappings":";;;;;;;;;AAmBO,IAAM,sBAAA,GAAyB,yBAAA;AAS/B,IAAM,eAAA,GAAkB,CAC7B,UAAA,KACmD;AACnD,EAAA,MAAM,UAAA,GAAa,WAAW,UAAA,CAAW,IAAA,EAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,SAAS,EAAE,CAAA;AACvE,EAAA,MAAM,QAAA,GAAW,UAAA,CAAW,KAAA,CAAM,GAAG,CAAA;AACrC,EAAA,MAAM,YAAA,GAAe,QAAA,CAAS,GAAA,EAAI,IAAK,EAAA;AACvC,EAAA,QAAA,CAAS,GAAA,EAAI;AACb,EAAA,MAAM,YAAA,GAAe,QAAA,CAAS,IAAA,CAAK,GAAG,CAAA;AACtC,EAAA,OAAO,EAAE,cAAc,YAAA,EA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IAAI,cAAc,cAAA,EAAgB;AAChC,MAAA;AAAA,IACF;AAGA,IAAA,IAAI,CAAC,SAAA,CAAU,UAAA,CAAW,CAAA,EAAG,cAAc,GAAG,CAAA,EAAG;AAC/C,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,sBAAA,EAAyB,MAAM,WAAW,CAAA,qBAAA,EACnB,SAAS,CAAA,0CAAA,EAA6C,cAAc,sEACvB,SAAS,CAAA,cAAA;AAAA,OAC/E;AAAA,IACF;AAEA,IAAA,UAAA,CAAW,IAAI,SAAS,CAAA;AAAA,EAC1B;AAEA,EAAA,OAAO,CAAC,GAAG,UAAU,CAAA;AACvB","file":"chunk-7PHPLDVS.js","sourcesContent":["/**\n * The pieces of the Windows git-mount fix (ADR-0006) that\n * `patchGitMountsForWindows` in `mountUtils.ts` puts together: reading a\n * worktree's `gitdir:` pointer, writing the corrected `.git` override file,\n * overlaying it on the git mounts, and removing its temp dir afterwards.\n */\n\nimport { rm as rmCallback } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { mkdtemp, writeFile } from \"node:fs/promises\";\nimport { Effect } from \"effect\";\nimport type { MountEntry } from \"./sandboxService.js\";\nimport { WorktreeError } from \"./errors.js\";\n\n/**\n * Deterministic mount point inside the sandbox for the parent repo's .git\n * directory when the workspace is a git worktree. See ADR-0006.\n */\nexport const PARENT_GIT_SANDBOX_DIR = \"/.sandcastle-parent-git\";\n\n/**\n * Parse a `gitdir:` path into its parent .git directory and worktree name.\n *\n * The gitdir path is like `/path/to/repo/.git/worktrees/<name>` or\n * `C:\\Users\\project\\.git\\worktrees\\<name>`. We split on both `/` and `\\`\n * so this works regardless of the host platform or which platform runs tests.\n */\nexport const parseGitdirPath = (\n gitdirPath: string,\n): { parentGitDir: string; worktreeName: string } => {\n const normalized = gitdirPath.replaceAll(\"\\\\\", \"/\").replace(/\\/+$/u, \"\");\n const segments = normalized.split(\"/\");\n const worktreeName = segments.pop() ?? \"\"; // <name>\n segments.pop(); // \"worktrees\"\n const parentGitDir = segments.join(\"/\");\n return { worktreeName, parentGitDir };\n};\n\n/**\n * The `gitdir:` path a worktree's `.git` file points at, or `undefined` when\n * `.git` is missing, unreadable, a directory, or not a `gitdir:` pointer.\n */\nexport const readWorktreeGitdir = (\n gitEntryPath: string,\n fileAccess: {\n readonly readFile: (path: string) => Promise<string>;\n readonly statFile: (path: string) => Promise<\"file\" | \"directory\">;\n },\n): Effect.Effect<string | undefined> =>\n Effect.gen(function* () {\n const { readFile, statFile } = fileAccess;\n\n const gitEntryType = yield* Effect.tryPromise({\n try: () => statFile(gitEntryPath),\n catch: () => null,\n }).pipe(Effect.catchAll(() => Effect.succeed(null)));\n // .git is a directory (normal clone): no gitdir indirection to fix.\n // `normalizeMounts` already remaps the .git mount to `${sandboxRepoDir}/.git`\n // because the host .git sits under `worktreeHostPath`. Removing this short-\n // circuit would break head mode against a normal clone.\n if (gitEntryType === null || gitEntryType === \"directory\") {\n return undefined;\n }\n\n const content = yield* Effect.tryPromise({\n try: () => readFile(gitEntryPath),\n catch: () => null,\n }).pipe(\n Effect.map((s) => s.trim()),\n Effect.catchAll(() => Effect.succeed(null)),\n );\n if (content === null) {\n return undefined;\n }\n return /^gitdir:\\s*(?<gitdir>.+)$/u.exec(content)?.groups?.gitdir;\n });\n\n/**\n * Writes a `.git` override file pointing at `correctedGitdir` into a fresh\n * temp dir. Returns the file and its temp dir.\n */\nexport const writeGitOverride = (\n correctedGitdir: string,\n): Effect.Effect<\n { readonly hostPath: string; readonly tempDir: string },\n WorktreeError\n> =>\n Effect.gen(function* () {\n const tempDir = yield* Effect.tryPromise({\n try: () => mkdtemp(join(tmpdir(), \"sandcastle-git-\")),\n catch: (e) =>\n new WorktreeError({\n message: `Failed to create temp dir for git override: ${e instanceof Error ? e.message : String(e)}`,\n }),\n });\n const tempGitFile = join(tempDir, \"git-override\");\n yield* Effect.tryPromise({\n try: () => writeFile(tempGitFile, `gitdir: ${correctedGitdir}\\n`),\n catch: (e) =>\n new WorktreeError({\n message: `Failed to write git override file: ${e instanceof Error ? e.message : String(e)}`,\n }),\n }).pipe(\n Effect.tapError(() =>\n removeMountTempDirs([\n { hostPath: tempGitFile, sandboxPath: \"\", tempDir },\n ]),\n ),\n );\n return { hostPath: tempGitFile, tempDir };\n });\n\n/**\n * Remaps the parent `.git` dir mount to `PARENT_GIT_SANDBOX_DIR` and puts\n * `overrideMount` in place of the worktree's `.git` file mount, or adds it\n * when there is none (a Sandcastle-created worktree).\n */\nexport const overlayGitMounts = (\n gitMounts: MountEntry[],\n paths: {\n readonly parentGitDir: string;\n readonly gitEntryPath: string;\n readonly overrideMount: MountEntry;\n },\n): MountEntry[] => {\n const normalizedParentGitDir = paths.parentGitDir.replaceAll(\"\\\\\", \"/\");\n const gitFileHostPath = paths.gitEntryPath.replaceAll(\"\\\\\", \"/\");\n\n const correctedMounts: MountEntry[] = [];\n let replacedGitFile = false;\n\n for (const m of gitMounts) {\n const normalizedHostPath = m.hostPath.replaceAll(\"\\\\\", \"/\");\n if (normalizedHostPath === normalizedParentGitDir) {\n // Remap parent .git dir to deterministic sandbox path\n correctedMounts.push({ ...m, sandboxPath: PARENT_GIT_SANDBOX_DIR });\n } else if (normalizedHostPath === gitFileHostPath) {\n // Replace .git file mount with corrected version (host repo is a worktree)\n correctedMounts.push({ ...m, ...paths.overrideMount });\n replacedGitFile = true;\n } else {\n correctedMounts.push(m);\n }\n }\n\n if (!replacedGitFile) {\n correctedMounts.push(paths.overrideMount);\n }\n\n return correctedMounts;\n};\n\n/**\n * Removes the temp dirs `patchGitMountsForWindows` created for `mounts`\n * (none off Windows). Run it once the sandbox using the mounts has closed, or\n * failed to start.\n */\nexport const removeMountTempDirs = (\n mounts: readonly MountEntry[],\n): Effect.Effect<void> =>\n Effect.forEach(\n mounts.flatMap((m) => (m.tempDir === undefined ? [] : [m.tempDir])),\n (dir) =>\n // A dir that can't be removed is left behind; nothing depends on it.\n Effect.async<NodeJS.ErrnoException | null>((resume) => {\n rmCallback(dir, { recursive: true, force: true }, (error) => {\n resume(Effect.succeed(error));\n });\n }),\n { discard: true },\n );\n","import { Effect } from \"effect\";\nimport { CopyError, ExecError } from \"./errors.js\";\nimport type {\n BindMountSandboxHandle,\n IsolatedSandboxHandle,\n NoSandboxHandle,\n} from \"./SandboxProvider.js\";\n\nexport interface ExecResult {\n readonly stdout: string;\n readonly stderr: string;\n readonly exitCode: number;\n}\n\nexport interface SandboxService {\n readonly exec: (\n command: string,\n options?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n },\n ) => Effect.Effect<ExecResult, ExecError>;\n\n /** Copy a file or directory from the host into the sandbox. */\n readonly copyIn: (\n hostPath: string,\n sandboxPath: string,\n ) => Effect.Effect<void, CopyError>;\n\n /** Copy a single file from the sandbox to the host. */\n readonly copyFileOut: (\n sandboxPath: string,\n hostPath: string,\n ) => Effect.Effect<void, CopyError>;\n}\n\nconst getCopyIn = (\n handle: BindMountSandboxHandle | IsolatedSandboxHandle | NoSandboxHandle,\n): SandboxService[\"copyIn\"] => {\n if (\"copyIn\" in handle) {\n return (hostPath, sandboxPath) =>\n Effect.tryPromise({\n try: () => handle.copyIn(hostPath, sandboxPath),\n catch: (e) =>\n new CopyError({\n message: `copyIn failed: ${e instanceof Error ? e.message : String(e)}`,\n }),\n });\n }\n if (\"copyFileIn\" in handle) {\n return (hostPath, sandboxPath) =>\n Effect.tryPromise({\n try: () => handle.copyFileIn(hostPath, sandboxPath),\n catch: (e) =>\n new CopyError({\n message: `copyFileIn failed: ${e instanceof Error ? e.message : String(e)}`,\n }),\n });\n }\n return () =>\n Effect.fail(\n new CopyError({\n message: \"copyIn is not supported for this sandbox provider\",\n }),\n );\n};\n\n/**\n * Wrap a Promise-based sandbox handle into an Effect-based SandboxService.\n * Delegates copyIn/copyFileOut to the handle when available.\n */\nexport const makeSandboxFromHandle = (\n handle: BindMountSandboxHandle | IsolatedSandboxHandle | NoSandboxHandle,\n): SandboxService => ({\n exec: (command, options) =>\n Effect.tryPromise({\n try: () => handle.exec(command, options),\n catch: (e) =>\n new ExecError({\n command,\n message: `exec failed: ${e instanceof Error ? e.message : String(e)}`,\n }),\n }),\n copyIn: getCopyIn(handle),\n copyFileOut:\n \"copyFileOut\" in handle\n ? (sandboxPath, hostPath) =>\n Effect.tryPromise({\n try: () => handle.copyFileOut(sandboxPath, hostPath),\n catch: (e) =>\n new CopyError({\n message: `copyFileOut failed: ${e instanceof Error ? e.message : String(e)}`,\n }),\n })\n : () =>\n Effect.fail(\n new CopyError({\n message: \"copyFileOut is not supported for this sandbox provider\",\n }),\n ),\n});\n\n/** The mount point inside the sandbox where the project worktree is bound. */\nexport const SANDBOX_REPO_DIR = \"/home/agent/workspace\";\n\n/** A git mount for a bind-mount sandbox. */\nexport interface MountEntry {\n readonly hostPath: string;\n readonly sandboxPath: string;\n /** Mount read-only. */\n readonly readonly?: boolean;\n /** A temp dir holding `hostPath`, removed when the sandbox closes. */\n readonly tempDir?: string;\n}\n","/**\n * Host and sandbox path resolution for mounts: tilde expansion, then\n * resolving relative paths against the host cwd or the sandbox repo dir.\n */\n\nimport { homedir } from \"node:os\";\nimport { isAbsolute, resolve } from \"node:path\";\nimport { SANDBOX_REPO_DIR } from \"./sandboxService.js\";\n\n/**\n * Expand tilde (`~`) to the given home directory (or `os.homedir()` if omitted).\n * Handles both `~/path` (POSIX) and `~\\path` (Windows).\n */\nexport const expandTilde = (p: string, homeDirPath?: string): string => {\n const home = homeDirPath ?? homedir();\n if (p === \"~\") {\n return home;\n }\n if (p.startsWith(\"~/\") || p.startsWith(\"~\\\\\")) {\n return `${home}/${p.slice(2)}`;\n }\n return p;\n};\n\n/**\n * Resolve a host path: expand tilde, then resolve relative paths from `process.cwd()`.\n */\nexport const resolveHostPath = (hostPath: string): string => {\n const expanded = expandTilde(hostPath);\n return isAbsolute(expanded) ? expanded : resolve(process.cwd(), expanded);\n};\n\n/**\n * Resolve a sandbox path: expands tilde using `sandboxHomedir`, then resolves\n * relative paths from `SANDBOX_REPO_DIR`.\n *\n * Throws if `sandboxPath` starts with `~` but `sandboxHomedir` is `undefined`.\n */\nexport const resolveSandboxPath = (\n sandboxPath: string,\n sandboxHomedir?: string,\n): string => {\n const hasTilde =\n sandboxPath === \"~\" ||\n sandboxPath.startsWith(\"~/\") ||\n sandboxPath.startsWith(\"~\\\\\");\n if (hasTilde && sandboxHomedir === undefined) {\n throw new Error(\n `sandboxPath \"${sandboxPath}\" contains a tilde but the provider has no sandboxHomedir set`,\n );\n }\n const expanded = hasTilde\n ? expandTilde(sandboxPath, sandboxHomedir)\n : sandboxPath;\n return isAbsolute(expanded) ? expanded : resolve(SANDBOX_REPO_DIR, expanded);\n};\n","/**\n * Shared mount utilities for Docker and Podman sandbox providers.\n *\n * Handles host/sandbox path resolution, tilde expansion, user mount\n * validation, image naming, and Windows path normalization.\n */\n\nimport { existsSync, statSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { Effect } from \"effect\";\nimport type { MountConfig } from \"./MountConfig.js\";\nimport type { MountEntry } from \"./sandboxService.js\";\nimport type { WorktreeError } from \"./errors.js\";\nimport {\n PARENT_GIT_SANDBOX_DIR,\n overlayGitMounts,\n parseGitdirPath,\n readWorktreeGitdir,\n writeGitOverride,\n} from \"./gitMountOverride.js\";\nimport { resolveHostPath, resolveSandboxPath } from \"./mountPaths.js\";\n\nexport {\n PARENT_GIT_SANDBOX_DIR,\n parseGitdirPath,\n removeMountTempDirs,\n} from \"./gitMountOverride.js\";\nexport {\n expandTilde,\n resolveHostPath,\n resolveSandboxPath,\n} from \"./mountPaths.js\";\n\n/**\n * SELinux volume label suffix applied to bind mounts.\n *\n * - `\"z\"` — shared label. No-op on non-SELinux systems.\n * - `\"Z\"` — private label; only this container can access the mount.\n * - `false` — disable labeling entirely.\n */\nexport type SelinuxLabel = \"z\" | \"Z\" | false;\n\n/**\n * Derive the default image name from the repo directory.\n * Returns `sandcastle:<dir-name>` where dir-name is the last path segment,\n * lowercased and sanitized for image tag rules.\n *\n * Handles both POSIX (`/`) and Windows (`\\`) path separators.\n */\nexport const defaultImageName = (repoDir: string): string => {\n const dirName =\n repoDir\n .replace(/[\\\\/]+$/u, \"\")\n .split(/[\\\\/]/u)\n .pop() ?? \"local\";\n // One dash per UTF-16 unit, as before the `u` flag, so the default image\n // name for a directory with an astral character (e.g. an emoji) is unchanged.\n const sanitized = dirName\n .toLowerCase()\n .replaceAll(/[^a-z0-9_.-]/gu, (char) => \"-\".repeat(char.length));\n return `sandcastle:${sanitized || \"local\"}`;\n};\n\n/**\n * Resolve and validate user-provided mount configurations.\n * Throws if a hostPath does not exist on the filesystem.\n * Throws if a sandboxPath uses tilde but `sandboxHomedir` is `undefined`.\n */\nexport const resolveUserMounts = (\n mounts: readonly MountConfig[],\n sandboxHomedir?: string,\n): { hostPath: string; sandboxPath: string; readonly?: boolean }[] =>\n mounts.map((m) => {\n const resolvedHostPath = resolveHostPath(m.hostPath);\n\n if (!existsSync(resolvedHostPath)) {\n throw new Error(\n `Mount hostPath does not exist: ${m.hostPath}${\n m.hostPath === resolvedHostPath\n ? \"\"\n : ` (resolved to ${resolvedHostPath})`\n }`,\n );\n }\n\n return {\n hostPath: resolvedHostPath,\n sandboxPath: resolveSandboxPath(m.sandboxPath, sandboxHomedir),\n ...(m.readonly === true ? { readonly: true } : {}),\n };\n });\n\n/**\n * Normalize mount entries for cross-platform compatibility.\n *\n * On Windows (`platform === \"win32\"`):\n * - Replaces backslashes with forward slashes in all `hostPath` values\n * - Remaps `sandboxPath` values that look like Windows paths to valid POSIX\n * paths relative to `sandboxRepoDir` when the host path is under the\n * worktree host path\n *\n * On non-Windows platforms, returns mounts unchanged (preserving\n * `sandboxPath === hostPath` for git mounts so that `gitdir:` references\n * resolve correctly inside the container).\n *\n * This is a pure function — no filesystem access, accepts a `platform`\n * parameter so it can be unit-tested with fake Windows paths.\n */\nexport const normalizeMounts = <\n M extends { hostPath: string; sandboxPath: string },\n>(\n mounts: M[],\n repo: { readonly worktreeHostPath: string; readonly sandboxRepoDir: string },\n platform: string = process.platform,\n): M[] => {\n if (platform !== \"win32\") {\n return mounts;\n }\n const { worktreeHostPath, sandboxRepoDir } = repo;\n\n const normalizedWorktree = worktreeHostPath.replaceAll(\"\\\\\", \"/\");\n\n return mounts.map((m) => {\n const hostPath = m.hostPath.replaceAll(\"\\\\\", \"/\");\n let { sandboxPath } = m;\n\n // If sandboxPath is already a valid POSIX absolute path (e.g., user-specified\n // sandbox paths like /mnt/data or /home/agent/workspace), leave it as-is.\n // Otherwise, normalize it — Windows-style sandboxPaths (from resolveGitMounts\n // setting sandboxPath === hostPath) need remapping.\n if (/^[A-Za-z]:[/\\\\]/u.test(sandboxPath) || sandboxPath.includes(\"\\\\\")) {\n // This is a Windows-style path — remap it\n const normalizedSandboxPath = sandboxPath.replaceAll(\"\\\\\", \"/\");\n\n if (normalizedSandboxPath.startsWith(`${normalizedWorktree}/`)) {\n // Under the worktree: derive sandbox path relative to sandboxRepoDir\n const relativeSuffix = normalizedSandboxPath.slice(\n normalizedWorktree.length,\n );\n sandboxPath = sandboxRepoDir + relativeSuffix;\n } else if (normalizedSandboxPath === normalizedWorktree) {\n sandboxPath = sandboxRepoDir;\n } else {\n // Not under the worktree — just normalize slashes\n sandboxPath = normalizedSandboxPath;\n }\n }\n\n return { ...m, hostPath, sandboxPath };\n });\n};\n\n/**\n * On Windows, patch git mounts so that worktree `.git` files resolve inside\n * the Linux sandbox. See ADR-0006 for the full rationale.\n *\n * Two fixes are applied:\n * 1. The parent `.git` directory mount is remapped to `PARENT_GIT_SANDBOX_DIR`.\n * 2. A corrected `.git` file (with a POSIX `gitdir:` path) is created and\n * mounted read-only at `sandboxRepoDir/.git`, overlaying the original. Its\n * temp dir is named on the mount (`tempDir`) and removed by `startSandbox`\n * when the sandbox closes.\n *\n * On non-Windows platforms, or when the worktree's `.git` is a directory\n * (not a worktree pointer), returns the mounts unchanged.\n *\n * @param gitMounts - Raw mounts from `resolveGitMounts`.\n * @param worktreeHostPath - Host path to the directory mounted at `sandboxRepoDir`.\n * @param sandboxRepoDir - Where the worktree is mounted inside the sandbox.\n * @param readFile - Read a file's content (injectable for tests).\n * @param statFile - Stat a file to check if it's a directory (injectable for tests).\n * @param platform - Override for `process.platform` (injectable for tests).\n */\nexport const patchGitMountsForWindows = (\n gitMounts: MountEntry[],\n worktreeHostPath: string,\n sandboxRepoDir: string,\n readFile?: (path: string) => Promise<string>,\n statFile?: (path: string) => Promise<\"file\" | \"directory\">,\n platform: string = process.platform,\n): Effect.Effect<MountEntry[], WorktreeError> =>\n Effect.gen(function* () {\n if (platform !== \"win32\") {\n return gitMounts;\n }\n\n const gitEntryPath = join(worktreeHostPath, \".git\");\n const gitdirPath = yield* readWorktreeGitdir(gitEntryPath, {\n readFile: readFile ?? defaultReadFile,\n statFile: statFile ?? defaultStatFile,\n });\n if (gitdirPath === undefined) {\n return gitMounts;\n }\n\n const { parentGitDir, worktreeName } = parseGitdirPath(gitdirPath);\n const override = yield* writeGitOverride(\n `${PARENT_GIT_SANDBOX_DIR}/worktrees/${worktreeName}`,\n );\n return overlayGitMounts(gitMounts, {\n parentGitDir,\n gitEntryPath,\n overrideMount: {\n ...override,\n sandboxPath: `${sandboxRepoDir}/.git`,\n readonly: true,\n },\n });\n });\n\nconst defaultReadFile = async (p: string): Promise<string> => {\n const { readFile: rf } = await import(\"node:fs/promises\");\n return rf(p, \"utf8\");\n};\n\nconst defaultStatFile = async (p: string): Promise<\"file\" | \"directory\"> => {\n const { stat } = await import(\"node:fs/promises\");\n const s = await stat(p);\n return s.isDirectory() ? (\"directory\" as const) : (\"file\" as const);\n};\n\n/**\n * Format a bind mount into a `-v` style string for container runtimes.\n *\n * Produces: `hostPath:sandboxPath[:ro][,z|Z]`\n *\n * Used by both Podman and Docker providers.\n */\nexport const formatVolumeMount = (\n mount: { hostPath: string; sandboxPath: string; readonly?: boolean },\n selinuxLabel: SelinuxLabel | undefined,\n): string => {\n const base = `${mount.hostPath}:${mount.sandboxPath}`;\n const options = [\n mount.readonly === true ? \"ro\" : undefined,\n selinuxLabel === false ? undefined : selinuxLabel,\n ]\n .filter((option): option is string => option !== undefined)\n .join(\",\");\n\n return options ? `${base}:${options}` : base;\n};\n\n/**\n * Detect file-target mounts whose sandbox-side parent directory may not\n * exist in the container image, and return the parent dirs that need to\n * be created at container start.\n *\n * Validates at config time: if a file mount's sandbox parent is outside\n * `sandboxHomedir`, throws with a clear error and remediation guidance.\n *\n * For file mounts whose parent is under `sandboxHomedir` (but not equal\n * to it — `/home/agent` always exists), returns the unique set of parent\n * directories that must be `mkdir -p` + `chown`'d before the agent runs.\n *\n * @param mounts - Resolved mounts (hostPath already validated to exist).\n * @param sandboxHomedir - The agent's home directory in the sandbox (e.g. `/home/agent`).\n * @param statFn - Injectable stat function for testing (defaults to `statSync`).\n */\nexport const processFileMountParents = (\n mounts: readonly { hostPath: string; sandboxPath: string }[],\n sandboxHomedir: string,\n statFn: (path: string) => { isFile(): boolean } = statSync,\n): string[] => {\n const parentDirs = new Set<string>();\n\n for (const mount of mounts) {\n let isFile: boolean;\n try {\n isFile = statFn(mount.hostPath).isFile();\n } catch {\n continue;\n }\n\n if (!isFile) {\n continue;\n }\n\n const parentDir = dirname(mount.sandboxPath);\n\n // Parent IS sandboxHomedir — it always exists in the image\n if (parentDir === sandboxHomedir) {\n continue;\n }\n\n // Parent is outside sandboxHomedir — fail at config time\n if (!parentDir.startsWith(`${sandboxHomedir}/`)) {\n throw new Error(\n `Cannot mount file to '${mount.sandboxPath}': ` +\n `parent directory '${parentDir}' is outside the sandbox home directory ('${sandboxHomedir}'). ` +\n `Mount the parent directory instead, or rebuild the image with '${parentDir}' pre-created.`,\n );\n }\n\n parentDirs.add(parentDir);\n }\n\n return [...parentDirs];\n};\n"]}
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import {
|
|
2
|
+
import { resolveUserMounts } from './chunk-7PHPLDVS.js';
|
|
3
|
+
import { registerShutdown } from './chunk-EXYXBRCX.js';
|
|
4
|
+
import { FileSystem_exports, CopyError } from './chunk-YDQW5IOY.js';
|
|
5
|
+
import { Effect_exports, Config_exports, Option_exports } from './chunk-JEQ4IVQM.js';
|
|
3
6
|
import { BoundedTail } from './chunk-6NQPCXSG.js';
|
|
4
7
|
import { dirname, posix } from 'path';
|
|
5
8
|
import { createInterface } from 'readline';
|
|
9
|
+
import { rmSync } from 'fs';
|
|
6
10
|
import { homedir } from 'os';
|
|
7
11
|
|
|
8
12
|
createRequire(import.meta.url);
|
|
@@ -36,6 +40,13 @@ var copyCreatingParents = (from, to) => Effect_exports.gen(function* () {
|
|
|
36
40
|
})
|
|
37
41
|
)
|
|
38
42
|
);
|
|
43
|
+
var registerNativeSandboxShutdown = (killAll, dirs) => registerShutdown(() => {
|
|
44
|
+
killAll();
|
|
45
|
+
try {
|
|
46
|
+
rmSync(dirs.root, { recursive: true, force: true });
|
|
47
|
+
} catch {
|
|
48
|
+
}
|
|
49
|
+
});
|
|
39
50
|
var isWithin = (path, root) => root === "/" || path === root || path.startsWith(`${root}/`);
|
|
40
51
|
var isWithinAny = (path, roots) => roots.some((root) => isWithin(path, root));
|
|
41
52
|
var isHomeOrAncestor = (path, home) => isWithin(home, path);
|
|
@@ -143,6 +154,6 @@ var resolveIdentityMounts = (provider, mounts, sandboxHomedir) => resolveUserMou
|
|
|
143
154
|
};
|
|
144
155
|
});
|
|
145
156
|
|
|
146
|
-
export { collectOutput, copyCreatingParents, hostPathToolchainFromEnv, resolveIdentityMounts };
|
|
147
|
-
//# sourceMappingURL=chunk-
|
|
148
|
-
//# sourceMappingURL=chunk-
|
|
157
|
+
export { collectOutput, copyCreatingParents, hostPathToolchainFromEnv, registerNativeSandboxShutdown, resolveIdentityMounts };
|
|
158
|
+
//# sourceMappingURL=chunk-BXLS4HRY.js.map
|
|
159
|
+
//# sourceMappingURL=chunk-BXLS4HRY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
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AAAA,MACR,GAAG,QAAQ,CAAA,sFAAA,EACO,KAAA,EAAO,QAAA,IAAY,SAAS,QAAQ,CAAA,cAAA,EAAiB,QAAA,CAAS,QAAQ,qBACnE,KAAA,EAAO,WAAA,IAAe,SAAS,WAAW,CAAA,cAAA,EAAiB,SAAS,WAAW,CAAA,EAAA;AAAA,KACtG;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,UAAU,QAAA,CAAS,QAAA;AAAA,IACnB,QAAA,EAAU,SAAS,QAAA,KAAa;AAAA,GAClC;AACF,CAAC","file":"chunk-BXLS4HRY.js","sourcesContent":["/**\n * Provider-agnostic helpers for the native sandbox providers (`bwrap()`,\n * `seatbelt()`): collecting a child process's output, and copying a file\n * between host paths. Each is purely a function of its inputs.\n */\n\nimport type { ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\nimport { BoundedTail } from \"./boundedTail.js\";\nimport { CopyError } from \"./errors.js\";\n\n/** Collects a child's output: streamed line by line with a bounded tail, or whole. */\nexport const collectOutput = (\n proc: ChildProcessWithoutNullStreams,\n onLine: ((line: string) => void) | undefined,\n maxTailChars: number,\n): (() => { stdout: string; stderr: string }) => {\n const streaming = onLine !== undefined;\n const stdout = streaming\n ? new BoundedTail(maxTailChars, \"\\n\")\n : new BoundedTail(Infinity);\n const stderr = new BoundedTail(streaming ? maxTailChars : Infinity);\n if (onLine === undefined) {\n proc.stdout.on(\"data\", (chunk: Buffer) => {\n stdout.push(chunk.toString());\n });\n } else {\n createInterface({ input: proc.stdout }).on(\"line\", (line) => {\n stdout.push(line);\n onLine(line);\n });\n }\n proc.stderr.on(\"data\", (chunk: Buffer) => {\n stderr.push(chunk.toString());\n });\n return () => ({ stdout: stdout.toString(), stderr: stderr.toString() });\n};\n\n/** Copies a file, creating the target's parent dirs. */\nexport const copyCreatingParents = (\n from: string,\n to: string,\n): Effect.Effect<void, CopyError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs.makeDirectory(dirname(to), { recursive: true });\n yield* fs.copyFile(from, to);\n }).pipe(\n Effect.mapError(\n (e) =>\n new CopyError({\n message: `Couldn't copy ${from} to ${to}: ${e.message}`,\n }),\n ),\n );\n","/**\n * A native sandbox's shutdown teardown (src/shutdownRegistry.ts). On\n * SIGINT/SIGTERM nothing calls `close()`, and the registry exits as soon as\n * its teardowns return, so the private dirs are removed synchronously: async\n * removal would never finish.\n */\n\n/* oxlint-disable node/no-sync -- a shutdown teardown is synchronous (allowlisted in scripts/lint-ratchet-config.ts). */\n\nimport { rmSync } from \"node:fs\";\nimport { registerShutdown } from \"./shutdownRegistry.js\";\n\n/**\n * Registers the teardown that runs if the process is interrupted or exits\n * before the sandbox is closed: `killAll`, then removing the private dirs\n * under `dirs.root`, best-effort.\n *\n * @returns An idempotent function that unregisters the teardown.\n */\nexport const registerNativeSandboxShutdown = (\n killAll: () => void,\n dirs: { readonly root: string },\n): (() => void) =>\n registerShutdown(() => {\n killAll();\n try {\n rmSync(dirs.root, { recursive: true, force: true });\n } catch {\n // Best-effort: the process is exiting either way.\n }\n });\n","/**\n * Resolves the host toolchain a native sandbox provider should make readable,\n * from the host `PATH`: every `PATH` dir, plus the install root of each\n * executable symlinked from those dirs (an nvm-installed `codex`, a `claude`\n * symlinked into `~/.local/bin`). A dir equal to the home dir or an ancestor\n * of it is refused, so the toolchain never exposes the whole home, and an\n * install root that holds a `.git` is refused, so it never exposes a repo.\n *\n * Provider-agnostic: it takes paths and returns paths. Shared by the native\n * sandbox providers.\n */\n\nimport { homedir } from \"node:os\";\nimport { posix } from \"node:path\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Config, Effect, Option } from \"effect\";\n\n/** What to resolve the toolchain from. */\nexport interface HostPathToolchainInput {\n /** The host `PATH`. */\n readonly path: string;\n /** The host home dir: it and its ancestors are never made readable. */\n readonly home: string;\n /** Dirs the sandbox already shows: nothing inside them is returned to mount. */\n readonly coveredRoots: readonly string[];\n /** Dirs that must stay hidden: `PATH` dirs and install roots inside them are refused. */\n readonly deniedRoots: readonly string[];\n}\n\n/** The toolchain a sandbox needs, all at host paths. */\nexport interface HostPathToolchain {\n /** The `PATH` for the sandboxed child: the host `PATH` dirs it can see, in order. */\n readonly pathEntries: readonly string[];\n /** Real dirs to make readable at their own paths. */\n readonly readableDirs: readonly string[];\n /** `PATH` dirs that are symlinks on the host, to recreate pointing at their real dir. */\n readonly symlinks: readonly {\n readonly path: string;\n readonly target: string;\n }[];\n}\n\nconst isWithin = (path: string, root: string): boolean =>\n root === \"/\" || path === root || path.startsWith(`${root}/`);\n\nconst isWithinAny = (path: string, roots: readonly string[]): boolean =>\n roots.some((root) => isWithin(path, root));\n\n/** True for the home dir itself and every ancestor of it, `/` included. */\nconst isHomeOrAncestor = (path: string, home: string): boolean =>\n isWithin(home, path);\n\nconst normalizeEntry = (entry: string): string => {\n const normalized = posix.normalize(entry);\n return normalized.length > 1 && normalized.endsWith(\"/\")\n ? normalized.slice(0, -1)\n : normalized;\n};\n\nconst realPathOf = (\n fs: FileSystem.FileSystem,\n path: string,\n): Effect.Effect<Option.Option<string>> => Effect.option(fs.realPath(path));\n\n/** True when `dir` sits inside a `node_modules` tree. */\nconst isInNodeModules = (dir: string): boolean =>\n dir.split(\"/\").includes(\"node_modules\");\n\n/**\n * The install root of an executable's real file: the nearest ancestor holding\n * a `package.json` inside a `node_modules` tree (a globally installed Node\n * package's bin pulls in its own files), else the file's dir. A `package.json`\n * outside `node_modules` (an `npm link`ed checkout, a stray one above a\n * projects dir) is not an install root: mounting it would expose a project.\n * The search stops below the home dir.\n */\nconst installRootOf = (\n fs: FileSystem.FileSystem,\n file: string,\n home: string,\n): Effect.Effect<string> =>\n Effect.gen(function* () {\n const fileDir = posix.dirname(file);\n let dir = fileDir;\n while (isInNodeModules(dir) && !isHomeOrAncestor(dir, home)) {\n const hasPackageJson = yield* fs\n .exists(posix.join(dir, \"package.json\"))\n .pipe(Effect.orElseSucceed(() => false));\n if (hasPackageJson) {\n return dir;\n }\n dir = posix.dirname(dir);\n }\n return fileDir;\n });\n\n/** True when `dir` holds a `.git`: a repo's checkout is never an install root. */\nconst isRepoRoot = (\n fs: FileSystem.FileSystem,\n dir: string,\n): Effect.Effect<boolean> =>\n fs.exists(posix.join(dir, \".git\")).pipe(Effect.orElseSucceed(() => false));\n\n/** The real files behind the symlinks directly inside `dir`. */\nconst symlinkTargetsIn = (\n fs: FileSystem.FileSystem,\n dir: string,\n): Effect.Effect<string[]> =>\n Effect.gen(function* () {\n const names = yield* fs\n .readDirectory(dir)\n .pipe(Effect.orElseSucceed((): string[] => []));\n const targets = yield* Effect.forEach(\n names,\n (name) =>\n Effect.gen(function* () {\n const entry = posix.join(dir, name);\n const link = yield* Effect.option(fs.readLink(entry));\n return Option.isSome(link)\n ? yield* realPathOf(fs, entry)\n : Option.none<string>();\n }),\n { concurrency: 32 },\n );\n return targets.flatMap((t) => (Option.isSome(t) ? [t.value] : []));\n });\n\n/** The rules every resolved path is held to. */\ninterface Rules {\n readonly home: string;\n readonly coveredRoots: readonly string[];\n readonly deniedRoots: readonly string[];\n}\n\nconst isRefused = (path: string, rules: Rules): boolean =>\n isHomeOrAncestor(path, rules.home) || isWithinAny(path, rules.deniedRoots);\n\n/** A `PATH` entry the sandbox may see, and the real dir behind it. */\ninterface AcceptedEntry {\n readonly entry: string;\n readonly real: string;\n}\n\n/** Accepts a `PATH` entry that exists and isn't refused, by itself or by its real dir. */\nconst acceptEntry = (\n fs: FileSystem.FileSystem,\n entry: string,\n rules: Rules,\n): Effect.Effect<Option.Option<AcceptedEntry>> =>\n isRefused(entry, rules)\n ? Effect.succeed(Option.none())\n : realPathOf(fs, entry).pipe(\n Effect.map(Option.filter((real) => !isRefused(real, rules))),\n Effect.map(Option.map((real) => ({ entry, real }))),\n );\n\n/** The install roots of the executables symlinked from `dir` to outside it. */\nconst installRootsIn = (\n fs: FileSystem.FileSystem,\n dir: string,\n rules: Rules,\n): Effect.Effect<string[]> =>\n Effect.gen(function* () {\n const targets = (yield* symlinkTargetsIn(fs, dir)).filter(\n (target) =>\n !isWithin(target, dir) && !isWithinAny(target, rules.coveredRoots),\n );\n const roots = yield* Effect.all(\n targets.map((target) => installRootOf(fs, target, rules.home)),\n );\n return yield* Effect.filter(\n roots.filter((root) => !isRefused(root, rules)),\n (root) => Effect.map(isRepoRoot(fs, root), (isRepo) => !isRepo),\n );\n });\n\n/** Keeps only the dirs not inside another dir of the list. */\nconst outermost = (dirs: readonly string[]): string[] => {\n const unique = [...new Set(dirs)];\n return unique.filter(\n (dir) => !unique.some((other) => other !== dir && isWithin(dir, other)),\n );\n};\n\n/** Resolves the toolchain a sandbox needs from the host `PATH`. */\nexport const resolveHostPathToolchain = (\n input: HostPathToolchainInput,\n): Effect.Effect<HostPathToolchain, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const rules: Rules = { ...input, home: normalizeEntry(input.home) };\n const entries = [\n ...new Set(\n input.path\n .split(\":\")\n .filter((entry) => entry.startsWith(\"/\"))\n .map((entry) => normalizeEntry(entry)),\n ),\n ];\n const accepted = (yield* Effect.all(\n entries.map((entry) => acceptEntry(fs, entry, rules)),\n )).flatMap((a) => (Option.isSome(a) ? [a.value] : []));\n const uncovered = accepted.filter(\n (a) => !isWithinAny(a.real, rules.coveredRoots),\n );\n const installRoots = yield* Effect.all(\n [...new Set(accepted.map((a) => a.real))].map((dir) =>\n installRootsIn(fs, dir, rules),\n ),\n );\n return {\n pathEntries: accepted.map((a) => a.entry),\n readableDirs: outermost([\n ...uncovered.map((a) => a.real),\n ...installRoots.flat(),\n ]),\n symlinks: uncovered\n .filter(\n (a) =>\n a.real !== a.entry && !isWithinAny(a.entry, rules.coveredRoots),\n )\n .map((a) => ({ path: a.entry, target: a.real })),\n };\n });\n\n/**\n * {@link resolveHostPathToolchain} for this process: the host `PATH` and home\n * dir come from the environment.\n */\nexport const hostPathToolchainFromEnv = (roots: {\n readonly coveredRoots: readonly string[];\n readonly deniedRoots: readonly string[];\n}): Effect.Effect<HostPathToolchain, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const path = yield* Config.string(\"PATH\").pipe(Config.withDefault(\"\"));\n return yield* resolveHostPathToolchain({ path, home: homedir(), ...roots });\n }).pipe(Effect.orDie);\n","/**\n * Identity mounts: the `mounts` option of the native sandbox providers, where\n * every path appears inside the sandbox at its own host path. Provider-agnostic:\n * shared by the native sandbox providers.\n */\n\nimport type { MountConfig } from \"./MountConfig.js\";\nimport { resolveUserMounts } from \"./mountUtils.js\";\n\nexport type { MountConfig } from \"./MountConfig.js\";\n\n/** A resolved mount that appears at its own host path. */\nexport interface IdentityMount {\n readonly hostPath: string;\n readonly readonly: boolean;\n}\n\n/**\n * Resolves `mounts` (tilde and relative paths, as for every provider) and\n * checks each appears at its own host path. Throws, naming `provider`, when a\n * resolved `sandboxPath` differs from its resolved `hostPath`, or when a\n * `hostPath` doesn't exist.\n */\nexport const resolveIdentityMounts = (\n provider: string,\n mounts: readonly MountConfig[],\n sandboxHomedir: string,\n): IdentityMount[] =>\n resolveUserMounts(mounts, sandboxHomedir).map((resolved, i) => {\n if (resolved.sandboxPath !== resolved.hostPath) {\n const given = mounts[i];\n throw new Error(\n `${provider}() mounts appear at their host path, so sandboxPath must equal hostPath: ` +\n `got hostPath ${given?.hostPath ?? resolved.hostPath} (resolved to ${resolved.hostPath}) ` +\n `and sandboxPath ${given?.sandboxPath ?? resolved.sandboxPath} (resolved to ${resolved.sandboxPath}).`,\n );\n }\n return {\n hostPath: resolved.hostPath,\n readonly: resolved.readonly === true,\n };\n });\n"]}
|