@banzhe/dsh-devcontainer 0.0.0-stage → 0.2.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/lib/fs.js ADDED
@@ -0,0 +1,1737 @@
1
+ import { B as toPosixSlashes, C as presetKindOf, F as isWindowsPath, H as containerOptions, I as joinHostRoot, L as relativeWithinHostRoot, M as hostPathStyle, N as isPathInsideContainer, P as isPosixAbsolute, R as toContainerPath, V as containerOptionFields, c as sbxWorkspaceRootFor, h as callingContainerPreset, i as sandboxHostPathFor, j as containerRemainder, l as repoRegistry, n as bindSbxMount, o as sandboxWorkspacePath, s as sbxSpecFor, t as asSbxSpec, v as fsEscapeRefusalText, y as fsRefusalText, z as toHostPath } from "./sbx-1GsFjQBk.js";
2
+ import { n as runContainerCommand, r as resolveContainerTarget, t as containerCliEnv } from "./exec-CKAAz2zz.js";
3
+ import z from "@deepseek-ai/schemastery";
4
+ import { dirname, join, posix } from "node:path";
5
+ import { readFileSync } from "node:fs";
6
+ import { randomUUID } from "node:crypto";
7
+ import "@deepseek-ai/cordis";
8
+ import { spawn } from "node:child_process";
9
+ import { FsError, FsTargetKey, FsVersion } from "@deepseek-ai/dsh-fs";
10
+ import { SandboxedFileSystem } from "@deepseek-ai/dsh-fs-sandbox";
11
+ import { fileURLToPath } from "node:url";
12
+ //#region src/helper-source.ts
13
+ /**
14
+ * The container-side helper program, as text.
15
+ *
16
+ * The source ships as a plain \`.mjs\` next to the bundled rows because the
17
+ * container runs it with its own \`node\` — nothing in this repository compiles it.
18
+ * Both layouts resolve through the same relative path: \`src/helper/main.mjs\`
19
+ * while running from source, and \`lib/helper/main.mjs\` in the built package.
20
+ * @module @banzhe/dsh-devcontainer/helper-source
21
+ */
22
+ /** Where the helper program lives inside the container. */
23
+ const HELPER_CONTAINER_PATH = "/tmp/.dsh-devcontainer/helper.mjs";
24
+ /** The container directory the helper is staged in. */
25
+ const HELPER_CONTAINER_DIRECTORY = "/tmp/.dsh-devcontainer";
26
+ let cached;
27
+ /**
28
+ * The absolute path of the helper program on this host.
29
+ * @returns the path of the shipped \`main.mjs\`.
30
+ */
31
+ function helperSourcePath() {
32
+ return join(dirname(fileURLToPath(import.meta.url)), "helper", "main.mjs");
33
+ }
34
+ /**
35
+ * Read the helper program that is staged into the container.
36
+ * @returns the program text, read once per process.
37
+ * @throws Error naming the missing path when the packaged file is absent.
38
+ */
39
+ function helperSource() {
40
+ if (cached !== void 0) return cached;
41
+ const path = helperSourcePath();
42
+ try {
43
+ cached = readFileSync(path, "utf8");
44
+ } catch (error) {
45
+ throw new Error(`devcontainer: cannot read the container helper at "${path}"; reinstall the bundle`, { cause: error });
46
+ }
47
+ return cached;
48
+ }
49
+ //#endregion
50
+ //#region src/rpc/errors.ts
51
+ /**
52
+ * The failure vocabulary of the container filesystem RPC.
53
+ *
54
+ * The helper answers with a `error` frame whose `code` is already a DSH filesystem
55
+ * code, because it maps POSIX errno values (`ENOENT`, `EACCES`, `EISDIR`, ...)
56
+ * inside the container. This module translates that back into the seam's own
57
+ * `FsError`, so a caller cannot tell a remote refusal from a local one.
58
+ * @module @banzhe/dsh-devcontainer/rpc/errors
59
+ */
60
+ /**
61
+ * The seam's failure codes, as a runtime set.
62
+ *
63
+ * The array is typed by `FsErrorCode`, so a code this DSH version does not have
64
+ * fails the build instead of silently becoming a generic I/O failure.
65
+ */
66
+ const FS_ERROR_CODES = [
67
+ "FS_NOT_FOUND",
68
+ "FS_NOT_DIRECTORY",
69
+ "FS_NOT_TEXT",
70
+ "FS_NOT_REGULAR_FILE",
71
+ "FS_TOO_LARGE",
72
+ "FS_PERMISSION_DENIED",
73
+ "FS_SANDBOX_DENIED",
74
+ "FS_IO_ERROR",
75
+ "FS_STALE_VERSION",
76
+ "FS_NOT_OBSERVED",
77
+ "FS_AMBIGUOUS_EDIT",
78
+ "FS_EDIT_NOT_FOUND",
79
+ "FS_ABORTED"
80
+ ];
81
+ const KNOWN_CODES$1 = new Set(FS_ERROR_CODES);
82
+ /**
83
+ * A failure the container helper reported.
84
+ *
85
+ * It stays a distinct class so the transport and the filesystem vocabulary are
86
+ * separable: a `code` the seam does not know (an unexpected remote failure)
87
+ * becomes a generic I/O failure rather than an invented taxonomy entry.
88
+ */
89
+ var RpcOperationError = class extends Error {
90
+ /** The remote filesystem code, when the helper named one. */
91
+ code;
92
+ /**
93
+ * @param message - the remote diagnostic.
94
+ * @param code - the remote `FS_*` code, when it has one.
95
+ */
96
+ constructor(message, code) {
97
+ super(message);
98
+ this.name = "RpcOperationError";
99
+ this.code = code;
100
+ }
101
+ };
102
+ /**
103
+ * Translate one remote or transport failure into the seam's typed error.
104
+ * @param error - whatever the channel rejected with.
105
+ * @param signal - the caller's cancellation signal, for attributing an abort.
106
+ * @returns the `FsError` the filesystem seam reports.
107
+ */
108
+ function rpcFsError(error, signal) {
109
+ if (error instanceof FsError) return error;
110
+ if (error instanceof RpcOperationError && error.code !== void 0 && KNOWN_CODES$1.has(error.code)) return new FsError(error.message, error.code, { cause: error });
111
+ if (signal?.aborted === true) return new FsError("the container filesystem operation was cancelled", "FS_ABORTED", { cause: error });
112
+ const message = error instanceof Error ? error.message : String(error);
113
+ return new FsError(message, "FS_IO_ERROR", { cause: error });
114
+ }
115
+ /**
116
+ * Encode one frame as a length header plus its JSON body.
117
+ * @param frame - the frame to encode.
118
+ * @returns the bytes to write to the pipe.
119
+ * @throws Error when the encoded body is empty or larger than {@link MAX_FRAME_BYTES}.
120
+ */
121
+ function encodeFrame(frame) {
122
+ const body = Buffer.from(JSON.stringify(frame), "utf8");
123
+ if (body.length === 0 || body.length > 67108864) throw new Error(`devcontainer: refusing to send a ${body.length}-byte RPC frame`);
124
+ const bytes = Buffer.allocUnsafe(4 + body.length);
125
+ bytes.writeUInt32BE(body.length, 0);
126
+ body.copy(bytes, 4);
127
+ return bytes;
128
+ }
129
+ function isRecord(value) {
130
+ return typeof value === "object" && value !== null && !Array.isArray(value);
131
+ }
132
+ /**
133
+ * Validate one decoded frame.
134
+ * @param value - the parsed JSON document.
135
+ * @returns the frame, typed.
136
+ * @throws Error when the document is not one of the four frame shapes.
137
+ */
138
+ function parseFrame(value) {
139
+ if (!isRecord(value)) throw new Error("devcontainer: RPC frame is not an object");
140
+ const { type, id } = value;
141
+ if (typeof id !== "string" || id.length === 0) throw new Error("devcontainer: RPC frame carries no request id");
142
+ if (type === "request") {
143
+ if (typeof value.method !== "string" || value.method.length === 0) throw new Error("devcontainer: RPC request frame carries no method");
144
+ return {
145
+ type,
146
+ id,
147
+ method: value.method,
148
+ params: value.params
149
+ };
150
+ }
151
+ if (type === "result") return {
152
+ type,
153
+ id,
154
+ value: value.value
155
+ };
156
+ if (type === "cancel") return {
157
+ type,
158
+ id
159
+ };
160
+ if (type === "error") {
161
+ const error = value.error;
162
+ if (!isRecord(error) || typeof error.message !== "string") throw new Error("devcontainer: RPC error frame carries no message");
163
+ return {
164
+ type,
165
+ id,
166
+ error: {
167
+ name: typeof error.name === "string" ? error.name : "Error",
168
+ message: error.message,
169
+ ...typeof error.code === "string" ? { code: error.code } : {}
170
+ }
171
+ };
172
+ }
173
+ throw new Error(`devcontainer: unknown RPC frame type "${String(type)}"`);
174
+ }
175
+ /**
176
+ * Buffered decoder: pipe chunks arrive at arbitrary boundaries, frames do not.
177
+ *
178
+ * The header of a frame in progress is retained across chunks, and so is its
179
+ * body, so a peer may split a frame anywhere.
180
+ */
181
+ var FrameDecoder = class {
182
+ header = Buffer.alloc(4);
183
+ headerBytes = 0;
184
+ payload;
185
+ payloadBytes = 0;
186
+ /**
187
+ * Consume one chunk.
188
+ * @param chunk - bytes read from the pipe.
189
+ * @returns every frame the chunk completed, in arrival order.
190
+ * @throws Error when a frame declares an impossible length or is not JSON.
191
+ */
192
+ push(chunk) {
193
+ const frames = [];
194
+ let offset = 0;
195
+ while (offset < chunk.length) {
196
+ if (this.payload === void 0) {
197
+ const count = Math.min(4 - this.headerBytes, chunk.length - offset);
198
+ chunk.copy(this.header, this.headerBytes, offset, offset + count);
199
+ this.headerBytes += count;
200
+ offset += count;
201
+ if (this.headerBytes < 4) continue;
202
+ const size = this.header.readUInt32BE(0);
203
+ if (size === 0 || size > 67108864) throw new Error(`devcontainer: peer announced an invalid ${size}-byte RPC frame`);
204
+ this.payload = Buffer.alloc(size);
205
+ this.payloadBytes = 0;
206
+ }
207
+ const count = Math.min(this.payload.length - this.payloadBytes, chunk.length - offset);
208
+ chunk.copy(this.payload, this.payloadBytes, offset, offset + count);
209
+ this.payloadBytes += count;
210
+ offset += count;
211
+ if (this.payloadBytes === this.payload.length) {
212
+ const body = this.payload.toString("utf8");
213
+ this.payload = void 0;
214
+ this.headerBytes = 0;
215
+ let decoded;
216
+ try {
217
+ decoded = JSON.parse(body);
218
+ } catch (error) {
219
+ throw new Error("devcontainer: peer sent a frame that is not JSON", { cause: error });
220
+ }
221
+ frames.push(parseFrame(decoded));
222
+ }
223
+ }
224
+ return frames;
225
+ }
226
+ /**
227
+ * Whether bytes of an unfinished frame are buffered.
228
+ * @returns true when the peer stopped mid-frame.
229
+ */
230
+ get pending() {
231
+ return this.headerBytes > 0 || this.payload !== void 0;
232
+ }
233
+ /**
234
+ * The buffered header bytes read as text, when they are printable ASCII.
235
+ *
236
+ * A runtime that cannot start the helper answers the pipe with its own exec
237
+ * diagnostic instead of frames, and those first four bytes decode as a length
238
+ * far above {@link MAX_FRAME_BYTES}. No accepted length can look like this:
239
+ * every frame under the limit starts with a byte below `0x05`, and the rest of
240
+ * the printable range begins at `0x20`.
241
+ * @returns the printable prefix buffered so far, or undefined when the bytes are a frame header.
242
+ */
243
+ get proseHeader() {
244
+ if (this.headerBytes === 0) return void 0;
245
+ const bytes = this.header.subarray(0, this.headerBytes);
246
+ for (const byte of bytes) if (!(byte === 9 || byte === 10 || byte === 13) && (byte < 32 || byte > 126)) return void 0;
247
+ return bytes.toString("utf8");
248
+ }
249
+ };
250
+ //#endregion
251
+ //#region src/rpc/client.ts
252
+ /**
253
+ * The host half of the container filesystem RPC: one persistent
254
+ * `docker exec -i <container> node <helper>` pipe that carries framed requests.
255
+ *
256
+ * The channel owns the whole exchange — staging the helper into the container,
257
+ * the `hello` handshake, request/response correlation, cancellation, and the
258
+ * teardown that fails every pending call when the pipe dies. It never replays a
259
+ * request: a caller that loses the connection learns that the remote outcome is
260
+ * unknown, which is the only honest answer for a mutation that may have
261
+ * committed.
262
+ * @module @banzhe/dsh-devcontainer/rpc/client
263
+ */
264
+ /** Request budget when the row configures none. */
265
+ const DEFAULT_RPC_TIMEOUT_MS = 6e4;
266
+ /** Requests one channel may have in flight before it refuses more. */
267
+ const DEFAULT_MAX_PENDING = 256;
268
+ /** Diagnostic bytes kept from the helper's own streams, for the failure that needs them. */
269
+ const DIAGNOSTIC_BYTES = 4096;
270
+ /**
271
+ * Start one child with the filtered CLI environment, so a Docker call carries
272
+ * neither the harness's credentials nor the session's `DSH_*` facts.
273
+ * @param argv - program and arguments, never shell-interpreted.
274
+ * @param options - optional working directory.
275
+ * @returns the child with its piped streams and exit promise.
276
+ */
277
+ const spawnContainerChild = (argv, options = {}) => {
278
+ const [program, ...args] = argv;
279
+ if (program === void 0) throw new Error("devcontainer: empty command");
280
+ const child = spawn(program, args, {
281
+ stdio: [
282
+ "pipe",
283
+ "pipe",
284
+ "pipe"
285
+ ],
286
+ windowsHide: true,
287
+ env: containerCliEnv(),
288
+ ...options.cwd === void 0 ? {} : { cwd: options.cwd }
289
+ });
290
+ child.stdin.on("error", () => {});
291
+ const exited = new Promise((resolve) => {
292
+ child.once("exit", (code, signal) => {
293
+ resolve({
294
+ code,
295
+ signal
296
+ });
297
+ });
298
+ child.once("error", () => {
299
+ resolve({
300
+ code: null,
301
+ signal: null
302
+ });
303
+ });
304
+ });
305
+ return {
306
+ stdin: child.stdin,
307
+ stdout: child.stdout,
308
+ stderr: child.stderr,
309
+ exited,
310
+ kill: (signal) => {
311
+ child.kill(signal);
312
+ }
313
+ };
314
+ };
315
+ /**
316
+ * The argv that runs one program inside the runtime.
317
+ *
318
+ * Both drivers take `-i` so the helper keeps its stdio pipe; `sbx` separates its
319
+ * own flags from the command with `--`, which `docker exec` does not need.
320
+ * @param target - the runtime to run in.
321
+ * @param program - the program and its arguments, never shell-interpreted.
322
+ * @returns the complete argv.
323
+ */
324
+ function runtimeExecArgv(target, program) {
325
+ switch (target.kind) {
326
+ case "docker": return [
327
+ "docker",
328
+ "exec",
329
+ "-i",
330
+ target.containerId,
331
+ ...program
332
+ ];
333
+ case "sbx": return [
334
+ "sbx",
335
+ "exec",
336
+ "-i",
337
+ target.sandboxName,
338
+ "--",
339
+ ...program
340
+ ];
341
+ }
342
+ }
343
+ /**
344
+ * How a diagnostic names one runtime.
345
+ * @param target - the runtime.
346
+ * @returns `container "<id>"` or `sandbox "<name>"`.
347
+ */
348
+ function runtimeLabel(target) {
349
+ return target.kind === "sbx" ? `sandbox "${target.sandboxName}"` : `container "${target.containerId}"`;
350
+ }
351
+ /** A promise and its settlement functions, for the pending-request table. */
352
+ function deferred() {
353
+ let resolve;
354
+ let reject;
355
+ return {
356
+ promise: new Promise((settle, fail) => {
357
+ resolve = settle;
358
+ reject = fail;
359
+ }),
360
+ resolve,
361
+ reject
362
+ };
363
+ }
364
+ /** Keep the last bytes of a stream, for the failure message that needs them. */
365
+ function tail(current, chunk) {
366
+ const merged = current + chunk;
367
+ return merged.length <= DIAGNOSTIC_BYTES ? merged : merged.slice(merged.length - DIAGNOSTIC_BYTES);
368
+ }
369
+ /** Keep the first bytes of a stream, for the failure message that needs them. */
370
+ function head(current, chunk) {
371
+ const merged = current + chunk;
372
+ return merged.length <= DIAGNOSTIC_BYTES ? merged : merged.slice(0, DIAGNOSTIC_BYTES);
373
+ }
374
+ /**
375
+ * Resolve once a scope aborts; never reject, because it only ends a race.
376
+ * @param scope - the scope to watch.
377
+ * @returns a promise that settles when the scope aborts.
378
+ */
379
+ function abortedScope(scope) {
380
+ if (scope.aborted) return Promise.resolve();
381
+ return new Promise((resolve) => {
382
+ scope.addEventListener("abort", () => {
383
+ resolve();
384
+ }, { once: true });
385
+ });
386
+ }
387
+ /** Race one promise against the request budget and the caller's cancellation. */
388
+ async function withDeadline(promise, timeoutMs, signal, what) {
389
+ const timeout = AbortSignal.timeout(timeoutMs);
390
+ const scope = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
391
+ const expired = new Promise((_resolve, reject) => {
392
+ scope.addEventListener("abort", () => {
393
+ reject(/* @__PURE__ */ new Error(signal?.aborted === true ? `devcontainer: ${what} was cancelled` : `devcontainer: ${what} timed out after ${timeoutMs} ms`));
394
+ }, { once: true });
395
+ });
396
+ return await Promise.race([promise, expired]);
397
+ }
398
+ /**
399
+ * Write the helper program into the runtime and wait for the write to land.
400
+ * @param spawn - the process starter.
401
+ * @param target - the runtime to stage into.
402
+ * @param timeoutMs - budget for the whole stage.
403
+ * @param signal - cancellation.
404
+ * @throws Error when the runtime rejects the write or the budget expires.
405
+ */
406
+ async function stageHelper(spawn, target, timeoutMs, signal) {
407
+ const child = spawn(runtimeExecArgv(target, [
408
+ "sh",
409
+ "-c",
410
+ `mkdir -p ${HELPER_CONTAINER_DIRECTORY} && cat > ${HELPER_CONTAINER_PATH}`
411
+ ]));
412
+ let stderr = "";
413
+ child.stderr.on("data", (chunk) => {
414
+ stderr = tail(stderr, chunk.toString("utf8"));
415
+ });
416
+ const source = helperSource();
417
+ try {
418
+ child.stdin.end(source, "utf8");
419
+ } catch {}
420
+ const exit = await withDeadline(child.exited, timeoutMs, signal, "staging the filesystem helper");
421
+ if (exit.code !== 0) {
422
+ const detail = stderr.trim() === "" ? "no output" : stderr.trim();
423
+ throw new Error(`devcontainer: cannot stage the filesystem helper in ${runtimeLabel(target)} (exit ${exit.code === null ? "unknown" : exit.code}): ${detail}`);
424
+ }
425
+ }
426
+ /**
427
+ * One live request/response pipe to a container's filesystem helper.
428
+ *
429
+ * A channel is single-use in the sense that matters: once the pipe fails, every
430
+ * later call rejects, and the pool that owns it opens a fresh one. Nothing is
431
+ * replayed, because a mutation that died mid-flight has an unknown outcome.
432
+ */
433
+ var ContainerRpcChannel = class ContainerRpcChannel {
434
+ pending = /* @__PURE__ */ new Map();
435
+ decoder = new FrameDecoder();
436
+ child;
437
+ label;
438
+ timeoutMs;
439
+ maxPending;
440
+ closed = deferred();
441
+ writeTail = Promise.resolve();
442
+ stderrTail = "";
443
+ preface = "";
444
+ proseOnly = false;
445
+ framesStarted = false;
446
+ failure;
447
+ handshakeValue;
448
+ constructor(child, label, timeoutMs, maxPending) {
449
+ this.child = child;
450
+ this.label = label;
451
+ this.timeoutMs = timeoutMs;
452
+ this.maxPending = maxPending;
453
+ child.stdout.on("data", (chunk) => {
454
+ this.consume(chunk);
455
+ });
456
+ child.stdout.on("error", (error) => {
457
+ this.fail(error);
458
+ });
459
+ child.stderr.on("data", (chunk) => {
460
+ this.stderrTail = tail(this.stderrTail, chunk.toString("utf8"));
461
+ });
462
+ child.exited.then((exit) => {
463
+ this.fail(this.proseOnly ? this.proseFailure(exit) : this.transportFailure(exit));
464
+ }, () => {
465
+ this.fail(/* @__PURE__ */ new Error("devcontainer: the container filesystem helper could not be started"));
466
+ });
467
+ }
468
+ /**
469
+ * Stage the helper, start its process, and complete the handshake.
470
+ * @param options - the container, its workspace, and the process starter.
471
+ * @returns the open channel.
472
+ * @throws Error when staging, the process start, or the handshake fails.
473
+ */
474
+ static async open(options) {
475
+ const spawn = options.spawn ?? spawnContainerChild;
476
+ const timeoutMs = options.timeoutMs ?? 6e4;
477
+ const target = options.target;
478
+ await stageHelper(spawn, target, timeoutMs, void 0);
479
+ const child = spawn(runtimeExecArgv(target, ["node", HELPER_CONTAINER_PATH]));
480
+ const channel = new ContainerRpcChannel(child, runtimeLabel(target), timeoutMs, options.maxPending ?? DEFAULT_MAX_PENDING);
481
+ try {
482
+ const hello = await channel.request("hello", {
483
+ protocol: 3,
484
+ workspace: target.workspace
485
+ }, { timeoutMs });
486
+ if (hello.protocol !== 3) throw new Error(`devcontainer: the container helper speaks protocol ${hello.protocol}, not 3`);
487
+ for (const field of [
488
+ "platform",
489
+ "nodeVersion",
490
+ "workspace",
491
+ "workspaceReal"
492
+ ]) if (typeof hello[field] !== "string") throw new Error(`devcontainer: the container helper sent no ${field}`);
493
+ channel.handshakeValue = hello;
494
+ return channel;
495
+ } catch (error) {
496
+ await channel.close();
497
+ throw error;
498
+ }
499
+ }
500
+ /** What the helper reported during the handshake. */
501
+ get handshake() {
502
+ if (this.handshakeValue === void 0) throw new Error("devcontainer: the container helper is not handshaken");
503
+ return this.handshakeValue;
504
+ }
505
+ /** Whether the pipe failed or was closed; a closed channel never recovers. */
506
+ get isClosed() {
507
+ return this.failure !== void 0;
508
+ }
509
+ /** Resolves once the channel is unusable. */
510
+ get closedPromise() {
511
+ return this.closed.promise;
512
+ }
513
+ /**
514
+ * Send one request and settle with the helper's answer.
515
+ *
516
+ * The frame is written under the same scope as the answer, so the budget and
517
+ * the caller's cancellation end a write that is still waiting for a pipe that
518
+ * will not take the bytes. A pipe that stays wedged is reset rather than left
519
+ * to block every later request behind the same write.
520
+ * @param method - the helper operation, for example `fs.readText`.
521
+ * @param params - JSON parameters.
522
+ * @param options - cancellation and a per-request budget.
523
+ * @returns the validated remote value.
524
+ * @throws RpcOperationError for a remote failure, Error for transport, cancellation and timeouts.
525
+ */
526
+ async request(method, params, options = {}) {
527
+ const { signal } = options;
528
+ if (this.failure !== void 0) throw this.failure;
529
+ signal?.throwIfAborted();
530
+ if (this.pending.size >= this.maxPending) throw new Error(`devcontainer: the container filesystem helper already has ${this.pending.size} pending requests`);
531
+ const id = randomUUID();
532
+ const settled = deferred();
533
+ settled.promise.catch(() => {});
534
+ this.pending.set(id, {
535
+ resolve: (value) => {
536
+ settled.resolve(value);
537
+ },
538
+ reject: (error) => {
539
+ settled.reject(error);
540
+ }
541
+ });
542
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
543
+ const timeout = AbortSignal.timeout(timeoutMs);
544
+ const scope = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
545
+ const giveUp = () => /* @__PURE__ */ new Error(signal?.aborted === true ? `devcontainer: "${method}" was cancelled` : `devcontainer: "${method}" timed out after ${timeoutMs} ms`);
546
+ const cancel = () => {
547
+ this.pending.delete(id);
548
+ this.send({
549
+ type: "cancel",
550
+ id
551
+ }).catch(() => {});
552
+ settled.reject(giveUp());
553
+ };
554
+ scope.addEventListener("abort", cancel, { once: true });
555
+ try {
556
+ await this.send({
557
+ type: "request",
558
+ id,
559
+ method,
560
+ params
561
+ }, {
562
+ scope,
563
+ failure: giveUp
564
+ });
565
+ return await settled.promise;
566
+ } catch (error) {
567
+ this.pending.delete(id);
568
+ throw error;
569
+ } finally {
570
+ scope.removeEventListener("abort", cancel);
571
+ }
572
+ }
573
+ /**
574
+ * Probe the helper's liveness.
575
+ * @param options - cancellation and a per-request budget.
576
+ * @returns the helper's clock, once it answered.
577
+ */
578
+ async ping(options = {}) {
579
+ return await this.request("ping", {}, options);
580
+ }
581
+ /**
582
+ * Stop the helper and fail everything still pending.
583
+ * @param reason - the failure reported to pending callers; a closure message by default.
584
+ */
585
+ async close(reason) {
586
+ this.fail(reason ?? /* @__PURE__ */ new Error("devcontainer: the container filesystem channel was closed"));
587
+ await this.closed.promise;
588
+ }
589
+ consume(chunk) {
590
+ if (!this.framesStarted) this.preface = head(this.preface, chunk.toString("utf8"));
591
+ if (this.proseOnly) return;
592
+ let frames;
593
+ try {
594
+ frames = this.decoder.push(chunk);
595
+ } catch (error) {
596
+ if (this.decoder.proseHeader !== void 0) {
597
+ this.proseOnly = true;
598
+ return;
599
+ }
600
+ this.fail(error instanceof Error ? error : new Error(String(error)));
601
+ return;
602
+ }
603
+ for (const frame of frames) this.receive(frame);
604
+ if (frames.length > 0) {
605
+ this.framesStarted = true;
606
+ this.preface = "";
607
+ }
608
+ }
609
+ receive(frame) {
610
+ if (frame.type === "result" || frame.type === "error") {
611
+ const pending = this.pending.get(frame.id);
612
+ if (pending === void 0) return;
613
+ this.pending.delete(frame.id);
614
+ if (frame.type === "result") pending.resolve(frame.value);
615
+ else pending.reject(new RpcOperationError(frame.error.message, frame.error.code));
616
+ return;
617
+ }
618
+ this.fail(/* @__PURE__ */ new Error(`devcontainer: the container helper sent an unexpected ${frame.type} frame`));
619
+ }
620
+ /**
621
+ * Put one frame on the pipe.
622
+ * @param frame - the frame to write.
623
+ * @param interruption - ends the write when the caller behind it gives up; omitted for the frames the channel writes on its own behalf.
624
+ * @throws Error when the channel is broken, or when the interruption ended the write.
625
+ */
626
+ async send(frame, interruption) {
627
+ if (this.failure !== void 0) throw this.failure;
628
+ const bytes = encodeFrame(frame);
629
+ const write = this.writeTail.then(async () => {
630
+ this.throwIfBroken();
631
+ if (interruption === void 0) {
632
+ if (!this.child.stdin.write(bytes)) await this.awaitDrain();
633
+ this.throwIfBroken();
634
+ return;
635
+ }
636
+ if (interruption.scope.aborted) throw interruption.failure();
637
+ if (this.child.stdin.write(bytes)) return;
638
+ const drained = await this.awaitDrain(interruption.scope);
639
+ this.throwIfBroken();
640
+ if (drained) return;
641
+ this.fail(/* @__PURE__ */ new Error("devcontainer: the container filesystem pipe stopped draining; the channel was closed"));
642
+ throw interruption.failure();
643
+ });
644
+ this.writeTail = write.catch(() => {});
645
+ if (interruption === void 0) {
646
+ await write;
647
+ return;
648
+ }
649
+ await Promise.race([write, abortedScope(interruption.scope)]);
650
+ }
651
+ /**
652
+ * Wait for the pipe to take buffered bytes.
653
+ * @param scope - ends the wait when the caller gives up.
654
+ * @returns true when the pipe drained, false when the wait ended another way.
655
+ * @throws Error when the pipe died during the wait.
656
+ */
657
+ async awaitDrain(scope) {
658
+ let onDrain = () => {};
659
+ const drained = new Promise((resolve) => {
660
+ onDrain = () => {
661
+ this.child.stdin.off("drain", onDrain);
662
+ resolve(true);
663
+ };
664
+ });
665
+ this.child.stdin.once("drain", onDrain);
666
+ let stopped;
667
+ try {
668
+ return await Promise.race([
669
+ drained,
670
+ this.closed.promise.then(() => false),
671
+ ...scope === void 0 ? [] : [new Promise((resolve) => {
672
+ stopped = () => {
673
+ resolve(false);
674
+ };
675
+ scope.addEventListener("abort", stopped, { once: true });
676
+ })]
677
+ ]);
678
+ } finally {
679
+ this.child.stdin.off("drain", onDrain);
680
+ if (stopped !== void 0 && scope !== void 0) scope.removeEventListener("abort", stopped);
681
+ }
682
+ }
683
+ /** Re-read the channel state, which an awaited step may have changed. */
684
+ throwIfBroken() {
685
+ const failure = this.failure;
686
+ if (failure !== void 0) throw failure;
687
+ }
688
+ transportFailure(exit) {
689
+ const detail = this.stderrTail.trim() === "" ? "no output" : this.stderrTail.trim();
690
+ const status = exit.signal !== null ? `signal ${exit.signal}` : `exit ${exit.code === null ? "unknown" : exit.code}`;
691
+ return /* @__PURE__ */ new Error(`devcontainer: the container filesystem helper stopped (${status}): ${detail}. The outcome of any request that was in flight is unknown.`);
692
+ }
693
+ /**
694
+ * The failure of a pipe that answered with prose instead of frames.
695
+ *
696
+ * A runtime without the `node` the helper needs replies with its own exec
697
+ * diagnostic, so the first four bytes of `exec: ...` decode as a length header
698
+ * of 1702389091 bytes. Reporting the frame size hides the cause; the collected
699
+ * text is what the reader can act on.
700
+ */
701
+ proseFailure(exit) {
702
+ const status = exit.signal !== null ? `signal ${exit.signal}` : `exit ${exit.code === null ? "unknown" : exit.code}`;
703
+ const detail = this.preface.trim() === "" ? "no output" : this.preface.trim();
704
+ return /* @__PURE__ */ new Error(`devcontainer: the filesystem helper could not be started in ${this.label} (${status}); the runtime answered its pipe with text instead of RPC frames: ${detail}`);
705
+ }
706
+ fail(error) {
707
+ if (this.failure !== void 0) return;
708
+ const partial = this.proseOnly ? false : this.decoder.pending;
709
+ this.failure = partial ? new Error(`${error.message} (the pipe ended inside a frame)`, { cause: error }) : error;
710
+ for (const pending of this.pending.values()) pending.reject(this.failure);
711
+ this.pending.clear();
712
+ this.closed.resolve();
713
+ try {
714
+ this.child.kill("SIGTERM");
715
+ } catch {}
716
+ }
717
+ };
718
+ //#endregion
719
+ //#region src/rpc/pool.ts
720
+ /**
721
+ * The channel pool: one live RPC pipe per container, shared by every filesystem
722
+ * call in a composition and re-opened after the pipe or the container dies.
723
+ *
724
+ * A shared open is deliberately not cancellable by one caller's signal: another
725
+ * caller may be waiting for the same handshake, and aborting the open would
726
+ * destroy their connection too. Callers check their own signal before joining.
727
+ * @module @banzhe/dsh-devcontainer/rpc/pool
728
+ */
729
+ const SEPARATOR = "\0";
730
+ /** The pool key of one runtime endpoint. */
731
+ function keyOf(target) {
732
+ return `${target.kind === "sbx" ? `sbx:${target.sandboxName}` : `docker:${target.containerId}`}${SEPARATOR}${target.workspace}`;
733
+ }
734
+ /**
735
+ * Live channels, keyed by runtime endpoint and workspace.
736
+ *
737
+ * A channel that failed is dropped as soon as it settles, so the next call
738
+ * handshakes again — that is what makes a restarted container recoverable
739
+ * without restarting the session.
740
+ */
741
+ var ContainerRpcPool = class {
742
+ channels = /* @__PURE__ */ new Map();
743
+ spawn;
744
+ /**
745
+ * @param spawn - the process starter; the Docker CLI unless a test replaces it.
746
+ */
747
+ constructor(spawn = spawnContainerChild) {
748
+ this.spawn = spawn;
749
+ }
750
+ /**
751
+ * The live channel for one container, opened and handshaken on demand.
752
+ * @param target - the container and the workspace it should treat as home.
753
+ * @param options - the per-request budget.
754
+ * @returns the usable channel.
755
+ * @throws Error when the helper cannot be staged or handshaken.
756
+ */
757
+ async channel(target, options) {
758
+ const key = keyOf(target);
759
+ const cached = this.channels.get(key);
760
+ if (cached !== void 0) {
761
+ const channel = await cached.catch(() => void 0);
762
+ if (channel !== void 0 && !channel.isClosed) return channel;
763
+ if (this.channels.get(key) === cached) this.channels.delete(key);
764
+ }
765
+ const opening = ContainerRpcChannel.open({
766
+ target,
767
+ spawn: this.spawn,
768
+ timeoutMs: options.timeoutMs
769
+ });
770
+ this.channels.set(key, opening);
771
+ const forget = () => {
772
+ if (this.channels.get(key) === opening) this.channels.delete(key);
773
+ };
774
+ opening.then((channel) => {
775
+ channel.closedPromise.then(forget);
776
+ }, forget).catch(() => {});
777
+ return await opening;
778
+ }
779
+ /**
780
+ * Drop one cached channel without touching the others.
781
+ * @param target - the container and workspace to forget.
782
+ */
783
+ forget(target) {
784
+ this.channels.delete(keyOf(target));
785
+ }
786
+ /** Close every channel this pool opened, waiting for each process to settle. */
787
+ async closeAll() {
788
+ const opening = [...this.channels.values()];
789
+ this.channels.clear();
790
+ for (const pending of opening) {
791
+ const channel = await pending.catch(() => void 0);
792
+ if (channel !== void 0) await channel.close();
793
+ }
794
+ }
795
+ };
796
+ //#endregion
797
+ //#region src/rpc/wire.ts
798
+ /**
799
+ * The JSON documents the container helper exchanges with the host.
800
+ *
801
+ * These mirror the seam's types with plain strings where the seam brands
802
+ * identity (`FsTargetKey`, `FsVersion`), because a brand cannot cross a wire.
803
+ * Conversion back happens in one place — `src/fs.ts` — so nothing else sees an
804
+ * unbranded key.
805
+ * @module @banzhe/dsh-devcontainer/rpc/wire
806
+ */
807
+ const KNOWN_CODES = new Set(FS_ERROR_CODES);
808
+ /** Brand one travelled target back into the seam's identity type. */
809
+ function toFsTarget(target) {
810
+ return {
811
+ targetKey: FsTargetKey(target.targetKey),
812
+ displayPath: target.displayPath
813
+ };
814
+ }
815
+ /** Brand `fs.stat` metadata back into the seam's type. */
816
+ function toFsInfo(info) {
817
+ return {
818
+ version: FsVersion(info.version),
819
+ type: info.type,
820
+ ...info.size === void 0 ? {} : { size: info.size }
821
+ };
822
+ }
823
+ /** Brand `fs.lstat` metadata back into the seam's type. */
824
+ function toFsPathInfo(info) {
825
+ return {
826
+ version: FsVersion(info.version),
827
+ type: info.type,
828
+ ...info.size === void 0 ? {} : { size: info.size }
829
+ };
830
+ }
831
+ /** Brand one listing entry back into the seam's type. */
832
+ function toFsDirEntry(entry) {
833
+ return {
834
+ name: entry.name,
835
+ type: entry.type,
836
+ target: toFsTarget(entry.target),
837
+ ...entry.version === void 0 ? {} : { version: FsVersion(entry.version) },
838
+ ...entry.size === void 0 ? {} : { size: entry.size }
839
+ };
840
+ }
841
+ /** Brand a write outcome back into the seam's type. */
842
+ function toFsWriteOutcome(outcome) {
843
+ return {
844
+ operation: outcome.operation,
845
+ version: FsVersion(outcome.version),
846
+ before: outcome.before,
847
+ after: outcome.after
848
+ };
849
+ }
850
+ /** Brand an edit or patch outcome back into the seam's type. */
851
+ function toFsEditOutcome(outcome) {
852
+ return {
853
+ version: FsVersion(outcome.version),
854
+ before: outcome.before,
855
+ after: outcome.after
856
+ };
857
+ }
858
+ /** Pass a delete outcome through; its only field is already plain text. */
859
+ function toFsDeleteOutcome(outcome) {
860
+ return { before: outcome.before };
861
+ }
862
+ /** Brand a move outcome back into the seam's type. */
863
+ function toFsMoveOutcome(outcome) {
864
+ const destination = toFsWriteOutcome(outcome.destination);
865
+ if (outcome.sourceDeleted || outcome.sourceFailure === void 0) return {
866
+ sourceBefore: outcome.sourceBefore,
867
+ destination,
868
+ sourceDeleted: true
869
+ };
870
+ return {
871
+ sourceBefore: outcome.sourceBefore,
872
+ destination,
873
+ sourceDeleted: false,
874
+ sourceFailure: {
875
+ code: KNOWN_CODES.has(outcome.sourceFailure.code) ? outcome.sourceFailure.code : "FS_IO_ERROR",
876
+ message: outcome.sourceFailure.message
877
+ }
878
+ };
879
+ }
880
+ //#endregion
881
+ //#region src/fs.ts
882
+ /**
883
+ * `ctx.fs` for repositories that declare a Dev Container, or run in a Docker
884
+ * Sandbox.
885
+ *
886
+ * A derived preset promises that nothing the session touches happens on the host. This backend keeps that promise at the filesystem seam instead of
887
+ * fencing the host path by path: in a container-bound session every operation —
888
+ * `resolve`, `lstat`, `stat`, reads, listings, writes, edits, patches, deletes,
889
+ * and moves — is delegated over a persistent RPC pipe to a Node helper running
890
+ * inside the Linux container (see `src/helper/main.mjs` and `src/rpc/`). The
891
+ * container resolves the path, follows the symlink, and performs the I/O, so a
892
+ * Windows drive letter is not merely refused but physically unreachable.
893
+ *
894
+ * Two cases keep their earlier behaviour on purpose:
895
+ *
896
+ * - An ordinary preset in the same repository keeps the host backend, mapped
897
+ * onto the bind mount, so a session that never entered the container sees the
898
+ * files exactly as before this row existed.
899
+ * - A `(devContainer)` preset over a repository that declares no container still
900
+ * fails fast with `FS_PERMISSION_DENIED`: there is nowhere to delegate to, and
901
+ * quietly writing the host while the model believes it wrote Linux is the
902
+ * worst possible outcome.
903
+ *
904
+ * The runtime behind the pipe is either a Docker container or a Docker Sandbox
905
+ * (`ChannelTarget`): the second one mounts the host workspace at its own absolute
906
+ * path, so the delegated paths are the ones the model already writes, and the
907
+ * helper still runs the sandbox's own Linux `node`.
908
+ *
909
+ * Containment inside the runtime is still enforced here — a request, and every
910
+ * identity the runtime resolves, must stay inside the repository's mount, in any
911
+ * spelling that mount has inside the runtime — so a session cannot wander off
912
+ * into the container's own `/etc` either.
913
+ * @module @banzhe/dsh-devcontainer/fs
914
+ */
915
+ /** Plugin name used by the Loader row. */
916
+ const name = "devcontainer-fs";
917
+ /** The local backend's own overwrite-diff budget; the constructor validates it, so it must be defaulted here. */
918
+ const DEFAULT_DIFF_BASIS_MAX_BYTES = 10485760;
919
+ /** How often a container-backed watch re-probes the target it follows. */
920
+ const REMOTE_WATCH_INTERVAL_MS = 1e3;
921
+ /** Key separator for the per-repository container cache. */
922
+ const KEY_SEPARATOR = "\0";
923
+ /** Mirrors `@deepseek-ai/dsh-fs-local`'s schema plus the shared container options. */
924
+ const ConfigSchema = z.object({
925
+ cwd: z.string().default(process.cwd()),
926
+ diffBasisMaxBytes: z.number().default(DEFAULT_DIFF_BASIS_MAX_BYTES),
927
+ rpcTimeoutMs: z.number().default(DEFAULT_RPC_TIMEOUT_MS),
928
+ ...containerOptionFields()
929
+ });
930
+ /** The row's schema, typed for callers; the loader reads the class's static copy. */
931
+ const Config = ConfigSchema;
932
+ /**
933
+ * Target-taking mutation entry points a NEWER base backend declares.
934
+ *
935
+ * The installed `@deepseek-ai/dsh-fs-sandbox` fences only `writeText` and
936
+ * `editText`, so `patchText`, `deleteFile`, and `moveFile` exist in no type this
937
+ * build can `override`. They are still the way a caller holding a target reaches
938
+ * a file, so each is installed as an own property: a container-bound call is
939
+ * delegated over RPC, and an ordinary one runs the inherited implementation when
940
+ * the base declares it.
941
+ */
942
+ const INHERITED_MUTATIONS = [
943
+ "patchText",
944
+ "deleteFile",
945
+ "moveFile"
946
+ ];
947
+ /**
948
+ * The stdio endpoint one resolved runtime offers the helper.
949
+ * @param target - the resolved runtime.
950
+ * @param workspace - the mount point the helper treats as home.
951
+ * @returns the channel target the pool keys and the helper is started against.
952
+ * @throws Error when the runtime has no stdio endpoint at all.
953
+ */
954
+ function channelTargetOf(target, workspace) {
955
+ switch (target.kind) {
956
+ case "docker": return {
957
+ kind: "docker",
958
+ containerId: target.containerId,
959
+ workspace
960
+ };
961
+ case "sbx": return {
962
+ kind: "sbx",
963
+ sandboxName: target.sandboxName,
964
+ workspace
965
+ };
966
+ case "devcontainer-cli": throw new Error("devcontainer: the Dev Container CLI offers no stdio channel for the filesystem helper");
967
+ }
968
+ }
969
+ /** Serialize one target for the wire. */
970
+ function wireTargetOf(target) {
971
+ return {
972
+ targetKey: String(target.targetKey),
973
+ displayPath: target.displayPath
974
+ };
975
+ }
976
+ /**
977
+ * Every folder a container path this session may use starts in.
978
+ *
979
+ * The specification's own mount point comes first. A Docker Sandbox also spells
980
+ * the same workspace the way its host convention does — a Windows drive
981
+ * directory is mounted without the drive colon, so `F:\personal\asmr-manager` is
982
+ * `/f/personal/asmr-manager` inside the sandbox — and a listing that reported no
983
+ * mounts leaves that spelling as the only usable one. The container's realpath of
984
+ * the mount point is a third, because a Dev Container feature may have moved it.
985
+ * @param spec - the repository container specification the call runs under.
986
+ * @param workspaceReal - the realpath the container reported for its handshake workspace, when known.
987
+ * @returns the mount spellings a request and a resolved identity may start with.
988
+ */
989
+ function containerMountsOf(spec, workspaceReal) {
990
+ const folders = [spec.containerWorkspaceFolder];
991
+ if (spec.cli === "sbx") {
992
+ const sandbox = sandboxWorkspacePath(spec.hostWorkspaceRoot);
993
+ if (sandbox !== void 0 && sandbox !== spec.containerWorkspaceFolder) folders.push(sandbox);
994
+ }
995
+ if (workspaceReal !== void 0 && !folders.includes(workspaceReal)) folders.push(workspaceReal);
996
+ return folders;
997
+ }
998
+ /**
999
+ * The filesystem seam for container-bound sessions: host behaviour for ordinary
1000
+ * presets, full remote delegation for `(devContainer)` ones.
1001
+ */
1002
+ var DevcontainerFileSystem = class extends SandboxedFileSystem {
1003
+ /**
1004
+ * The schema the Loader resolves this row's config through; a static because
1005
+ * the module's `default` export is this class (see
1006
+ * `DevcontainerShellExecutor.Config` for the same reason).
1007
+ */
1008
+ static Config = ConfigSchema;
1009
+ /** Test seam: replaces the host CLI runner, the container process starter, and the channel. */
1010
+ containerInternals = {};
1011
+ /** The container options this row was configured with (the inherited `config` is typed by the local backend). */
1012
+ options;
1013
+ /** Budget for one RPC round trip. */
1014
+ rpcTimeoutMs;
1015
+ /** Whether the configured directory has been walked for a declaration yet. */
1016
+ warmed = false;
1017
+ /** Whether this composition has learned where its sandbox mounts the workspace. */
1018
+ sbxProbed = false;
1019
+ /** One channel per container, shared by every call of this composition. */
1020
+ pool;
1021
+ /** One resolved runtime per repository, so a burst of calls probes the CLI once. */
1022
+ containers = /* @__PURE__ */ new Map();
1023
+ constructor(ctx, config) {
1024
+ super(ctx, config);
1025
+ this.options = containerOptions(config);
1026
+ this.rpcTimeoutMs = config.rpcTimeoutMs ?? 6e4;
1027
+ this.pool = new ContainerRpcPool((argv, options) => (this.containerInternals.spawn ?? spawnContainerChild)(argv, options));
1028
+ this.installTargetMutations();
1029
+ ctx.effect(() => {
1030
+ const cache = repoRegistry(ctx);
1031
+ return () => {
1032
+ cache.reset();
1033
+ };
1034
+ });
1035
+ ctx.effect(() => () => this.pool.closeAll());
1036
+ }
1037
+ /**
1038
+ * Resolve a model-supplied path inside the container, or translate it onto the
1039
+ * host bind mount for an ordinary preset.
1040
+ * @param path - the path to resolve; relative paths resolve against `opts.cwd`.
1041
+ * @param opts - optional cwd override and cancellation signal.
1042
+ * @returns the stable target.
1043
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this path is outside the repository's mount.
1044
+ */
1045
+ async resolve(path, opts) {
1046
+ const route = await this.route(path, opts?.cwd);
1047
+ if (route === void 0) {
1048
+ const mapped = this.mapPath(path, opts?.cwd);
1049
+ const next = {};
1050
+ if (mapped.cwd !== void 0) next.cwd = mapped.cwd;
1051
+ if (opts?.signal !== void 0) next.signal = opts.signal;
1052
+ return await super.resolve(mapped.path, next);
1053
+ }
1054
+ const requested = this.remotePath(path, opts?.cwd, route);
1055
+ return await this.withChannel(route.spec, opts?.signal, async (channel) => {
1056
+ const answer = await this.request(channel, "fs.resolve", { path: requested }, opts?.signal);
1057
+ this.assertInsideMount(answer.targetKey, path, route, channel.handshake.workspaceReal);
1058
+ return toFsTarget(answer);
1059
+ });
1060
+ }
1061
+ /**
1062
+ * The host path a target stands for, when the container's spelling is not one.
1063
+ *
1064
+ * A container path names a directory inside the runtime. On a POSIX host that
1065
+ * namespace is still the host's own root, so the container spelling is a usable
1066
+ * host path and the inherited identity — the target key, which the wire also
1067
+ * carries — is the right answer. A Windows host has no such root: `/f/personal/repo`
1068
+ * is a drive-relative path there, and `path.resolve('/f/personal/repo', '.git')`
1069
+ * yields `F:\f\personal\repo\.git`, a directory no repository contains.
1070
+ *
1071
+ * Host-bound consumers read this value as a HOST path — `WorkingDirectoryService`
1072
+ * commits it as the Session directory, the project-root walk appends `.git` to
1073
+ * it, and `ctx.subprocess` starts a process in it — so a container spelling that
1074
+ * no host path module can resolve would fail them all. A Windows-rooted
1075
+ * repository therefore answers the host path of its mount; the container spelling
1076
+ * keeps the two jobs it owns, the argv a runtime is started with
1077
+ * (`buildExecArgv`) and the payload of an RPC request (`wireTargetOf`).
1078
+ * @param target - the resolved target.
1079
+ * @returns its host path, or the inherited identity outside a Windows-rooted repository.
1080
+ */
1081
+ processPath(target) {
1082
+ const spec = this.repositoryFor(target.displayPath, void 0, this.containerRequirement()?.kind);
1083
+ if (spec === void 0 || hostPathStyle(spec.hostWorkspaceRoot) !== "win32") return super.processPath(target);
1084
+ return toHostPath(String(target.targetKey), spec);
1085
+ }
1086
+ /**
1087
+ * Probe a path inside the container without following its final symlink.
1088
+ * @param path - the path to inspect.
1089
+ * @param opts - `cwd` overrides the base for relative paths.
1090
+ * @param signal - aborts the metadata round-trip.
1091
+ * @returns metadata only, or undefined when the path is absent.
1092
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this path is outside the repository's mount.
1093
+ */
1094
+ async lstat(path, opts, signal) {
1095
+ const route = await this.route(path, opts?.cwd);
1096
+ if (route === void 0) {
1097
+ const mapped = this.mapPath(path, opts?.cwd);
1098
+ const next = {};
1099
+ if (mapped.cwd !== void 0) next.cwd = mapped.cwd;
1100
+ return await super.lstat(mapped.path, next, signal);
1101
+ }
1102
+ const requested = this.remotePath(path, opts?.cwd, route);
1103
+ return await this.withChannel(route.spec, signal, async (channel) => {
1104
+ const info = await this.request(channel, "fs.lstat", { path: requested }, signal);
1105
+ return info === null ? void 0 : toFsPathInfo(info);
1106
+ });
1107
+ }
1108
+ /**
1109
+ * Read metadata of a resolved target.
1110
+ * @param target - the resolved target.
1111
+ * @param signal - aborts the metadata round-trip.
1112
+ * @returns metadata only, or undefined when the target is absent.
1113
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1114
+ */
1115
+ async stat(target, signal) {
1116
+ const route = await this.routeTarget(target);
1117
+ if (route === void 0) return await super.stat(this.fenced(target), signal);
1118
+ return await this.withChannel(route.spec, signal, async (channel) => {
1119
+ this.assertTargetInsideMount(target, route, channel);
1120
+ const value = await this.request(channel, "fs.stat", { target: wireTargetOf(target) }, signal);
1121
+ return value === null ? void 0 : toFsInfo(value);
1122
+ });
1123
+ }
1124
+ /**
1125
+ * Read a whole text file inside the container.
1126
+ * @param target - the resolved target.
1127
+ * @param signal - aborts the read.
1128
+ * @returns the file's text.
1129
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1130
+ */
1131
+ async readText(target, signal) {
1132
+ const route = await this.routeTarget(target);
1133
+ if (route === void 0) return await super.readText(this.fenced(target), signal);
1134
+ return await this.withChannel(route.spec, signal, async (channel) => {
1135
+ this.assertTargetInsideMount(target, route, channel);
1136
+ return await this.request(channel, "fs.readText", { target: wireTargetOf(target) }, signal);
1137
+ });
1138
+ }
1139
+ /**
1140
+ * Stream a text file through the container helper's iterator.
1141
+ *
1142
+ * Only the refusal is decided here; the `fs.stream` request belongs to the
1143
+ * first iteration, so an iterator nobody reads holds no helper slot.
1144
+ * @param target - the resolved target.
1145
+ * @param signal - aborts the stream.
1146
+ * @returns the text stream.
1147
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1148
+ */
1149
+ async streamText(target, signal) {
1150
+ const route = await this.routeTarget(target);
1151
+ if (route === void 0) return await super.streamText(this.fenced(target), signal);
1152
+ const channel = await this.remoteChannel(route.spec, signal);
1153
+ this.assertTargetInsideMount(target, route, channel);
1154
+ return this.iterate(channel, wireTargetOf(target), route.spec, signal);
1155
+ }
1156
+ /**
1157
+ * Read a file as bytes inside the container.
1158
+ * @param target - the resolved target.
1159
+ * @param signal - aborts the read.
1160
+ * @param maxBytes - the exclusive size limit.
1161
+ * @returns the file's bytes.
1162
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1163
+ */
1164
+ async readBytes(target, signal, maxBytes) {
1165
+ const route = await this.routeTarget(target);
1166
+ if (route === void 0) return await super.readBytes(this.fenced(target), signal, maxBytes);
1167
+ return await this.withChannel(route.spec, signal, async (channel) => {
1168
+ this.assertTargetInsideMount(target, route, channel);
1169
+ const encoded = await this.request(channel, "fs.readBytes", {
1170
+ target: wireTargetOf(target),
1171
+ maxBytes
1172
+ }, signal);
1173
+ return Buffer.from(encoded, "base64");
1174
+ });
1175
+ }
1176
+ /**
1177
+ * Read a bounded byte range inside the container.
1178
+ * @param target - the resolved target.
1179
+ * @param range - offset and length of the window.
1180
+ * @param signal - aborts the read.
1181
+ * @returns the bytes of that window.
1182
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1183
+ */
1184
+ async readByteRange(target, range, signal) {
1185
+ const route = await this.routeTarget(target);
1186
+ if (route === void 0) return await super.readByteRange(this.fenced(target), range, signal);
1187
+ return await this.withChannel(route.spec, signal, async (channel) => {
1188
+ this.assertTargetInsideMount(target, route, channel);
1189
+ const encoded = await this.request(channel, "fs.readRange", {
1190
+ target: wireTargetOf(target),
1191
+ offset: range.offset,
1192
+ length: range.length
1193
+ }, signal);
1194
+ return Buffer.from(encoded, "base64");
1195
+ });
1196
+ }
1197
+ /**
1198
+ * List one directory inside the container.
1199
+ * @param target - the resolved directory target.
1200
+ * @param signal - aborts the listing.
1201
+ * @returns the direct children with their resolved targets.
1202
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1203
+ */
1204
+ async listDir(target, signal) {
1205
+ const route = await this.routeTarget(target);
1206
+ if (route === void 0) return await super.listDir(this.fenced(target), signal);
1207
+ return await this.withChannel(route.spec, signal, async (channel) => {
1208
+ this.assertTargetInsideMount(target, route, channel);
1209
+ return (await this.request(channel, "fs.list", { target: wireTargetOf(target) }, signal)).map(toFsDirEntry);
1210
+ });
1211
+ }
1212
+ /**
1213
+ * Watch one target for the GUI.
1214
+ *
1215
+ * A host watcher would have to open a host path, which is exactly the
1216
+ * penetration this row exists to prevent, so a container-backed watcher
1217
+ * re-probes the target over RPC and reports a change when its version token
1218
+ * moves.
1219
+ * @param target - the resolved target to watch.
1220
+ * @param changed - reports each change, or a watcher failure.
1221
+ * @param signal - aborts the watch: aborting stops the polling even when the caller never calls the disposer.
1222
+ * @returns the disposer of the watcher.
1223
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1224
+ */
1225
+ async watch(target, changed, signal) {
1226
+ const route = await this.routeTarget(target);
1227
+ if (route === void 0) return await super.watch(this.fenced(target), changed, signal);
1228
+ signal.throwIfAborted();
1229
+ const channel = await this.remoteChannel(route.spec, signal);
1230
+ this.assertTargetInsideMount(target, route, channel);
1231
+ let version = await this.versionOf(channel, target);
1232
+ let busy = false;
1233
+ let disposed = false;
1234
+ const report = (error) => {
1235
+ try {
1236
+ changed(error);
1237
+ } catch {}
1238
+ };
1239
+ const timer = setInterval(() => {
1240
+ if (busy || disposed) return;
1241
+ busy = true;
1242
+ this.versionOf(channel, target).then((next) => {
1243
+ if (disposed || next === version) return;
1244
+ version = next;
1245
+ report();
1246
+ }, (error) => {
1247
+ stop();
1248
+ report(error instanceof Error ? error : new Error(String(error)));
1249
+ }).finally(() => {
1250
+ busy = false;
1251
+ });
1252
+ }, REMOTE_WATCH_INTERVAL_MS);
1253
+ timer.unref();
1254
+ /** Stop polling, once; the caller's disposer and its signal both reach it. */
1255
+ const stop = () => {
1256
+ if (disposed) return;
1257
+ disposed = true;
1258
+ clearInterval(timer);
1259
+ signal.removeEventListener("abort", stop);
1260
+ };
1261
+ signal.addEventListener("abort", stop, { once: true });
1262
+ return () => {
1263
+ stop();
1264
+ return Promise.resolve();
1265
+ };
1266
+ }
1267
+ /**
1268
+ * Write a whole file inside the container.
1269
+ *
1270
+ * The per-call sandbox policy is deliberately not applied: it describes host
1271
+ * paths and a host mode, while the container is the confinement here.
1272
+ * @param target - the resolved target to write.
1273
+ * @param content - the full new file content.
1274
+ * @param expected - the write intent guarding the write; omit for unconditional.
1275
+ * @param signal - aborts before atomic publication takes effect.
1276
+ * @param _sandboxPolicy - the host policy, unused for a container target.
1277
+ * @returns the write outcome from the container helper.
1278
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1279
+ */
1280
+ async writeText(target, content, expected, signal, _sandboxPolicy) {
1281
+ const route = await this.routeTarget(target);
1282
+ if (route === void 0) return await super.writeText(this.fenced(target), content, expected, signal, _sandboxPolicy);
1283
+ return await this.withChannel(route.spec, signal, async (channel) => {
1284
+ this.assertTargetInsideMount(target, route, channel);
1285
+ return toFsWriteOutcome(await this.request(channel, "fs.write", {
1286
+ target: wireTargetOf(target),
1287
+ content,
1288
+ expected
1289
+ }, signal));
1290
+ });
1291
+ }
1292
+ /**
1293
+ * Apply a literal edit inside the container.
1294
+ * @param target - the resolved target to edit.
1295
+ * @param edit - the literal search/replace request.
1296
+ * @param expected - the version guard; omit for an unconditional edit.
1297
+ * @param signal - aborts before atomic publication takes effect.
1298
+ * @param _sandboxPolicy - the host policy, unused for a container target.
1299
+ * @returns the edit outcome from the container helper.
1300
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1301
+ */
1302
+ async editText(target, edit, expected, signal, _sandboxPolicy) {
1303
+ const route = await this.routeTarget(target);
1304
+ if (route === void 0) return await super.editText(this.fenced(target), edit, expected, signal, _sandboxPolicy);
1305
+ return await this.withChannel(route.spec, signal, async (channel) => {
1306
+ this.assertTargetInsideMount(target, route, channel);
1307
+ return toFsEditOutcome(await this.request(channel, "fs.edit", {
1308
+ target: wireTargetOf(target),
1309
+ edit,
1310
+ expected
1311
+ }, signal));
1312
+ });
1313
+ }
1314
+ /** The container channel for one route, translated into the seam's error vocabulary. */
1315
+ async remoteChannel(spec, signal) {
1316
+ signal?.throwIfAborted();
1317
+ const runtime = await this.runtimeTarget(spec, signal);
1318
+ const target = channelTargetOf(runtime, bindSbxMount(spec, runtime).containerWorkspaceFolder);
1319
+ const channel = this.containerInternals.channel;
1320
+ if (channel !== void 0) return await channel(target);
1321
+ return await this.pool.channel(target, { timeoutMs: this.rpcTimeoutMs });
1322
+ }
1323
+ /**
1324
+ * Run one operation against a live channel, mapping its failures.
1325
+ * @param spec - the repository whose container is used.
1326
+ * @param signal - the caller's cancellation.
1327
+ * @param operation - the work to run with the channel.
1328
+ * @returns what the operation produced.
1329
+ * @throws FsError for every transport and remote failure.
1330
+ */
1331
+ async withChannel(spec, signal, operation) {
1332
+ try {
1333
+ return await operation(await this.remoteChannel(spec, signal));
1334
+ } catch (error) {
1335
+ if (!(error instanceof RpcOperationError)) this.forgetContainer(spec);
1336
+ throw rpcFsError(error, signal);
1337
+ }
1338
+ }
1339
+ /** Send one request with this row's budget. */
1340
+ async request(channel, method, params, signal) {
1341
+ const options = signal === void 0 ? { timeoutMs: this.rpcTimeoutMs } : {
1342
+ timeoutMs: this.rpcTimeoutMs,
1343
+ signal
1344
+ };
1345
+ return await channel.request(method, params, options);
1346
+ }
1347
+ /**
1348
+ * One text stream, opened by its first iteration and closed however it ends.
1349
+ *
1350
+ * Opening inside the generator is what makes the lifecycle airtight: an
1351
+ * iterator the caller drops without reading never sends `fs.stream`, and
1352
+ * every way an iteration can stop — completion, `break`, a throw, a cancelled
1353
+ * scope — runs the `finally` that sends `fs.streamClose`. The helper holds 64
1354
+ * streams at most, so a leaked slot is a permanent loss for the session.
1355
+ * A broken pipe drops the cached container too.
1356
+ * @param channel - the live container channel.
1357
+ * @param target - the target to stream, as the helper names it.
1358
+ * @param spec - the repository whose container is used.
1359
+ * @param signal - aborts the stream.
1360
+ * @returns the text stream.
1361
+ */
1362
+ iterate(channel, target, spec, signal) {
1363
+ const request = async (method, params, scope) => {
1364
+ try {
1365
+ return await this.request(channel, method, params, scope);
1366
+ } catch (error) {
1367
+ if (!(error instanceof RpcOperationError)) this.forgetContainer(spec);
1368
+ throw rpcFsError(error, scope);
1369
+ }
1370
+ };
1371
+ return (async function* stream() {
1372
+ let opened;
1373
+ let ended = false;
1374
+ try {
1375
+ signal?.throwIfAborted();
1376
+ opened = (await request("fs.stream", { target }, signal)).id;
1377
+ const id = opened;
1378
+ while (!ended) {
1379
+ signal?.throwIfAborted();
1380
+ const step = await request("fs.next", { id }, signal);
1381
+ ended = step.done;
1382
+ if (!ended && step.value.length > 0) yield step.value;
1383
+ }
1384
+ } finally {
1385
+ const id = opened;
1386
+ if (id !== void 0 && !ended) await request("fs.streamClose", { id }).catch(() => {});
1387
+ }
1388
+ })();
1389
+ }
1390
+ /** The version token of one target, for the polling watcher. */
1391
+ async versionOf(channel, target) {
1392
+ const info = await this.request(channel, "fs.stat", { target: wireTargetOf(target) });
1393
+ return info === null ? "absent" : info.version;
1394
+ }
1395
+ /**
1396
+ * The runtime filesystem calls are delegated to.
1397
+ * @param spec - the repository container specification.
1398
+ * @param signal - cancels the Docker / sandbox probe.
1399
+ * @returns the resolved target the channel speaks to.
1400
+ * @throws FsError `FS_IO_ERROR` when the runtime has no stdio endpoint for the helper.
1401
+ */
1402
+ runtimeTarget(spec, signal) {
1403
+ const key = this.containerKey(spec);
1404
+ const cached = this.containers.get(key);
1405
+ if (cached !== void 0) return cached;
1406
+ const pending = this.probeContainer(spec, signal);
1407
+ this.containers.set(key, pending);
1408
+ pending.catch(() => {
1409
+ if (this.containers.get(key) === pending) this.containers.delete(key);
1410
+ });
1411
+ return pending;
1412
+ }
1413
+ /** The cache key of one repository's container. */
1414
+ containerKey(spec) {
1415
+ return [
1416
+ spec.hostWorkspaceRoot,
1417
+ spec.cli,
1418
+ spec.container ?? "",
1419
+ spec.sandbox ?? "",
1420
+ String(spec.ensureUp)
1421
+ ].join(KEY_SEPARATOR);
1422
+ }
1423
+ /** Drop one cached runtime, so the next call probes again. */
1424
+ forgetContainer(spec) {
1425
+ this.containers.delete(this.containerKey(spec));
1426
+ }
1427
+ /** Probe where the repository's container is, requiring an endpoint the helper can be started in. */
1428
+ async probeContainer(spec, signal) {
1429
+ const target = await resolveContainerTarget(spec, this.containerInternals.run ?? runContainerCommand, signal);
1430
+ if (target.kind === "devcontainer-cli") throw new FsError("devcontainer: \"" + spec.configPath + "\": the filesystem bridge needs a running Docker container for \"" + spec.hostWorkspaceRoot + "\", but none was found; set \"container\" or \"containerName\", or let the Dev Container CLI start one with \"cli: auto\" and \"ensureUp: true\".", "FS_IO_ERROR");
1431
+ return target;
1432
+ }
1433
+ /** Translate one path for a container-bound call, refusing anything outside the mount. */
1434
+ remotePath(path, cwd, route) {
1435
+ const base = toContainerPath(cwd ?? this.config.cwd, route.spec);
1436
+ const absolute = isWindowsPath(path) || isPosixAbsolute(path) ? toContainerPath(path, route.spec) : posix.resolve(base, toPosixSlashes(path));
1437
+ this.assertInsideMount(absolute, path, route);
1438
+ return absolute;
1439
+ }
1440
+ /** Refuse a container path that leaves every spelling of the repository's mount. */
1441
+ assertInsideMount(containerPath, displayPath, route, workspaceReal) {
1442
+ for (const folder of containerMountsOf(route.spec, workspaceReal)) if (containerRemainder(containerPath, folder) !== void 0) return;
1443
+ throw new FsError(fsEscapeRefusalText(displayPath, containerPath, route.preset), "FS_PERMISSION_DENIED");
1444
+ }
1445
+ /** Refuse an already-resolved target that leaves the repository's mount. */
1446
+ assertTargetInsideMount(target, route, channel) {
1447
+ this.assertInsideMount(String(target.targetKey), target.displayPath, route, channel.handshake.workspaceReal);
1448
+ }
1449
+ /**
1450
+ * Install the target-taking mutations this build's base class may not declare.
1451
+ *
1452
+ * An own property shadows the inherited method, so the wrapper is what every
1453
+ * caller reaches: a container-bound call becomes an RPC, and an ordinary one
1454
+ * still runs the inherited implementation — read from the prototype it was
1455
+ * reached through — or reports a typed failure when this backend has none.
1456
+ */
1457
+ installTargetMutations() {
1458
+ const backend = this;
1459
+ for (const method of INHERITED_MUTATIONS) {
1460
+ const inherited = backend[method];
1461
+ Object.defineProperty(this, method, {
1462
+ configurable: true,
1463
+ writable: true,
1464
+ value: async (...args) => {
1465
+ const target = args[0];
1466
+ const route = target === void 0 ? void 0 : await this.routeTarget(target);
1467
+ if (route === void 0) {
1468
+ if (typeof inherited !== "function") throw new FsError(method + " is not supported by this filesystem backend", "FS_IO_ERROR");
1469
+ return await inherited.apply(this, args);
1470
+ }
1471
+ return await this.remoteMutation(method, route, args);
1472
+ }
1473
+ });
1474
+ }
1475
+ }
1476
+ /** Run one installed mutation over RPC. */
1477
+ async remoteMutation(method, route, args) {
1478
+ if (method === "patchText") {
1479
+ const [target, hunks, expected, signal] = args;
1480
+ return await this.withChannel(route.spec, signal, async (channel) => {
1481
+ this.assertTargetInsideMount(target, route, channel);
1482
+ return toFsEditOutcome(await this.request(channel, "fs.patch", {
1483
+ target: wireTargetOf(target),
1484
+ hunks,
1485
+ expected
1486
+ }, signal));
1487
+ });
1488
+ }
1489
+ if (method === "deleteFile") {
1490
+ const [target, expected, signal] = args;
1491
+ return await this.withChannel(route.spec, signal, async (channel) => {
1492
+ this.assertTargetInsideMount(target, route, channel);
1493
+ return toFsDeleteOutcome(await this.request(channel, "fs.delete", {
1494
+ target: wireTargetOf(target),
1495
+ expected
1496
+ }));
1497
+ });
1498
+ }
1499
+ const [source, destination, options, signal] = args;
1500
+ const destinationRoute = await this.routeTarget(destination);
1501
+ if (destinationRoute === void 0) throw new FsError("devcontainer: the move destination is outside every container repository", "FS_PERMISSION_DENIED");
1502
+ return await this.withChannel(route.spec, signal, async (channel) => {
1503
+ this.assertTargetInsideMount(source, route, channel);
1504
+ this.assertTargetInsideMount(destination, destinationRoute, channel);
1505
+ return toFsMoveOutcome(await this.request(channel, "fs.move", {
1506
+ source: wireTargetOf(source),
1507
+ destination: wireTargetOf(destination),
1508
+ options
1509
+ }));
1510
+ });
1511
+ }
1512
+ /**
1513
+ * Route one path-taking call.
1514
+ * @param path - the path the caller named.
1515
+ * @param cwd - the directory relative paths resolve against.
1516
+ * @returns the container route, or undefined when this call keeps the host backend.
1517
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and nothing declares a container for the path.
1518
+ */
1519
+ async route(path, cwd) {
1520
+ const requirement = this.containerRequirement();
1521
+ await this.prepareSbxMount(requirement?.kind, cwd ?? this.config.cwd);
1522
+ const spec = this.repositoryFor(path, cwd, requirement?.kind);
1523
+ if (spec === void 0) {
1524
+ this.refuseHostAccess(path);
1525
+ return;
1526
+ }
1527
+ if (requirement === void 0) return void 0;
1528
+ return {
1529
+ spec,
1530
+ preset: requirement.preset
1531
+ };
1532
+ }
1533
+ /**
1534
+ * Route one already-resolved call.
1535
+ * @param target - the target the caller holds.
1536
+ * @returns the container route, or undefined when this call keeps the host backend.
1537
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and this target is not in a container repository.
1538
+ */
1539
+ async routeTarget(target) {
1540
+ const requirement = this.containerRequirement();
1541
+ if (requirement === void 0) return void 0;
1542
+ await this.prepareSbxMount(requirement.kind, this.config.cwd);
1543
+ const spec = this.repositoryFor(target.displayPath, void 0, requirement.kind);
1544
+ if (spec === void 0) {
1545
+ this.refuseHostAccess(target.displayPath);
1546
+ return;
1547
+ }
1548
+ return {
1549
+ spec,
1550
+ preset: requirement.preset
1551
+ };
1552
+ }
1553
+ /** Translate one path and its base directory onto the host, refusing a host-only call when the caller is container-bound. */
1554
+ mapPath(path, cwd) {
1555
+ const repository = this.repositoryFor(path, cwd, this.containerRequirement()?.kind);
1556
+ if (repository === void 0) {
1557
+ this.refuseHostAccess(path);
1558
+ return {
1559
+ path,
1560
+ cwd
1561
+ };
1562
+ }
1563
+ return {
1564
+ path: toHostPath(path, repository),
1565
+ cwd: cwd === void 0 ? void 0 : toHostPath(cwd, repository)
1566
+ };
1567
+ }
1568
+ /**
1569
+ * The repository whose container governs one path.
1570
+ * @param path - a host path, a container path, a sandbox path, or a relative path.
1571
+ * @param cwd - the directory relative paths resolve against; the row's configured one when absent.
1572
+ * @returns the governing specification, or undefined when the path belongs to no Dev Container repository.
1573
+ */
1574
+ repositoryFor(path, cwd, kind) {
1575
+ const base = cwd ?? this.config.cwd;
1576
+ const options = {
1577
+ ...this.options,
1578
+ cwd: base
1579
+ };
1580
+ const registry = repoRegistry(this.ctx);
1581
+ const adopt = (spec) => kind === "sbx" ? asSbxSpec(spec) : spec;
1582
+ if (!this.warmed) {
1583
+ this.warmed = true;
1584
+ registry.discover(this.config.cwd, {
1585
+ ...this.options,
1586
+ cwd: this.config.cwd
1587
+ });
1588
+ }
1589
+ const governing = registry.locate(path, options);
1590
+ if (governing !== void 0) return adopt(governing);
1591
+ const fallback = registry.locate(base, {
1592
+ ...this.options,
1593
+ cwd: this.config.cwd
1594
+ });
1595
+ if (fallback !== void 0) {
1596
+ const adopted = adopt(fallback);
1597
+ if (this.belongsTo(path, base, adopted)) return adopted;
1598
+ }
1599
+ if (kind !== "sbx") return void 0;
1600
+ const attributed = this.specForSandboxPath(path, adopt);
1601
+ if (attributed !== void 0) return attributed;
1602
+ const root = sbxWorkspaceRootFor(path, base, void 0);
1603
+ return root === void 0 ? void 0 : sbxSpecFor(root, this.options);
1604
+ }
1605
+ /**
1606
+ * The specification a sandbox-spelled path names, reversed onto the host.
1607
+ *
1608
+ * A path a sandbox mounts is attributed from the mount itself: the host
1609
+ * directory it reported, and the workspace root that directory names — enough
1610
+ * even for a workspace that declares no container, which is exactly what a
1611
+ * `(sbx)` session mounts. The drive convention names no workspace root, only the
1612
+ * spelling this host gives such a path, so it decides only when a repository
1613
+ * declares a container above the directory it spells: `/f/…` cannot claim
1614
+ * whatever host path it happens to name, and a sandbox path outside every mount
1615
+ * stays refused locally.
1616
+ * @param path - the path the call named.
1617
+ * @param adopt - the calling track's view of a declared specification.
1618
+ * @returns the governing specification, or undefined when nothing attributes the path.
1619
+ */
1620
+ specForSandboxPath(path, adopt) {
1621
+ const attributed = sandboxHostPathFor(path);
1622
+ if (attributed === void 0) return void 0;
1623
+ const declared = repoRegistry(this.ctx).locate(attributed.host, {
1624
+ ...this.options,
1625
+ cwd: attributed.host
1626
+ });
1627
+ if (declared !== void 0) return adopt(declared);
1628
+ if (attributed.workspaceRoot === void 0) return void 0;
1629
+ return sbxSpecFor(attributed.workspaceRoot, this.options);
1630
+ }
1631
+ /**
1632
+ * Whether the fallback repository may claim one path.
1633
+ *
1634
+ * A container path of that repository, a host path under its root, or a
1635
+ * relative path that resolves — against the same base the fallback names —
1636
+ * to somewhere inside it. Anything else is a host path the repository does
1637
+ * not own: `..` traversal and absolute paths elsewhere on the machine
1638
+ * included.
1639
+ * @param path - the path the call named.
1640
+ * @param base - the directory relative paths resolve against.
1641
+ * @param spec - the fallback repository specification.
1642
+ * @returns true when that repository owns the path.
1643
+ */
1644
+ belongsTo(path, base, spec) {
1645
+ if (isPathInsideContainer(path, spec)) return true;
1646
+ if (relativeWithinHostRoot(path, spec.hostWorkspaceRoot) !== void 0) return true;
1647
+ if (isWindowsPath(path) || isPosixAbsolute(path)) return false;
1648
+ const hostBase = toHostPath(base, spec);
1649
+ if (!isWindowsPath(hostBase) && !isPosixAbsolute(hostBase)) return true;
1650
+ return relativeWithinHostRoot(joinHostRoot(hostBase, path), spec.hostWorkspaceRoot) !== void 0;
1651
+ }
1652
+ /**
1653
+ * Learn where the sandbox really mounts this workspace, before a path is
1654
+ * attributed to it.
1655
+ *
1656
+ * A `(sbx)` session names paths in its sandbox's spelling, while a
1657
+ * specification built from a host directory carries the host spelling until a
1658
+ * listing reports the mount. Routing therefore asks the runtime once — the same
1659
+ * probe the first call would run anyway — so `/f/personal/repo` is measured
1660
+ * against the folder the sandbox reports instead of the drive path the host
1661
+ * named. A probe that fails is not reported here: the call that needs the
1662
+ * container reports it with the runtime's own diagnostic.
1663
+ * @param kind - the runtime the calling preset selects, when one does.
1664
+ * @param base - the directory this call resolves relative paths against.
1665
+ */
1666
+ async prepareSbxMount(kind, base) {
1667
+ if (kind !== "sbx" || this.sbxProbed) return;
1668
+ this.sbxProbed = true;
1669
+ const declared = repoRegistry(this.ctx).locate(base, {
1670
+ ...this.options,
1671
+ cwd: this.config.cwd
1672
+ });
1673
+ const root = declared?.hostWorkspaceRoot ?? base;
1674
+ if (root === "") return;
1675
+ await this.runtimeTarget(sbxSpecFor(root, this.options, declared)).catch(() => {});
1676
+ }
1677
+ /**
1678
+ * The container requirement governing this call.
1679
+ *
1680
+ * A `(devContainer)` preset promises container execution, so its filesystem
1681
+ * calls must not reach the host either; `requireContainer` asks for the same
1682
+ * guarantee from every preset. Both are read per call, so switching presets
1683
+ * mid-session needs no reload.
1684
+ * @returns the requirement and the preset that states it, or undefined when this call may use the host.
1685
+ */
1686
+ containerRequirement() {
1687
+ const preset = callingContainerPreset(this.ctx);
1688
+ if (preset !== void 0) return {
1689
+ preset,
1690
+ kind: presetKindOf(preset)
1691
+ };
1692
+ return this.options.requireContainer ? {
1693
+ preset: void 0,
1694
+ kind: void 0
1695
+ } : void 0;
1696
+ }
1697
+ /**
1698
+ * Refuse a call that would leave the container's repository.
1699
+ * @param path - the path the call names, for the diagnostic.
1700
+ * @param resolved - the resolved path the helper would use for I/O, when it differs from `path`.
1701
+ * @throws FsError `FS_PERMISSION_DENIED` when nothing in that path's ancestry declares a container.
1702
+ */
1703
+ refuseHostAccess(path, resolved) {
1704
+ const requirement = this.containerRequirement();
1705
+ if (requirement === void 0) return;
1706
+ const text = resolved === void 0 ? fsRefusalText(path, requirement.preset) : fsEscapeRefusalText(path, resolved, requirement.preset);
1707
+ throw new FsError(text, "FS_PERMISSION_DENIED");
1708
+ }
1709
+ /**
1710
+ * Fence one already-resolved target for a host call.
1711
+ *
1712
+ * A target can outlive the state it was resolved under — a preset switched
1713
+ * between the read and the write, a declaration deleted mid-session — so the
1714
+ * requirement is re-read here rather than trusted from the ingress check. Both
1715
+ * spellings a target carries are fenced, because they answer different
1716
+ * questions: `displayPath` is the path the caller named, while `targetKey` is
1717
+ * the realpath the backend actually opens.
1718
+ * @param target - the target the operation would use.
1719
+ * @returns the same target, so callers fence in place.
1720
+ * @throws FsError `FS_PERMISSION_DENIED` when the caller is container-bound and either spelling belongs to no container repository.
1721
+ */
1722
+ fenced(target) {
1723
+ const requirement = this.containerRequirement();
1724
+ if (requirement === void 0) return target;
1725
+ if (this.repositoryFor(target.displayPath, void 0, requirement.kind) === void 0) {
1726
+ this.refuseHostAccess(target.displayPath);
1727
+ return target;
1728
+ }
1729
+ const resolved = String(target.targetKey);
1730
+ if (this.repositoryFor(resolved, void 0, requirement.kind) === void 0) this.refuseHostAccess(target.displayPath, resolved);
1731
+ return target;
1732
+ }
1733
+ };
1734
+ //#endregion
1735
+ export { Config, DevcontainerFileSystem, DevcontainerFileSystem as default, name };
1736
+
1737
+ //# sourceMappingURL=fs.js.map