dsh-plugin-wsl-env 0.23.1 → 0.25.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +9 -5
  3. package/SECURITY.md +10 -0
  4. package/client.js +974 -165
  5. package/cordis.patch.yml +28 -3
  6. package/docs/API.md +2 -1
  7. package/docs/ARCHITECTURE.md +36 -13
  8. package/docs/COMPATIBILITY.md +5 -0
  9. package/docs/CONFIGURATION.md +80 -9
  10. package/docs/CONFIGURATION.zh.md +64 -8
  11. package/docs/DIAGNOSTICS.md +48 -20
  12. package/docs/DIAGNOSTICS.zh.md +36 -14
  13. package/docs/LIMITATIONS.md +36 -9
  14. package/docs/LIMITATIONS.zh.md +26 -7
  15. package/docs/MIGRATION.md +1 -1
  16. package/docs/PEER-PARITY.md +4 -4
  17. package/docs/QUICKSTART.md +42 -12
  18. package/docs/QUICKSTART.zh.md +29 -8
  19. package/docs/README.zh.md +9 -5
  20. package/docs/RELEASING.md +17 -13
  21. package/docs/REQUIREMENTS.zh.md +5 -4
  22. package/docs/UPSTREAM-FSIO-EXPORT.md +5 -4
  23. package/docs/UPSTREAM-PROMPT-ADAPTERS.md +85 -0
  24. package/docs/root-fs-routing.md +1 -1
  25. package/lib/agent-confined.d.ts +7 -1
  26. package/lib/agent-confined.js +3 -3
  27. package/lib/auto-preset.d.ts +27 -0
  28. package/lib/auto-preset.js +40 -3
  29. package/lib/bwrap.d.ts +14 -0
  30. package/lib/bwrap.js +11 -0
  31. package/lib/client-host.d.ts +2 -2
  32. package/lib/client-host.js +2 -2
  33. package/lib/cwd-prompt.d.ts +41 -3
  34. package/lib/cwd-prompt.js +125 -8
  35. package/lib/doctor-report.d.ts +50 -0
  36. package/lib/doctor-report.js +172 -0
  37. package/lib/fs-routing.d.ts +1 -1
  38. package/lib/fs-routing.js +1 -1
  39. package/lib/fs.d.ts +1 -1
  40. package/lib/fs.js +1 -1
  41. package/lib/index.d.ts +6 -1464
  42. package/lib/index.js +5 -2120
  43. package/lib/listing.d.ts +21 -9
  44. package/lib/listing.js +25 -21
  45. package/lib/messages.d.ts +1 -1
  46. package/lib/messages.js +3 -3
  47. package/lib/picker.d.ts +50 -16
  48. package/lib/picker.js +103 -23
  49. package/lib/preflight.d.ts +7 -4
  50. package/lib/preflight.js +27 -13
  51. package/lib/preset-choice.d.ts +22 -3
  52. package/lib/preset-choice.js +36 -3
  53. package/lib/provider-common.d.ts +58 -0
  54. package/lib/provider-common.js +123 -0
  55. package/lib/sandbox-core.d.ts +1 -0
  56. package/lib/sandbox-core.js +4 -2
  57. package/lib/session-runtime.d.ts +7 -1
  58. package/lib/session-runtime.js +9 -2
  59. package/lib/shell.d.ts +1 -1
  60. package/lib/shell.js +1 -1
  61. package/lib/status.d.ts +261 -0
  62. package/lib/status.js +425 -0
  63. package/lib/writable-roots.d.ts +109 -0
  64. package/lib/writable-roots.js +257 -0
  65. package/lib/wsl-doctor-tool.d.ts +8 -0
  66. package/lib/wsl-doctor-tool.js +18 -20
  67. package/lib/wsl-filesystem.d.ts +692 -0
  68. package/lib/wsl-filesystem.js +897 -0
  69. package/lib/wsl-shell.d.ts +742 -0
  70. package/lib/wsl-shell.js +965 -0
  71. package/lib/wsl.d.ts +13 -1
  72. package/lib/wsl.js +16 -1
  73. package/locale/doctor/en.json +3 -2
  74. package/locale/doctor/zh.json +3 -2
  75. package/package.json +12 -4
  76. package/scripts/doctor.mjs +436 -226
  77. package/scripts/profile-preset.mjs +17 -5
@@ -0,0 +1,965 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { randomUUID } from "node:crypto";
3
+ import { LocalBashExecutor } from "@deepseek-ai/dsh-bash-local";
4
+ import { classifyRunnerFailure, isRunnerSpawnFailure, matchesSignature, SandboxUnavailableError } from "@deepseek-ai/dsh-sandbox";
5
+ import { isAnotherDistrosUnc, isRelativeWorldPath, toLinuxPath } from "./paths.js";
6
+ import { pinnedDistro } from "./distro-route.js";
7
+ import { WslSandbox } from "./sandbox.js";
8
+ import { withBwrapHint } from "./sandbox-core.js";
9
+ import { AgentUnavailableError, SpawnError } from "./agent-errors.js";
10
+ import { agentExecutionHandle } from "./agent-exec.js";
11
+ import { sharedAgent } from "./agent-shared.js";
12
+ import { SessionRuntimes, probeSessionRuntime, sessionRuntimes, setSessionNativeAgent } from "./session-runtime.js";
13
+ import { configureAgentBackend, ensureNativeSessionAgent } from "./native-agent.js";
14
+ import { installMessagesLocale, t } from "./messages.js";
15
+ import { defaultDistro, defaultShell, runCapture, shellArgs, workdirFailure, wslErrorCode } from "./wsl.js";
16
+ import { validateWritableRootsConfig } from "./writable-roots.js";
17
+ import { configuredCwd, distroHome, effectiveMaskWindowsDrive, effectiveWritableRoots, resolveOperationDistro, sessionRuntimeWanted } from "./provider-common.js";
18
+ /**
19
+ * Every model shell call gets a rebuilt managed `DSH_*` namespace (see
20
+ * `dsh-shell-env` / `ctx.shellEnv`). Those names exist only in the Windows-side
21
+ * process, so unless they are listed in WSLENV they never reach the distro and
22
+ * the model sees none of its environment facts.
23
+ */
24
+ /**
25
+ * Of the managed facts, these two carry Windows paths. WSL's `WSLENV` `/p` flag
26
+ * translates them on the way in, so a command inside the distro gets a usable
27
+ * `/mnt/c/...` path instead of `C:\...`. `DSH_WSL_HOME` is deliberately absent:
28
+ * it is already a POSIX path, and translating it would corrupt it.
29
+ */
30
+ const DSH_ENV_PREFIX = "DSH_";
31
+ const PATH_TRANSLATED = new Set([`${DSH_ENV_PREFIX}HOME`, `${DSH_ENV_PREFIX}PROFILE_DIR`]);
32
+ /** Env names that are meaningful on the Linux side and safe to forward. */
33
+ const SAFE_FORWARD = ["NO_COLOR", "TERM", "PAGER", "GIT_PAGER", "LANG", "LC_ALL"];
34
+ const inheritedSpawnSpec = LocalBashExecutor.prototype.spawnSpec;
35
+ /**
36
+ * The refusal both shell resolvers share: the probes named no shell, and the
37
+ * command must not quietly run under some other interpreter.
38
+ * the probes named no shell, and the
39
+ * command must not quietly run under some other interpreter. The wording is
40
+ * the one `runInDistro` already throws with.
41
+ *
42
+ * @param distro - the distro whose shell could not be resolved.
43
+ */
44
+ const unusableShell = (distro) => new Error(`dsh-plugin-wsl: distro "${distro}" named no usable shell (passwd probe and $SHELL both failed). ` +
45
+ `Check the user's login shell in /etc/passwd (\`getent passwd "$(id -u)"\` inside the distro), ` +
46
+ `or point this row's \`shell\` at an existing absolute path.`);
47
+ /**
48
+ * Bash executor that runs every command inside a WSL distro.
49
+ *
50
+ * Extends the unconfined `LocalBashExecutor`, so command defaulting, deadline
51
+ * handling, output caps, spill files and background-process management are the
52
+ * shipped implementation's; this subclass replaces only the argv (prefix with
53
+ * `wsl.exe`) and the process working directory (wsl.exe must be started from a
54
+ * Windows directory, while the Linux directory rides on `--cd`).
55
+ */
56
+ // @ts-expect-error — LocalBashExecutor.spawnSpec is private upstream; a wsl.exe spawn must start from a Windows directory (docs/UPSTREAM-SPAWN-SEAM.md)
57
+ export class WslShellExecutor extends LocalBashExecutor {
58
+ static inject = ["subprocess", "sandboxPolicy"];
59
+ static Config = z.object({
60
+ /**
61
+ * Distro mode: empty/`"auto"` follows the request workdir, `"default"`
62
+ * forces WSL's default, and an explicit name pins every command.
63
+ */
64
+ distro: z.string().default(""),
65
+ /** Path to `wsl.exe`; overridable for a non-standard install. */
66
+ wslPath: z.string().default("wsl.exe"),
67
+ /**
68
+ * The shell commands run in. Empty means "resolve the login shell of the
69
+ * distro's user" — hardcoding bash silently ignores a user whose passwd
70
+ * entry points at zsh, fish, dash, or anything else, losing their PATH and
71
+ * rc setup. Set an absolute path inside the distro to pin one.
72
+ */
73
+ shell: z.string().default(""),
74
+ /**
75
+ * Login-shell semantics (`<shell> -lc`) source the profile scripts, which is
76
+ * what makes an interactive WSL setup's PATH (nvm, cargo, pyenv) visible.
77
+ * Set false for a fast, fully deterministic `<shell> -c`. Applies only to the
78
+ * POSIX family — see `shellArgs` for why other shells get a bare `-c`.
79
+ */
80
+ loginShell: z.boolean().default(true),
81
+ /**
82
+ * Confine every command inside the distro with `bwrap`, and report the
83
+ * policy's mode through {@link sandboxMode}. Fails closed: a distro without
84
+ * a usable `bwrap` produces `SANDBOX_UNAVAILABLE` rather than an unconfined
85
+ * run. `false` restores the pre-sandbox behaviour exactly — commands run
86
+ * unconfined and `sandboxMode` is `undefined`, so the model is told so.
87
+ */
88
+ sandbox: z.boolean().default(true),
89
+ /**
90
+ * Shadow `/mnt` with an empty tmpfs in every confined profile, hiding the
91
+ * Windows drive from confined commands: its files cannot be read or
92
+ * exfiltrated and its executables cannot be launched through interop —
93
+ * the hole that lets a "sandboxed" command reach your full Windows token.
94
+ * A narrowing, not a closure (a command can still write an executable
95
+ * into the workspace and run it — binfmt dispatches on content, not
96
+ * location), so enforcement stays `partial` and the sandbox fact reports
97
+ * `windowsDrive: "masked"`. Costs: confined commands cannot read or touch
98
+ * anything under `/mnt`, and tools that probe the drive degrade. The
99
+ * complete closure is distro-level: `[interop] enabled=false` in
100
+ * `wsl.conf`.
101
+ */
102
+ /**
103
+ * The interop stance in one key (WSL-314), expanding to the per-key
104
+ * values the measured matrix documents:
105
+ *
106
+ * - `visible` (default) — nothing masked; a confined command can read
107
+ * `/mnt` and launch Windows executables through interop, which escapes
108
+ * the Linux sandbox entirely.
109
+ * - `masked` — `maskWindowsDrive: true`: `/mnt` is shadowed with an empty
110
+ * tmpfs; the drive's files and executables are unreachable (binfmt can
111
+ * still run a workspace-written .exe, so enforcement stays `partial`).
112
+ * - `disabled` — `masked`, plus the distro-level closure: `[interop]
113
+ * enabled=false` in `/etc/wsl.conf` + `wsl --shutdown`, which the
114
+ * doctor's remedy prints as copy-paste (a config key does not write
115
+ * distro config; enforcement is the kernel's, not the schema's).
116
+ *
117
+ * When set at all it takes precedence over the legacy
118
+ * `maskWindowsDrive` boolean below (unset — the default — lets that
119
+ * boolean answer); the boolean remains for existing profiles.
120
+ */
121
+ interopVisibility: z.union(["visible", "masked", "disabled"]),
122
+ maskWindowsDrive: z.boolean().default(false),
123
+ /**
124
+ * Extra directories under `workspace-write`, in distro spelling. The
125
+ * plugin grants them together with the workspace, so toolchain caches
126
+ * (`~/.npm`, pnpm's store, `~/.cargo/registry`) and a linked worktree's
127
+ * shared Git directory work without escalating the whole command to
128
+ * `danger-full-access`. `~` and `~/...` expand against the distro user's
129
+ * home; every entry must be an existing physical directory. Entries
130
+ * already writable (inside the workspace, `/tmp`, `/dev/shm`) and entries
131
+ * nested inside another grant are ignored. The same list belongs on
132
+ * `wsl-fs` so writes and commands see the same mount table. Default empty:
133
+ * the mode still grants only the workspace and the temp areas.
134
+ */
135
+ writableRoots: z.array(z.string()).default([]),
136
+ /**
137
+ * Default workdir for a request that names none; accepts `/home/andy/proj`,
138
+ * a UNC path, or `C:\...`. Empty — the default — means the distro user's
139
+ * home, resolved inside the distro.
140
+ */
141
+ cwd: z.string().volatile(),
142
+ /** Windows directory the `wsl.exe` process itself starts in. */
143
+ hostCwd: z.string().volatile(),
144
+ /** Extra env names to forward into the distro through WSLENV. */
145
+ forwardEnv: z.array(z.string()).default([]),
146
+ timeoutMs: z.number().default(12e4).volatile(),
147
+ maxTimeoutMs: z.number().default(6e5).volatile(),
148
+ maxOutputBytes: z.number().default(64e3).volatile(),
149
+ maxSpillBytes: z.number().default(64 * 1024 * 1024).volatile(),
150
+ graceMs: z.number().default(3e3).volatile(),
151
+ /**
152
+ * Run commands through the resident agent when it is up (one long-lived
153
+ * in-distro process; in-distro timeout semantics), falling back to the
154
+ * one-shot `wsl.exe` path whenever the agent is out. `false` never uses
155
+ * the agent. The confinement, the output budgets' shapes and the result
156
+ * decoration are identical on both paths.
157
+ */
158
+ agent: z.boolean().default(true),
159
+ agentBackend: z.union(["auto", "native", "shell"]).default("auto"),
160
+ /**
161
+ * Run this session's commands in one persistent systemd user scope (ADR
162
+ * 0001): background processes survive the command that started them, `/tmp`
163
+ * is the distro's real `/tmp` under workspace-write, and `ps` sees the
164
+ * session. The executor holds the runtime until the session's scope
165
+ * disposes, then stops it. Requires systemd, a reachable user manager and
166
+ * `Linger`; the preflight refuses with the remedy when one is missing, and
167
+ * only a success is cached. Off by default; requires `agent: true`.
168
+ */
169
+ sessionSandbox: z.union([z.boolean(), z.const("auto")]).default(false),
170
+ });
171
+ /**
172
+ * @param ctx - the composition context.
173
+ * @param config - the validated plugin config.
174
+ */
175
+ constructor(ctx, config) {
176
+ super(ctx, config);
177
+ validateWritableRootsConfig(config.writableRoots);
178
+ configureAgentBackend(config.agentBackend ?? "auto");
179
+ installMessagesLocale(ctx);
180
+ this.resolvedDistro = pinnedDistro(config.distro) ?? "";
181
+ this.resolvedShell = config.shell;
182
+ this.resolvedShells = new Map();
183
+ this.resolvedHome = undefined;
184
+ this.resolvedHomes = new Map();
185
+ this.mode = config.sandbox ? ctx.sandboxPolicy.defaultMode : undefined;
186
+ this.sandbox = config.sandbox
187
+ ? new WslSandbox({ wslPath: config.wslPath, maskWindowsDrive: effectiveMaskWindowsDrive(config) })
188
+ : undefined;
189
+ this.processFacts = new Map();
190
+ this.sessionRuntimes = sessionRuntimes;
191
+ this.sessionRuntimeEntries = new Map();
192
+ this.sessionRuntimeOwner = randomUUID();
193
+ this.sessionScopeProbe = (argv) => runCapture(argv);
194
+ this.writableRootsProbe = (argv) => runCapture(argv);
195
+ this.sessionRuntimePreflight = new Set();
196
+ this.autoSessionScope = new Map();
197
+ // The preset realm disposes when the session ends; the scope must go with
198
+ // it, or a dev server outlives the session that started it.
199
+ ctx.effect(() => () => this.disposeSessionRuntimes().catch(() => { }), "wsl session runtimes");
200
+ }
201
+ /**
202
+ * The mode this executor confines with, or `undefined` when it does not
203
+ * confine at all. `dsh-tool-bash` reads exactly this to decide whether to
204
+ * advertise the escalation field, so it must disappear together with the
205
+ * enforcement — never claim a boundary that is not applied.
206
+ *
207
+ * @returns the deployment default mode, or `undefined` when unconfined.
208
+ */
209
+ get sandboxMode() {
210
+ return this.mode;
211
+ }
212
+ /**
213
+ * The distro used when no path supplies evidence: the pinned name, WSL's
214
+ * default, or the default for the automatic modes.
215
+ *
216
+ * @returns the distro name.
217
+ */
218
+ async distro() {
219
+ const config = this.config;
220
+ if (this.resolvedDistro.length === 0)
221
+ this.resolvedDistro = await defaultDistro({ wslPath: config.wslPath });
222
+ return this.resolvedDistro;
223
+ }
224
+ /**
225
+ * The distro one command belongs to: an explicit pin wins; otherwise the
226
+ * request workdir, then the configured `cwd`, may name a distro; both
227
+ * absent falls back to WSL's default.
228
+ *
229
+ * @param workdir - the request's workdir, in any coordinate system.
230
+ * @param cwd - the configured default workdir, when the caller has it.
231
+ * @returns the distro name.
232
+ */
233
+ async distroFor(workdir, cwd) {
234
+ const config = this.config;
235
+ return resolveOperationDistro(config.distro, [workdir, cwd ?? configuredCwd(this.config)], () => this.distro());
236
+ }
237
+ /**
238
+ * The shell name for the default/pinned distro, as the shell tool presents
239
+ * it.
240
+ *
241
+ * @returns the basename of the shell; `shell` while the probe fails, and
242
+ * `bash` for an implausible basename.
243
+ */
244
+ async shellName() {
245
+ // Consumed by the shell tool after upstream change A: it names and describes
246
+ // itself from the executor, so a zsh distro is never presented as bash. The
247
+ // naming path must not crash on a failed probe — "shell" is the honest
248
+ // neutral — while an implausible basename keeps the bash fallback below.
249
+ const shell = await this.shell().catch(() => undefined);
250
+ if (shell === undefined)
251
+ return "shell";
252
+ const base = String(shell ?? "").split("/").pop() ?? "";
253
+ const name = base.replace(/\.exe$/i, "").replace(/^[-.]+/, "");
254
+ return /^[a-z0-9_+-]+$/i.test(name) ? name : "bash";
255
+ }
256
+ /**
257
+ * The shell for one distro: the configured shell, else that distro's login
258
+ * shell. The default/pinned distro keeps the legacy {@link resolvedShell}
259
+ * cache; every other distro gets an entry in {@link resolvedShells}.
260
+ *
261
+ * @param distro - the distro name.
262
+ * @returns an absolute path to the shell inside the distro.
263
+ * @throws {Error} when neither the config nor the distro names a usable
264
+ * shell — the failure is not cached, so the next call re-probes.
265
+ */
266
+ async shellFor(distro) {
267
+ const config = this.config;
268
+ if (config.shell.length > 0)
269
+ return config.shell;
270
+ if (this.resolvedDistro.length > 0 && distro === this.resolvedDistro)
271
+ return this.shell();
272
+ const cached = this.resolvedShells.get(distro);
273
+ if (cached !== undefined)
274
+ return cached;
275
+ const resolved = await defaultShell(distro, { wslPath: config.wslPath });
276
+ if (resolved !== undefined)
277
+ this.resolvedShells.set(distro, resolved);
278
+ if (resolved === undefined)
279
+ throw unusableShell(distro);
280
+ return resolved;
281
+ }
282
+ /**
283
+ * The shell for the default/pinned distro: the configured one, else the
284
+ * login shell, resolved once and cached.
285
+ *
286
+ * @returns an absolute path to the shell inside the distro.
287
+ * @throws {Error} when neither the config nor the distro names a usable
288
+ * shell — the failure is not cached, so the next call re-probes.
289
+ */
290
+ async shell() {
291
+ const config = this.config;
292
+ if (this.resolvedShell.length === 0) {
293
+ const distro = await this.distro();
294
+ // An unresolvable shell fails the command loudly: the probes both came
295
+ // back empty (a cold distro, a flaky first wsl.exe call, a musl distro
296
+ // without getent), and running the command under some other interpreter
297
+ // would hide that from the caller. The failure is not cached — a later
298
+ // call re-probes and resolves the real shell once the distro is warm.
299
+ const resolved = await defaultShell(distro, { wslPath: config.wslPath });
300
+ if (resolved)
301
+ this.resolvedShell = resolved;
302
+ else
303
+ throw unusableShell(distro);
304
+ }
305
+ return this.resolvedShell;
306
+ }
307
+ /**
308
+ * Windows directory the `wsl.exe` process is started from.
309
+ *
310
+ * @returns the host directory to spawn in.
311
+ */
312
+ hostCwd() {
313
+ const config = this.config;
314
+ return config.hostCwd.get() ?? process.env.SystemRoot ?? process.cwd();
315
+ }
316
+ /**
317
+ * The shared resident agent serving this executor's distro.
318
+ *
319
+ * @param distro - the resolved distro name.
320
+ * @returns the shared agent.
321
+ */
322
+ executionAgent(distro) {
323
+ return sharedAgent(distro);
324
+ }
325
+ /**
326
+ * The persistent session runtime for one policy, when `sessionSandbox` is
327
+ * on. The executor holds one reference per `(session, distro, workspace, policy)` and
328
+ * releases them when the session's scope disposes.
329
+ *
330
+ * @param policy - the resolved file-effect policy, when the executor has one.
331
+ * @param resolved - the resolved spec, for the fallback workspace.
332
+ * @param distro - the resolved distro name.
333
+ * @returns the runtime entry, or undefined when the mode is off.
334
+ */
335
+ sessionRuntimeFor(policy, resolved, distro, writableRoots = []) {
336
+ const config = this.config;
337
+ if (!config.sessionSandbox)
338
+ return undefined;
339
+ const mode = policy?.mode ?? "danger-full-access";
340
+ const workspaceRoot = policy?.workspaceRoot ?? (configuredCwd(this.config) || resolved.workdir);
341
+ const sessionId = policy?.sessionId || resolved.dshEnv?.DSH_SESSION_ID || this.sessionRuntimeOwner;
342
+ const key = SessionRuntimes.key({ sessionId, distro, workspaceRoot, mode, maskWindowsDrive: effectiveMaskWindowsDrive(config), writableRoots });
343
+ const held = this.sessionRuntimeEntries.get(key);
344
+ if (held !== undefined)
345
+ return held;
346
+ const entry = this.sessionRuntimes.acquire({
347
+ sessionId,
348
+ distro,
349
+ wslPath: config.wslPath,
350
+ workspaceRoot,
351
+ mode,
352
+ maskWindowsDrive: effectiveMaskWindowsDrive(config),
353
+ writableRoots,
354
+ });
355
+ this.sessionRuntimeEntries.set(key, entry);
356
+ return entry;
357
+ }
358
+ /**
359
+ * Run the session runtime's preflight once per executor. A failure is a
360
+ * configuration verdict, not an agent outage: it is raised as an Error with
361
+ * the remedy, so the command fails closed instead of falling back to the
362
+ * per-command sandbox. Only success is cached, so a user who follows the
363
+ * remedy (`loginctl enable-linger`, `[boot] systemd=true`) does not need to
364
+ * restart the app.
365
+ *
366
+ * @param distro - the resolved distro name.
367
+ * @returns resolved once the platform can host a session runtime.
368
+ * @throws {Error} with the remedy when it cannot.
369
+ */
370
+ async ensureSessionRuntimeUsable(distro) {
371
+ if (this.sessionRuntimePreflight.has(distro))
372
+ return;
373
+ const config = this.config;
374
+ const problem = await probeSessionRuntime({ wslPath: config.wslPath, distro, run: this.sessionScopeProbe });
375
+ if (problem !== null)
376
+ throw new Error(problem);
377
+ await ensureNativeSessionAgent({ wslPath: config.wslPath, distro, setNative: setSessionNativeAgent });
378
+ this.sessionRuntimePreflight.add(distro);
379
+ }
380
+ /**
381
+ * Whether this executor should use the session runtime for one distro, with
382
+ * the `auto` downgrade and its bounded re-probe. `true` keeps the refusing
383
+ * behavior; `false` stays off.
384
+ *
385
+ * @param distro - the resolved distro.
386
+ * @returns whether to acquire the per-session scope.
387
+ */
388
+ async wantsSessionRuntime(distro) {
389
+ const config = this.config;
390
+ return sessionRuntimeWanted(config.sessionSandbox, distro, () => this.ensureSessionRuntimeUsable(distro), this.autoSessionScope);
391
+ }
392
+ /**
393
+ * Release every runtime this executor holds, stopping each scope. Called
394
+ * from the session's dispose hook; public so tests and shutdown paths can
395
+ * await it.
396
+ *
397
+ * @returns resolved once every runtime is torn down.
398
+ */
399
+ async disposeSessionRuntimes() {
400
+ const entries = [...this.sessionRuntimeEntries.values()];
401
+ this.sessionRuntimeEntries.clear();
402
+ for (const entry of entries)
403
+ await this.sessionRuntimes.release(entry.key);
404
+ }
405
+ /**
406
+ * The argv that runs INSIDE the distro for one spec: the resolved shell, its
407
+ * login/command flags, and the command string. This is the argv a
408
+ * distro-side sandbox wraps, which is why it is built separately from the
409
+ * `wsl.exe` invocation around it.
410
+ *
411
+ * @param spec - the resolved spec from {@link LocalBashExecutor.resolve}.
412
+ * @param shell - the resolved distro shell.
413
+ * @returns the distro-side argv.
414
+ */
415
+ distroArgv(spec, shell) {
416
+ const config = this.config;
417
+ return [shell, ...shellArgs(shell, config.loginShell), spec.command];
418
+ }
419
+ /**
420
+ * Build the `wsl.exe` argv for one resolved spec. The command string is
421
+ * passed as a single argv element to the resolved shell, so there is no
422
+ * quoting layer of our own; Node's argv array reaches `wsl.exe` verbatim.
423
+ *
424
+ * `--exec` is load-bearing — see the comment inside.
425
+ *
426
+ * @param spec - the resolved spec from {@link LocalBashExecutor.resolve}.
427
+ * @param distro - the resolved distro name.
428
+ * @param shell - the resolved distro shell.
429
+ * @param inner - the already-confined distro argv, when confinement applies.
430
+ * @returns the argv to spawn.
431
+ */
432
+ argv(spec, distro, shell, inner) {
433
+ const config = this.config;
434
+ const distroArgs = distro.length > 0 ? ["-d", distro] : [];
435
+ return [
436
+ config.wslPath,
437
+ ...distroArgs,
438
+ "--cd",
439
+ toLinuxPath(spec.workdir),
440
+ // `--exec` is essential, not decoration. Without it wsl.exe hands the
441
+ // command line to the distro's DEFAULT SHELL, which expands it once before
442
+ // our own shell ever sees it: `x=1; echo "$x"` arrives as `x=1; echo ""`,
443
+ // `$?` becomes the outer shell's status, and `$(...)`, `${...}`, `$1` and
444
+ // backticks are eaten the same way. With `--exec` the argv is passed
445
+ // straight through, so the command string reaches the shell verbatim.
446
+ //
447
+ // Note the shell is named explicitly here even though `--exec` plus the
448
+ // distro's default shell would look equivalent: without `--exec` we get the
449
+ // double parse above, so the shell has to be resolved by us instead.
450
+ "--exec",
451
+ ...(inner ?? this.distroArgv(spec, shell)),
452
+ ];
453
+ }
454
+ /**
455
+ * Override only the spawn's working directory and environment. `spec.workdir`
456
+ * is a Linux path, which a Windows CreateProcess call cannot use as `cwd`.
457
+ *
458
+ * The inherited builder is private, so the call goes through the
459
+ * {@link SpawnSeamExecutor} bridge (`inheritedSpawnSpec`) instead of `super`
460
+ * — see docs/UPSTREAM-SPAWN-SEAM.md.
461
+ *
462
+ * @param spec - resolved execution settings.
463
+ * @param argv - the argv from {@link WslShellExecutor.argv}.
464
+ * @param stdoutMaxBytes - per-call stdout cap.
465
+ * @param signal - the spawn cancellation signal.
466
+ * @returns the subprocess spawn spec.
467
+ */
468
+ spawnSpec(spec, argv, stdoutMaxBytes, signal) {
469
+ const config = this.config;
470
+ const base = inheritedSpawnSpec.call(this, spec, argv, stdoutMaxBytes, signal);
471
+ const forward = new Set([...SAFE_FORWARD, ...config.forwardEnv]);
472
+ const forwarded = Object.keys(base.env ?? {}).filter((name) => forward.has(name) || name.startsWith(DSH_ENV_PREFIX));
473
+ return {
474
+ ...base,
475
+ cwd: this.hostCwd(),
476
+ env: {
477
+ ...base.env,
478
+ // wsl.exe writes its own diagnostics as UTF-16LE unless this is set, and a
479
+ // UTF-16 message read as UTF-8 is mojibake — including the `WSL_E_*` codes
480
+ // that say why a command could not start. The distro-missing check below
481
+ // reads those codes, so the encoding has to be pinned here.
482
+ WSL_UTF8: "1",
483
+ // WSL imports only the names listed in WSLENV. The managed DSH_* facts are
484
+ // included by prefix so every contributed variable rides along. PATH is deliberately
485
+ // never listed: putting it here would replace the distro's PATH with
486
+ // the Windows one instead of appending the interop entries WSL adds
487
+ // on its own.
488
+ ...(forwarded.length > 0 ? { WSLENV: forwarded.map((name) => (PATH_TRANSLATED.has(name) ? `${name}/p` : name)).join(":") } : {}),
489
+ },
490
+ };
491
+ }
492
+ /**
493
+ * Resolve a request into a spec, replacing the parent's `process.cwd()`
494
+ * fallback with this provider's distro-home marker and stamping the per-call
495
+ * sandbox policy.
496
+ *
497
+ * The seam requires this step to be synchronous — the tool layer calls
498
+ * `ctx.shell.execute(ctx.shell.resolve(…))` with no `await` between them — so
499
+ * neither the home nor a confinement decision can be made here. Two request
500
+ * shapes default to the home when no `cwd` is configured: one that names no
501
+ * `workdir` at all, and one that names it only RELATIVELY — the parent
502
+ * resolves the first against `process.cwd()` (a Windows directory) and has
503
+ * nothing of its own to join the second onto. Both are stamped as the empty
504
+ * marker, with a relative tail carried verbatim in `relativeWorkdir`;
505
+ * {@link withDefaultWorkdir} resolves the pair against the home. The policy
506
+ * travels on the spec to {@link execute}, which awaits the wrap.
507
+ *
508
+ * @param request - the caller's request.
509
+ * @returns the fully-resolved spec.
510
+ */
511
+ resolve(request) {
512
+ const config = this.config;
513
+ const spec = super.resolve(request);
514
+ const sandboxPolicy = this.sandbox === undefined ? undefined : (request?.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve());
515
+ const workdir = typeof request?.workdir === "string" ? request.workdir : undefined;
516
+ const needsHome = configuredCwd(config).length === 0 && (workdir === undefined || isRelativeWorldPath(workdir));
517
+ if (!needsHome && sandboxPolicy === undefined)
518
+ return spec;
519
+ return {
520
+ ...spec,
521
+ ...(needsHome ? { workdir: "", relativeWorkdir: workdir } : {}),
522
+ ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }),
523
+ };
524
+ }
525
+ /**
526
+ * The spec to execute, with the home marker resolved against the distro
527
+ * user's home: `workdir: ""` becomes the home itself, and a relative tail
528
+ * carried by {@link WslShellExecutor.resolve} is joined under it. That is one
529
+ * `sh -c 'printf %s "$HOME"'` per provider instance, cached, and it happens
530
+ * only for a request that defaulted — an absolute workdir never reaches here.
531
+ *
532
+ * @param spec - the resolved spec.
533
+ * @returns the spec to execute.
534
+ */
535
+ async withDefaultWorkdir(spec) {
536
+ const tail = typeof spec?.relativeWorkdir === "string" ? spec.relativeWorkdir : undefined;
537
+ if (String(spec?.workdir ?? "").trim().length > 0 && tail === undefined)
538
+ return spec;
539
+ const distro = await this.distroFor(spec.workdir, configuredCwd(this.config));
540
+ const home = await distroHome(this, distro);
541
+ if (tail === undefined || tail.length === 0)
542
+ return { ...spec, workdir: home };
543
+ return { ...spec, workdir: toLinuxPath(tail, { cwd: home }) };
544
+ }
545
+ /**
546
+ * Decorate a handle's foreground projection in place, memoized once. The
547
+ * handle keeps its identity — never wrapped in a second object — because the
548
+ * per-process facts and `onProcessDone` key on the exact instance.
549
+ *
550
+ * @template H - the concrete handle type, preserved so the decorated handle
551
+ * keeps its identity in the callers' types; the settled result row the maps
552
+ * are spelled in is derived from its `result()`.
553
+ * @param ex - the execution handle to decorate.
554
+ * @param map - maps the settled result.
555
+ * @param mapError - maps a rejection, when the caller has one.
556
+ * @returns the same handle.
557
+ */
558
+ static decorateResult(ex, map, mapError) {
559
+ const handle = ex;
560
+ const base = handle.result.bind(handle);
561
+ let decorated;
562
+ handle.result = () => {
563
+ decorated ??= base().then(map, mapError);
564
+ return decorated;
565
+ };
566
+ return ex;
567
+ }
568
+ /**
569
+ * Stamp the per-process sandbox facts before `done` settles, so a background
570
+ * process reports the same mode, denial and enforcement a foreground run
571
+ * would. Signal deaths are not denials.
572
+ *
573
+ * @param proc - the settled process handle.
574
+ * @param stderr - the process's retained stderr tail used by subclasses for settlement classification.
575
+ * @param providerRejected - whether the subprocess promise rejected without a direct outcome.
576
+ * @param providerError - the provider rejection reason, which may itself be undefined.
577
+ */
578
+ onProcessDone(proc, stderr, providerRejected, providerError) {
579
+ const facts = this.processFacts.get(proc);
580
+ if (facts !== undefined) {
581
+ this.processFacts.delete(proc);
582
+ // A provider rejection exposes no public failure stage; attribute it to
583
+ // the confinement runner only when the error independently names argv[0].
584
+ const runnerFailed = providerRejected
585
+ ? isRunnerSpawnFailure(providerError, facts.runnerProgram, facts.workdir)
586
+ : classifyRunnerFailure(proc.exitCode, stderr, facts.runnerFailureRules) !== undefined;
587
+ proc.sandbox = {
588
+ mode: facts.mode,
589
+ denied: !runnerFailed && matchesSignature(proc.exitCode, stderr, facts.denialSignatures),
590
+ enforcement: facts.enforcement,
591
+ ...(facts.windowsDrive ? { windowsDrive: facts.windowsDrive } : {}),
592
+ sessionScope: facts.sessionScope,
593
+ ...(runnerFailed ? { runnerFailed } : {}),
594
+ };
595
+ }
596
+ super.onProcessDone(proc, stderr, providerRejected, providerError);
597
+ }
598
+ /**
599
+ * Reject a settled command that failed because the distro itself is missing,
600
+ * stopped or unregistered.
601
+ *
602
+ * `wsl.exe` exits non-zero for that with an EMPTY stderr and its diagnostic on
603
+ * stdout, so nothing else here can see it: the denial signatures read stderr, and
604
+ * the result would otherwise reach the model as a bare non-zero code with no
605
+ * cause. The message names the remedy and says plainly that a wider permission
606
+ * cannot help — a sandbox flag does not create a distro.
607
+ *
608
+ * @param result - the settled shell result.
609
+ * @param distro - the distro the command asked for.
610
+ * @throws {Error} carrying the `WSL_E_*` code and the remedy.
611
+ */
612
+ throwIfDistroUnavailable(result, distro) {
613
+ if (result?.exitCode === 0)
614
+ return;
615
+ const code = wslErrorCode(result?.stdout?.text, result?.stderr?.text);
616
+ if (code === undefined)
617
+ return;
618
+ throw new Error(t("distroUnavailable", { code, distro }));
619
+ }
620
+ /**
621
+ * Reject a command that ran in the wrong directory.
622
+ *
623
+ * `wsl.exe --cd <path>` does not fail on a missing directory: it warns on stderr,
624
+ * runs the command in `/`, and exits 0. Reporting that as success would let a write
625
+ * or a build act on the wrong tree while every signal says it worked, so it becomes
626
+ * an error naming the directory that could not be entered.
627
+ *
628
+ * @param result - the settled shell result.
629
+ * @param workdir - the Linux directory the request asked for.
630
+ * @throws {Error} naming the directory and the fallback that happened.
631
+ */
632
+ throwIfWorkdirMissing(result, workdir) {
633
+ const missing = workdirFailure(result?.stdout?.text, result?.stderr?.text);
634
+ if (missing === undefined)
635
+ return;
636
+ throw new Error(t("workdirMissing", { missing }));
637
+ }
638
+ /**
639
+ * The effective extra writable roots for one command: the row's
640
+ * `writableRoots` plus the shared policy's `additionalWritableRoots`,
641
+ * resolved to Linux paths and checked once per process. Empty unless the
642
+ * command is confined under `workspace-write`.
643
+ *
644
+ * @param distro - the distro the command runs in.
645
+ * @param policy - the per-call file-effect policy, when there is one.
646
+ * @param signal - optional cancellation for the one-time check.
647
+ * @returns the roots every confinement site binds.
648
+ * @throws {SandboxInvalidRootError} when an entry cannot be granted or checked.
649
+ */
650
+ async writableRootsFor(distro, policy, signal) {
651
+ const config = this.config;
652
+ if (!config.sandbox || policy === undefined || policy.mode !== "workspace-write")
653
+ return [];
654
+ if ((config.writableRoots?.length ?? 0) === 0 && (policy.additionalWritableRoots?.length ?? 0) === 0)
655
+ return [];
656
+ // Only a `~` entry needs the distro home. Policy entries are absolute
657
+ // execution-world paths, and absolute row entries need no probe — which
658
+ // keeps a policy-only grant (the composition tests' case) from spawning
659
+ // `wsl.exe` on a machine that has none.
660
+ const needsHome = (config.writableRoots ?? []).some((root) => root === "~" || root.startsWith("~/"));
661
+ const home = needsHome ? await distroHome(this, distro) : "";
662
+ return effectiveWritableRoots({
663
+ configured: config.writableRoots,
664
+ policy,
665
+ distro,
666
+ home,
667
+ wslPath: config.wslPath,
668
+ signal,
669
+ run: this.writableRootsProbe,
670
+ });
671
+ }
672
+ /**
673
+ * Execute one resolved spec inside the distro, confined by the per-call policy
674
+ * when there is one.
675
+ *
676
+ * Confinement wraps the DISTRO-side argv (`<shell> -lc <command>`) in `bwrap`
677
+ * and hands the result to `wsl.exe --exec`, so the sandbox is built inside the
678
+ * distro while the process that spawns it stays the ordinary Windows one. The
679
+ * `danger-full-access` escalation — and an operator's `sandbox: false` — skip
680
+ * the wrap entirely and run the command as before.
681
+ *
682
+ * @param spec - resolved execution settings.
683
+ * @returns the live shell process handle.
684
+ */
685
+ async execute(spec) {
686
+ const config = this.config;
687
+ const resolved = await this.withDefaultWorkdir(spec);
688
+ const distro = await this.distroFor(resolved.workdir, configuredCwd(config));
689
+ const shell = await this.shellFor(distro);
690
+ this.throwIfWorkdirInAnotherDistro(resolved.workdir, distro);
691
+ const writableRoots = await this.writableRootsFor(distro, resolved.sandboxPolicy, resolved.signal);
692
+ if (config.agent) {
693
+ try {
694
+ return await this.executeViaAgent(resolved, distro, shell, writableRoots);
695
+ }
696
+ catch (error) {
697
+ // Only an out-of-service agent falls back; anything else (a cwd
698
+ // refusal, a sandbox refusal) is the command's own verdict.
699
+ if (!(error instanceof AgentUnavailableError))
700
+ throw error;
701
+ }
702
+ }
703
+ return this.executeOneShot(resolved, distro, shell, writableRoots);
704
+ }
705
+ /**
706
+ * Refuse a workdir that names another WSL distro — the shell-side twin of
707
+ * the filesystem's `FS_OUTSIDE_DISTRO` fence. Left unguarded, `toLinuxPath`
708
+ * strips the UNC's distro name and the command runs inside THIS distro
709
+ * against whatever tree happens to share the path, silently, while the fs
710
+ * side refuses the same workspace outright. The wording mirrors the fs
711
+ * refusal (minus `restrictToDistro`, which is an fs-only key).
712
+ *
713
+ * @param workdir - the resolved workdir (UNC, Linux path, or Windows path).
714
+ * @param distro - the pinned distro name.
715
+ * @throws {Error} naming both distros and both ways out.
716
+ */
717
+ throwIfWorkdirInAnotherDistro(workdir, distro) {
718
+ if (!isAnotherDistrosUnc(workdir, distro))
719
+ return;
720
+ throw new Error(t("workdirAnotherDistro", { workdir, distro }));
721
+ }
722
+ /**
723
+ * The agent-backed execution path: one long-lived in-distro process, the
724
+ * confinement argv unchanged, the handle shape unchanged. Any
725
+ * {@link AgentUnavailableError} propagates for the caller's fallback.
726
+ *
727
+ * @param resolved - the resolved spec from {@link WslShellExecutor.execute}.
728
+ * @param distro - the resolved distro name.
729
+ * @param shell - the resolved distro shell.
730
+ * @returns the decorated execution result.
731
+ */
732
+ async executeViaAgent(resolved, distro, shell, writableRoots = []) {
733
+ const config = this.config;
734
+ const policy = resolved.sandboxPolicy;
735
+ const confined = this.sandbox !== undefined && policy !== undefined && policy.mode !== "danger-full-access"
736
+ ? await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode: policy.mode }, { distro, signal: resolved.signal, writableRoots })
737
+ : undefined;
738
+ const mode = policy?.mode;
739
+ const useScope = await this.wantsSessionRuntime(distro);
740
+ const runtime = useScope ? this.sessionRuntimeFor(policy, resolved, distro, writableRoots) : undefined;
741
+ const agent = runtime !== undefined ? runtime.agent : await this.executionAgent(distro);
742
+ // A session runtime's own bwrap profile applies the mounts, so the
743
+ // command must NOT be wrapped a second time: the per-command probe still
744
+ // runs (it is the bwrap availability check and the denial facts), but its
745
+ // argv is discarded.
746
+ const argv = runtime !== undefined
747
+ ? this.distroArgv(resolved, shell)
748
+ : confined !== undefined ? confined.argv : this.distroArgv(resolved, shell);
749
+ // The managed `DSH_*` snapshot merges last, exactly as the one-shot path's
750
+ // spawn env does (`ShellExecSpec`: `dshEnv` wins over `env`). The agent
751
+ // applies these to the individual command, so
752
+ // the resident path now carries `DSH_HOME`, `DSH_SESSION_ID` and the
753
+ // `DSH_WSL_*` facts too — without this the whole registry was invisible on
754
+ // the default path while the one-shot fallback forwarded it.
755
+ const env = { ...resolved.env, ...resolved.dshEnv };
756
+ const execution = agentExecutionHandle({
757
+ agent,
758
+ // The one-shot path converts the spec's workdir into the distro's
759
+ // coordinate system inside argv(); the agent carries the cwd as a frame
760
+ // field, so the SAME conversion happens here — a raw UNC must never
761
+ // reach `chdir` (that is the bug this line fixes).
762
+ cwd: toLinuxPath(resolved.workdir),
763
+ argv,
764
+ env: Object.keys(env).length > 0 ? env : undefined,
765
+ timeoutMs: resolved.timeoutMs,
766
+ // The agent enforces the collect budget distro-side (the EXEC frame
767
+ // carries it); `maxSpillBytes` stays one-shot-only — the agent path has
768
+ // no spill files by design, its capture is bounded instead. The budget
769
+ // is the executor's own per-stream cap, read through the volatile
770
+ // wrapper like every other volatile field: handing the wrapper over raw
771
+ // made `encodeExecFrame`'s `> 0` test false, so the frame carried 0 —
772
+ // which the agent reads as "uncapped", and the documented cut never ran.
773
+ maxOutputBytes: config.maxOutputBytes.get(),
774
+ signal: resolved.signal,
775
+ onStarted: confined !== undefined
776
+ ? (proc) => {
777
+ // The untyped guard cannot narrow the captured profile inside the
778
+ // callback, so the confined shape is asserted once here.
779
+ const profile = confined;
780
+ this.processFacts.set(proc, {
781
+ mode,
782
+ enforcement: profile.enforcement,
783
+ denialSignatures: profile.denialSignatures,
784
+ runnerFailureRules: profile.runnerFailureRules,
785
+ runnerProgram: profile.argv[0] ?? "",
786
+ workdir: resolved.workdir,
787
+ windowsDrive: profile.windowsDrive,
788
+ sessionScope: useScope ? "session" : "per-command",
789
+ });
790
+ }
791
+ : undefined,
792
+ });
793
+ const decorated = WslShellExecutor.decorateResult(execution, (result) => {
794
+ this.throwIfDistroUnavailable(result, distro);
795
+ this.throwIfWorkdirMissing(result, resolved.workdir);
796
+ if (this.sandbox === undefined)
797
+ return result;
798
+ if (confined === undefined) {
799
+ return ({ ...result, sandbox: { mode, denied: false, sessionScope: useScope ? "session" : "per-command" } });
800
+ }
801
+ const { enforcement, denialSignatures, runnerFailureRules, windowsDrive } = confined;
802
+ const runnerFailure = classifyRunnerFailure(result.exitCode, result.stderr.text, runnerFailureRules);
803
+ if (runnerFailure !== undefined) {
804
+ // This path computes `mode` as `policy?.mode`, which the seam spells as
805
+ // the wider union: a runner failure is only ever thrown under a
806
+ // confinement, and there the mode is one of the two confined ones.
807
+ throw new SandboxUnavailableError(mode, withBwrapHint(runnerFailure.detail, distro));
808
+ }
809
+ return ({
810
+ ...result,
811
+ sandbox: {
812
+ mode,
813
+ denied: matchesSignature(result.exitCode, result.stderr.text, denialSignatures),
814
+ enforcement,
815
+ windowsDrive,
816
+ sessionScope: useScope ? "session" : "per-command",
817
+ },
818
+ });
819
+ }, (error) => {
820
+ if (resolved.signal?.aborted === true)
821
+ resolved.signal.throwIfAborted();
822
+ // The native agent reports a missing workdir as a spawn failure without
823
+ // naming it. Retry that command on the one-shot path, whose `--cd`
824
+ // warning names the directory — the failure path pays the extra spawn,
825
+ // the hot path does not.
826
+ if (error instanceof SpawnError) {
827
+ return this.executeOneShot(resolved, distro, shell, writableRoots).then((fallback) => fallback.result());
828
+ }
829
+ throw error;
830
+ });
831
+ // The agent handle IS the upstream execution shape at runtime; its typedef
832
+ // spells `signal` as `string` and the captured streams without `spillPath`,
833
+ // so the upstream-facing return rides one type-level cast.
834
+ return decorated;
835
+ }
836
+ /**
837
+ * The pre-agent execution path, verbatim: one `wsl.exe` per command through
838
+ * the inherited `executeArgv` machinery. Kept as the permanent fallback for
839
+ * an out-of-service agent and as the `agent: false` behaviour.
840
+ *
841
+ * @param resolved - the resolved spec.
842
+ * @param distro - the resolved distro name.
843
+ * @param shell - the resolved distro shell.
844
+ * @returns the decorated execution result.
845
+ */
846
+ async executeOneShot(resolved, distro, shell, writableRoots = []) {
847
+ const policy = resolved.sandboxPolicy;
848
+ if (this.sandbox === undefined || policy === undefined || policy.mode === "danger-full-access") {
849
+ // `executeArgv` resolves to the execution handle, so it has to be awaited
850
+ // before it can be decorated — the confined branch below does the same.
851
+ // The sync thunk is the prepare form at runtime (`executeArgv` awaits any
852
+ // function it is given); the type spells it as the async prepare it is
853
+ // used as, which is why the thunk rides a type-level cast.
854
+ const execution = await this.executeArgv(resolved, (() => this.argv(resolved, distro, shell)));
855
+ return WslShellExecutor.decorateResult(execution, (result) => {
856
+ this.throwIfDistroUnavailable(result, distro);
857
+ this.throwIfWorkdirMissing(result, resolved.workdir);
858
+ return result;
859
+ }, (error) => {
860
+ throw error;
861
+ });
862
+ }
863
+ // The confined prepare closes over this slot: the argv builder assigns it,
864
+ // the fact-stamper and the settlement mapping read it. `executeArgv` runs
865
+ // the builder before either callback can fire, so the reads always see the
866
+ // assigned profile (or the run never happened). The mode is captured once
867
+ // here: the guard above narrowed it, and property narrowings do not reach
868
+ // closures.
869
+ const mode = policy.mode;
870
+ const confinement = { profile: undefined };
871
+ const execution = await this.executeArgv(resolved, (signal) => this.prepareConfinedArgv(resolved, distro, shell, policy, mode, confinement, writableRoots, signal), (process) => this.stampConfinedFacts(resolved, mode, confinement, process));
872
+ return WslShellExecutor.decorateResult(execution, (result) => {
873
+ return this.settleConfinedOneShot(result, distro, resolved, mode, confinement.profile);
874
+ }, (error) => {
875
+ // An upstream abort remains cancellation even when it prevents spawn.
876
+ if (resolved.signal?.aborted === true)
877
+ resolved.signal.throwIfAborted();
878
+ if (confinement.profile !== undefined && isRunnerSpawnFailure(error, confinement.profile.argv[0], resolved.workdir)) {
879
+ throw new SandboxUnavailableError(mode, withBwrapHint(String(error), distro));
880
+ }
881
+ throw error;
882
+ });
883
+ }
884
+ /**
885
+ * The confined one-shot's argv prepare: confine the distro argv under the
886
+ * policy, keep the resulting profile for the fact-stamper and the settlement
887
+ * mapping, and hand back the wrapped host argv.
888
+ *
889
+ * @param resolved - the resolved spec.
890
+ * @param distro - the resolved distro name.
891
+ * @param shell - the resolved distro shell.
892
+ * @param policy - the confined policy (narrowed in by `executeOneShot`).
893
+ * @param slot - the closure the builder assigns the profile into.
894
+ * @param writableRoots - the effective extra roots the profile binds.
895
+ * @param signal - the caller's cancellation.
896
+ */
897
+ async prepareConfinedArgv(resolved, distro, shell, policy, mode, slot, writableRoots, signal) {
898
+ // Preparation is async, so it runs under executeArgv's deadline and
899
+ // cancellation handling rather than before them. A distro without a
900
+ // usable runner throws here, before anything is spawned. The outer
901
+ // guard narrowed the sandbox in, but narrowings do not reach closures —
902
+ // so the confined sandbox is asserted here, type-level only.
903
+ const profile = await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode }, { distro, signal, writableRoots });
904
+ slot.profile = profile;
905
+ signal.throwIfAborted();
906
+ return this.argv(resolved, distro, shell, profile.argv);
907
+ }
908
+ /**
909
+ * Stamp the per-process sandbox facts before `done` settles, so a background
910
+ * process reports the same mode, denial and enforcement a foreground run
911
+ * would.
912
+ *
913
+ * @param resolved - the resolved spec.
914
+ * @param mode - the confined policy's mode.
915
+ * @param slot - the closure holding the assigned profile.
916
+ * @param process - the spawned handle.
917
+ */
918
+ stampConfinedFacts(resolved, mode, slot, process) {
919
+ // The builder has run before any process callback can fire; the confined
920
+ // shape is asserted once here, type-level only.
921
+ const profile = slot.profile;
922
+ this.processFacts.set(process, {
923
+ mode,
924
+ enforcement: profile.enforcement,
925
+ denialSignatures: profile.denialSignatures,
926
+ runnerFailureRules: profile.runnerFailureRules,
927
+ runnerProgram: profile.argv[0] ?? "",
928
+ workdir: resolved.workdir,
929
+ windowsDrive: profile.windowsDrive,
930
+ sessionScope: "per-command",
931
+ });
932
+ }
933
+ /**
934
+ * Settle one confined one-shot result: the distro and workdir verdicts, the
935
+ * never-armed honesty stamp, the runner-failure throw, and the denial facts.
936
+ *
937
+ * @param result - the settled process result.
938
+ * @param distro - the resolved distro name.
939
+ * @param resolved - the resolved spec.
940
+ * @param mode - the confined policy's mode.
941
+ * @param confined - the profile the argv prepare armed, when it ran.
942
+ */
943
+ settleConfinedOneShot(result, distro, resolved, mode, confined) {
944
+ this.throwIfDistroUnavailable(result, distro);
945
+ this.throwIfWorkdirMissing(result, resolved.workdir);
946
+ if (confined === undefined) {
947
+ return ({ ...result, sandbox: { mode, denied: false, sessionScope: "per-command" } });
948
+ }
949
+ const { enforcement, denialSignatures, runnerFailureRules, windowsDrive } = confined;
950
+ // Runner failure outranks denial because the command did not run at all.
951
+ const runnerFailure = classifyRunnerFailure(result.exitCode, result.stderr.text, runnerFailureRules);
952
+ if (runnerFailure !== undefined)
953
+ throw new SandboxUnavailableError(mode, withBwrapHint(runnerFailure.detail, distro));
954
+ return ({
955
+ ...result,
956
+ sandbox: {
957
+ mode,
958
+ denied: matchesSignature(result.exitCode, result.stderr.text, denialSignatures),
959
+ enforcement,
960
+ windowsDrive,
961
+ sessionScope: "per-command",
962
+ },
963
+ });
964
+ }
965
+ }