@banzhe/dsh-devcontainer 0.0.0-stage → 0.2.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/README.md +79 -2
- package/README.zh-CN.md +80 -0
- package/cordis.patch.yml +71 -0
- package/lib/client.js +789 -0
- package/lib/client.js.map +1 -0
- package/lib/exec-CKAAz2zz.js +241 -0
- package/lib/exec-CKAAz2zz.js.map +1 -0
- package/lib/exec-_8g5fdSx.d.ts +26 -0
- package/lib/exec-_8g5fdSx.d.ts.map +1 -0
- package/lib/fs.d.ts +530 -0
- package/lib/fs.d.ts.map +1 -0
- package/lib/fs.js +1737 -0
- package/lib/fs.js.map +1 -0
- package/lib/helper/main.mjs +1008 -0
- package/lib/index.d.ts +88 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +927 -0
- package/lib/index.js.map +1 -0
- package/lib/sbx-1GsFjQBk.js +1489 -0
- package/lib/sbx-1GsFjQBk.js.map +1 -0
- package/lib/shell.d.ts +175 -0
- package/lib/shell.d.ts.map +1 -0
- package/lib/shell.js +454 -0
- package/lib/shell.js.map +1 -0
- package/lib/types-DsF9Hz5P.d.ts +33 -0
- package/lib/types-DsF9Hz5P.d.ts.map +1 -0
- package/package.json +116 -3
|
@@ -0,0 +1,1489 @@
|
|
|
1
|
+
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
import { posix, win32 } from "node:path";
|
|
3
|
+
import { DSH_ENV_PREFIX } from "@deepseek-ai/dsh-shell";
|
|
4
|
+
import { readFileSync, statSync } from "node:fs";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
//#region src/options.ts
|
|
7
|
+
/**
|
|
8
|
+
* The configuration fields every row of this Bundle shares. The three rows are
|
|
9
|
+
* separate Cordis plugins (one service each), and a repository's own file may
|
|
10
|
+
* override each of these per repository — the row's value is only the default
|
|
11
|
+
* discovery applies.
|
|
12
|
+
* @module @banzhe/dsh-devcontainer/options
|
|
13
|
+
*/
|
|
14
|
+
/** Defaults for {@link ContainerOptions}. */
|
|
15
|
+
const CONTAINER_OPTION_DEFAULTS = {
|
|
16
|
+
shell: "/bin/bash",
|
|
17
|
+
cli: "auto",
|
|
18
|
+
ensureUp: true,
|
|
19
|
+
containerTimeoutMs: 3e5,
|
|
20
|
+
requireContainer: false
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Apply {@link CONTAINER_OPTION_DEFAULTS} to a possibly-partial configuration, so
|
|
24
|
+
* a programmatic `apply()` behaves like a Loader row whose schema already filled
|
|
25
|
+
* the defaults in.
|
|
26
|
+
* @param config - the row's configuration, or nothing.
|
|
27
|
+
* @returns the complete container options.
|
|
28
|
+
*/
|
|
29
|
+
function containerOptions(config = {}) {
|
|
30
|
+
return {
|
|
31
|
+
shell: config.shell ?? CONTAINER_OPTION_DEFAULTS.shell,
|
|
32
|
+
cli: config.cli ?? CONTAINER_OPTION_DEFAULTS.cli,
|
|
33
|
+
ensureUp: config.ensureUp ?? CONTAINER_OPTION_DEFAULTS.ensureUp,
|
|
34
|
+
containerTimeoutMs: config.containerTimeoutMs ?? CONTAINER_OPTION_DEFAULTS.containerTimeoutMs,
|
|
35
|
+
requireContainer: config.requireContainer ?? CONTAINER_OPTION_DEFAULTS.requireContainer
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The shared Schemastery fields, spread into each row's `Config` so the three
|
|
40
|
+
* rows cannot drift apart. `cli` is `auto`: an explicit container wins, the
|
|
41
|
+
* running-container label lookup comes next, and the Dev Container CLI is the
|
|
42
|
+
* fallback that can start the container. `sbx` selects the Docker Sandbox
|
|
43
|
+
* driver, which mounts the host workspace instead of reading a declaration.
|
|
44
|
+
* @returns schemastery fields for {@link ContainerOptions}.
|
|
45
|
+
*/
|
|
46
|
+
function containerOptionFields() {
|
|
47
|
+
return {
|
|
48
|
+
shell: z.string().default(CONTAINER_OPTION_DEFAULTS.shell),
|
|
49
|
+
cli: z.union([
|
|
50
|
+
"auto",
|
|
51
|
+
"devcontainer",
|
|
52
|
+
"docker",
|
|
53
|
+
"sbx"
|
|
54
|
+
]).default(CONTAINER_OPTION_DEFAULTS.cli),
|
|
55
|
+
ensureUp: z.boolean().default(CONTAINER_OPTION_DEFAULTS.ensureUp),
|
|
56
|
+
containerTimeoutMs: z.number().default(CONTAINER_OPTION_DEFAULTS.containerTimeoutMs),
|
|
57
|
+
requireContainer: z.boolean().default(CONTAINER_OPTION_DEFAULTS.requireContainer)
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The two preset-source fields as the Loader validates them.
|
|
62
|
+
*
|
|
63
|
+
* They are `volatile`, so a settings write lands in the live reference the Host
|
|
64
|
+
* row reads on its next sync instead of needing a reload, and they are defaults
|
|
65
|
+
* of the Host row only: the shell and filesystem rows have no preset set.
|
|
66
|
+
* @returns schemastery fields for {@link PresetSourceOptions}.
|
|
67
|
+
*/
|
|
68
|
+
function presetSourceFields() {
|
|
69
|
+
return {
|
|
70
|
+
sources: z.array(z.string()).default([]).volatile(),
|
|
71
|
+
sbxSources: z.array(z.string()).default([]).volatile()
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
//#endregion
|
|
75
|
+
//#region src/paths.ts
|
|
76
|
+
/**
|
|
77
|
+
* Two-way translation between the host workspace path a session carries and the
|
|
78
|
+
* POSIX path the same directory has inside the container.
|
|
79
|
+
*
|
|
80
|
+
* The model writes container paths (`/workspaces/repo/src`), and on Windows it
|
|
81
|
+
* sometimes writes them after something win32 resolved the leading slash into a
|
|
82
|
+
* drive (`F:\\workspaces\\repo\\src`); the host hands over native paths with
|
|
83
|
+
* either separator style. Every function here is pure and idempotent: a value it
|
|
84
|
+
* cannot attribute to the repository comes back unchanged.
|
|
85
|
+
* @module @banzhe/dsh-devcontainer/paths
|
|
86
|
+
*/
|
|
87
|
+
const DRIVE_PREFIX = /^[A-Za-z]:[\\/]/;
|
|
88
|
+
const UNC_PREFIX = /^\\\\/;
|
|
89
|
+
/**
|
|
90
|
+
* Whether a path is written in Windows form (drive letter or UNC share).
|
|
91
|
+
* @param path - the path to classify.
|
|
92
|
+
* @returns true for `F:\\x`, `f:/x`, and `\\\\server\\share`.
|
|
93
|
+
*/
|
|
94
|
+
function isWindowsPath(path) {
|
|
95
|
+
return DRIVE_PREFIX.test(path) || UNC_PREFIX.test(path);
|
|
96
|
+
}
|
|
97
|
+
/** Replace every backslash with a forward slash. */
|
|
98
|
+
function toPosixSlashes(path) {
|
|
99
|
+
return path.replaceAll("\\", "/");
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Whether a path is a POSIX-absolute path rather than a host path. A bare
|
|
103
|
+
* `/workspaces/x` is what the model writes; the win32 module also calls it
|
|
104
|
+
* absolute, so callers must consult the container mount point first.
|
|
105
|
+
* @param path - the path to classify.
|
|
106
|
+
* @returns true when the path starts at the POSIX root.
|
|
107
|
+
*/
|
|
108
|
+
function isPosixAbsolute(path) {
|
|
109
|
+
return path.startsWith("/") && !isWindowsPath(path);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Which path module owns this host root.
|
|
113
|
+
* @param hostRoot - an absolute host directory.
|
|
114
|
+
* @returns `'win32'` for a drive/UNC root, `'posix'` otherwise.
|
|
115
|
+
*/
|
|
116
|
+
function hostPathStyle(hostRoot) {
|
|
117
|
+
return isWindowsPath(hostRoot) ? "win32" : "posix";
|
|
118
|
+
}
|
|
119
|
+
/** Normalize a host root into its native absolute spelling. */
|
|
120
|
+
function normalizeHostRoot(hostRoot) {
|
|
121
|
+
return hostPathStyle(hostRoot) === "win32" ? win32.resolve(hostRoot) : posix.resolve(hostRoot);
|
|
122
|
+
}
|
|
123
|
+
/** Join a POSIX relative path onto a host root using that root's separator style. */
|
|
124
|
+
function joinHostRoot(hostRoot, relative) {
|
|
125
|
+
return hostPathStyle(hostRoot) === "win32" ? win32.join(hostRoot, toPosixSlashes(relative)) : posix.join(hostRoot, relative);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The mount point the Dev Container specification uses when the configuration
|
|
129
|
+
* omits `workspaceFolder`: `/workspaces/<basename of the repository root>`.
|
|
130
|
+
* @param hostRoot - the absolute host repository root.
|
|
131
|
+
* @returns the POSIX mount point.
|
|
132
|
+
*/
|
|
133
|
+
function defaultContainerWorkspaceFolder(hostRoot) {
|
|
134
|
+
const base = hostPathStyle(hostRoot) === "win32" ? win32.basename(hostRoot) : posix.basename(hostRoot);
|
|
135
|
+
return posix.join("/workspaces", base === "" ? "workspace" : base);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Match a path against a container mount point.
|
|
139
|
+
* @param path - candidate path, in either separator style.
|
|
140
|
+
* @param folder - the container mount point.
|
|
141
|
+
* @returns the POSIX remainder (`''` for the mount point itself), or undefined when the path is elsewhere.
|
|
142
|
+
*/
|
|
143
|
+
function containerRemainder(path, folder) {
|
|
144
|
+
const normalized = posix.normalize(toPosixSlashes(path));
|
|
145
|
+
const root = posix.normalize(toPosixSlashes(folder));
|
|
146
|
+
if (normalized === root) return "";
|
|
147
|
+
const prefix = root.endsWith("/") ? root : `${root}/`;
|
|
148
|
+
return normalized.startsWith(prefix) ? normalized.slice(prefix.length) : void 0;
|
|
149
|
+
}
|
|
150
|
+
/** The spellings a model-supplied container path may have degraded into. */
|
|
151
|
+
function containerCandidates(path) {
|
|
152
|
+
const candidates = [toPosixSlashes(path)];
|
|
153
|
+
if (DRIVE_PREFIX.test(path)) candidates.push(toPosixSlashes(path).slice(2));
|
|
154
|
+
return candidates;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Whether the path names something inside the repository's container mount.
|
|
158
|
+
* @param path - candidate path, in either separator style.
|
|
159
|
+
* @param spec - the repository container specification.
|
|
160
|
+
* @returns true when the path is the mount point or lies under it.
|
|
161
|
+
*/
|
|
162
|
+
function isPathInsideContainer(path, spec) {
|
|
163
|
+
return containerCandidates(path).some((candidate) => containerRemainder(candidate, spec.containerWorkspaceFolder) !== void 0);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The POSIX relative path from a host root, or undefined when the path escapes it.
|
|
167
|
+
* Comparison folds case on win32 (drive letters and Windows paths are
|
|
168
|
+
* case-insensitive) and preserves it elsewhere.
|
|
169
|
+
* @param path - candidate host path.
|
|
170
|
+
* @param hostRoot - the absolute host repository root.
|
|
171
|
+
* @returns the relative path (`''` for the root itself), or undefined when it is outside.
|
|
172
|
+
*/
|
|
173
|
+
function relativeWithinHostRoot(path, hostRoot) {
|
|
174
|
+
const style = hostPathStyle(hostRoot);
|
|
175
|
+
const module = style === "win32" ? win32 : posix;
|
|
176
|
+
const absolutePath = toPosixSlashes(module.resolve(path));
|
|
177
|
+
const absoluteRoot = toPosixSlashes(module.resolve(hostRoot));
|
|
178
|
+
const folder = (value) => style === "win32" ? value.toLowerCase() : value;
|
|
179
|
+
const foldedPath = folder(absolutePath);
|
|
180
|
+
const foldedRoot = folder(absoluteRoot);
|
|
181
|
+
if (foldedPath === foldedRoot) return "";
|
|
182
|
+
const prefix = foldedRoot.endsWith("/") ? foldedRoot : `${foldedRoot}/`;
|
|
183
|
+
if (!foldedPath.startsWith(prefix)) return void 0;
|
|
184
|
+
return absolutePath.slice(prefix.length);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Join a relative path onto a mount point, in that mount's own style.
|
|
188
|
+
*
|
|
189
|
+
* A Dev Container mount is POSIX, so this is `posix.join` for every container.
|
|
190
|
+
* A Docker Sandbox mounts the host directory under its own absolute path, so its
|
|
191
|
+
* mount point can be a Windows path, and joining it as POSIX would produce the
|
|
192
|
+
* mixed `F:\\repo/src` spelling no shell on either side accepts.
|
|
193
|
+
* @param folder - the mount point.
|
|
194
|
+
* @param relative - the relative path inside it.
|
|
195
|
+
* @returns the joined path, using the mount point's separator style.
|
|
196
|
+
*/
|
|
197
|
+
function joinMount(folder, relative) {
|
|
198
|
+
return isWindowsPath(folder) ? joinHostRoot(folder, relative) : posix.join(folder, toPosixSlashes(relative));
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Translate one model/plugin-supplied path into the container's POSIX view.
|
|
202
|
+
* @param path - a host path, a mixed-separator host path, an already-container
|
|
203
|
+
* path, or a path relative to the mount point.
|
|
204
|
+
* @param spec - the repository container specification.
|
|
205
|
+
* @returns the POSIX container path; a path outside the repository comes back slash-normalized.
|
|
206
|
+
*/
|
|
207
|
+
function toContainerPath(path, spec) {
|
|
208
|
+
const folder = spec.containerWorkspaceFolder;
|
|
209
|
+
if (path === "") return folder;
|
|
210
|
+
for (const candidate of containerCandidates(path)) {
|
|
211
|
+
const remainder = containerRemainder(candidate, folder);
|
|
212
|
+
if (remainder !== void 0) return remainder === "" ? folder : joinMount(folder, remainder);
|
|
213
|
+
}
|
|
214
|
+
if (!isWindowsPath(path) && !path.startsWith("/")) {
|
|
215
|
+
const normalized = posix.normalize(toPosixSlashes(path));
|
|
216
|
+
if (normalized === ".." || normalized.startsWith("../")) return path;
|
|
217
|
+
return normalized === "." ? folder : joinMount(folder, normalized);
|
|
218
|
+
}
|
|
219
|
+
const relative = relativeWithinHostRoot(path, spec.hostWorkspaceRoot);
|
|
220
|
+
if (relative === void 0) return toPosixSlashes(path);
|
|
221
|
+
return relative === "" ? folder : joinMount(folder, relative);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Translate one container path back into the host path of the bind mount.
|
|
225
|
+
* @param path - a container path, a drive-mangled container path, a host path, or a relative path.
|
|
226
|
+
* @param spec - the repository container specification.
|
|
227
|
+
* @returns the native host path inside the repository, or `path` unchanged when it is not container-side.
|
|
228
|
+
*/
|
|
229
|
+
function toHostPath(path, spec) {
|
|
230
|
+
for (const candidate of containerCandidates(path)) {
|
|
231
|
+
const remainder = containerRemainder(candidate, spec.containerWorkspaceFolder);
|
|
232
|
+
if (remainder === void 0) continue;
|
|
233
|
+
return remainder === "" ? normalizeHostRoot(spec.hostWorkspaceRoot) : joinHostRoot(spec.hostWorkspaceRoot, remainder);
|
|
234
|
+
}
|
|
235
|
+
return path;
|
|
236
|
+
}
|
|
237
|
+
//#endregion
|
|
238
|
+
//#region src/ids.ts
|
|
239
|
+
/**
|
|
240
|
+
* The suffixes and display labels that mark a derived preset, shared by both
|
|
241
|
+
* halves of the Bundle.
|
|
242
|
+
*
|
|
243
|
+
* Two independent tracks exist: a `… (devContainer)` variant for repositories
|
|
244
|
+
* that declare a Dev Container, and a `… (sbx)` variant for Docker Sandbox
|
|
245
|
+
* (`sbx`) sessions. They differ only in the suffix, the label, and the
|
|
246
|
+
* `DSH_*` marker the shell row injects; everything else about a derived preset
|
|
247
|
+
* is identical, so one module owns the naming for both.
|
|
248
|
+
*
|
|
249
|
+
* The browser half needs these to keep derived presets out of its own picker
|
|
250
|
+
* list, and must not import the Host modules to get them: this file has no
|
|
251
|
+
* imports.
|
|
252
|
+
*/
|
|
253
|
+
/** Appended to a source preset id to name its Dev Container variant. */
|
|
254
|
+
const DEVCONTAINER_VARIANT_SUFFIX = "-devcontainer";
|
|
255
|
+
/** Appended to a source preset id to name its Docker Sandbox variant. */
|
|
256
|
+
const SBX_VARIANT_SUFFIX = "-sbx";
|
|
257
|
+
/** Appended to a source preset's display name for the Dev Container variant. */
|
|
258
|
+
const DEVCONTAINER_NAME_SUFFIX = " (devContainer)";
|
|
259
|
+
/** Appended to a source preset's display name for the Docker Sandbox variant. */
|
|
260
|
+
const SBX_NAME_SUFFIX = " (sbx)";
|
|
261
|
+
/** Every kind, in the order the planner emits them. */
|
|
262
|
+
const VARIANT_KINDS = ["devcontainer", "sbx"];
|
|
263
|
+
/**
|
|
264
|
+
* The id suffix of one track.
|
|
265
|
+
* @param kind - the track.
|
|
266
|
+
* @returns `-devcontainer` or `-sbx`.
|
|
267
|
+
*/
|
|
268
|
+
function variantSuffixOf(kind) {
|
|
269
|
+
return kind === "sbx" ? SBX_VARIANT_SUFFIX : DEVCONTAINER_VARIANT_SUFFIX;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The display-name suffix of one track.
|
|
273
|
+
* @param kind - the track.
|
|
274
|
+
* @returns ` (devContainer)` or ` (sbx)`.
|
|
275
|
+
*/
|
|
276
|
+
function variantNameSuffixOf(kind) {
|
|
277
|
+
return kind === "sbx" ? SBX_NAME_SUFFIX : DEVCONTAINER_NAME_SUFFIX;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* The derived id of one source preset on one track.
|
|
281
|
+
* @param source - the source preset id.
|
|
282
|
+
* @param kind - the track the variant belongs to.
|
|
283
|
+
* @returns the variant id.
|
|
284
|
+
*/
|
|
285
|
+
function variantIdOf(source, kind) {
|
|
286
|
+
return `${source}${variantSuffixOf(kind)}`;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* The track one variant id belongs to.
|
|
290
|
+
* @param id - any preset id.
|
|
291
|
+
* @returns the track, or undefined when the id names no derived preset.
|
|
292
|
+
*/
|
|
293
|
+
function variantKindOf(id) {
|
|
294
|
+
if (id.endsWith("-devcontainer")) return "devcontainer";
|
|
295
|
+
if (id.endsWith("-sbx")) return "sbx";
|
|
296
|
+
}
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/refusal.ts
|
|
299
|
+
/** The managed `DSH_*` variable that marks a command issued from a derived preset. */
|
|
300
|
+
const DEVCONTAINER_ENV_KEY = `${DSH_ENV_PREFIX}DEVCONTAINER`;
|
|
301
|
+
/** The preset id that set the marker, so a refusal can name it. */
|
|
302
|
+
const DEVCONTAINER_PRESET_ENV_KEY = `${DSH_ENV_PREFIX}DEVCONTAINER_PRESET`;
|
|
303
|
+
/** The managed `DSH_*` variable that marks a command issued from a `(sbx)` preset. */
|
|
304
|
+
const SBX_ENV_KEY = `${DSH_ENV_PREFIX}SBX`;
|
|
305
|
+
/** The preset id that set the sandbox marker, so a diagnostic can name it. */
|
|
306
|
+
const SBX_PRESET_ENV_KEY = `${DSH_ENV_PREFIX}SBX_PRESET`;
|
|
307
|
+
/** Every scheduling marker this Bundle owns; none of them is forwarded into a runtime. */
|
|
308
|
+
const CONTAINER_MARKER_KEYS = [
|
|
309
|
+
DEVCONTAINER_ENV_KEY,
|
|
310
|
+
DEVCONTAINER_PRESET_ENV_KEY,
|
|
311
|
+
SBX_ENV_KEY,
|
|
312
|
+
SBX_PRESET_ENV_KEY
|
|
313
|
+
];
|
|
314
|
+
/**
|
|
315
|
+
* The derived preset an agent runs under, on either track.
|
|
316
|
+
* @param presets - the Host preset registry, when the composition supplies one.
|
|
317
|
+
* @param session - the calling agent's session, when the call has one.
|
|
318
|
+
* @returns the derived preset id, or undefined for an ordinary preset or no lookup.
|
|
319
|
+
*/
|
|
320
|
+
function containerPresetOf(presets, session) {
|
|
321
|
+
if (presets === void 0 || session === void 0 || session === null) return void 0;
|
|
322
|
+
let id;
|
|
323
|
+
try {
|
|
324
|
+
id = presets.presetForSession(session);
|
|
325
|
+
} catch {
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
return id !== null && variantKindOf(id) !== void 0 ? id : void 0;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Which runtime one preset id targets.
|
|
332
|
+
* @param preset - a preset id, or undefined when the session committed to none.
|
|
333
|
+
* @returns the track, or undefined for an ordinary preset.
|
|
334
|
+
*/
|
|
335
|
+
function presetKindOf(preset) {
|
|
336
|
+
return preset === void 0 ? void 0 : variantKindOf(preset);
|
|
337
|
+
}
|
|
338
|
+
/** Read one service without a typed `Context` augmentation, as the Host row does. */
|
|
339
|
+
function serviceOf(ctx, service) {
|
|
340
|
+
return ctx.get(service);
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* The derived preset the CALLING agent runs, on either track.
|
|
344
|
+
*
|
|
345
|
+
* A shell call carries its agent in `spec.dshEnv`; a filesystem call carries
|
|
346
|
+
* nothing, so this reads the initiator the loop establishes around every turn —
|
|
347
|
+
* a subagent's own Session answers `presetForSession`, so a delegated agent is
|
|
348
|
+
* attributed to its own preset exactly as it is for a command. A call made
|
|
349
|
+
* outside any turn (a file read by the settings page, a plugin's own
|
|
350
|
+
* bookkeeping) inherits no initiator and therefore no requirement.
|
|
351
|
+
* @param ctx - the calling row's context.
|
|
352
|
+
* @returns the derived preset id, or undefined for an ordinary or agentless call.
|
|
353
|
+
*/
|
|
354
|
+
function callingContainerPreset(ctx) {
|
|
355
|
+
const agents = serviceOf(ctx, "agents");
|
|
356
|
+
const presets = serviceOf(ctx, "agentPresets");
|
|
357
|
+
if (agents === void 0) return void 0;
|
|
358
|
+
let initiator;
|
|
359
|
+
try {
|
|
360
|
+
initiator = agents.currentInitiator();
|
|
361
|
+
} catch {
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
return containerPresetOf(presets, initiator?.session);
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Which runtime the CALLING agent's preset targets.
|
|
368
|
+
*
|
|
369
|
+
* The filesystem, subprocess, and PTC seams carry no per-call marker, so they ask
|
|
370
|
+
* the initiator boundary the same way {@link callingContainerPreset} does.
|
|
371
|
+
* @param ctx - the calling row's context.
|
|
372
|
+
* @returns the track, or undefined for an ordinary or agentless call.
|
|
373
|
+
*/
|
|
374
|
+
function callingVariantKind(ctx) {
|
|
375
|
+
return presetKindOf(callingContainerPreset(ctx));
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Whether one execution is marked as bound to a derived preset's runtime.
|
|
379
|
+
* @param dshEnv - the managed environment the shell tool passed down.
|
|
380
|
+
* @returns true when either marker is present.
|
|
381
|
+
*/
|
|
382
|
+
function markedContainerOnly(dshEnv) {
|
|
383
|
+
if (dshEnv === void 0) return false;
|
|
384
|
+
return Reflect.get(dshEnv, DEVCONTAINER_ENV_KEY) === "1" || Reflect.get(dshEnv, SBX_ENV_KEY) === "1";
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Which runtime one execution is marked for.
|
|
388
|
+
*
|
|
389
|
+
* The sandbox marker is checked first: a `(sbx)` preset never sets the Dev
|
|
390
|
+
* Container one, and a call that somehow carried both must be answered by the
|
|
391
|
+
* marker whose runtime mounts the workspace without a declaration.
|
|
392
|
+
* @param dshEnv - the managed environment the shell tool passed down.
|
|
393
|
+
* @returns the track, or undefined when the call is unmarked.
|
|
394
|
+
*/
|
|
395
|
+
function markedVariantKind(dshEnv) {
|
|
396
|
+
if (dshEnv === void 0) return void 0;
|
|
397
|
+
if (Reflect.get(dshEnv, SBX_ENV_KEY) === "1") return "sbx";
|
|
398
|
+
if (Reflect.get(dshEnv, DEVCONTAINER_ENV_KEY) === "1") return "devcontainer";
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* The preset id recorded alongside the marker.
|
|
402
|
+
* @param dshEnv - the managed environment the shell tool passed down.
|
|
403
|
+
* @returns the derived preset id, or undefined when no marker carries one.
|
|
404
|
+
*/
|
|
405
|
+
function markedPreset(dshEnv) {
|
|
406
|
+
if (dshEnv === void 0) return void 0;
|
|
407
|
+
for (const key of [SBX_PRESET_ENV_KEY, DEVCONTAINER_PRESET_ENV_KEY]) {
|
|
408
|
+
const value = Reflect.get(dshEnv, key);
|
|
409
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* The diagnostic a refused command reports.
|
|
414
|
+
* @param workdir - the host directory the command named.
|
|
415
|
+
* @param preset - the derived preset the session runs, when it is known.
|
|
416
|
+
* @returns the stderr text.
|
|
417
|
+
*/
|
|
418
|
+
function refusalText(workdir, preset) {
|
|
419
|
+
return [
|
|
420
|
+
`devcontainer: refused to run this command on the host.`,
|
|
421
|
+
`This session uses ${preset === void 0 ? "a (devContainer) preset" : `the (devContainer) preset "${preset}"`}, so every command must run inside the repository's Linux container, but "${workdir}" declares none.`,
|
|
422
|
+
`Looked for .devcontainer/devcontainer.json, .devcontainer.json, .dsh/devcontainer.json, or .dsh/docker.json in that directory and its ancestors.`,
|
|
423
|
+
`Add one of those files to the repository, or switch to an ordinary preset without the (devContainer) suffix.`,
|
|
424
|
+
""
|
|
425
|
+
].join("\n");
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* The diagnostic a refused `(sbx)` command reports.
|
|
429
|
+
*
|
|
430
|
+
* A sandbox needs no declaration, so this refusal only happens when the session
|
|
431
|
+
* has no host directory at all to mount — a row mounted without `cwd` and a
|
|
432
|
+
* relative workdir. Naming the row's own setting is the way out.
|
|
433
|
+
* @param workdir - the directory the command named.
|
|
434
|
+
* @param preset - the derived preset the session runs, when it is known.
|
|
435
|
+
* @returns the stderr text.
|
|
436
|
+
*/
|
|
437
|
+
function sbxRefusalText(workdir, preset) {
|
|
438
|
+
return [
|
|
439
|
+
"sbx: refused to run this command on the host.",
|
|
440
|
+
`This session uses ${preset === void 0 ? "a (sbx) preset" : `the (sbx) preset "${preset}"`}, so every command must run inside its Docker Sandbox, but no host workspace directory could be resolved for "${workdir}".`,
|
|
441
|
+
"A Docker Sandbox mounts a host directory, and this row was configured without a \"cwd\" to fall back on.",
|
|
442
|
+
"Set the row's \"cwd\" to the repository directory, or switch to a preset without the (sbx) suffix.",
|
|
443
|
+
""
|
|
444
|
+
].join("\n");
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* The diagnostic a refused filesystem call reports.
|
|
448
|
+
*
|
|
449
|
+
* It names the preset, the path, and every file discovery looked for, then the
|
|
450
|
+
* two ways out — adding a declaration or switching to an ordinary preset — so
|
|
451
|
+
* the refusal cannot be mistaken for a broken tool.
|
|
452
|
+
* @param path - the path the call named.
|
|
453
|
+
* @param preset - the derived preset the session runs, when it is known.
|
|
454
|
+
* @returns the refusal text.
|
|
455
|
+
*/
|
|
456
|
+
function fsRefusalText(path, preset) {
|
|
457
|
+
return [
|
|
458
|
+
`devcontainer: refused to access this path on the host.`,
|
|
459
|
+
`This session uses ${preset === void 0 ? "a (devContainer) preset" : `the (devContainer) preset "${preset}"`}, so every file it reads or writes must live in the repository its Linux container mounts, but the repository that owns "${path}" declares none.`,
|
|
460
|
+
`Looked for .devcontainer/devcontainer.json, .devcontainer.json, .dsh/devcontainer.json, or .dsh/docker.json next to that path and in its ancestors.`,
|
|
461
|
+
`Add one of those files to the repository, or switch to an ordinary preset without the (devContainer) suffix.`,
|
|
462
|
+
""
|
|
463
|
+
].join("\n");
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* The diagnostic a filesystem call reports when the target escapes the repository mount.
|
|
467
|
+
*
|
|
468
|
+
* A path inside the repository can still name something outside it: a symbolic
|
|
469
|
+
* link resolves wherever it points, and a target resolved before the session
|
|
470
|
+
* became container-bound carries a host spelling. Both are refused, and the two
|
|
471
|
+
* spellings are both reported so the link can be found and removed instead of
|
|
472
|
+
* the refusal reading as a bug.
|
|
473
|
+
* @param displayPath - the path the call named.
|
|
474
|
+
* @param targetKey - the resolved path the backend would have used for I/O.
|
|
475
|
+
* @param preset - the derived preset the session runs, when it is known.
|
|
476
|
+
* @returns the refusal text.
|
|
477
|
+
*/
|
|
478
|
+
function fsEscapeRefusalText(displayPath, targetKey, preset) {
|
|
479
|
+
return [
|
|
480
|
+
`devcontainer: refused to access this path.`,
|
|
481
|
+
`This session uses ${preset === void 0 ? "a (devContainer) preset" : `the (devContainer) preset "${preset}"`}, so everything it reads or writes must stay inside the repository its Linux container mounts.`,
|
|
482
|
+
`"${displayPath}" resolves to "${targetKey}", which is outside that repository.`,
|
|
483
|
+
`A symbolic link inside the repository must not point out of it, and a location resolved on the host must be resolved again inside the container.`,
|
|
484
|
+
`Switch to an ordinary preset without the (devContainer) suffix to work on host files.`,
|
|
485
|
+
""
|
|
486
|
+
].join("\n");
|
|
487
|
+
}
|
|
488
|
+
/** A captured stream that already holds its whole text. */
|
|
489
|
+
function settledReader(text) {
|
|
490
|
+
return { readFrom: (fromByte) => ({
|
|
491
|
+
text: text.slice(fromByte),
|
|
492
|
+
nextOffset: text.length,
|
|
493
|
+
lossy: false
|
|
494
|
+
}) };
|
|
495
|
+
}
|
|
496
|
+
/** A captured stream with no truncation. */
|
|
497
|
+
function collected(text) {
|
|
498
|
+
return {
|
|
499
|
+
text,
|
|
500
|
+
truncated: false
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* The completed execution a refused command returns.
|
|
505
|
+
*
|
|
506
|
+
* A command that never ran still has to answer in the shape the tool expects:
|
|
507
|
+
* `exitCode: 1` and the diagnostic on stderr, so the model reads a failure it can
|
|
508
|
+
* act on instead of a host-side result that looks like success.
|
|
509
|
+
* @param spec - the resolved spec that was refused.
|
|
510
|
+
* @param text - the diagnostic to report.
|
|
511
|
+
* @returns the settled execution handle.
|
|
512
|
+
*/
|
|
513
|
+
function refusedExecution(spec, text) {
|
|
514
|
+
let drained = false;
|
|
515
|
+
const stderr = settledReader(text);
|
|
516
|
+
const stdout = settledReader("");
|
|
517
|
+
const result = {
|
|
518
|
+
exitCode: 1,
|
|
519
|
+
signal: null,
|
|
520
|
+
timedOut: false,
|
|
521
|
+
aborted: false,
|
|
522
|
+
timeoutMs: spec.timeoutMs,
|
|
523
|
+
stdout: collected(""),
|
|
524
|
+
stderr: collected(text)
|
|
525
|
+
};
|
|
526
|
+
return {
|
|
527
|
+
status: "completed",
|
|
528
|
+
exitCode: 1,
|
|
529
|
+
signal: null,
|
|
530
|
+
done: Promise.resolve(),
|
|
531
|
+
readOutput: () => {
|
|
532
|
+
if (drained) return {
|
|
533
|
+
delta: "",
|
|
534
|
+
lossy: false
|
|
535
|
+
};
|
|
536
|
+
drained = true;
|
|
537
|
+
return {
|
|
538
|
+
delta: text,
|
|
539
|
+
lossy: false
|
|
540
|
+
};
|
|
541
|
+
},
|
|
542
|
+
observed: {
|
|
543
|
+
stdout,
|
|
544
|
+
stderr
|
|
545
|
+
},
|
|
546
|
+
kill: () => false,
|
|
547
|
+
result: () => Promise.resolve(result)
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
//#endregion
|
|
551
|
+
//#region src/jsonc.ts
|
|
552
|
+
/**
|
|
553
|
+
* Just enough JSONC for `devcontainer.json`: the Dev Container specification
|
|
554
|
+
* allows `//` and `/* *\/` comments plus trailing commas, and no shipped parser
|
|
555
|
+
* accepts them. Stripping happens string-aware, so a `//` inside a value (a URL,
|
|
556
|
+
* a shell fragment) survives.
|
|
557
|
+
* @module @banzhe/dsh-devcontainer/jsonc
|
|
558
|
+
*/
|
|
559
|
+
/** Copy one double-quoted literal starting at `start`, honoring escapes. */
|
|
560
|
+
function stringEnd(text, start) {
|
|
561
|
+
let index = start + 1;
|
|
562
|
+
while (index < text.length) {
|
|
563
|
+
const character = text.charAt(index);
|
|
564
|
+
if (character === "\\") {
|
|
565
|
+
index += 2;
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
index += 1;
|
|
569
|
+
if (character === "\"") return index;
|
|
570
|
+
}
|
|
571
|
+
return text.length;
|
|
572
|
+
}
|
|
573
|
+
/** Remove comments and trailing commas so strict `JSON.parse` accepts the text. */
|
|
574
|
+
function stripJsonComments(text) {
|
|
575
|
+
let out = "";
|
|
576
|
+
let index = 0;
|
|
577
|
+
while (index < text.length) {
|
|
578
|
+
const character = text.charAt(index);
|
|
579
|
+
const next = text[index + 1];
|
|
580
|
+
if (character === "\"") {
|
|
581
|
+
const end = stringEnd(text, index);
|
|
582
|
+
out += text.slice(index, end);
|
|
583
|
+
index = end;
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
if (character === "/" && next === "/") {
|
|
587
|
+
while (index < text.length && text[index] !== "\n") index += 1;
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
if (character === "/" && next === "*") {
|
|
591
|
+
index += 2;
|
|
592
|
+
while (index < text.length && !(text[index] === "*" && text[index + 1] === "/")) index += 1;
|
|
593
|
+
index += 2;
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
out += character;
|
|
597
|
+
index += 1;
|
|
598
|
+
}
|
|
599
|
+
return stripTrailingCommas(out);
|
|
600
|
+
}
|
|
601
|
+
/** Drop commas that are followed only by whitespace and a closing bracket. */
|
|
602
|
+
function stripTrailingCommas(text) {
|
|
603
|
+
let out = "";
|
|
604
|
+
let index = 0;
|
|
605
|
+
while (index < text.length) {
|
|
606
|
+
const character = text.charAt(index);
|
|
607
|
+
if (character === "\"") {
|
|
608
|
+
const end = stringEnd(text, index);
|
|
609
|
+
out += text.slice(index, end);
|
|
610
|
+
index = end;
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
if (character === ",") {
|
|
614
|
+
let lookahead = index + 1;
|
|
615
|
+
while (lookahead < text.length && /\s/.test(text[lookahead])) lookahead += 1;
|
|
616
|
+
const closing = text[lookahead];
|
|
617
|
+
if (closing === "}" || closing === "]") {
|
|
618
|
+
index += 1;
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
out += character;
|
|
623
|
+
index += 1;
|
|
624
|
+
}
|
|
625
|
+
return out;
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Parse one JSONC document (a leading BOM is tolerated).
|
|
629
|
+
* @param text - the file content.
|
|
630
|
+
* @returns the parsed value.
|
|
631
|
+
* @throws SyntaxError when the document is not valid JSONC.
|
|
632
|
+
*/
|
|
633
|
+
function parseJsonc(text) {
|
|
634
|
+
return JSON.parse(stripJsonComments(text.replace(/^\uFEFF/, "")));
|
|
635
|
+
}
|
|
636
|
+
//#endregion
|
|
637
|
+
//#region src/config-loader.ts
|
|
638
|
+
/**
|
|
639
|
+
* Repository-level Dev Container discovery and parsing.
|
|
640
|
+
*
|
|
641
|
+
* Discovery walks the ancestors of whatever directory a tool call arrives with
|
|
642
|
+
* and takes the nearest repository declaration. Three shapes are honoured, in
|
|
643
|
+
* this order:
|
|
644
|
+
*
|
|
645
|
+
* 1. `.dsh/devcontainer.json` and `.dsh/docker.json` — the lightweight form this
|
|
646
|
+
* Bundle adds: it may name an already-running `container` instead of asking
|
|
647
|
+
* the Dev Container CLI to build one.
|
|
648
|
+
* 2. `.devcontainer/devcontainer.json` — the Dev Container specification.
|
|
649
|
+
* 3. `.devcontainer.json` — the single-file variant of the same specification.
|
|
650
|
+
*
|
|
651
|
+
* @module @banzhe/dsh-devcontainer/config-loader
|
|
652
|
+
*/
|
|
653
|
+
/** The configuration files to probe in each ancestor directory, most specific first. */
|
|
654
|
+
const CONFIG_CANDIDATES = [
|
|
655
|
+
{ relativePath: ".dsh/devcontainer.json" },
|
|
656
|
+
{ relativePath: ".dsh/docker.json" },
|
|
657
|
+
{ relativePath: ".devcontainer/devcontainer.json" },
|
|
658
|
+
{ relativePath: ".devcontainer.json" }
|
|
659
|
+
];
|
|
660
|
+
/** The filesystem read discovery uses unless a caller supplies one. */
|
|
661
|
+
const readTextFile = (path) => {
|
|
662
|
+
try {
|
|
663
|
+
return readFileSync(path, "utf8");
|
|
664
|
+
} catch {
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
const MAX_ANCESTOR_DEPTH = 64;
|
|
669
|
+
function asRecord(value) {
|
|
670
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
671
|
+
}
|
|
672
|
+
function asString(value) {
|
|
673
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
674
|
+
}
|
|
675
|
+
function asBoolean(value) {
|
|
676
|
+
return typeof value === "boolean" ? value : void 0;
|
|
677
|
+
}
|
|
678
|
+
function asStringMap(value) {
|
|
679
|
+
const record = asRecord(value);
|
|
680
|
+
if (record === void 0) return void 0;
|
|
681
|
+
const entries = [];
|
|
682
|
+
for (const [key, entry] of Object.entries(record)) if (typeof entry === "string") entries.push([key, entry]);
|
|
683
|
+
else if (typeof entry === "number" || typeof entry === "boolean") entries.push([key, String(entry)]);
|
|
684
|
+
return entries.length === 0 ? void 0 : Object.fromEntries(entries);
|
|
685
|
+
}
|
|
686
|
+
function asCli(value) {
|
|
687
|
+
return value === "auto" || value === "devcontainer" || value === "docker" || value === "sbx" ? value : void 0;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Build one specification from a configuration file's text.
|
|
691
|
+
*
|
|
692
|
+
* A declared `workspaceFolder` wins over the specification's default mount
|
|
693
|
+
* point, and both must be POSIX: a Windows-shaped value would produce a
|
|
694
|
+
* container path no shell in the container could enter.
|
|
695
|
+
* @param input - the repository root, the configuration path, its text, and the row's defaults.
|
|
696
|
+
* @returns the resolved specification.
|
|
697
|
+
* @throws Error when the document is unparsable or a field is unusable.
|
|
698
|
+
*/
|
|
699
|
+
function buildSpec(input) {
|
|
700
|
+
let parsed;
|
|
701
|
+
try {
|
|
702
|
+
parsed = parseJsonc(input.text);
|
|
703
|
+
} catch (error) {
|
|
704
|
+
throw new Error(`devcontainer: cannot parse ${input.configPath}: ${error.message}`);
|
|
705
|
+
}
|
|
706
|
+
const record = asRecord(parsed) ?? {};
|
|
707
|
+
const hostRoot = normalizeHostRoot(input.hostRoot);
|
|
708
|
+
const declaredFolder = asString(record.workspaceFolder);
|
|
709
|
+
const containerWorkspaceFolder = declaredFolder === void 0 ? defaultContainerWorkspaceFolder(hostRoot) : toPosixSlashes(declaredFolder).replace(/\/+$/, "");
|
|
710
|
+
if (!posix.isAbsolute(containerWorkspaceFolder)) throw new Error(`devcontainer: ${input.configPath}: workspaceFolder must be an absolute POSIX path, got ${JSON.stringify(declaredFolder)}`);
|
|
711
|
+
const remoteEnv = asStringMap(record.remoteEnv);
|
|
712
|
+
const container = asString(record.container) ?? asString(record.containerName);
|
|
713
|
+
const composeService = asString(record.service);
|
|
714
|
+
const remoteUser = asString(record.remoteUser);
|
|
715
|
+
const sandbox = asString(record.sandbox) ?? asString(record.sandboxName);
|
|
716
|
+
const shell = asString(record.shell) ?? input.options?.shell ?? CONTAINER_OPTION_DEFAULTS.shell;
|
|
717
|
+
const cli = asCli(record.cli) ?? input.options?.cli ?? CONTAINER_OPTION_DEFAULTS.cli;
|
|
718
|
+
const ensureUp = asBoolean(record.ensureUp) ?? input.options?.ensureUp ?? CONTAINER_OPTION_DEFAULTS.ensureUp;
|
|
719
|
+
const containerTimeoutMs = input.options?.containerTimeoutMs ?? CONTAINER_OPTION_DEFAULTS.containerTimeoutMs;
|
|
720
|
+
return {
|
|
721
|
+
hostWorkspaceRoot: hostRoot,
|
|
722
|
+
containerWorkspaceFolder,
|
|
723
|
+
configPath: input.configPath,
|
|
724
|
+
...container === void 0 ? {} : { container },
|
|
725
|
+
...composeService === void 0 ? {} : { composeService },
|
|
726
|
+
...remoteUser === void 0 ? {} : { remoteUser },
|
|
727
|
+
...remoteEnv === void 0 ? {} : { remoteEnv },
|
|
728
|
+
...sandbox === void 0 ? {} : { sandbox },
|
|
729
|
+
shell,
|
|
730
|
+
cli,
|
|
731
|
+
ensureUp,
|
|
732
|
+
containerTimeoutMs
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Walk the ancestors of one directory and return the nearest configuration file.
|
|
737
|
+
* @param startDir - absolute host path of a file or directory inside the repository.
|
|
738
|
+
* @param read - file reader; absent files return undefined.
|
|
739
|
+
* @returns the found file and its repository root, or undefined when no ancestor declares one.
|
|
740
|
+
*/
|
|
741
|
+
function findConfigFile(startDir, read = readTextFile) {
|
|
742
|
+
const paths = hostPathStyle(startDir) === "win32" ? win32 : posix;
|
|
743
|
+
let current = normalizeHostRoot(startDir);
|
|
744
|
+
for (let depth = 0; depth < MAX_ANCESTOR_DEPTH; depth += 1) {
|
|
745
|
+
for (const candidate of CONFIG_CANDIDATES) {
|
|
746
|
+
const configPath = paths.join(current, ...candidate.relativePath.split("/"));
|
|
747
|
+
if (read(configPath) === void 0) continue;
|
|
748
|
+
return {
|
|
749
|
+
configPath,
|
|
750
|
+
hostRoot: current
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
const parent = paths.dirname(current);
|
|
754
|
+
if (parent === current) break;
|
|
755
|
+
current = parent;
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
/** How many repositories the container-path index keeps before dropping the oldest. */
|
|
759
|
+
const MAX_DISCOVERED = 64;
|
|
760
|
+
/**
|
|
761
|
+
* Last-modified time of one file, or undefined when it cannot be stat'd.
|
|
762
|
+
* @param path - absolute path of the file.
|
|
763
|
+
* @returns the mtime in milliseconds.
|
|
764
|
+
*/
|
|
765
|
+
function statMtimeMs(path) {
|
|
766
|
+
try {
|
|
767
|
+
return statSync(path).mtimeMs;
|
|
768
|
+
} catch {
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* Per-context cache of discovered specifications.
|
|
774
|
+
*
|
|
775
|
+
* Every shell command and every filesystem call asks for the repository
|
|
776
|
+
* specification, so the ancestor walk is memoized per directory and the parse
|
|
777
|
+
* per option signature. Two rules keep the cache honest:
|
|
778
|
+
*
|
|
779
|
+
* - a directory that declares nothing is NOT remembered: a person who adds
|
|
780
|
+
* `.dsh/docker.json` after being told the repository declares none must be
|
|
781
|
+
* picked up by the very next command;
|
|
782
|
+
* - a parse is remembered together with the configuration file's `mtimeMs` and
|
|
783
|
+
* re-used only while the file still exists with that exact mtime, so editing or
|
|
784
|
+
* deleting a declaration takes effect immediately.
|
|
785
|
+
*/
|
|
786
|
+
var RepoContainerRegistry = class {
|
|
787
|
+
read;
|
|
788
|
+
mtime;
|
|
789
|
+
/** Directory → found config. Only hits are remembered. */
|
|
790
|
+
directories = /* @__PURE__ */ new Map();
|
|
791
|
+
/** Option signature → parsed specification. */
|
|
792
|
+
specifications = /* @__PURE__ */ new Map();
|
|
793
|
+
/** Configuration path → the parse it produced most recently. */
|
|
794
|
+
latest = /* @__PURE__ */ new Map();
|
|
795
|
+
/** Every specification discovered so far, for container-path matching. */
|
|
796
|
+
discovered = [];
|
|
797
|
+
/**
|
|
798
|
+
* @param read - file reader; an absent file returns undefined.
|
|
799
|
+
* @param mtime - file clock used to detect edits; undefined means "cannot tell".
|
|
800
|
+
*/
|
|
801
|
+
constructor(read = readTextFile, mtime = statMtimeMs) {
|
|
802
|
+
this.read = read;
|
|
803
|
+
this.mtime = mtime;
|
|
804
|
+
}
|
|
805
|
+
/** Drop every cached discovery and parse. */
|
|
806
|
+
reset() {
|
|
807
|
+
this.directories.clear();
|
|
808
|
+
this.specifications.clear();
|
|
809
|
+
this.latest.clear();
|
|
810
|
+
this.discovered.length = 0;
|
|
811
|
+
}
|
|
812
|
+
/** Every specification discovered so far. */
|
|
813
|
+
knownSpecs() {
|
|
814
|
+
return this.discovered;
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Find the repository container specification that governs one path.
|
|
818
|
+
*
|
|
819
|
+
* Container paths carry no host ancestry, so the caller's host `cwd` is asked
|
|
820
|
+
* first: it reaches the repository from disk without any earlier call, and it
|
|
821
|
+
* separates two repositories that happen to mount at the same container folder.
|
|
822
|
+
* @param path - the path a tool call carries: a host path, a container path, or a relative path.
|
|
823
|
+
* @param options - the calling row's defaults plus the directory relative paths resolve against.
|
|
824
|
+
* @returns the governing specification, or undefined when the path belongs to no Dev Container repository.
|
|
825
|
+
*/
|
|
826
|
+
locate(path, options = {}) {
|
|
827
|
+
const cwd = options.cwd;
|
|
828
|
+
const target = path === void 0 || path === "" ? cwd : path;
|
|
829
|
+
if (target === void 0 || target === "") return void 0;
|
|
830
|
+
if (cwd !== void 0 && cwd !== "" && cwd !== target && !isWindowsPath(target)) {
|
|
831
|
+
const fromCwd = this.discover(cwd, options);
|
|
832
|
+
if (fromCwd !== void 0 && isPathInsideContainer(target, fromCwd) && relativeWithinHostRoot(target, fromCwd.hostWorkspaceRoot) === void 0) return fromCwd;
|
|
833
|
+
}
|
|
834
|
+
const stale = [];
|
|
835
|
+
const match = this.discovered.find((spec) => {
|
|
836
|
+
if (!isPathInsideContainer(target, spec)) return false;
|
|
837
|
+
if (this.isStale(spec)) {
|
|
838
|
+
stale.push(spec.configPath);
|
|
839
|
+
return false;
|
|
840
|
+
}
|
|
841
|
+
return true;
|
|
842
|
+
});
|
|
843
|
+
for (const configPath of stale) this.forgetConfig(configPath);
|
|
844
|
+
if (match !== void 0) return match;
|
|
845
|
+
const direct = this.discover(target, options);
|
|
846
|
+
if (direct !== void 0) return direct;
|
|
847
|
+
if (cwd === void 0 || cwd === target) return void 0;
|
|
848
|
+
const fromCwd = this.discover(cwd, options);
|
|
849
|
+
if (fromCwd === void 0) return void 0;
|
|
850
|
+
return this.belongsTo(target, fromCwd) ? fromCwd : void 0;
|
|
851
|
+
}
|
|
852
|
+
/** Whether one path lies inside a specification's host root or container mount. */
|
|
853
|
+
belongsTo(path, spec) {
|
|
854
|
+
return isPathInsideContainer(path, spec) || relativeWithinHostRoot(path, spec.hostWorkspaceRoot) !== void 0;
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* Discover from one path's ancestry, memoized per directory.
|
|
858
|
+
* @param start - a file or directory inside the repository.
|
|
859
|
+
* @param options - the calling row's defaults.
|
|
860
|
+
* @returns the specification, or undefined when no ancestor declares one.
|
|
861
|
+
*/
|
|
862
|
+
discover(start, options = {}) {
|
|
863
|
+
const found = this.findConfig(start);
|
|
864
|
+
if (found === void 0) return void 0;
|
|
865
|
+
return this.specFor(found, options);
|
|
866
|
+
}
|
|
867
|
+
/** The cached hit for one start directory, or a fresh walk. Misses are not cached. */
|
|
868
|
+
findConfig(start) {
|
|
869
|
+
if (!(start.startsWith("/") || start.startsWith("\\\\") || /^[A-Za-z]:[\\/]/.test(start))) return findConfigFile(start, this.read);
|
|
870
|
+
const cached = this.directories.get(start);
|
|
871
|
+
if (cached !== void 0) return cached;
|
|
872
|
+
const found = findConfigFile(start, this.read);
|
|
873
|
+
if (found !== void 0) this.directories.set(start, found);
|
|
874
|
+
return found;
|
|
875
|
+
}
|
|
876
|
+
/** Parse one found file for one option signature, re-using the parse only while the file is unchanged. */
|
|
877
|
+
specFor(found, options) {
|
|
878
|
+
const signature = [
|
|
879
|
+
found.configPath,
|
|
880
|
+
options.cli ?? "",
|
|
881
|
+
options.shell ?? "",
|
|
882
|
+
options.ensureUp ?? "",
|
|
883
|
+
options.containerTimeoutMs ?? "",
|
|
884
|
+
options.requireContainer ?? ""
|
|
885
|
+
].join("\0");
|
|
886
|
+
const cached = this.specifications.get(signature);
|
|
887
|
+
if (cached !== void 0 && !this.isStale(cached.spec)) return cached.spec;
|
|
888
|
+
if (cached !== void 0) this.forgetConfig(found.configPath);
|
|
889
|
+
const text = this.read(found.configPath);
|
|
890
|
+
if (text === void 0) {
|
|
891
|
+
this.forgetConfig(found.configPath);
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
const entry = {
|
|
895
|
+
spec: buildSpec({
|
|
896
|
+
hostRoot: found.hostRoot,
|
|
897
|
+
configPath: found.configPath,
|
|
898
|
+
text,
|
|
899
|
+
options
|
|
900
|
+
}),
|
|
901
|
+
mtimeMs: this.mtime(found.configPath)
|
|
902
|
+
};
|
|
903
|
+
this.specifications.set(signature, entry);
|
|
904
|
+
this.latest.set(found.configPath, entry);
|
|
905
|
+
this.remember(entry.spec);
|
|
906
|
+
return entry.spec;
|
|
907
|
+
}
|
|
908
|
+
/** Whether the file behind one specification is gone or has been edited since it was parsed. */
|
|
909
|
+
isStale(spec) {
|
|
910
|
+
const entry = this.latest.get(spec.configPath);
|
|
911
|
+
if (entry === void 0) return true;
|
|
912
|
+
const clock = this.mtime(spec.configPath);
|
|
913
|
+
return clock === void 0 || clock !== entry.mtimeMs;
|
|
914
|
+
}
|
|
915
|
+
/** Keep the container-path index free of duplicates and bounded. */
|
|
916
|
+
remember(spec) {
|
|
917
|
+
const index = this.discovered.findIndex((known) => known.configPath === spec.configPath && known.cli === spec.cli);
|
|
918
|
+
if (index >= 0) this.discovered[index] = spec;
|
|
919
|
+
else this.discovered.push(spec);
|
|
920
|
+
while (this.discovered.length > MAX_DISCOVERED) this.discovered.shift();
|
|
921
|
+
}
|
|
922
|
+
/** Forget every trace of one configuration file, so the next call walks the disk again. */
|
|
923
|
+
forgetConfig(configPath) {
|
|
924
|
+
for (const [start, found] of this.directories) if (found.configPath === configPath) this.directories.delete(start);
|
|
925
|
+
for (const [signature, entry] of this.specifications) if (entry.spec.configPath === configPath) this.specifications.delete(signature);
|
|
926
|
+
this.latest.delete(configPath);
|
|
927
|
+
const index = this.discovered.findIndex((known) => known.configPath === configPath);
|
|
928
|
+
if (index >= 0) this.discovered.splice(index, 1);
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
//#endregion
|
|
932
|
+
//#region src/registry.ts
|
|
933
|
+
const REGISTRIES = /* @__PURE__ */ new WeakMap();
|
|
934
|
+
const DEFAULT = new RepoContainerRegistry();
|
|
935
|
+
/** The composition root one context belongs to. */
|
|
936
|
+
function rootOf(scope) {
|
|
937
|
+
const root = scope.root;
|
|
938
|
+
return typeof root === "object" && root !== null ? root : scope;
|
|
939
|
+
}
|
|
940
|
+
/**
|
|
941
|
+
* The discovery cache for one composition.
|
|
942
|
+
* @param scope - a row's context, or the composition root; omitted for a bare cache.
|
|
943
|
+
* @returns the registry shared by every row of that composition.
|
|
944
|
+
*/
|
|
945
|
+
function repoRegistry(scope) {
|
|
946
|
+
if (scope === void 0) return DEFAULT;
|
|
947
|
+
const key = rootOf(scope);
|
|
948
|
+
const cached = REGISTRIES.get(key);
|
|
949
|
+
if (cached !== void 0) return cached;
|
|
950
|
+
const registry = new RepoContainerRegistry();
|
|
951
|
+
REGISTRIES.set(key, registry);
|
|
952
|
+
return registry;
|
|
953
|
+
}
|
|
954
|
+
//#endregion
|
|
955
|
+
//#region src/sbx.ts
|
|
956
|
+
/**
|
|
957
|
+
* Docker Sandbox (`sbx`) target discovery.
|
|
958
|
+
*
|
|
959
|
+
* A sandbox is not a Dev Container: a `(sbx)` preset needs no
|
|
960
|
+
* `.devcontainer/devcontainer.json` at all. This module therefore answers two
|
|
961
|
+
* questions the Dev Container driver answers from a declaration: which sandbox
|
|
962
|
+
* belongs to a host directory (a naming convention makes it deterministic), and
|
|
963
|
+
* where commands run inside it (the sandbox's own mount of that directory).
|
|
964
|
+
*
|
|
965
|
+
* That second answer is not the host spelling. A Linux or macOS sandbox mounts a
|
|
966
|
+
* workspace at the same absolute path it has on the host, while a Windows host's
|
|
967
|
+
* MicroVM maps `F:\personal\repo` to `/f/personal/repo`. `sbx ls --json` reports
|
|
968
|
+
* the mounts, so the listing decides the folder; a sandbox whose mounts say
|
|
969
|
+
* nothing about the workspace keeps the host path as its fallback.
|
|
970
|
+
*
|
|
971
|
+
* The CLI surface used here is the documented one: `sbx ls --json` lists
|
|
972
|
+
* sandboxes, `sbx create --name <name> shell <path>` creates one around a host
|
|
973
|
+
* directory without attaching, and `sbx run -d --name <name>` starts an existing
|
|
974
|
+
* sandbox detached. `sbx exec` reports a missing sandbox with exit code 125.
|
|
975
|
+
* @module @banzhe/dsh-devcontainer/sbx
|
|
976
|
+
*/
|
|
977
|
+
/** Prefix every sandbox this Bundle creates carries, so it is recognizable on a host. */
|
|
978
|
+
const SANDBOX_NAME_PREFIX = "dsh-";
|
|
979
|
+
/** The template a created sandbox runs: Docker's agent-less shell template. */
|
|
980
|
+
const SANDBOX_TEMPLATE = "shell";
|
|
981
|
+
/**
|
|
982
|
+
* What a missing `sbx` CLI means for the person reading the diagnostic.
|
|
983
|
+
*
|
|
984
|
+
* The name is deliberately long-form: `command not found: sbx` says nothing
|
|
985
|
+
* about what to install, and a `(sbx)` preset otherwise looks like a broken
|
|
986
|
+
* shell tool.
|
|
987
|
+
*/
|
|
988
|
+
const SBX_INSTALL_HINT = "Install the Docker Sandbox CLI (\"sbx\", shipped with Docker Desktop) so it is on PATH, sign in with \"sbx login\", or switch to a preset without the (sbx) suffix.";
|
|
989
|
+
/**
|
|
990
|
+
* The deterministic sandbox name of one host workspace.
|
|
991
|
+
*
|
|
992
|
+
* `dsh-<repo>-<hash>`: the readable part so a person recognizes the project in
|
|
993
|
+
* `sbx ls`, the digest so two repositories with the same directory name never
|
|
994
|
+
* share a sandbox. The digest folds case only for a Windows-rooted path, because
|
|
995
|
+
* that host reports one directory with either spelling; a case-sensitive host
|
|
996
|
+
* keeps the spelling it was given, where `Repo` and `repo` are two directories
|
|
997
|
+
* that must not share a sandbox.
|
|
998
|
+
* @param hostWorkspaceRoot - absolute host path of the workspace.
|
|
999
|
+
* @returns the sandbox name.
|
|
1000
|
+
*/
|
|
1001
|
+
function sandboxNameFor(hostWorkspaceRoot) {
|
|
1002
|
+
const root = normalizeHostRoot(hostWorkspaceRoot);
|
|
1003
|
+
const windows = hostPathStyle(root) === "win32";
|
|
1004
|
+
const base = windows ? win32.basename(root) : posix.basename(root);
|
|
1005
|
+
const slug = (base === "" ? "workspace" : base).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
1006
|
+
const spelled = root.replaceAll("\\", "/");
|
|
1007
|
+
const digest = createHash("sha256").update(windows ? spelled.toLowerCase() : spelled).digest("hex").slice(0, 8);
|
|
1008
|
+
return `${SANDBOX_NAME_PREFIX}${slug === "" ? "workspace" : slug}-${digest}`;
|
|
1009
|
+
}
|
|
1010
|
+
/** The state names a listed sandbox may report while it is running. */
|
|
1011
|
+
const RUNNING_STATES = /* @__PURE__ */ new Set([
|
|
1012
|
+
"running",
|
|
1013
|
+
"ready",
|
|
1014
|
+
"up",
|
|
1015
|
+
"started"
|
|
1016
|
+
]);
|
|
1017
|
+
/**
|
|
1018
|
+
* Read one mount entry a listing reports.
|
|
1019
|
+
*
|
|
1020
|
+
* The separator is the LAST `:/` of the entry: a Windows host directory carries a
|
|
1021
|
+
* drive colon of its own, while the sandbox side of a mount is always
|
|
1022
|
+
* POSIX-absolute. An entry that does not split into two absolute paths is
|
|
1023
|
+
* dropped rather than guessed at, which leaves its sandbox on the host-path
|
|
1024
|
+
* fallback instead of a path that exists nowhere.
|
|
1025
|
+
* @param value - one entry of a row's `mounts` array.
|
|
1026
|
+
* @returns the mount, or undefined when the entry names none.
|
|
1027
|
+
*/
|
|
1028
|
+
function sandboxMount(value) {
|
|
1029
|
+
if (typeof value !== "string") return void 0;
|
|
1030
|
+
const separator = value.lastIndexOf(":/");
|
|
1031
|
+
if (separator <= 0) return void 0;
|
|
1032
|
+
const host = value.slice(0, separator).trim();
|
|
1033
|
+
const sandbox = value.slice(separator + 1).trim();
|
|
1034
|
+
if (!isWindowsPath(host) && !isPosixAbsolute(host)) return void 0;
|
|
1035
|
+
if (!isPosixAbsolute(sandbox)) return void 0;
|
|
1036
|
+
return {
|
|
1037
|
+
host,
|
|
1038
|
+
sandbox
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
/** The mounts one row reports, in the order it reports them. */
|
|
1042
|
+
function mountsOf(row) {
|
|
1043
|
+
const listed = row["mounts"];
|
|
1044
|
+
if (!Array.isArray(listed)) return [];
|
|
1045
|
+
return listed.map(sandboxMount).filter((mount) => mount !== void 0);
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Read one listed sandbox, tolerating the field names the CLI has used across
|
|
1049
|
+
* releases (snake_case JSON, a `detached` flag, or a plain `running` boolean).
|
|
1050
|
+
*
|
|
1051
|
+
* A row that says nothing about its state is reported as NOT running: starting an
|
|
1052
|
+
* existing sandbox again is harmless, while treating a stopped sandbox as running
|
|
1053
|
+
* would make every later `sbx exec` fail with exit code 125 and never recover.
|
|
1054
|
+
* @param value - one row of the listing.
|
|
1055
|
+
* @returns the sandbox, or undefined when the row names none.
|
|
1056
|
+
*/
|
|
1057
|
+
function listedSandbox(value) {
|
|
1058
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
1059
|
+
const row = value;
|
|
1060
|
+
const name = row["name"];
|
|
1061
|
+
if (typeof name !== "string" || name.trim() === "") return void 0;
|
|
1062
|
+
const mounts = mountsOf(row);
|
|
1063
|
+
if (row["running"] === true || row["detached"] === true) return {
|
|
1064
|
+
name: name.trim(),
|
|
1065
|
+
running: true,
|
|
1066
|
+
mounts
|
|
1067
|
+
};
|
|
1068
|
+
for (const field of ["status", "state"]) {
|
|
1069
|
+
const state = row[field];
|
|
1070
|
+
if (typeof state === "string") return {
|
|
1071
|
+
name: name.trim(),
|
|
1072
|
+
running: RUNNING_STATES.has(state.trim().toLowerCase()),
|
|
1073
|
+
mounts
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
return {
|
|
1077
|
+
name: name.trim(),
|
|
1078
|
+
running: false,
|
|
1079
|
+
mounts
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Parse `sbx ls --json`.
|
|
1084
|
+
*
|
|
1085
|
+
* Both the current array form and the older `{ "sandboxes": [...] }` envelope are
|
|
1086
|
+
* accepted, and anything unparsable yields no sandboxes rather than throwing: a
|
|
1087
|
+
* listing this module cannot read must fall through to "create or start it", not
|
|
1088
|
+
* fail the command.
|
|
1089
|
+
* @param stdout - the CLI's standard output.
|
|
1090
|
+
* @returns the listed sandboxes.
|
|
1091
|
+
*/
|
|
1092
|
+
function parseSandboxList(stdout) {
|
|
1093
|
+
const text = stdout.trim();
|
|
1094
|
+
if (text === "") return [];
|
|
1095
|
+
let parsed;
|
|
1096
|
+
try {
|
|
1097
|
+
parsed = JSON.parse(text);
|
|
1098
|
+
} catch {
|
|
1099
|
+
return [];
|
|
1100
|
+
}
|
|
1101
|
+
return (Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.sandboxes) ? parsed.sandboxes : []).map(listedSandbox).filter((row) => row !== void 0);
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Ask the CLI which sandboxes exist.
|
|
1105
|
+
*
|
|
1106
|
+
* The mounts of a successful listing are remembered, because the specification
|
|
1107
|
+
* builders below are synchronous and have no CLI in reach.
|
|
1108
|
+
* @param run - the CLI runner.
|
|
1109
|
+
* @param timeoutMs - budget for the call.
|
|
1110
|
+
* @param signal - cancellation.
|
|
1111
|
+
* @returns the listing, with `available: false` when `sbx` could not be started.
|
|
1112
|
+
*/
|
|
1113
|
+
async function listSandboxes(run, timeoutMs, signal) {
|
|
1114
|
+
const result = await run([
|
|
1115
|
+
"sbx",
|
|
1116
|
+
"ls",
|
|
1117
|
+
"--json"
|
|
1118
|
+
], {
|
|
1119
|
+
...signal === void 0 ? {} : { signal },
|
|
1120
|
+
timeoutMs
|
|
1121
|
+
});
|
|
1122
|
+
if (result.exitCode === null) return {
|
|
1123
|
+
available: false,
|
|
1124
|
+
sandboxes: []
|
|
1125
|
+
};
|
|
1126
|
+
if (result.exitCode !== 0) return {
|
|
1127
|
+
available: true,
|
|
1128
|
+
sandboxes: []
|
|
1129
|
+
};
|
|
1130
|
+
const sandboxes = parseSandboxList(result.stdout);
|
|
1131
|
+
recordMounts(sandboxes);
|
|
1132
|
+
return {
|
|
1133
|
+
available: true,
|
|
1134
|
+
sandboxes
|
|
1135
|
+
};
|
|
1136
|
+
}
|
|
1137
|
+
/** Whether this host spells directories the Windows way. */
|
|
1138
|
+
const WINDOWS_HOST = process.platform === "win32";
|
|
1139
|
+
/**
|
|
1140
|
+
* The host directory a `(sbx)` session mounts.
|
|
1141
|
+
*
|
|
1142
|
+
* A declaration wins, because the sandbox mounts the repository the declaration
|
|
1143
|
+
* was found in. Without one, the row's configured cwd is the workspace — that is
|
|
1144
|
+
* the directory the session was started in, and the only one a sandbox may
|
|
1145
|
+
* claim. The path a call names is the last resort, and only when it is an
|
|
1146
|
+
* absolute HOST path: a POSIX-absolute path is a host path on a POSIX host only,
|
|
1147
|
+
* since on Windows `/workspaces/<repo>` is the Dev Container spelling.
|
|
1148
|
+
* @param workdir - the directory the call named.
|
|
1149
|
+
* @param cwd - the directory the row was configured with.
|
|
1150
|
+
* @param declared - the specification a declaration produced, when one exists.
|
|
1151
|
+
* @returns the absolute host path to mount, or undefined when none can be named.
|
|
1152
|
+
*/
|
|
1153
|
+
function sbxWorkspaceRootFor(workdir, cwd, declared) {
|
|
1154
|
+
if (declared !== void 0) return declared.hostWorkspaceRoot;
|
|
1155
|
+
if (cwd !== void 0 && cwd !== "") return cwd;
|
|
1156
|
+
if (isWindowsPath(workdir) || !WINDOWS_HOST && isPosixAbsolute(workdir)) return workdir;
|
|
1157
|
+
}
|
|
1158
|
+
/**
|
|
1159
|
+
* The path a sandbox has for one host workspace, from the host convention alone.
|
|
1160
|
+
*
|
|
1161
|
+
* A sandbox is a Linux machine, so it cannot mount a Windows drive path: its
|
|
1162
|
+
* MicroVM maps the directory without the drive colon, which turns
|
|
1163
|
+
* `F:\personal\asmr-manager` into `/f/personal/asmr-manager`. A Linux or macOS
|
|
1164
|
+
* sandbox mounts a directory at the absolute path it already has.
|
|
1165
|
+
*
|
|
1166
|
+
* This answers the attribution question a call must settle before the listing
|
|
1167
|
+
* has run or when the listing reported no mounts; mounts a listing did report
|
|
1168
|
+
* always win over it.
|
|
1169
|
+
* @param hostWorkspaceRoot - absolute host path of the workspace.
|
|
1170
|
+
* @returns the absolute POSIX path the sandbox has for it, or undefined for a UNC path no convention maps.
|
|
1171
|
+
*/
|
|
1172
|
+
function sandboxWorkspacePath(hostWorkspaceRoot) {
|
|
1173
|
+
const root = normalizeHostRoot(hostWorkspaceRoot);
|
|
1174
|
+
if (hostPathStyle(root) !== "win32") return toPosixSlashes(root);
|
|
1175
|
+
if (root.startsWith("\\\\")) return void 0;
|
|
1176
|
+
const slashed = toPosixSlashes(root);
|
|
1177
|
+
return posix.normalize(`/${slashed.slice(0, 1).toLowerCase()}${slashed.slice(2)}`).replace(/\/+$/, "") || "/";
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* The path one host workspace has inside a sandbox, from the mounts it reported.
|
|
1181
|
+
*
|
|
1182
|
+
* The deepest mount containing the workspace wins, so a sandbox created around a
|
|
1183
|
+
* parent directory still maps the repository inside it. A host whose sandbox
|
|
1184
|
+
* mounts directories at their own absolute path — Linux and macOS both do —
|
|
1185
|
+
* yields that same path, which is the fallback anyway.
|
|
1186
|
+
* @param hostWorkspaceRoot - absolute host path of the workspace.
|
|
1187
|
+
* @param mounts - the mounts a listing reported.
|
|
1188
|
+
* @returns the absolute POSIX sandbox path, or undefined when no mount covers the workspace.
|
|
1189
|
+
*/
|
|
1190
|
+
function sandboxMountFor(hostWorkspaceRoot, mounts) {
|
|
1191
|
+
const root = normalizeHostRoot(hostWorkspaceRoot);
|
|
1192
|
+
let found;
|
|
1193
|
+
for (const mount of mounts) {
|
|
1194
|
+
if (!isPosixAbsolute(mount.sandbox)) continue;
|
|
1195
|
+
const relative = relativeWithinHostRoot(root, mount.host);
|
|
1196
|
+
if (relative === void 0) continue;
|
|
1197
|
+
if (found !== void 0 && found.hostLength >= mount.host.length) continue;
|
|
1198
|
+
const base = posix.normalize(mount.sandbox);
|
|
1199
|
+
found = {
|
|
1200
|
+
hostLength: mount.host.length,
|
|
1201
|
+
path: relative === "" ? base : posix.join(base, relative)
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
return found?.path;
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* The mounts the last listing reported, per sandbox name.
|
|
1208
|
+
*
|
|
1209
|
+
* {@link sbxSpecFor} and {@link asSbxSpec} are synchronous — the preset builder,
|
|
1210
|
+
* the filesystem route, and the spawn-cwd mapping all build a specification on a
|
|
1211
|
+
* path that a listing has already answered for — so the listing leaves its mounts
|
|
1212
|
+
* here for them. Mounts handed to those functions explicitly always win.
|
|
1213
|
+
*/
|
|
1214
|
+
const reportedMounts = /* @__PURE__ */ new Map();
|
|
1215
|
+
/**
|
|
1216
|
+
* Remember one listing's mounts.
|
|
1217
|
+
* @param sandboxes - the sandboxes the listing reported.
|
|
1218
|
+
*/
|
|
1219
|
+
function recordMounts(sandboxes) {
|
|
1220
|
+
for (const sandbox of sandboxes) reportedMounts.set(sandbox.name, sandbox.mounts);
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* The host directory a path inside a sandbox names.
|
|
1224
|
+
*
|
|
1225
|
+
* This is the inverse of {@link sandboxWorkspacePath} and {@link sandboxMountFor},
|
|
1226
|
+
* and a `(sbx)` session's filesystem calls need it: the paths such a session names
|
|
1227
|
+
* exist only inside its sandbox, so walking their ancestors on the host finds no
|
|
1228
|
+
* repository — on a Windows host `/f/personal/repo` is `F:\personal\repo`, one
|
|
1229
|
+
* namespace away from the directory that declares the container.
|
|
1230
|
+
*
|
|
1231
|
+
* A mount the last listing reported is direct evidence and wins, deepest first, so
|
|
1232
|
+
* a sandbox that mounts its workspace somewhere of its own is attributed correctly
|
|
1233
|
+
* — and only a mount says which host directory the sandbox has, which is the
|
|
1234
|
+
* workspace root a caller needs. Without one, only the host convention can answer:
|
|
1235
|
+
* a Windows host maps `F:\personal\repo` to `/f/personal/repo`, so a path whose
|
|
1236
|
+
* first segment is a single letter spells a drive. Anything else —
|
|
1237
|
+
* `/workspaces/repo`, `/etc` — names no host directory, and the caller keeps
|
|
1238
|
+
* whatever it had.
|
|
1239
|
+
* @param sandboxPath - absolute POSIX path inside a sandbox.
|
|
1240
|
+
* @returns the host path it stands for, or undefined when nothing attributes it.
|
|
1241
|
+
*/
|
|
1242
|
+
function sandboxHostPathFor(sandboxPath) {
|
|
1243
|
+
const normalized = posix.normalize(toPosixSlashes(sandboxPath));
|
|
1244
|
+
if (!isPosixAbsolute(normalized)) return void 0;
|
|
1245
|
+
const mounted = mountedHostFor(normalized);
|
|
1246
|
+
if (mounted !== void 0) return {
|
|
1247
|
+
host: mounted.host,
|
|
1248
|
+
workspaceRoot: normalizeHostRoot(mounted.root)
|
|
1249
|
+
};
|
|
1250
|
+
const drive = driveHostFor(normalized);
|
|
1251
|
+
return drive === void 0 ? void 0 : { host: drive };
|
|
1252
|
+
}
|
|
1253
|
+
/** The host directory and workspace a reported mount covers, the deepest mount winning. */
|
|
1254
|
+
function mountedHostFor(sandboxPath) {
|
|
1255
|
+
let found;
|
|
1256
|
+
for (const mounts of reportedMounts.values()) for (const mount of mounts) {
|
|
1257
|
+
const relative = containerRemainder(sandboxPath, mount.sandbox);
|
|
1258
|
+
if (relative === void 0) continue;
|
|
1259
|
+
const depth = posix.normalize(mount.sandbox).length;
|
|
1260
|
+
if (found !== void 0 && found.depth >= depth) continue;
|
|
1261
|
+
found = {
|
|
1262
|
+
depth,
|
|
1263
|
+
root: mount.host,
|
|
1264
|
+
host: relative === "" ? normalizeHostRoot(mount.host) : joinHostRoot(mount.host, relative)
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
return found === void 0 ? void 0 : {
|
|
1268
|
+
host: found.host,
|
|
1269
|
+
root: found.root
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
/** The drive-letter directory a sandbox path spells on a Windows host, when its first segment is a letter. */
|
|
1273
|
+
function driveHostFor(sandboxPath) {
|
|
1274
|
+
const match = /^\/([A-Za-z])(?:\/|$)/.exec(sandboxPath);
|
|
1275
|
+
if (match === null) return void 0;
|
|
1276
|
+
const drive = (match[1] ?? "").toUpperCase();
|
|
1277
|
+
const rest = sandboxPath.slice(2).replaceAll("/", "\\");
|
|
1278
|
+
return rest === "" ? `${drive}:\\` : win32.resolve(`${drive}:${rest}`);
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* The sandbox one specification runs in.
|
|
1282
|
+
* @param spec - the repository container specification.
|
|
1283
|
+
* @returns the declared sandbox name, or the deterministic name of the host root.
|
|
1284
|
+
*/
|
|
1285
|
+
function sandboxNameOf(spec) {
|
|
1286
|
+
return spec.sandbox ?? sandboxNameFor(spec.hostWorkspaceRoot);
|
|
1287
|
+
}
|
|
1288
|
+
/**
|
|
1289
|
+
* The path a specification's workspace has inside its sandbox, as last listed.
|
|
1290
|
+
* @param spec - the repository container specification.
|
|
1291
|
+
* @returns the absolute sandbox path, or undefined when no listing covered the workspace.
|
|
1292
|
+
*/
|
|
1293
|
+
function sbxMountOf(spec) {
|
|
1294
|
+
const mounts = reportedMounts.get(sandboxNameOf(spec));
|
|
1295
|
+
return mounts === void 0 ? void 0 : sandboxMountFor(spec.hostWorkspaceRoot, mounts);
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
1298
|
+
* The target one specification's sandbox becomes.
|
|
1299
|
+
* @param spec - the repository container specification.
|
|
1300
|
+
* @param mounts - the mounts of a fresh listing; when absent, the mounts the last one reported are used.
|
|
1301
|
+
* @returns the sandbox target, with the folder the sandbox really has for this workspace.
|
|
1302
|
+
*/
|
|
1303
|
+
function sbxTargetOf(spec, mounts) {
|
|
1304
|
+
const mounted = mounts === void 0 ? sbxMountOf(spec) : sandboxMountFor(spec.hostWorkspaceRoot, mounts);
|
|
1305
|
+
return {
|
|
1306
|
+
kind: "sbx",
|
|
1307
|
+
sandboxName: sandboxNameOf(spec),
|
|
1308
|
+
workspaceFolder: mounted ?? spec.containerWorkspaceFolder
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* The sandbox view of a declared repository.
|
|
1313
|
+
*
|
|
1314
|
+
* A Dev Container declaration's `/workspaces/<repo>` describes a directory a
|
|
1315
|
+
* sandbox may not have, so the mount takes its place: the folder a listing
|
|
1316
|
+
* reported for this workspace, else {@link sandboxWorkspacePath} — the same path
|
|
1317
|
+
* on a Linux or macOS host, and the drive-letter spelling (`/f/…` for `F:\…`) on
|
|
1318
|
+
* a Windows one. The one exception is a declaration that names `cli: "sbx"`
|
|
1319
|
+
* itself — that repository opted into the sandbox driver, so its own
|
|
1320
|
+
* `workspaceFolder` is the fallback when no mount was reported.
|
|
1321
|
+
* @param spec - the declared specification.
|
|
1322
|
+
* @param mounts - the mounts of a fresh listing; when absent, the mounts the last one reported are used.
|
|
1323
|
+
* @returns the same repository, reachable through `sbx`.
|
|
1324
|
+
*/
|
|
1325
|
+
function asSbxSpec(spec, mounts) {
|
|
1326
|
+
const root = normalizeHostRoot(spec.hostWorkspaceRoot);
|
|
1327
|
+
const declared = spec.cli === "sbx" ? spec.containerWorkspaceFolder : sandboxWorkspacePath(root) ?? root;
|
|
1328
|
+
const mounted = mounts === void 0 ? sbxMountOf(spec) : sandboxMountFor(root, mounts);
|
|
1329
|
+
return {
|
|
1330
|
+
...spec,
|
|
1331
|
+
hostWorkspaceRoot: root,
|
|
1332
|
+
containerWorkspaceFolder: mounted ?? declared,
|
|
1333
|
+
cli: "sbx"
|
|
1334
|
+
};
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* The sandbox specification of one host directory, declared or not.
|
|
1338
|
+
* @param hostWorkspaceRoot - absolute host path of the workspace.
|
|
1339
|
+
* @param options - the row's container defaults.
|
|
1340
|
+
* @param declared - the specification a declaration produced, when one exists.
|
|
1341
|
+
* @param mounts - the mounts of a fresh listing; when absent, the mounts the last one reported are used.
|
|
1342
|
+
* @returns the specification a `(sbx)` session runs under.
|
|
1343
|
+
*/
|
|
1344
|
+
function sbxSpecFor(hostWorkspaceRoot, options, declared, mounts) {
|
|
1345
|
+
const root = normalizeHostRoot(hostWorkspaceRoot);
|
|
1346
|
+
if (declared !== void 0 && normalizeHostRoot(declared.hostWorkspaceRoot) === root) return asSbxSpec(declared, mounts);
|
|
1347
|
+
return asSbxSpec({
|
|
1348
|
+
hostWorkspaceRoot: root,
|
|
1349
|
+
containerWorkspaceFolder: sandboxWorkspacePath(root) ?? root,
|
|
1350
|
+
configPath: "",
|
|
1351
|
+
shell: options.shell,
|
|
1352
|
+
cli: "sbx",
|
|
1353
|
+
ensureUp: options.ensureUp,
|
|
1354
|
+
containerTimeoutMs: options.containerTimeoutMs
|
|
1355
|
+
}, mounts);
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Align a specification with the mount its resolved target reports.
|
|
1359
|
+
*
|
|
1360
|
+
* A specification is built on a path alone, while the folder a sandbox really has
|
|
1361
|
+
* arrives with the listing the resolver performs. Only a sandbox target carries a
|
|
1362
|
+
* different folder; a container the Dev Container CLI declared keeps its own.
|
|
1363
|
+
* @param spec - the specification the caller built.
|
|
1364
|
+
* @param target - the resolved target.
|
|
1365
|
+
* @returns the specification whose mount point is the target's folder.
|
|
1366
|
+
*/
|
|
1367
|
+
function bindSbxMount(spec, target) {
|
|
1368
|
+
return target.kind === "sbx" && target.workspaceFolder !== spec.containerWorkspaceFolder ? {
|
|
1369
|
+
...spec,
|
|
1370
|
+
containerWorkspaceFolder: target.workspaceFolder
|
|
1371
|
+
} : spec;
|
|
1372
|
+
}
|
|
1373
|
+
/** The last lines of a CLI failure, for a diagnostic that fits in one sentence. */
|
|
1374
|
+
function failureDetail(result) {
|
|
1375
|
+
return (result.stderr.trim() || result.stdout.trim() || "no output").split("\n").slice(-3).join(" ");
|
|
1376
|
+
}
|
|
1377
|
+
/**
|
|
1378
|
+
* Create one sandbox around a host workspace, without attaching to it.
|
|
1379
|
+
* @param spec - the sandbox specification.
|
|
1380
|
+
* @param sandboxName - the name to create.
|
|
1381
|
+
* @param run - the CLI runner.
|
|
1382
|
+
* @param signal - cancellation.
|
|
1383
|
+
* @throws Error when `sbx` is missing or the creation failed.
|
|
1384
|
+
*/
|
|
1385
|
+
async function createSandbox(spec, sandboxName, run, signal) {
|
|
1386
|
+
const result = await run([
|
|
1387
|
+
"sbx",
|
|
1388
|
+
"create",
|
|
1389
|
+
"--name",
|
|
1390
|
+
sandboxName,
|
|
1391
|
+
SANDBOX_TEMPLATE,
|
|
1392
|
+
spec.hostWorkspaceRoot
|
|
1393
|
+
], {
|
|
1394
|
+
...signal === void 0 ? {} : { signal },
|
|
1395
|
+
timeoutMs: spec.containerTimeoutMs
|
|
1396
|
+
});
|
|
1397
|
+
if (result.exitCode === null) throw new Error(`sbx: the CLI could not be started. ${SBX_INSTALL_HINT}`);
|
|
1398
|
+
if (result.exitCode !== 0) throw new Error(`sbx: "sbx create" failed for ${spec.hostWorkspaceRoot} (sandbox "${sandboxName}"): ${failureDetail(result)}`);
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* Start one existing sandbox detached, so it survives the command that needed it.
|
|
1402
|
+
* @param spec - the sandbox specification.
|
|
1403
|
+
* @param sandboxName - the sandbox to start.
|
|
1404
|
+
* @param run - the CLI runner.
|
|
1405
|
+
* @param signal - cancellation.
|
|
1406
|
+
* @throws Error when `sbx` is missing or the start failed.
|
|
1407
|
+
*/
|
|
1408
|
+
async function startSandbox(spec, sandboxName, run, signal) {
|
|
1409
|
+
const result = await run([
|
|
1410
|
+
"sbx",
|
|
1411
|
+
"run",
|
|
1412
|
+
"--detach",
|
|
1413
|
+
"--name",
|
|
1414
|
+
sandboxName
|
|
1415
|
+
], {
|
|
1416
|
+
...signal === void 0 ? {} : { signal },
|
|
1417
|
+
timeoutMs: spec.containerTimeoutMs
|
|
1418
|
+
});
|
|
1419
|
+
if (result.exitCode === null) throw new Error(`sbx: the CLI could not be started. ${SBX_INSTALL_HINT}`);
|
|
1420
|
+
if (result.exitCode !== 0) throw new Error(`sbx: "sbx run" could not start sandbox "${sandboxName}": ${failureDetail(result)}`);
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* Confirm the sandbox can run the filesystem helper.
|
|
1424
|
+
*
|
|
1425
|
+
* The helper is a `.mjs` program the sandbox starts with its own `node`, so a
|
|
1426
|
+
* sandbox image without one answers that exec with prose on the helper's pipe
|
|
1427
|
+
* instead of frames. Probing first turns that into a diagnostic that names the
|
|
1428
|
+
* missing runtime and the sandbox that lacks it.
|
|
1429
|
+
* @param spec - the sandbox specification, for its time budget.
|
|
1430
|
+
* @param sandboxName - the running sandbox to probe.
|
|
1431
|
+
* @param run - the CLI runner.
|
|
1432
|
+
* @param signal - cancellation.
|
|
1433
|
+
* @throws Error when the sandbox has no `node` on PATH.
|
|
1434
|
+
*/
|
|
1435
|
+
async function assertSandboxNode(spec, sandboxName, run, signal) {
|
|
1436
|
+
const result = await run([
|
|
1437
|
+
"sbx",
|
|
1438
|
+
"exec",
|
|
1439
|
+
sandboxName,
|
|
1440
|
+
"--",
|
|
1441
|
+
"which",
|
|
1442
|
+
"node"
|
|
1443
|
+
], {
|
|
1444
|
+
...signal === void 0 ? {} : { signal },
|
|
1445
|
+
timeoutMs: spec.containerTimeoutMs
|
|
1446
|
+
});
|
|
1447
|
+
if (result.exitCode === 0 && result.stdout.trim() !== "") return;
|
|
1448
|
+
throw new Error(`sbx: Docker Sandbox "${sandboxName}" does not have Node.js installed, so the filesystem bridge and the tools that use it cannot run there. Install Node.js 18 or newer inside the sandbox (for example "sbx exec ${sandboxName} -- sudo apt-get install -y nodejs", or an official tarball from nodejs.org unpacked into /usr/local), then retry. The probe "sbx exec ${sandboxName} -- which node" reported: ${failureDetail(result)}`);
|
|
1449
|
+
}
|
|
1450
|
+
/**
|
|
1451
|
+
* Resolve the sandbox agent commands run in, creating or starting it when asked.
|
|
1452
|
+
*
|
|
1453
|
+
* A sandbox that `sbx ls` lists as running is used as it is. Otherwise, and only
|
|
1454
|
+
* with `ensureUp`, a missing sandbox is created around the host workspace and an
|
|
1455
|
+
* existing one is started detached. Without `ensureUp` the resolver reports the
|
|
1456
|
+
* state instead of changing it.
|
|
1457
|
+
*
|
|
1458
|
+
* Either way the sandbox is probed for `node` before it is returned: without one
|
|
1459
|
+
* it cannot start the filesystem helper, and reporting the missing runtime here
|
|
1460
|
+
* is more useful than the broken pipe it would otherwise cause.
|
|
1461
|
+
*
|
|
1462
|
+
* The listing also names the mounts, so the returned target carries the folder
|
|
1463
|
+
* the sandbox really has for this workspace instead of the host spelling.
|
|
1464
|
+
* @param spec - the sandbox specification.
|
|
1465
|
+
* @param run - the CLI runner.
|
|
1466
|
+
* @param signal - cancellation of the probe / start sequence.
|
|
1467
|
+
* @returns the sandbox target.
|
|
1468
|
+
* @throws Error when `sbx` is missing, the sandbox cannot be prepared, one is required and absent, or it has no Node.js.
|
|
1469
|
+
*/
|
|
1470
|
+
async function resolveSbxTarget(spec, run, signal) {
|
|
1471
|
+
const name = sandboxNameOf(spec);
|
|
1472
|
+
const listing = await listSandboxes(run, spec.containerTimeoutMs, signal);
|
|
1473
|
+
if (!listing.available) throw new Error(`sbx: ${SBX_INSTALL_HINT}`);
|
|
1474
|
+
const listed = listing.sandboxes.find((sandbox) => sandbox.name === name);
|
|
1475
|
+
const target = sbxTargetOf(spec, listed?.mounts ?? []);
|
|
1476
|
+
if (listed?.running === true) {
|
|
1477
|
+
await assertSandboxNode(spec, name, run, signal);
|
|
1478
|
+
return target;
|
|
1479
|
+
}
|
|
1480
|
+
if (!spec.ensureUp) throw new Error(listed === void 0 ? `sbx: no Docker Sandbox named "${name}" exists for "${spec.hostWorkspaceRoot}"; create it with "sbx create --name ${name} ${SANDBOX_TEMPLATE} ${spec.hostWorkspaceRoot}", or set ensureUp: true` : `sbx: Docker Sandbox "${name}" for "${spec.hostWorkspaceRoot}" is not running; start it with "sbx run --detach --name ${name}", or set ensureUp: true`);
|
|
1481
|
+
if (listed === void 0) await createSandbox(spec, name, run, signal);
|
|
1482
|
+
await startSandbox(spec, name, run, signal);
|
|
1483
|
+
await assertSandboxNode(spec, name, run, signal);
|
|
1484
|
+
return target;
|
|
1485
|
+
}
|
|
1486
|
+
//#endregion
|
|
1487
|
+
export { variantNameSuffixOf as A, toPosixSlashes as B, presetKindOf as C, VARIANT_KINDS as D, sbxRefusalText as E, isWindowsPath as F, containerOptions as H, joinHostRoot as I, relativeWithinHostRoot as L, hostPathStyle as M, isPathInsideContainer as N, variantIdOf as O, isPosixAbsolute as P, toContainerPath as R, markedVariantKind as S, refusedExecution as T, presetSourceFields as U, containerOptionFields as V, containerPresetOf as _, sandboxNameFor as a, markedContainerOnly as b, sbxWorkspaceRootFor as c, DEVCONTAINER_ENV_KEY as d, DEVCONTAINER_PRESET_ENV_KEY as f, callingVariantKind as g, callingContainerPreset as h, sandboxHostPathFor as i, containerRemainder as j, variantKindOf as k, repoRegistry as l, SBX_PRESET_ENV_KEY as m, bindSbxMount as n, sandboxWorkspacePath as o, SBX_ENV_KEY as p, resolveSbxTarget as r, sbxSpecFor as s, asSbxSpec as t, CONTAINER_MARKER_KEYS as u, fsEscapeRefusalText as v, refusalText as w, markedPreset as x, fsRefusalText as y, toHostPath as z };
|
|
1488
|
+
|
|
1489
|
+
//# sourceMappingURL=sbx-1GsFjQBk.js.map
|