dsh-plugin-wsl-env 0.24.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +136 -0
- package/CODE_OF_CONDUCT.md +85 -0
- package/CODE_OF_CONDUCT.zh.md +85 -0
- package/CONTRIBUTING.md +19 -3
- package/CONTRIBUTING.zh.md +200 -0
- package/README.md +18 -6
- package/SECURITY.md +12 -0
- package/SECURITY.zh.md +108 -0
- package/SUPPORT.md +2 -0
- package/SUPPORT.zh.md +99 -0
- package/client.js +409 -8
- package/cordis.patch.yml +17 -0
- package/docs/AGENT-PROTOCOL-V7.md +2 -2
- package/docs/API.md +2 -0
- package/docs/API.zh.md +38 -0
- package/docs/ARCHITECTURE.md +30 -9
- package/docs/ARCHITECTURE.zh.md +511 -0
- package/docs/COMPATIBILITY.md +2 -0
- package/docs/COMPATIBILITY.zh.md +117 -0
- package/docs/CONFIGURATION.md +45 -2
- package/docs/CONFIGURATION.zh.md +39 -3
- package/docs/DIAGNOSTICS.md +12 -2
- package/docs/DIAGNOSTICS.zh.md +5 -1
- package/docs/LIMITATIONS.md +60 -9
- package/docs/LIMITATIONS.zh.md +45 -9
- package/docs/MIGRATION.md +6 -3
- package/docs/MIGRATION.zh.md +91 -0
- package/docs/PEER-PARITY.md +63 -51
- package/docs/PERFORMANCE.md +2 -0
- package/docs/PERFORMANCE.zh.md +59 -0
- package/docs/QUICKSTART.md +21 -6
- package/docs/QUICKSTART.zh.md +16 -4
- package/docs/README.zh.md +28 -19
- package/docs/RELEASING.md +19 -14
- package/docs/REQUIREMENTS.zh.md +6 -3
- package/docs/ROADMAP-1.0.md +1 -1
- package/docs/UPSTREAM-FILE-REFERENCE-SEAM.md +1 -1
- package/docs/UPSTREAM-FSIO-EXPORT.md +5 -4
- package/docs/UPSTREAM-OPEN-IN-APP.md +33 -11
- package/docs/UPSTREAM-PROMPT-ADAPTERS.md +85 -0
- package/docs/UPSTREAM-SESSION-NOTICE.md +7 -0
- package/docs/VALUE.md +146 -0
- package/docs/VALUE.zh.md +15 -13
- package/docs/root-fs-routing.md +1 -1
- package/lib/agent-confined.d.ts +7 -1
- package/lib/agent-confined.js +3 -3
- package/lib/auto-preset-seam.d.ts +45 -0
- package/lib/auto-preset-seam.js +47 -0
- package/lib/auto-preset.d.ts +33 -10
- package/lib/auto-preset.js +148 -44
- package/lib/bwrap.d.ts +14 -0
- package/lib/bwrap.js +11 -0
- package/lib/cwd-prompt.d.ts +41 -3
- package/lib/cwd-prompt.js +125 -8
- package/lib/doctor-live.d.ts +30 -0
- package/lib/doctor-live.js +37 -0
- package/lib/doctor-report.d.ts +50 -0
- package/lib/doctor-report.js +172 -0
- package/lib/fs-routing.d.ts +1 -1
- package/lib/fs-routing.js +1 -1
- package/lib/fs.d.ts +1 -1
- package/lib/fs.js +1 -1
- package/lib/index.d.ts +6 -1464
- package/lib/index.js +5 -2120
- package/lib/messages.d.ts +20 -1
- package/lib/messages.js +31 -3
- package/lib/open-in-app.d.ts +206 -0
- package/lib/open-in-app.js +300 -0
- package/lib/preflight.d.ts +7 -4
- package/lib/preflight.js +27 -13
- package/lib/preset-choice.d.ts +13 -0
- package/lib/preset-choice.js +18 -1
- package/lib/provider-common.d.ts +58 -0
- package/lib/provider-common.js +123 -0
- package/lib/sandbox-core.d.ts +1 -0
- package/lib/sandbox-core.js +4 -2
- package/lib/session-runtime.d.ts +7 -1
- package/lib/session-runtime.js +9 -2
- package/lib/shell.d.ts +1 -1
- package/lib/shell.js +1 -1
- package/lib/status.js +2 -1
- package/lib/writable-roots.d.ts +109 -0
- package/lib/writable-roots.js +257 -0
- package/lib/wsl-doctor-command.js +2 -1
- package/lib/wsl-doctor-tool.js +2 -2
- package/lib/wsl-filesystem.d.ts +692 -0
- package/lib/wsl-filesystem.js +897 -0
- package/lib/wsl-shell.d.ts +742 -0
- package/lib/wsl-shell.js +965 -0
- package/lib/wsl.d.ts +1 -1
- package/lib/wsl.js +1 -1
- package/package.json +48 -24
- package/scripts/doctor.mjs +1 -1
- package/scripts/profile-preset.mjs +17 -5
package/lib/index.js
CHANGED
|
@@ -1,2120 +1,5 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
* `ctx.sandbox` (confinement), `ctx.directoryPicker`, `ctx.workspaceRegistry`.
|
|
7
|
-
* The model-facing tools (`dsh-tool-fs`, `dsh-tool-fs-search`, `dsh-tool-bash`)
|
|
8
|
-
* consume those seams and never talk to a filesystem or a shell directly. A WSL
|
|
9
|
-
* integration is therefore a seam provider, not a new tool.
|
|
10
|
-
*
|
|
11
|
-
* This package provides two of them:
|
|
12
|
-
*
|
|
13
|
-
* - {@link WslShellExecutor} registers `ctx.shell` and runs every command
|
|
14
|
-
* inside the distro as `wsl.exe -d <distro> --cd <linux dir> --exec <shell> -lc <cmd>`,
|
|
15
|
-
* where `<shell>` is the distro user's login shell (not a hardcoded bash).
|
|
16
|
-
* - {@link WslFileSystem} registers `ctx.fs` and maps Linux paths onto the
|
|
17
|
-
* distro's UNC share so the host's own fs stack (including the packaged
|
|
18
|
-
* ripgrep used by `dsh-tool-fs-search`) reads and writes real distro files.
|
|
19
|
-
*
|
|
20
|
-
* ## The one constraint that shapes everything
|
|
21
|
-
*
|
|
22
|
-
* On Windows, DSH confines commands with `dsh-sandbox-windows-acl`: a
|
|
23
|
-
* restricted, low-integrity token plus a capability-SID write allowlist. That
|
|
24
|
-
* token cannot reach WSL at all — `wsl.exe` fails with `Wsl/E_ACCESSDENIED` and
|
|
25
|
-
* the UNC share `\\wsl.localhost\<distro>` reports access denied. Both work
|
|
26
|
-
* normally outside the sandbox.
|
|
27
|
-
*
|
|
28
|
-
* The confinement is applied by the *sandboxing* executor (`pwsh-sandbox`),
|
|
29
|
-
* which wraps the argv through `ctx.sandbox.confine`. This plugin therefore
|
|
30
|
-
* subclasses the NON-sandboxing `LocalBashExecutor`, and inherits
|
|
31
|
-
* `sandboxMode === undefined` from the seam — which is the honest capability
|
|
32
|
-
* fact: the tool layer reads it and advertises that these commands are not
|
|
33
|
-
* confined. WSL access is inherently outside the harness's file sandbox; do not
|
|
34
|
-
* paper over that by reporting a mode this provider does not enforce.
|
|
35
|
-
*
|
|
36
|
-
* This is a TypeScript source built to `lib/index.js`; edit THIS file and run
|
|
37
|
-
* `pnpm run build` — the artifact under `lib/` is generated, and `pnpm test`
|
|
38
|
-
* fails when it drifts.
|
|
39
|
-
*
|
|
40
|
-
* @module dsh-plugin-wsl
|
|
41
|
-
*/
|
|
42
|
-
import z from "@deepseek-ai/schemastery";
|
|
43
|
-
import { randomUUID } from "node:crypto";
|
|
44
|
-
import { LocalBashExecutor } from "@deepseek-ai/dsh-bash-local";
|
|
45
|
-
import { LocalFileSystem } from "@deepseek-ai/dsh-fs-local";
|
|
46
|
-
import { FsError } from "@deepseek-ai/dsh-fs";
|
|
47
|
-
import { canonicalPath, classifyRunnerFailure, isRunnerSpawnFailure, matchesSignature, SandboxInvalidRootError, SandboxUnavailableError, writableRoots } from "@deepseek-ai/dsh-sandbox";
|
|
48
|
-
import { isAnotherDistrosUnc, isRelativeWorldPath, isWorldPathUnder, isWslUnc, posixToUnc, toLinuxPath, toWorldPath, uncToPosix, windowsToLinuxMount } from "./paths.js";
|
|
49
|
-
import { isConfinedMutation, mutationModeRefusal, outsideDistroRefusal, shareSubstrateRefusal, substrateFailure, workspaceWriteDenial } from "./fs-decisions.js";
|
|
50
|
-
import { distroOfUnc, isDefaultDistro, pinnedDistro, selectDistro } from "./distro-route.js";
|
|
51
|
-
import { WslSandbox } from "./sandbox.js";
|
|
52
|
-
import { bwrapFailure, missingBwrapRemedy, withBwrapHint } from "./sandbox-core.js";
|
|
53
|
-
import { armDistroWatcher } from "./watcher.js";
|
|
54
|
-
import { AgentUnavailableError, SpawnError } from "./agent-errors.js";
|
|
55
|
-
import { agentExecutionHandle } from "./agent-exec.js";
|
|
56
|
-
import { sharedAgent } from "./agent-shared.js";
|
|
57
|
-
import { AgentSubstrate } from "./fs-substrate.js";
|
|
58
|
-
import { FsCodedError } from "./fsio-text.js";
|
|
59
|
-
import { confinedAgent } from "./agent-confined.js";
|
|
60
|
-
import { SessionRuntimes, probeSessionRuntime, sessionRuntimes, setSessionNativeAgent } from "./session-runtime.js";
|
|
61
|
-
import { configureAgentBackend, ensureNativeSessionAgent } from "./native-agent.js";
|
|
62
|
-
import { installMessagesLocale, t } from "./messages.js";
|
|
63
|
-
import { mergeLiveResidentStatus } from "./doctor-live.js";
|
|
64
|
-
import { spawn } from "node:child_process";
|
|
65
|
-
import { fileURLToPath } from "node:url";
|
|
66
|
-
import { dirname, join } from "node:path";
|
|
67
|
-
// `runCapture` and distro discovery live in ./wsl.js so the directory picker
|
|
68
|
-
// can use them without pulling this file's executor and filesystem peers in.
|
|
69
|
-
import { defaultDistro, defaultShell, linuxHomePath, runCapture, shellArgs, workdirFailure, wslErrorCode } from "./wsl.js";
|
|
70
|
-
/**
|
|
71
|
-
* Every model shell call gets a rebuilt managed `DSH_*` namespace (see
|
|
72
|
-
* `dsh-shell-env` / `ctx.shellEnv`). Those names exist only in the Windows-side
|
|
73
|
-
* process, so unless they are listed in WSLENV they never reach the distro and
|
|
74
|
-
* the model sees none of its environment facts.
|
|
75
|
-
*/
|
|
76
|
-
/**
|
|
77
|
-
* Of the managed facts, these two carry Windows paths. WSL's `WSLENV` `/p` flag
|
|
78
|
-
* translates them on the way in, so a command inside the distro gets a usable
|
|
79
|
-
* `/mnt/c/...` path instead of `C:\...`. `DSH_WSL_HOME` is deliberately absent:
|
|
80
|
-
* it is already a POSIX path, and translating it would corrupt it.
|
|
81
|
-
*/
|
|
82
|
-
const DSH_ENV_PREFIX = "DSH_";
|
|
83
|
-
const PATH_TRANSLATED = new Set([`${DSH_ENV_PREFIX}HOME`, `${DSH_ENV_PREFIX}PROFILE_DIR`]);
|
|
84
|
-
/** Env names that are meaningful on the Linux side and safe to forward. */
|
|
85
|
-
const SAFE_FORWARD = ["NO_COLOR", "TERM", "PAGER", "GIT_PAGER", "LANG", "LC_ALL"];
|
|
86
|
-
/**
|
|
87
|
-
* The configured default workdir, or an empty string when the operator left it
|
|
88
|
-
* unset. `cwd` is a volatile field on both providers, so it is read through
|
|
89
|
-
* `.get()`, and it may be absent entirely.
|
|
90
|
-
*
|
|
91
|
-
* @param config - a provider's config.
|
|
92
|
-
* @returns the configured directory, trimmed, or `""`.
|
|
93
|
-
*/
|
|
94
|
-
/**
|
|
95
|
-
* Opt into the native agent for one distro when `DSH_WSL_AGENT_NATIVE` names a
|
|
96
|
-
* host binary. The copy/verify is cached in `native-agent.ts`; a failure (or
|
|
97
|
-
* an unset variable) leaves the shell agent in place.
|
|
98
|
-
*
|
|
99
|
-
* @param wslPath - the `wsl.exe` path.
|
|
100
|
-
* @param distro - the resolved distro.
|
|
101
|
-
*/
|
|
102
|
-
function configuredCwd(config) {
|
|
103
|
-
return String(config.cwd?.get?.() ?? "").trim();
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* The distro user's home as a Linux path, cached on the provider instance whose
|
|
107
|
-
* `distro`/`wslPath` config it belongs to.
|
|
108
|
-
*
|
|
109
|
-
* An empty `cwd` cannot mean the shipped default (`process.cwd()`, a Windows
|
|
110
|
-
* directory no `wsl.exe --cd` accepts) and it must not mean a hardcoded author
|
|
111
|
-
* path either, so both providers agree on this instead: the distro's own home,
|
|
112
|
-
* asked of the distro once per (provider, distro) pair.
|
|
113
|
-
*
|
|
114
|
-
* @param owner - a WslShellExecutor or WslFileSystem.
|
|
115
|
-
* @param distro - the distro whose home is wanted.
|
|
116
|
-
* @returns an absolute Linux path.
|
|
117
|
-
*/
|
|
118
|
-
async function distroHome(owner, distro) {
|
|
119
|
-
const cached = owner.resolvedHomes.get(distro);
|
|
120
|
-
if (cached !== undefined)
|
|
121
|
-
return cached;
|
|
122
|
-
// The single-home field predates the per-distro map and is still the test
|
|
123
|
-
// substitute for "a home is already known"; honour it before spawning.
|
|
124
|
-
if (owner.resolvedHome !== undefined && owner.resolvedDistro.length > 0 && distro === owner.resolvedDistro) {
|
|
125
|
-
owner.resolvedHomes.set(distro, owner.resolvedHome);
|
|
126
|
-
return owner.resolvedHome;
|
|
127
|
-
}
|
|
128
|
-
// Both providers carry `wslPath` in their own config; the base classes'
|
|
129
|
-
// `config` types do not know the key, so the shape is asserted here.
|
|
130
|
-
const config = owner.config;
|
|
131
|
-
const home = await linuxHomePath(distro, { wslPath: config.wslPath });
|
|
132
|
-
owner.resolvedHomes.set(distro, home);
|
|
133
|
-
// The legacy single-home cache is still what `processPathFromHostPath` and
|
|
134
|
-
// the existing tests read; keep it warm for the resolved default/pin.
|
|
135
|
-
if (owner.resolvedDistro.length > 0 && distro === owner.resolvedDistro)
|
|
136
|
-
owner.resolvedHome = home;
|
|
137
|
-
return home;
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* The roots a `workspace-write` policy may write under, in the vocabulary this
|
|
141
|
-
* backend's targets are spelled in.
|
|
142
|
-
*
|
|
143
|
-
* Upstream's {@link writableRoots} grants the workspace, its explicit extra
|
|
144
|
-
* directories (`additionalWritableRoots`), and the platform temp areas (`/tmp`,
|
|
145
|
-
* `os.tmpdir()`). A session whose workspace lives inside a distro speaks UNC,
|
|
146
|
-
* where neither host spelling matches anything, and the temp area that world
|
|
147
|
-
* actually exposes is the distro's own `/tmp` — so that is what is granted
|
|
148
|
-
* instead, and the Windows temp dir deliberately is NOT: it lies outside the
|
|
149
|
-
* execution world the policy describes. A session whose workspace is a Windows
|
|
150
|
-
* folder keeps upstream's grant verbatim.
|
|
151
|
-
*
|
|
152
|
-
* Extra directories follow the same world rule as the temp areas, and the same
|
|
153
|
-
* together-grant contract: an extra root that is a UNC path of the same distro
|
|
154
|
-
* is granted as-is; a Windows-path extra root cannot be granted inside the
|
|
155
|
-
* distro, and upstream's contract is that every backend grants every extra
|
|
156
|
-
* root together — so it fails closed with {@link SandboxInvalidRootError}
|
|
157
|
-
* rather than silently narrowing what `workspace-write` promised.
|
|
158
|
-
*
|
|
159
|
-
* @param policy - the per-call file-effect policy.
|
|
160
|
-
* @param distro - the distro a UNC workspace belongs to.
|
|
161
|
-
* @returns canonical writable roots; empty exactly under `read-only`.
|
|
162
|
-
*/
|
|
163
|
-
function wslWritableRoots(policy, distro) {
|
|
164
|
-
if (policy.mode !== "workspace-write")
|
|
165
|
-
return [];
|
|
166
|
-
const roots = new Set([canonicalPath(policy.workspaceRoot)]);
|
|
167
|
-
if (isWslUnc(policy.workspaceRoot)) {
|
|
168
|
-
roots.add(canonicalPath(posixToUnc(distro, "/tmp")));
|
|
169
|
-
for (const root of policy.additionalWritableRoots ?? []) {
|
|
170
|
-
const parsed = uncToPosix(root);
|
|
171
|
-
if (parsed === undefined || parsed.distro !== distro) {
|
|
172
|
-
throw new SandboxInvalidRootError(root, `the workspace is inside distro ${JSON.stringify(distro)}; a Windows-path extra directory cannot be granted there`);
|
|
173
|
-
}
|
|
174
|
-
roots.add(canonicalPath(root));
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
else {
|
|
178
|
-
for (const root of writableRoots(policy))
|
|
179
|
-
roots.add(root);
|
|
180
|
-
}
|
|
181
|
-
return [...roots];
|
|
182
|
-
}
|
|
183
|
-
/** The doctor script this package ships, resolved from the compiled module. */
|
|
184
|
-
const DOCTOR_SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "doctor.mjs");
|
|
185
|
-
/** How long the doctor subprocess may run before the collector kills it. */
|
|
186
|
-
const DOCTOR_TIMEOUT_MS = 120_000;
|
|
187
|
-
/**
|
|
188
|
-
* How much of one doctor stream the collector retains. The `--json` report is
|
|
189
|
-
* a few dozen KiB; the cap exists so a runaway child cannot grow the Host's
|
|
190
|
-
* memory without bound.
|
|
191
|
-
*/
|
|
192
|
-
const DOCTOR_OUTPUT_LIMIT_BYTES = 4 * 1024 * 1024;
|
|
193
|
-
/**
|
|
194
|
-
* How long after the doctor exits the collector waits for its pipes. A
|
|
195
|
-
* grandchild that inherited the pipes can keep them open forever; the report
|
|
196
|
-
* on stdout is complete once the doctor itself has exited, so the wait is
|
|
197
|
-
* bounded instead of following the pipes to EOF.
|
|
198
|
-
*/
|
|
199
|
-
const DOCTOR_DRAIN_GRACE_MS = 500;
|
|
200
|
-
/**
|
|
201
|
-
* Run the doctor CLI asynchronously and collect its streams.
|
|
202
|
-
*
|
|
203
|
-
* `spawnSync` would block the Host's event loop for the whole run — up to the
|
|
204
|
-
* deadline, with no way to cancel and every other tool stalled behind it — so
|
|
205
|
-
* the collector spawns, arms a deadline and the caller's abort signal, and
|
|
206
|
-
* settles on the child's exit plus a bounded drain window. A grandchild that
|
|
207
|
-
* inherits the pipes cannot hold the collector past that window.
|
|
208
|
-
*
|
|
209
|
-
* @param argv - the node argv (script path first).
|
|
210
|
-
* @param options - the child env, the deadline, and the caller's signal.
|
|
211
|
-
* @returns the finished run, including the spawn failure when it never started.
|
|
212
|
-
*/
|
|
213
|
-
function runDoctorProcess(argv, options) {
|
|
214
|
-
return new Promise((resolvePromise) => {
|
|
215
|
-
let stdout = "";
|
|
216
|
-
let stderr = "";
|
|
217
|
-
let timedOut = false;
|
|
218
|
-
let overLimit = false;
|
|
219
|
-
let spawnError;
|
|
220
|
-
let exit;
|
|
221
|
-
let drainTimer;
|
|
222
|
-
let settled = false;
|
|
223
|
-
const child = spawn(process.execPath, argv, {
|
|
224
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
225
|
-
windowsHide: true,
|
|
226
|
-
...(options.env === undefined ? {} : { env: options.env }),
|
|
227
|
-
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
228
|
-
});
|
|
229
|
-
const settle = () => {
|
|
230
|
-
if (settled)
|
|
231
|
-
return;
|
|
232
|
-
settled = true;
|
|
233
|
-
clearTimeout(deadlineTimer);
|
|
234
|
-
if (drainTimer !== undefined)
|
|
235
|
-
clearTimeout(drainTimer);
|
|
236
|
-
resolvePromise({
|
|
237
|
-
stdout,
|
|
238
|
-
stderr,
|
|
239
|
-
status: exit?.status ?? null,
|
|
240
|
-
signal: exit?.signal ?? null,
|
|
241
|
-
timedOut,
|
|
242
|
-
overLimit,
|
|
243
|
-
...(spawnError === undefined ? {} : { spawnError }),
|
|
244
|
-
});
|
|
245
|
-
};
|
|
246
|
-
const kill = () => {
|
|
247
|
-
try {
|
|
248
|
-
child.kill();
|
|
249
|
-
}
|
|
250
|
-
catch {
|
|
251
|
-
// An already-exited child: the exit handler settles the run.
|
|
252
|
-
}
|
|
253
|
-
};
|
|
254
|
-
const deadlineTimer = setTimeout(() => {
|
|
255
|
-
timedOut = true;
|
|
256
|
-
kill();
|
|
257
|
-
}, options.timeoutMs);
|
|
258
|
-
const capture = (chunk, which) => {
|
|
259
|
-
if (settled)
|
|
260
|
-
return;
|
|
261
|
-
if (which === "stdout")
|
|
262
|
-
stdout += chunk;
|
|
263
|
-
else
|
|
264
|
-
stderr += chunk;
|
|
265
|
-
if (stdout.length + stderr.length > DOCTOR_OUTPUT_LIMIT_BYTES) {
|
|
266
|
-
overLimit = true;
|
|
267
|
-
kill();
|
|
268
|
-
}
|
|
269
|
-
};
|
|
270
|
-
child.stdout?.on("data", (chunk) => capture(chunk.toString("utf8"), "stdout"));
|
|
271
|
-
child.stderr?.on("data", (chunk) => capture(chunk.toString("utf8"), "stderr"));
|
|
272
|
-
child.on("error", (error) => {
|
|
273
|
-
// A spawn failure never reaches `exit`; an abort is reported with the
|
|
274
|
-
// same event, so the marker is normalized into a plain message.
|
|
275
|
-
spawnError = error.name === "AbortError"
|
|
276
|
-
? new Error("doctor run aborted")
|
|
277
|
-
: error;
|
|
278
|
-
if (exit === undefined)
|
|
279
|
-
settle();
|
|
280
|
-
});
|
|
281
|
-
child.on("exit", (code, signalName) => {
|
|
282
|
-
exit = { status: code, signal: signalName ?? null };
|
|
283
|
-
// The report is complete at exit; give the pipes one bounded window to
|
|
284
|
-
// flush (a grandchild holding them must not stall the collector).
|
|
285
|
-
drainTimer = setTimeout(settle, DOCTOR_DRAIN_GRACE_MS);
|
|
286
|
-
});
|
|
287
|
-
child.on("close", () => {
|
|
288
|
-
if (exit !== undefined)
|
|
289
|
-
settle();
|
|
290
|
-
});
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
/**
|
|
294
|
-
* Collect the doctor's versioned JSON report and merge the live resident's
|
|
295
|
-
* own lifecycle facts when this process holds one (WSL-313).
|
|
296
|
-
*
|
|
297
|
-
* The doctor CLI is a separate process, so its handshake check can only probe
|
|
298
|
-
* a fresh resident; a live resident's `deaths` and `lastError` are
|
|
299
|
-
* host-process state with no IPC to reach them. This entry point runs from
|
|
300
|
-
* the plugin's own context instead: it collects the report as a subprocess
|
|
301
|
-
* (no plugin code is re-entered) and folds `sharedAgent(distro).status()` in
|
|
302
|
-
* — the sanctioned merge, since a snapshot that answers for no resident
|
|
303
|
-
* changes nothing. Outside the app the singleton was never started, so the
|
|
304
|
-
* returned report is the fresh probe verbatim; inside it, a wedged live
|
|
305
|
-
* resident's failures finally reach the report.
|
|
306
|
-
*
|
|
307
|
-
* @param distro - the distro the doctor examines.
|
|
308
|
-
* @param options - `doctorPath` overrides the shipped script (tests);
|
|
309
|
-
* `timeoutMs` bounds the run; `signal` lets the caller cancel it;
|
|
310
|
-
* `liveStatus` overrides the in-process status snapshot (tests).
|
|
311
|
-
* @returns the merged report.
|
|
312
|
-
*/
|
|
313
|
-
export async function doctorReport(distro, options) {
|
|
314
|
-
const script = options?.doctorPath ?? DOCTOR_SCRIPT;
|
|
315
|
-
const argv = [script, distro, "--json"];
|
|
316
|
-
if (options?.quick === true)
|
|
317
|
-
argv.push("--quick");
|
|
318
|
-
if (options?.sections !== undefined && options.sections.length > 0)
|
|
319
|
-
argv.push("--sections", [...options.sections].join(","));
|
|
320
|
-
if (options?.wslPath !== undefined)
|
|
321
|
-
argv.push("--wsl", options.wslPath);
|
|
322
|
-
// A nonzero doctor exit usually means an environment check FAILED on the
|
|
323
|
-
// machine being examined — that is a valid report, not a broken collection.
|
|
324
|
-
// The stdout is parsed regardless; only a run that produced no versioned
|
|
325
|
-
// report rejects.
|
|
326
|
-
const timeoutMs = options?.timeoutMs ?? DOCTOR_TIMEOUT_MS;
|
|
327
|
-
const run = await runDoctorProcess(argv, {
|
|
328
|
-
timeoutMs,
|
|
329
|
-
...(options?.envPath !== undefined ? { env: { ...process.env, PATH: `${options.envPath}:${process.env.PATH ?? ""}` } } : {}),
|
|
330
|
-
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
|
331
|
-
});
|
|
332
|
-
let report;
|
|
333
|
-
try {
|
|
334
|
-
report = JSON.parse(run.stdout);
|
|
335
|
-
}
|
|
336
|
-
catch {
|
|
337
|
-
// A run that produced no report rejects, naming the transport failure
|
|
338
|
-
// (spawn error, deadline, output cap, exit) and any stderr tail.
|
|
339
|
-
const cause = run.spawnError?.message
|
|
340
|
-
?? (run.timedOut
|
|
341
|
-
? `timed out after ${timeoutMs}ms`
|
|
342
|
-
: run.overLimit
|
|
343
|
-
? `produced more than ${DOCTOR_OUTPUT_LIMIT_BYTES} bytes`
|
|
344
|
-
: `exited with code ${run.status ?? run.signal ?? "unknown"}`);
|
|
345
|
-
throw new Error(`doctor run failed: ${cause}${run.stderr.length > 0 ? ` — ${run.stderr.trim().slice(-400)}` : ""}`);
|
|
346
|
-
}
|
|
347
|
-
const status = options?.liveStatus ?? sharedAgent(distro).status();
|
|
348
|
-
return mergeLiveResidentStatus(report, status);
|
|
349
|
-
}
|
|
350
|
-
/**
|
|
351
|
-
* The WSL shell executor's validated config — the keys of
|
|
352
|
-
* {@link WslShellExecutor.Config}, which the upstream `LocalBashExecutor`
|
|
353
|
-
* config type does not know. The seven volatile fields arrive as live
|
|
354
|
-
* wrappers, so they are spelled as their `.get()` shape (the reading
|
|
355
|
-
* {@link configuredCwd} and `hostCwd` perform).
|
|
356
|
-
*/
|
|
357
|
-
/**
|
|
358
|
-
* The effective `/mnt` mask for a config: `interopVisibility` is the stance
|
|
359
|
-
* key (WSL-314) and takes precedence whenever it names a stance; the legacy
|
|
360
|
-
* `maskWindowsDrive` boolean answers only when the stance key is left at its
|
|
361
|
-
* `visible` default. `disabled` masks in-session — the belt — while the
|
|
362
|
-
* distro-level closure (`[interop] enabled=false` + `wsl --shutdown`)
|
|
363
|
-
* remains a documented, user-applied step a config key must not perform.
|
|
364
|
-
*
|
|
365
|
-
* @param config - anything carrying the two keys.
|
|
366
|
-
* @returns whether confined profiles shadow `/mnt`.
|
|
367
|
-
*/
|
|
368
|
-
export function effectiveMaskWindowsDrive(config) {
|
|
369
|
-
if (config.interopVisibility !== undefined)
|
|
370
|
-
return config.interopVisibility !== "visible";
|
|
371
|
-
return config.maskWindowsDrive === true;
|
|
372
|
-
}
|
|
373
|
-
const inheritedSpawnSpec = LocalBashExecutor.prototype.spawnSpec;
|
|
374
|
-
/**
|
|
375
|
-
* How long an `auto` distro that could not host a session runtime stays
|
|
376
|
-
* downgraded before the probe is retried.
|
|
377
|
-
*/
|
|
378
|
-
const AUTO_SCOPE_RECHECK_MS = 60_000;
|
|
379
|
-
/**
|
|
380
|
-
* Whether a provider should use the session runtime for one distro.
|
|
381
|
-
*
|
|
382
|
-
* - `false` is off;
|
|
383
|
-
* - `true` refuses with the preflight remedy when the platform cannot host it;
|
|
384
|
-
* - `"auto"` downgrades to the per-command sandbox and reports that narrower
|
|
385
|
-
* scope in the result, re-probing a failed verdict at most once a minute so
|
|
386
|
-
* following the remedy (systemd, Linger) upgrades without an app restart.
|
|
387
|
-
*
|
|
388
|
-
* @param value - the configured `sessionSandbox` value.
|
|
389
|
-
* @param distro - the resolved distro.
|
|
390
|
-
* @param ensure - the provider's preflight, which throws the remedy on failure.
|
|
391
|
-
* @param cache - the provider's per-distro `auto` verdicts.
|
|
392
|
-
* @returns whether the session runtime should be used.
|
|
393
|
-
*/
|
|
394
|
-
async function sessionRuntimeWanted(value, distro, ensure, cache) {
|
|
395
|
-
if (value === false)
|
|
396
|
-
return false;
|
|
397
|
-
if (value === true) {
|
|
398
|
-
await ensure();
|
|
399
|
-
return true;
|
|
400
|
-
}
|
|
401
|
-
const cached = cache.get(distro);
|
|
402
|
-
if (cached?.usable === true)
|
|
403
|
-
return true;
|
|
404
|
-
if (cached !== undefined && Date.now() - cached.checkedAt < AUTO_SCOPE_RECHECK_MS)
|
|
405
|
-
return false;
|
|
406
|
-
try {
|
|
407
|
-
await ensure();
|
|
408
|
-
cache.set(distro, { usable: true, checkedAt: Date.now() });
|
|
409
|
-
return true;
|
|
410
|
-
}
|
|
411
|
-
catch {
|
|
412
|
-
cache.set(distro, { usable: false, checkedAt: Date.now() });
|
|
413
|
-
return false;
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
/**
|
|
417
|
-
* The distro one operation belongs to, shared by the shell and filesystem
|
|
418
|
-
* resolvers: a pinned name wins, `default` goes straight to the probe, the
|
|
419
|
-
* first candidate naming a UNC distro wins, and the probe closes the list.
|
|
420
|
-
* The probe is lazy on purpose — a pinned row never pays for a default-distro
|
|
421
|
-
* probe, and a failing probe fails only the calls that actually needed it.
|
|
422
|
-
* `selectDistro` (distro-route) is the pure sibling whose fallback arrives
|
|
423
|
-
* already resolved; this one owns the probing.
|
|
424
|
-
*
|
|
425
|
-
* @param configured - the row's `distro` value.
|
|
426
|
-
* @param candidates - paths in any coordinate system, strongest evidence first.
|
|
427
|
-
* @param probeDefault - the fallback probe, invoked at most once per call.
|
|
428
|
-
*/
|
|
429
|
-
async function resolveOperationDistro(configured, candidates, probeDefault) {
|
|
430
|
-
const pinned = pinnedDistro(configured);
|
|
431
|
-
if (pinned !== undefined)
|
|
432
|
-
return pinned;
|
|
433
|
-
if (!isDefaultDistro(configured)) {
|
|
434
|
-
for (const candidate of candidates) {
|
|
435
|
-
const named = distroOfUnc(candidate);
|
|
436
|
-
if (named !== undefined)
|
|
437
|
-
return named;
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
return probeDefault();
|
|
441
|
-
}
|
|
442
|
-
/**
|
|
443
|
-
* The refusal both shell resolvers share: the probes named no shell, and the
|
|
444
|
-
* command must not quietly run under some other interpreter.
|
|
445
|
-
* the probes named no shell, and the
|
|
446
|
-
* command must not quietly run under some other interpreter. The wording is
|
|
447
|
-
* the one `runInDistro` already throws with.
|
|
448
|
-
*
|
|
449
|
-
* @param distro - the distro whose shell could not be resolved.
|
|
450
|
-
*/
|
|
451
|
-
const unusableShell = (distro) => new Error(`dsh-plugin-wsl: distro "${distro}" named no usable shell (passwd probe and $SHELL both failed). ` +
|
|
452
|
-
`Check the user's login shell in /etc/passwd (\`getent passwd "$(id -u)"\` inside the distro), ` +
|
|
453
|
-
`or point this row's \`shell\` at an existing absolute path.`);
|
|
454
|
-
/**
|
|
455
|
-
* Bash executor that runs every command inside a WSL distro.
|
|
456
|
-
*
|
|
457
|
-
* Extends the unconfined `LocalBashExecutor`, so command defaulting, deadline
|
|
458
|
-
* handling, output caps, spill files and background-process management are the
|
|
459
|
-
* shipped implementation's; this subclass replaces only the argv (prefix with
|
|
460
|
-
* `wsl.exe`) and the process working directory (wsl.exe must be started from a
|
|
461
|
-
* Windows directory, while the Linux directory rides on `--cd`).
|
|
462
|
-
*/
|
|
463
|
-
// @ts-expect-error — LocalBashExecutor.spawnSpec is private upstream; a wsl.exe spawn must start from a Windows directory (docs/UPSTREAM-SPAWN-SEAM.md)
|
|
464
|
-
export class WslShellExecutor extends LocalBashExecutor {
|
|
465
|
-
static inject = ["subprocess", "sandboxPolicy"];
|
|
466
|
-
static Config = z.object({
|
|
467
|
-
/**
|
|
468
|
-
* Distro mode: empty/`"auto"` follows the request workdir, `"default"`
|
|
469
|
-
* forces WSL's default, and an explicit name pins every command.
|
|
470
|
-
*/
|
|
471
|
-
distro: z.string().default(""),
|
|
472
|
-
/** Path to `wsl.exe`; overridable for a non-standard install. */
|
|
473
|
-
wslPath: z.string().default("wsl.exe"),
|
|
474
|
-
/**
|
|
475
|
-
* The shell commands run in. Empty means "resolve the login shell of the
|
|
476
|
-
* distro's user" — hardcoding bash silently ignores a user whose passwd
|
|
477
|
-
* entry points at zsh, fish, dash, or anything else, losing their PATH and
|
|
478
|
-
* rc setup. Set an absolute path inside the distro to pin one.
|
|
479
|
-
*/
|
|
480
|
-
shell: z.string().default(""),
|
|
481
|
-
/**
|
|
482
|
-
* Login-shell semantics (`<shell> -lc`) source the profile scripts, which is
|
|
483
|
-
* what makes an interactive WSL setup's PATH (nvm, cargo, pyenv) visible.
|
|
484
|
-
* Set false for a fast, fully deterministic `<shell> -c`. Applies only to the
|
|
485
|
-
* POSIX family — see `shellArgs` for why other shells get a bare `-c`.
|
|
486
|
-
*/
|
|
487
|
-
loginShell: z.boolean().default(true),
|
|
488
|
-
/**
|
|
489
|
-
* Confine every command inside the distro with `bwrap`, and report the
|
|
490
|
-
* policy's mode through {@link sandboxMode}. Fails closed: a distro without
|
|
491
|
-
* a usable `bwrap` produces `SANDBOX_UNAVAILABLE` rather than an unconfined
|
|
492
|
-
* run. `false` restores the pre-sandbox behaviour exactly — commands run
|
|
493
|
-
* unconfined and `sandboxMode` is `undefined`, so the model is told so.
|
|
494
|
-
*/
|
|
495
|
-
sandbox: z.boolean().default(true),
|
|
496
|
-
/**
|
|
497
|
-
* Shadow `/mnt` with an empty tmpfs in every confined profile, hiding the
|
|
498
|
-
* Windows drive from confined commands: its files cannot be read or
|
|
499
|
-
* exfiltrated and its executables cannot be launched through interop —
|
|
500
|
-
* the hole that lets a "sandboxed" command reach your full Windows token.
|
|
501
|
-
* A narrowing, not a closure (a command can still write an executable
|
|
502
|
-
* into the workspace and run it — binfmt dispatches on content, not
|
|
503
|
-
* location), so enforcement stays `partial` and the sandbox fact reports
|
|
504
|
-
* `windowsDrive: "masked"`. Costs: confined commands cannot read or touch
|
|
505
|
-
* anything under `/mnt`, and tools that probe the drive degrade. The
|
|
506
|
-
* complete closure is distro-level: `[interop] enabled=false` in
|
|
507
|
-
* `wsl.conf`.
|
|
508
|
-
*/
|
|
509
|
-
/**
|
|
510
|
-
* The interop stance in one key (WSL-314), expanding to the per-key
|
|
511
|
-
* values the measured matrix documents:
|
|
512
|
-
*
|
|
513
|
-
* - `visible` (default) — nothing masked; a confined command can read
|
|
514
|
-
* `/mnt` and launch Windows executables through interop, which escapes
|
|
515
|
-
* the Linux sandbox entirely.
|
|
516
|
-
* - `masked` — `maskWindowsDrive: true`: `/mnt` is shadowed with an empty
|
|
517
|
-
* tmpfs; the drive's files and executables are unreachable (binfmt can
|
|
518
|
-
* still run a workspace-written .exe, so enforcement stays `partial`).
|
|
519
|
-
* - `disabled` — `masked`, plus the distro-level closure: `[interop]
|
|
520
|
-
* enabled=false` in `/etc/wsl.conf` + `wsl --shutdown`, which the
|
|
521
|
-
* doctor's remedy prints as copy-paste (a config key does not write
|
|
522
|
-
* distro config; enforcement is the kernel's, not the schema's).
|
|
523
|
-
*
|
|
524
|
-
* When set at all it takes precedence over the legacy
|
|
525
|
-
* `maskWindowsDrive` boolean below (unset — the default — lets that
|
|
526
|
-
* boolean answer); the boolean remains for existing profiles.
|
|
527
|
-
*/
|
|
528
|
-
interopVisibility: z.union(["visible", "masked", "disabled"]),
|
|
529
|
-
maskWindowsDrive: z.boolean().default(false),
|
|
530
|
-
/**
|
|
531
|
-
* Default workdir for a request that names none; accepts `/home/andy/proj`,
|
|
532
|
-
* a UNC path, or `C:\...`. Empty — the default — means the distro user's
|
|
533
|
-
* home, resolved inside the distro.
|
|
534
|
-
*/
|
|
535
|
-
cwd: z.string().volatile(),
|
|
536
|
-
/** Windows directory the `wsl.exe` process itself starts in. */
|
|
537
|
-
hostCwd: z.string().volatile(),
|
|
538
|
-
/** Extra env names to forward into the distro through WSLENV. */
|
|
539
|
-
forwardEnv: z.array(z.string()).default([]),
|
|
540
|
-
timeoutMs: z.number().default(12e4).volatile(),
|
|
541
|
-
maxTimeoutMs: z.number().default(6e5).volatile(),
|
|
542
|
-
maxOutputBytes: z.number().default(64e3).volatile(),
|
|
543
|
-
maxSpillBytes: z.number().default(64 * 1024 * 1024).volatile(),
|
|
544
|
-
graceMs: z.number().default(3e3).volatile(),
|
|
545
|
-
/**
|
|
546
|
-
* Run commands through the resident agent when it is up (one long-lived
|
|
547
|
-
* in-distro process; in-distro timeout semantics), falling back to the
|
|
548
|
-
* one-shot `wsl.exe` path whenever the agent is out. `false` never uses
|
|
549
|
-
* the agent. The confinement, the output budgets' shapes and the result
|
|
550
|
-
* decoration are identical on both paths.
|
|
551
|
-
*/
|
|
552
|
-
agent: z.boolean().default(true),
|
|
553
|
-
agentBackend: z.union(["auto", "native", "shell"]).default("auto"),
|
|
554
|
-
/**
|
|
555
|
-
* Run this session's commands in one persistent systemd user scope (ADR
|
|
556
|
-
* 0001): background processes survive the command that started them, `/tmp`
|
|
557
|
-
* is the distro's real `/tmp` under workspace-write, and `ps` sees the
|
|
558
|
-
* session. The executor holds the runtime until the session's scope
|
|
559
|
-
* disposes, then stops it. Requires systemd, a reachable user manager and
|
|
560
|
-
* `Linger`; the preflight refuses with the remedy when one is missing, and
|
|
561
|
-
* only a success is cached. Off by default; requires `agent: true`.
|
|
562
|
-
*/
|
|
563
|
-
sessionSandbox: z.union([z.boolean(), z.const("auto")]).default(false),
|
|
564
|
-
});
|
|
565
|
-
/**
|
|
566
|
-
* @param ctx - the composition context.
|
|
567
|
-
* @param config - the validated plugin config.
|
|
568
|
-
*/
|
|
569
|
-
constructor(ctx, config) {
|
|
570
|
-
super(ctx, config);
|
|
571
|
-
configureAgentBackend(config.agentBackend ?? "auto");
|
|
572
|
-
installMessagesLocale(ctx);
|
|
573
|
-
this.resolvedDistro = pinnedDistro(config.distro) ?? "";
|
|
574
|
-
this.resolvedShell = config.shell;
|
|
575
|
-
this.resolvedShells = new Map();
|
|
576
|
-
this.resolvedHome = undefined;
|
|
577
|
-
this.resolvedHomes = new Map();
|
|
578
|
-
this.mode = config.sandbox ? ctx.sandboxPolicy.defaultMode : undefined;
|
|
579
|
-
this.sandbox = config.sandbox
|
|
580
|
-
? new WslSandbox({ wslPath: config.wslPath, maskWindowsDrive: effectiveMaskWindowsDrive(config) })
|
|
581
|
-
: undefined;
|
|
582
|
-
this.processFacts = new Map();
|
|
583
|
-
this.sessionRuntimes = sessionRuntimes;
|
|
584
|
-
this.sessionRuntimeEntries = new Map();
|
|
585
|
-
this.sessionRuntimeOwner = randomUUID();
|
|
586
|
-
this.sessionScopeProbe = (argv) => runCapture(argv);
|
|
587
|
-
this.sessionRuntimePreflight = new Set();
|
|
588
|
-
this.autoSessionScope = new Map();
|
|
589
|
-
// The preset realm disposes when the session ends; the scope must go with
|
|
590
|
-
// it, or a dev server outlives the session that started it.
|
|
591
|
-
ctx.effect(() => () => this.disposeSessionRuntimes().catch(() => { }), "wsl session runtimes");
|
|
592
|
-
}
|
|
593
|
-
/**
|
|
594
|
-
* The mode this executor confines with, or `undefined` when it does not
|
|
595
|
-
* confine at all. `dsh-tool-bash` reads exactly this to decide whether to
|
|
596
|
-
* advertise the escalation field, so it must disappear together with the
|
|
597
|
-
* enforcement — never claim a boundary that is not applied.
|
|
598
|
-
*
|
|
599
|
-
* @returns the deployment default mode, or `undefined` when unconfined.
|
|
600
|
-
*/
|
|
601
|
-
get sandboxMode() {
|
|
602
|
-
return this.mode;
|
|
603
|
-
}
|
|
604
|
-
/**
|
|
605
|
-
* The distro used when no path supplies evidence: the pinned name, WSL's
|
|
606
|
-
* default, or the default for the automatic modes.
|
|
607
|
-
*
|
|
608
|
-
* @returns the distro name.
|
|
609
|
-
*/
|
|
610
|
-
async distro() {
|
|
611
|
-
const config = this.config;
|
|
612
|
-
if (this.resolvedDistro.length === 0)
|
|
613
|
-
this.resolvedDistro = await defaultDistro({ wslPath: config.wslPath });
|
|
614
|
-
return this.resolvedDistro;
|
|
615
|
-
}
|
|
616
|
-
/**
|
|
617
|
-
* The distro one command belongs to: an explicit pin wins; otherwise the
|
|
618
|
-
* request workdir, then the configured `cwd`, may name a distro; both
|
|
619
|
-
* absent falls back to WSL's default.
|
|
620
|
-
*
|
|
621
|
-
* @param workdir - the request's workdir, in any coordinate system.
|
|
622
|
-
* @param cwd - the configured default workdir, when the caller has it.
|
|
623
|
-
* @returns the distro name.
|
|
624
|
-
*/
|
|
625
|
-
async distroFor(workdir, cwd) {
|
|
626
|
-
const config = this.config;
|
|
627
|
-
return resolveOperationDistro(config.distro, [workdir, cwd ?? configuredCwd(this.config)], () => this.distro());
|
|
628
|
-
}
|
|
629
|
-
/**
|
|
630
|
-
* The shell name for the default/pinned distro, as the shell tool presents
|
|
631
|
-
* it.
|
|
632
|
-
*
|
|
633
|
-
* @returns the basename of the shell; `shell` while the probe fails, and
|
|
634
|
-
* `bash` for an implausible basename.
|
|
635
|
-
*/
|
|
636
|
-
async shellName() {
|
|
637
|
-
// Consumed by the shell tool after upstream change A: it names and describes
|
|
638
|
-
// itself from the executor, so a zsh distro is never presented as bash. The
|
|
639
|
-
// naming path must not crash on a failed probe — "shell" is the honest
|
|
640
|
-
// neutral — while an implausible basename keeps the bash fallback below.
|
|
641
|
-
const shell = await this.shell().catch(() => undefined);
|
|
642
|
-
if (shell === undefined)
|
|
643
|
-
return "shell";
|
|
644
|
-
const base = String(shell ?? "").split("/").pop() ?? "";
|
|
645
|
-
const name = base.replace(/\.exe$/i, "").replace(/^[-.]+/, "");
|
|
646
|
-
return /^[a-z0-9_+-]+$/i.test(name) ? name : "bash";
|
|
647
|
-
}
|
|
648
|
-
/**
|
|
649
|
-
* The shell for one distro: the configured shell, else that distro's login
|
|
650
|
-
* shell. The default/pinned distro keeps the legacy {@link resolvedShell}
|
|
651
|
-
* cache; every other distro gets an entry in {@link resolvedShells}.
|
|
652
|
-
*
|
|
653
|
-
* @param distro - the distro name.
|
|
654
|
-
* @returns an absolute path to the shell inside the distro.
|
|
655
|
-
* @throws {Error} when neither the config nor the distro names a usable
|
|
656
|
-
* shell — the failure is not cached, so the next call re-probes.
|
|
657
|
-
*/
|
|
658
|
-
async shellFor(distro) {
|
|
659
|
-
const config = this.config;
|
|
660
|
-
if (config.shell.length > 0)
|
|
661
|
-
return config.shell;
|
|
662
|
-
if (this.resolvedDistro.length > 0 && distro === this.resolvedDistro)
|
|
663
|
-
return this.shell();
|
|
664
|
-
const cached = this.resolvedShells.get(distro);
|
|
665
|
-
if (cached !== undefined)
|
|
666
|
-
return cached;
|
|
667
|
-
const resolved = await defaultShell(distro, { wslPath: config.wslPath });
|
|
668
|
-
if (resolved !== undefined)
|
|
669
|
-
this.resolvedShells.set(distro, resolved);
|
|
670
|
-
if (resolved === undefined)
|
|
671
|
-
throw unusableShell(distro);
|
|
672
|
-
return resolved;
|
|
673
|
-
}
|
|
674
|
-
/**
|
|
675
|
-
* The shell for the default/pinned distro: the configured one, else the
|
|
676
|
-
* login shell, resolved once and cached.
|
|
677
|
-
*
|
|
678
|
-
* @returns an absolute path to the shell inside the distro.
|
|
679
|
-
* @throws {Error} when neither the config nor the distro names a usable
|
|
680
|
-
* shell — the failure is not cached, so the next call re-probes.
|
|
681
|
-
*/
|
|
682
|
-
async shell() {
|
|
683
|
-
const config = this.config;
|
|
684
|
-
if (this.resolvedShell.length === 0) {
|
|
685
|
-
const distro = await this.distro();
|
|
686
|
-
// An unresolvable shell fails the command loudly: the probes both came
|
|
687
|
-
// back empty (a cold distro, a flaky first wsl.exe call, a musl distro
|
|
688
|
-
// without getent), and running the command under some other interpreter
|
|
689
|
-
// would hide that from the caller. The failure is not cached — a later
|
|
690
|
-
// call re-probes and resolves the real shell once the distro is warm.
|
|
691
|
-
const resolved = await defaultShell(distro, { wslPath: config.wslPath });
|
|
692
|
-
if (resolved)
|
|
693
|
-
this.resolvedShell = resolved;
|
|
694
|
-
else
|
|
695
|
-
throw unusableShell(distro);
|
|
696
|
-
}
|
|
697
|
-
return this.resolvedShell;
|
|
698
|
-
}
|
|
699
|
-
/**
|
|
700
|
-
* Windows directory the `wsl.exe` process is started from.
|
|
701
|
-
*
|
|
702
|
-
* @returns the host directory to spawn in.
|
|
703
|
-
*/
|
|
704
|
-
hostCwd() {
|
|
705
|
-
const config = this.config;
|
|
706
|
-
return config.hostCwd.get() ?? process.env.SystemRoot ?? process.cwd();
|
|
707
|
-
}
|
|
708
|
-
/**
|
|
709
|
-
* The shared resident agent serving this executor's distro.
|
|
710
|
-
*
|
|
711
|
-
* @param distro - the resolved distro name.
|
|
712
|
-
* @returns the shared agent.
|
|
713
|
-
*/
|
|
714
|
-
executionAgent(distro) {
|
|
715
|
-
return sharedAgent(distro);
|
|
716
|
-
}
|
|
717
|
-
/**
|
|
718
|
-
* The persistent session runtime for one policy, when `sessionSandbox` is
|
|
719
|
-
* on. The executor holds one reference per `(session, distro, workspace, policy)` and
|
|
720
|
-
* releases them when the session's scope disposes.
|
|
721
|
-
*
|
|
722
|
-
* @param policy - the resolved file-effect policy, when the executor has one.
|
|
723
|
-
* @param resolved - the resolved spec, for the fallback workspace.
|
|
724
|
-
* @param distro - the resolved distro name.
|
|
725
|
-
* @returns the runtime entry, or undefined when the mode is off.
|
|
726
|
-
*/
|
|
727
|
-
sessionRuntimeFor(policy, resolved, distro) {
|
|
728
|
-
const config = this.config;
|
|
729
|
-
if (!config.sessionSandbox)
|
|
730
|
-
return undefined;
|
|
731
|
-
const mode = policy?.mode ?? "danger-full-access";
|
|
732
|
-
const workspaceRoot = policy?.workspaceRoot ?? (configuredCwd(this.config) || resolved.workdir);
|
|
733
|
-
const sessionId = policy?.sessionId || resolved.dshEnv?.DSH_SESSION_ID || this.sessionRuntimeOwner;
|
|
734
|
-
const key = SessionRuntimes.key({ sessionId, distro, workspaceRoot, mode, maskWindowsDrive: effectiveMaskWindowsDrive(config) });
|
|
735
|
-
const held = this.sessionRuntimeEntries.get(key);
|
|
736
|
-
if (held !== undefined)
|
|
737
|
-
return held;
|
|
738
|
-
const entry = this.sessionRuntimes.acquire({
|
|
739
|
-
sessionId,
|
|
740
|
-
distro,
|
|
741
|
-
wslPath: config.wslPath,
|
|
742
|
-
workspaceRoot,
|
|
743
|
-
mode,
|
|
744
|
-
maskWindowsDrive: effectiveMaskWindowsDrive(config),
|
|
745
|
-
});
|
|
746
|
-
this.sessionRuntimeEntries.set(key, entry);
|
|
747
|
-
return entry;
|
|
748
|
-
}
|
|
749
|
-
/**
|
|
750
|
-
* Run the session runtime's preflight once per executor. A failure is a
|
|
751
|
-
* configuration verdict, not an agent outage: it is raised as an Error with
|
|
752
|
-
* the remedy, so the command fails closed instead of falling back to the
|
|
753
|
-
* per-command sandbox. Only success is cached, so a user who follows the
|
|
754
|
-
* remedy (`loginctl enable-linger`, `[boot] systemd=true`) does not need to
|
|
755
|
-
* restart the app.
|
|
756
|
-
*
|
|
757
|
-
* @param distro - the resolved distro name.
|
|
758
|
-
* @returns resolved once the platform can host a session runtime.
|
|
759
|
-
* @throws {Error} with the remedy when it cannot.
|
|
760
|
-
*/
|
|
761
|
-
async ensureSessionRuntimeUsable(distro) {
|
|
762
|
-
if (this.sessionRuntimePreflight.has(distro))
|
|
763
|
-
return;
|
|
764
|
-
const config = this.config;
|
|
765
|
-
const problem = await probeSessionRuntime({ wslPath: config.wslPath, distro, run: this.sessionScopeProbe });
|
|
766
|
-
if (problem !== null)
|
|
767
|
-
throw new Error(problem);
|
|
768
|
-
await ensureNativeSessionAgent({ wslPath: config.wslPath, distro, setNative: setSessionNativeAgent });
|
|
769
|
-
this.sessionRuntimePreflight.add(distro);
|
|
770
|
-
}
|
|
771
|
-
/**
|
|
772
|
-
* Whether this executor should use the session runtime for one distro, with
|
|
773
|
-
* the `auto` downgrade and its bounded re-probe. `true` keeps the refusing
|
|
774
|
-
* behavior; `false` stays off.
|
|
775
|
-
*
|
|
776
|
-
* @param distro - the resolved distro.
|
|
777
|
-
* @returns whether to acquire the per-session scope.
|
|
778
|
-
*/
|
|
779
|
-
async wantsSessionRuntime(distro) {
|
|
780
|
-
const config = this.config;
|
|
781
|
-
return sessionRuntimeWanted(config.sessionSandbox, distro, () => this.ensureSessionRuntimeUsable(distro), this.autoSessionScope);
|
|
782
|
-
}
|
|
783
|
-
/**
|
|
784
|
-
* Release every runtime this executor holds, stopping each scope. Called
|
|
785
|
-
* from the session's dispose hook; public so tests and shutdown paths can
|
|
786
|
-
* await it.
|
|
787
|
-
*
|
|
788
|
-
* @returns resolved once every runtime is torn down.
|
|
789
|
-
*/
|
|
790
|
-
async disposeSessionRuntimes() {
|
|
791
|
-
const entries = [...this.sessionRuntimeEntries.values()];
|
|
792
|
-
this.sessionRuntimeEntries.clear();
|
|
793
|
-
for (const entry of entries)
|
|
794
|
-
await this.sessionRuntimes.release(entry.key);
|
|
795
|
-
}
|
|
796
|
-
/**
|
|
797
|
-
* The argv that runs INSIDE the distro for one spec: the resolved shell, its
|
|
798
|
-
* login/command flags, and the command string. This is the argv a
|
|
799
|
-
* distro-side sandbox wraps, which is why it is built separately from the
|
|
800
|
-
* `wsl.exe` invocation around it.
|
|
801
|
-
*
|
|
802
|
-
* @param spec - the resolved spec from {@link LocalBashExecutor.resolve}.
|
|
803
|
-
* @param shell - the resolved distro shell.
|
|
804
|
-
* @returns the distro-side argv.
|
|
805
|
-
*/
|
|
806
|
-
distroArgv(spec, shell) {
|
|
807
|
-
const config = this.config;
|
|
808
|
-
return [shell, ...shellArgs(shell, config.loginShell), spec.command];
|
|
809
|
-
}
|
|
810
|
-
/**
|
|
811
|
-
* Build the `wsl.exe` argv for one resolved spec. The command string is
|
|
812
|
-
* passed as a single argv element to the resolved shell, so there is no
|
|
813
|
-
* quoting layer of our own; Node's argv array reaches `wsl.exe` verbatim.
|
|
814
|
-
*
|
|
815
|
-
* `--exec` is load-bearing — see the comment inside.
|
|
816
|
-
*
|
|
817
|
-
* @param spec - the resolved spec from {@link LocalBashExecutor.resolve}.
|
|
818
|
-
* @param distro - the resolved distro name.
|
|
819
|
-
* @param shell - the resolved distro shell.
|
|
820
|
-
* @param inner - the already-confined distro argv, when confinement applies.
|
|
821
|
-
* @returns the argv to spawn.
|
|
822
|
-
*/
|
|
823
|
-
argv(spec, distro, shell, inner) {
|
|
824
|
-
const config = this.config;
|
|
825
|
-
const distroArgs = distro.length > 0 ? ["-d", distro] : [];
|
|
826
|
-
return [
|
|
827
|
-
config.wslPath,
|
|
828
|
-
...distroArgs,
|
|
829
|
-
"--cd",
|
|
830
|
-
toLinuxPath(spec.workdir),
|
|
831
|
-
// `--exec` is essential, not decoration. Without it wsl.exe hands the
|
|
832
|
-
// command line to the distro's DEFAULT SHELL, which expands it once before
|
|
833
|
-
// our own shell ever sees it: `x=1; echo "$x"` arrives as `x=1; echo ""`,
|
|
834
|
-
// `$?` becomes the outer shell's status, and `$(...)`, `${...}`, `$1` and
|
|
835
|
-
// backticks are eaten the same way. With `--exec` the argv is passed
|
|
836
|
-
// straight through, so the command string reaches the shell verbatim.
|
|
837
|
-
//
|
|
838
|
-
// Note the shell is named explicitly here even though `--exec` plus the
|
|
839
|
-
// distro's default shell would look equivalent: without `--exec` we get the
|
|
840
|
-
// double parse above, so the shell has to be resolved by us instead.
|
|
841
|
-
"--exec",
|
|
842
|
-
...(inner ?? this.distroArgv(spec, shell)),
|
|
843
|
-
];
|
|
844
|
-
}
|
|
845
|
-
/**
|
|
846
|
-
* Override only the spawn's working directory and environment. `spec.workdir`
|
|
847
|
-
* is a Linux path, which a Windows CreateProcess call cannot use as `cwd`.
|
|
848
|
-
*
|
|
849
|
-
* The inherited builder is private, so the call goes through the
|
|
850
|
-
* {@link SpawnSeamExecutor} bridge (`inheritedSpawnSpec`) instead of `super`
|
|
851
|
-
* — see docs/UPSTREAM-SPAWN-SEAM.md.
|
|
852
|
-
*
|
|
853
|
-
* @param spec - resolved execution settings.
|
|
854
|
-
* @param argv - the argv from {@link WslShellExecutor.argv}.
|
|
855
|
-
* @param stdoutMaxBytes - per-call stdout cap.
|
|
856
|
-
* @param signal - the spawn cancellation signal.
|
|
857
|
-
* @returns the subprocess spawn spec.
|
|
858
|
-
*/
|
|
859
|
-
spawnSpec(spec, argv, stdoutMaxBytes, signal) {
|
|
860
|
-
const config = this.config;
|
|
861
|
-
const base = inheritedSpawnSpec.call(this, spec, argv, stdoutMaxBytes, signal);
|
|
862
|
-
const forward = new Set([...SAFE_FORWARD, ...config.forwardEnv]);
|
|
863
|
-
const forwarded = Object.keys(base.env ?? {}).filter((name) => forward.has(name) || name.startsWith(DSH_ENV_PREFIX));
|
|
864
|
-
return {
|
|
865
|
-
...base,
|
|
866
|
-
cwd: this.hostCwd(),
|
|
867
|
-
env: {
|
|
868
|
-
...base.env,
|
|
869
|
-
// wsl.exe writes its own diagnostics as UTF-16LE unless this is set, and a
|
|
870
|
-
// UTF-16 message read as UTF-8 is mojibake — including the `WSL_E_*` codes
|
|
871
|
-
// that say why a command could not start. The distro-missing check below
|
|
872
|
-
// reads those codes, so the encoding has to be pinned here.
|
|
873
|
-
WSL_UTF8: "1",
|
|
874
|
-
// WSL imports only the names listed in WSLENV. The managed DSH_* facts are
|
|
875
|
-
// included by prefix so every contributed variable rides along. PATH is deliberately
|
|
876
|
-
// never listed: putting it here would replace the distro's PATH with
|
|
877
|
-
// the Windows one instead of appending the interop entries WSL adds
|
|
878
|
-
// on its own.
|
|
879
|
-
...(forwarded.length > 0 ? { WSLENV: forwarded.map((name) => (PATH_TRANSLATED.has(name) ? `${name}/p` : name)).join(":") } : {}),
|
|
880
|
-
},
|
|
881
|
-
};
|
|
882
|
-
}
|
|
883
|
-
/**
|
|
884
|
-
* Resolve a request into a spec, replacing the parent's `process.cwd()`
|
|
885
|
-
* fallback with this provider's distro-home marker and stamping the per-call
|
|
886
|
-
* sandbox policy.
|
|
887
|
-
*
|
|
888
|
-
* The seam requires this step to be synchronous — the tool layer calls
|
|
889
|
-
* `ctx.shell.execute(ctx.shell.resolve(…))` with no `await` between them — so
|
|
890
|
-
* neither the home nor a confinement decision can be made here. Two request
|
|
891
|
-
* shapes default to the home when no `cwd` is configured: one that names no
|
|
892
|
-
* `workdir` at all, and one that names it only RELATIVELY — the parent
|
|
893
|
-
* resolves the first against `process.cwd()` (a Windows directory) and has
|
|
894
|
-
* nothing of its own to join the second onto. Both are stamped as the empty
|
|
895
|
-
* marker, with a relative tail carried verbatim in `relativeWorkdir`;
|
|
896
|
-
* {@link withDefaultWorkdir} resolves the pair against the home. The policy
|
|
897
|
-
* travels on the spec to {@link execute}, which awaits the wrap.
|
|
898
|
-
*
|
|
899
|
-
* @param request - the caller's request.
|
|
900
|
-
* @returns the fully-resolved spec.
|
|
901
|
-
*/
|
|
902
|
-
resolve(request) {
|
|
903
|
-
const config = this.config;
|
|
904
|
-
const spec = super.resolve(request);
|
|
905
|
-
const sandboxPolicy = this.sandbox === undefined ? undefined : (request?.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve());
|
|
906
|
-
const workdir = typeof request?.workdir === "string" ? request.workdir : undefined;
|
|
907
|
-
const needsHome = configuredCwd(config).length === 0 && (workdir === undefined || isRelativeWorldPath(workdir));
|
|
908
|
-
if (!needsHome && sandboxPolicy === undefined)
|
|
909
|
-
return spec;
|
|
910
|
-
return {
|
|
911
|
-
...spec,
|
|
912
|
-
...(needsHome ? { workdir: "", relativeWorkdir: workdir } : {}),
|
|
913
|
-
...(sandboxPolicy === undefined ? {} : { sandboxPolicy }),
|
|
914
|
-
};
|
|
915
|
-
}
|
|
916
|
-
/**
|
|
917
|
-
* The spec to execute, with the home marker resolved against the distro
|
|
918
|
-
* user's home: `workdir: ""` becomes the home itself, and a relative tail
|
|
919
|
-
* carried by {@link WslShellExecutor.resolve} is joined under it. That is one
|
|
920
|
-
* `sh -c 'printf %s "$HOME"'` per provider instance, cached, and it happens
|
|
921
|
-
* only for a request that defaulted — an absolute workdir never reaches here.
|
|
922
|
-
*
|
|
923
|
-
* @param spec - the resolved spec.
|
|
924
|
-
* @returns the spec to execute.
|
|
925
|
-
*/
|
|
926
|
-
async withDefaultWorkdir(spec) {
|
|
927
|
-
const tail = typeof spec?.relativeWorkdir === "string" ? spec.relativeWorkdir : undefined;
|
|
928
|
-
if (String(spec?.workdir ?? "").trim().length > 0 && tail === undefined)
|
|
929
|
-
return spec;
|
|
930
|
-
const distro = await this.distroFor(spec.workdir, configuredCwd(this.config));
|
|
931
|
-
const home = await distroHome(this, distro);
|
|
932
|
-
if (tail === undefined || tail.length === 0)
|
|
933
|
-
return { ...spec, workdir: home };
|
|
934
|
-
return { ...spec, workdir: toLinuxPath(tail, { cwd: home }) };
|
|
935
|
-
}
|
|
936
|
-
/**
|
|
937
|
-
* Decorate a handle's foreground projection in place, memoized once. The
|
|
938
|
-
* handle keeps its identity — never wrapped in a second object — because the
|
|
939
|
-
* per-process facts and `onProcessDone` key on the exact instance.
|
|
940
|
-
*
|
|
941
|
-
* @template H - the concrete handle type, preserved so the decorated handle
|
|
942
|
-
* keeps its identity in the callers' types; the settled result row the maps
|
|
943
|
-
* are spelled in is derived from its `result()`.
|
|
944
|
-
* @param ex - the execution handle to decorate.
|
|
945
|
-
* @param map - maps the settled result.
|
|
946
|
-
* @param mapError - maps a rejection, when the caller has one.
|
|
947
|
-
* @returns the same handle.
|
|
948
|
-
*/
|
|
949
|
-
static decorateResult(ex, map, mapError) {
|
|
950
|
-
const handle = ex;
|
|
951
|
-
const base = handle.result.bind(handle);
|
|
952
|
-
let decorated;
|
|
953
|
-
handle.result = () => {
|
|
954
|
-
decorated ??= base().then(map, mapError);
|
|
955
|
-
return decorated;
|
|
956
|
-
};
|
|
957
|
-
return ex;
|
|
958
|
-
}
|
|
959
|
-
/**
|
|
960
|
-
* Stamp the per-process sandbox facts before `done` settles, so a background
|
|
961
|
-
* process reports the same mode, denial and enforcement a foreground run
|
|
962
|
-
* would. Signal deaths are not denials.
|
|
963
|
-
*
|
|
964
|
-
* @param proc - the settled process handle.
|
|
965
|
-
* @param stderr - the process's retained stderr tail used by subclasses for settlement classification.
|
|
966
|
-
* @param providerRejected - whether the subprocess promise rejected without a direct outcome.
|
|
967
|
-
* @param providerError - the provider rejection reason, which may itself be undefined.
|
|
968
|
-
*/
|
|
969
|
-
onProcessDone(proc, stderr, providerRejected, providerError) {
|
|
970
|
-
const facts = this.processFacts.get(proc);
|
|
971
|
-
if (facts !== undefined) {
|
|
972
|
-
this.processFacts.delete(proc);
|
|
973
|
-
// A provider rejection exposes no public failure stage; attribute it to
|
|
974
|
-
// the confinement runner only when the error independently names argv[0].
|
|
975
|
-
const runnerFailed = providerRejected
|
|
976
|
-
? isRunnerSpawnFailure(providerError, facts.runnerProgram, facts.workdir)
|
|
977
|
-
: classifyRunnerFailure(proc.exitCode, stderr, facts.runnerFailureRules) !== undefined;
|
|
978
|
-
proc.sandbox = {
|
|
979
|
-
mode: facts.mode,
|
|
980
|
-
denied: !runnerFailed && matchesSignature(proc.exitCode, stderr, facts.denialSignatures),
|
|
981
|
-
enforcement: facts.enforcement,
|
|
982
|
-
...(facts.windowsDrive ? { windowsDrive: facts.windowsDrive } : {}),
|
|
983
|
-
sessionScope: facts.sessionScope,
|
|
984
|
-
...(runnerFailed ? { runnerFailed } : {}),
|
|
985
|
-
};
|
|
986
|
-
}
|
|
987
|
-
super.onProcessDone(proc, stderr, providerRejected, providerError);
|
|
988
|
-
}
|
|
989
|
-
/**
|
|
990
|
-
* Reject a settled command that failed because the distro itself is missing,
|
|
991
|
-
* stopped or unregistered.
|
|
992
|
-
*
|
|
993
|
-
* `wsl.exe` exits non-zero for that with an EMPTY stderr and its diagnostic on
|
|
994
|
-
* stdout, so nothing else here can see it: the denial signatures read stderr, and
|
|
995
|
-
* the result would otherwise reach the model as a bare non-zero code with no
|
|
996
|
-
* cause. The message names the remedy and says plainly that a wider permission
|
|
997
|
-
* cannot help — a sandbox flag does not create a distro.
|
|
998
|
-
*
|
|
999
|
-
* @param result - the settled shell result.
|
|
1000
|
-
* @param distro - the distro the command asked for.
|
|
1001
|
-
* @throws {Error} carrying the `WSL_E_*` code and the remedy.
|
|
1002
|
-
*/
|
|
1003
|
-
throwIfDistroUnavailable(result, distro) {
|
|
1004
|
-
if (result?.exitCode === 0)
|
|
1005
|
-
return;
|
|
1006
|
-
const code = wslErrorCode(result?.stdout?.text, result?.stderr?.text);
|
|
1007
|
-
if (code === undefined)
|
|
1008
|
-
return;
|
|
1009
|
-
throw new Error(t("distroUnavailable", { code, distro }));
|
|
1010
|
-
}
|
|
1011
|
-
/**
|
|
1012
|
-
* Reject a command that ran in the wrong directory.
|
|
1013
|
-
*
|
|
1014
|
-
* `wsl.exe --cd <path>` does not fail on a missing directory: it warns on stderr,
|
|
1015
|
-
* runs the command in `/`, and exits 0. Reporting that as success would let a write
|
|
1016
|
-
* or a build act on the wrong tree while every signal says it worked, so it becomes
|
|
1017
|
-
* an error naming the directory that could not be entered.
|
|
1018
|
-
*
|
|
1019
|
-
* @param result - the settled shell result.
|
|
1020
|
-
* @param workdir - the Linux directory the request asked for.
|
|
1021
|
-
* @throws {Error} naming the directory and the fallback that happened.
|
|
1022
|
-
*/
|
|
1023
|
-
throwIfWorkdirMissing(result, workdir) {
|
|
1024
|
-
const missing = workdirFailure(result?.stdout?.text, result?.stderr?.text);
|
|
1025
|
-
if (missing === undefined)
|
|
1026
|
-
return;
|
|
1027
|
-
throw new Error(t("workdirMissing", { missing }));
|
|
1028
|
-
}
|
|
1029
|
-
/**
|
|
1030
|
-
* Execute one resolved spec inside the distro, confined by the per-call policy
|
|
1031
|
-
* when there is one.
|
|
1032
|
-
*
|
|
1033
|
-
* Confinement wraps the DISTRO-side argv (`<shell> -lc <command>`) in `bwrap`
|
|
1034
|
-
* and hands the result to `wsl.exe --exec`, so the sandbox is built inside the
|
|
1035
|
-
* distro while the process that spawns it stays the ordinary Windows one. The
|
|
1036
|
-
* `danger-full-access` escalation — and an operator's `sandbox: false` — skip
|
|
1037
|
-
* the wrap entirely and run the command as before.
|
|
1038
|
-
*
|
|
1039
|
-
* @param spec - resolved execution settings.
|
|
1040
|
-
* @returns the live shell process handle.
|
|
1041
|
-
*/
|
|
1042
|
-
async execute(spec) {
|
|
1043
|
-
const config = this.config;
|
|
1044
|
-
const resolved = await this.withDefaultWorkdir(spec);
|
|
1045
|
-
const distro = await this.distroFor(resolved.workdir, configuredCwd(config));
|
|
1046
|
-
const shell = await this.shellFor(distro);
|
|
1047
|
-
this.throwIfWorkdirInAnotherDistro(resolved.workdir, distro);
|
|
1048
|
-
if (config.agent) {
|
|
1049
|
-
try {
|
|
1050
|
-
return await this.executeViaAgent(resolved, distro, shell);
|
|
1051
|
-
}
|
|
1052
|
-
catch (error) {
|
|
1053
|
-
// Only an out-of-service agent falls back; anything else (a cwd
|
|
1054
|
-
// refusal, a sandbox refusal) is the command's own verdict.
|
|
1055
|
-
if (!(error instanceof AgentUnavailableError))
|
|
1056
|
-
throw error;
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
return this.executeOneShot(resolved, distro, shell);
|
|
1060
|
-
}
|
|
1061
|
-
/**
|
|
1062
|
-
* Refuse a workdir that names another WSL distro — the shell-side twin of
|
|
1063
|
-
* the filesystem's `FS_OUTSIDE_DISTRO` fence. Left unguarded, `toLinuxPath`
|
|
1064
|
-
* strips the UNC's distro name and the command runs inside THIS distro
|
|
1065
|
-
* against whatever tree happens to share the path, silently, while the fs
|
|
1066
|
-
* side refuses the same workspace outright. The wording mirrors the fs
|
|
1067
|
-
* refusal (minus `restrictToDistro`, which is an fs-only key).
|
|
1068
|
-
*
|
|
1069
|
-
* @param workdir - the resolved workdir (UNC, Linux path, or Windows path).
|
|
1070
|
-
* @param distro - the pinned distro name.
|
|
1071
|
-
* @throws {Error} naming both distros and both ways out.
|
|
1072
|
-
*/
|
|
1073
|
-
throwIfWorkdirInAnotherDistro(workdir, distro) {
|
|
1074
|
-
if (!isAnotherDistrosUnc(workdir, distro))
|
|
1075
|
-
return;
|
|
1076
|
-
throw new Error(t("workdirAnotherDistro", { workdir, distro }));
|
|
1077
|
-
}
|
|
1078
|
-
/**
|
|
1079
|
-
* The agent-backed execution path: one long-lived in-distro process, the
|
|
1080
|
-
* confinement argv unchanged, the handle shape unchanged. Any
|
|
1081
|
-
* {@link AgentUnavailableError} propagates for the caller's fallback.
|
|
1082
|
-
*
|
|
1083
|
-
* @param resolved - the resolved spec from {@link WslShellExecutor.execute}.
|
|
1084
|
-
* @param distro - the resolved distro name.
|
|
1085
|
-
* @param shell - the resolved distro shell.
|
|
1086
|
-
* @returns the decorated execution result.
|
|
1087
|
-
*/
|
|
1088
|
-
async executeViaAgent(resolved, distro, shell) {
|
|
1089
|
-
const config = this.config;
|
|
1090
|
-
const policy = resolved.sandboxPolicy;
|
|
1091
|
-
const confined = this.sandbox !== undefined && policy !== undefined && policy.mode !== "danger-full-access"
|
|
1092
|
-
? await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode: policy.mode }, { distro, signal: resolved.signal })
|
|
1093
|
-
: undefined;
|
|
1094
|
-
const mode = policy?.mode;
|
|
1095
|
-
const useScope = await this.wantsSessionRuntime(distro);
|
|
1096
|
-
const runtime = useScope ? this.sessionRuntimeFor(policy, resolved, distro) : undefined;
|
|
1097
|
-
const agent = runtime !== undefined ? runtime.agent : await this.executionAgent(distro);
|
|
1098
|
-
// A session runtime's own bwrap profile applies the mounts, so the
|
|
1099
|
-
// command must NOT be wrapped a second time: the per-command probe still
|
|
1100
|
-
// runs (it is the bwrap availability check and the denial facts), but its
|
|
1101
|
-
// argv is discarded.
|
|
1102
|
-
const argv = runtime !== undefined
|
|
1103
|
-
? this.distroArgv(resolved, shell)
|
|
1104
|
-
: confined !== undefined ? confined.argv : this.distroArgv(resolved, shell);
|
|
1105
|
-
// The managed `DSH_*` snapshot merges last, exactly as the one-shot path's
|
|
1106
|
-
// spawn env does (`ShellExecSpec`: `dshEnv` wins over `env`). The agent
|
|
1107
|
-
// applies these to the individual command, so
|
|
1108
|
-
// the resident path now carries `DSH_HOME`, `DSH_SESSION_ID` and the
|
|
1109
|
-
// `DSH_WSL_*` facts too — without this the whole registry was invisible on
|
|
1110
|
-
// the default path while the one-shot fallback forwarded it.
|
|
1111
|
-
const env = { ...resolved.env, ...resolved.dshEnv };
|
|
1112
|
-
const execution = agentExecutionHandle({
|
|
1113
|
-
agent,
|
|
1114
|
-
// The one-shot path converts the spec's workdir into the distro's
|
|
1115
|
-
// coordinate system inside argv(); the agent carries the cwd as a frame
|
|
1116
|
-
// field, so the SAME conversion happens here — a raw UNC must never
|
|
1117
|
-
// reach `chdir` (that is the bug this line fixes).
|
|
1118
|
-
cwd: toLinuxPath(resolved.workdir),
|
|
1119
|
-
argv,
|
|
1120
|
-
env: Object.keys(env).length > 0 ? env : undefined,
|
|
1121
|
-
timeoutMs: resolved.timeoutMs,
|
|
1122
|
-
// The agent enforces the collect budget distro-side (the EXEC frame
|
|
1123
|
-
// carries it); `maxSpillBytes` stays one-shot-only — the agent path has
|
|
1124
|
-
// no spill files by design, its capture is bounded instead. The budget
|
|
1125
|
-
// is the executor's own per-stream cap, read through the volatile
|
|
1126
|
-
// wrapper like every other volatile field: handing the wrapper over raw
|
|
1127
|
-
// made `encodeExecFrame`'s `> 0` test false, so the frame carried 0 —
|
|
1128
|
-
// which the agent reads as "uncapped", and the documented cut never ran.
|
|
1129
|
-
maxOutputBytes: config.maxOutputBytes.get(),
|
|
1130
|
-
signal: resolved.signal,
|
|
1131
|
-
onStarted: confined !== undefined
|
|
1132
|
-
? (proc) => {
|
|
1133
|
-
// The untyped guard cannot narrow the captured profile inside the
|
|
1134
|
-
// callback, so the confined shape is asserted once here.
|
|
1135
|
-
const profile = confined;
|
|
1136
|
-
this.processFacts.set(proc, {
|
|
1137
|
-
mode,
|
|
1138
|
-
enforcement: profile.enforcement,
|
|
1139
|
-
denialSignatures: profile.denialSignatures,
|
|
1140
|
-
runnerFailureRules: profile.runnerFailureRules,
|
|
1141
|
-
runnerProgram: profile.argv[0] ?? "",
|
|
1142
|
-
workdir: resolved.workdir,
|
|
1143
|
-
windowsDrive: profile.windowsDrive,
|
|
1144
|
-
sessionScope: useScope ? "session" : "per-command",
|
|
1145
|
-
});
|
|
1146
|
-
}
|
|
1147
|
-
: undefined,
|
|
1148
|
-
});
|
|
1149
|
-
const decorated = WslShellExecutor.decorateResult(execution, (result) => {
|
|
1150
|
-
this.throwIfDistroUnavailable(result, distro);
|
|
1151
|
-
this.throwIfWorkdirMissing(result, resolved.workdir);
|
|
1152
|
-
if (this.sandbox === undefined)
|
|
1153
|
-
return result;
|
|
1154
|
-
if (confined === undefined) {
|
|
1155
|
-
return ({ ...result, sandbox: { mode, denied: false, sessionScope: useScope ? "session" : "per-command" } });
|
|
1156
|
-
}
|
|
1157
|
-
const { enforcement, denialSignatures, runnerFailureRules, windowsDrive } = confined;
|
|
1158
|
-
const runnerFailure = classifyRunnerFailure(result.exitCode, result.stderr.text, runnerFailureRules);
|
|
1159
|
-
if (runnerFailure !== undefined) {
|
|
1160
|
-
// This path computes `mode` as `policy?.mode`, which the seam spells as
|
|
1161
|
-
// the wider union: a runner failure is only ever thrown under a
|
|
1162
|
-
// confinement, and there the mode is one of the two confined ones.
|
|
1163
|
-
throw new SandboxUnavailableError(mode, withBwrapHint(runnerFailure.detail, distro));
|
|
1164
|
-
}
|
|
1165
|
-
return ({
|
|
1166
|
-
...result,
|
|
1167
|
-
sandbox: {
|
|
1168
|
-
mode,
|
|
1169
|
-
denied: matchesSignature(result.exitCode, result.stderr.text, denialSignatures),
|
|
1170
|
-
enforcement,
|
|
1171
|
-
windowsDrive,
|
|
1172
|
-
sessionScope: useScope ? "session" : "per-command",
|
|
1173
|
-
},
|
|
1174
|
-
});
|
|
1175
|
-
}, (error) => {
|
|
1176
|
-
if (resolved.signal?.aborted === true)
|
|
1177
|
-
resolved.signal.throwIfAborted();
|
|
1178
|
-
// The native agent reports a missing workdir as a spawn failure without
|
|
1179
|
-
// naming it. Retry that command on the one-shot path, whose `--cd`
|
|
1180
|
-
// warning names the directory — the failure path pays the extra spawn,
|
|
1181
|
-
// the hot path does not.
|
|
1182
|
-
if (error instanceof SpawnError) {
|
|
1183
|
-
return this.executeOneShot(resolved, distro, shell).then((fallback) => fallback.result());
|
|
1184
|
-
}
|
|
1185
|
-
throw error;
|
|
1186
|
-
});
|
|
1187
|
-
// The agent handle IS the upstream execution shape at runtime; its typedef
|
|
1188
|
-
// spells `signal` as `string` and the captured streams without `spillPath`,
|
|
1189
|
-
// so the upstream-facing return rides one type-level cast.
|
|
1190
|
-
return decorated;
|
|
1191
|
-
}
|
|
1192
|
-
/**
|
|
1193
|
-
* The pre-agent execution path, verbatim: one `wsl.exe` per command through
|
|
1194
|
-
* the inherited `executeArgv` machinery. Kept as the permanent fallback for
|
|
1195
|
-
* an out-of-service agent and as the `agent: false` behaviour.
|
|
1196
|
-
*
|
|
1197
|
-
* @param resolved - the resolved spec.
|
|
1198
|
-
* @param distro - the resolved distro name.
|
|
1199
|
-
* @param shell - the resolved distro shell.
|
|
1200
|
-
* @returns the decorated execution result.
|
|
1201
|
-
*/
|
|
1202
|
-
async executeOneShot(resolved, distro, shell) {
|
|
1203
|
-
const policy = resolved.sandboxPolicy;
|
|
1204
|
-
if (this.sandbox === undefined || policy === undefined || policy.mode === "danger-full-access") {
|
|
1205
|
-
// `executeArgv` resolves to the execution handle, so it has to be awaited
|
|
1206
|
-
// before it can be decorated — the confined branch below does the same.
|
|
1207
|
-
// The sync thunk is the prepare form at runtime (`executeArgv` awaits any
|
|
1208
|
-
// function it is given); the type spells it as the async prepare it is
|
|
1209
|
-
// used as, which is why the thunk rides a type-level cast.
|
|
1210
|
-
const execution = await this.executeArgv(resolved, (() => this.argv(resolved, distro, shell)));
|
|
1211
|
-
return WslShellExecutor.decorateResult(execution, (result) => {
|
|
1212
|
-
this.throwIfDistroUnavailable(result, distro);
|
|
1213
|
-
this.throwIfWorkdirMissing(result, resolved.workdir);
|
|
1214
|
-
return result;
|
|
1215
|
-
}, (error) => {
|
|
1216
|
-
throw error;
|
|
1217
|
-
});
|
|
1218
|
-
}
|
|
1219
|
-
// The confined prepare closes over this slot: the argv builder assigns it,
|
|
1220
|
-
// the fact-stamper and the settlement mapping read it. `executeArgv` runs
|
|
1221
|
-
// the builder before either callback can fire, so the reads always see the
|
|
1222
|
-
// assigned profile (or the run never happened). The mode is captured once
|
|
1223
|
-
// here: the guard above narrowed it, and property narrowings do not reach
|
|
1224
|
-
// closures.
|
|
1225
|
-
const mode = policy.mode;
|
|
1226
|
-
const confinement = { profile: undefined };
|
|
1227
|
-
const execution = await this.executeArgv(resolved, (signal) => this.prepareConfinedArgv(resolved, distro, shell, policy, mode, confinement, signal), (process) => this.stampConfinedFacts(resolved, mode, confinement, process));
|
|
1228
|
-
return WslShellExecutor.decorateResult(execution, (result) => {
|
|
1229
|
-
return this.settleConfinedOneShot(result, distro, resolved, mode, confinement.profile);
|
|
1230
|
-
}, (error) => {
|
|
1231
|
-
// An upstream abort remains cancellation even when it prevents spawn.
|
|
1232
|
-
if (resolved.signal?.aborted === true)
|
|
1233
|
-
resolved.signal.throwIfAborted();
|
|
1234
|
-
if (confinement.profile !== undefined && isRunnerSpawnFailure(error, confinement.profile.argv[0], resolved.workdir)) {
|
|
1235
|
-
throw new SandboxUnavailableError(mode, withBwrapHint(String(error), distro));
|
|
1236
|
-
}
|
|
1237
|
-
throw error;
|
|
1238
|
-
});
|
|
1239
|
-
}
|
|
1240
|
-
/**
|
|
1241
|
-
* The confined one-shot's argv prepare: confine the distro argv under the
|
|
1242
|
-
* policy, keep the resulting profile for the fact-stamper and the settlement
|
|
1243
|
-
* mapping, and hand back the wrapped host argv.
|
|
1244
|
-
*
|
|
1245
|
-
* @param resolved - the resolved spec.
|
|
1246
|
-
* @param distro - the resolved distro name.
|
|
1247
|
-
* @param shell - the resolved distro shell.
|
|
1248
|
-
* @param policy - the confined policy (narrowed in by `executeOneShot`).
|
|
1249
|
-
* @param slot - the closure the builder assigns the profile into.
|
|
1250
|
-
* @param signal - the caller's cancellation.
|
|
1251
|
-
*/
|
|
1252
|
-
async prepareConfinedArgv(resolved, distro, shell, policy, mode, slot, signal) {
|
|
1253
|
-
// Preparation is async, so it runs under executeArgv's deadline and
|
|
1254
|
-
// cancellation handling rather than before them. A distro without a
|
|
1255
|
-
// usable runner throws here, before anything is spawned. The outer
|
|
1256
|
-
// guard narrowed the sandbox in, but narrowings do not reach closures —
|
|
1257
|
-
// so the confined sandbox is asserted here, type-level only.
|
|
1258
|
-
const profile = await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode }, { distro, signal });
|
|
1259
|
-
slot.profile = profile;
|
|
1260
|
-
signal.throwIfAborted();
|
|
1261
|
-
return this.argv(resolved, distro, shell, profile.argv);
|
|
1262
|
-
}
|
|
1263
|
-
/**
|
|
1264
|
-
* Stamp the per-process sandbox facts before `done` settles, so a background
|
|
1265
|
-
* process reports the same mode, denial and enforcement a foreground run
|
|
1266
|
-
* would.
|
|
1267
|
-
*
|
|
1268
|
-
* @param resolved - the resolved spec.
|
|
1269
|
-
* @param mode - the confined policy's mode.
|
|
1270
|
-
* @param slot - the closure holding the assigned profile.
|
|
1271
|
-
* @param process - the spawned handle.
|
|
1272
|
-
*/
|
|
1273
|
-
stampConfinedFacts(resolved, mode, slot, process) {
|
|
1274
|
-
// The builder has run before any process callback can fire; the confined
|
|
1275
|
-
// shape is asserted once here, type-level only.
|
|
1276
|
-
const profile = slot.profile;
|
|
1277
|
-
this.processFacts.set(process, {
|
|
1278
|
-
mode,
|
|
1279
|
-
enforcement: profile.enforcement,
|
|
1280
|
-
denialSignatures: profile.denialSignatures,
|
|
1281
|
-
runnerFailureRules: profile.runnerFailureRules,
|
|
1282
|
-
runnerProgram: profile.argv[0] ?? "",
|
|
1283
|
-
workdir: resolved.workdir,
|
|
1284
|
-
windowsDrive: profile.windowsDrive,
|
|
1285
|
-
sessionScope: "per-command",
|
|
1286
|
-
});
|
|
1287
|
-
}
|
|
1288
|
-
/**
|
|
1289
|
-
* Settle one confined one-shot result: the distro and workdir verdicts, the
|
|
1290
|
-
* never-armed honesty stamp, the runner-failure throw, and the denial facts.
|
|
1291
|
-
*
|
|
1292
|
-
* @param result - the settled process result.
|
|
1293
|
-
* @param distro - the resolved distro name.
|
|
1294
|
-
* @param resolved - the resolved spec.
|
|
1295
|
-
* @param mode - the confined policy's mode.
|
|
1296
|
-
* @param confined - the profile the argv prepare armed, when it ran.
|
|
1297
|
-
*/
|
|
1298
|
-
settleConfinedOneShot(result, distro, resolved, mode, confined) {
|
|
1299
|
-
this.throwIfDistroUnavailable(result, distro);
|
|
1300
|
-
this.throwIfWorkdirMissing(result, resolved.workdir);
|
|
1301
|
-
if (confined === undefined) {
|
|
1302
|
-
return ({ ...result, sandbox: { mode, denied: false, sessionScope: "per-command" } });
|
|
1303
|
-
}
|
|
1304
|
-
const { enforcement, denialSignatures, runnerFailureRules, windowsDrive } = confined;
|
|
1305
|
-
// Runner failure outranks denial because the command did not run at all.
|
|
1306
|
-
const runnerFailure = classifyRunnerFailure(result.exitCode, result.stderr.text, runnerFailureRules);
|
|
1307
|
-
if (runnerFailure !== undefined)
|
|
1308
|
-
throw new SandboxUnavailableError(mode, withBwrapHint(runnerFailure.detail, distro));
|
|
1309
|
-
return ({
|
|
1310
|
-
...result,
|
|
1311
|
-
sandbox: {
|
|
1312
|
-
mode,
|
|
1313
|
-
denied: matchesSignature(result.exitCode, result.stderr.text, denialSignatures),
|
|
1314
|
-
enforcement,
|
|
1315
|
-
windowsDrive,
|
|
1316
|
-
sessionScope: "per-command",
|
|
1317
|
-
},
|
|
1318
|
-
});
|
|
1319
|
-
}
|
|
1320
|
-
}
|
|
1321
|
-
export class WslFileSystem extends LocalFileSystem {
|
|
1322
|
-
static inject = ["sandboxPolicy"];
|
|
1323
|
-
static Config = z.object({
|
|
1324
|
-
/**
|
|
1325
|
-
* Distro mode: empty/`"auto"` follows the target path, `"default"` forces
|
|
1326
|
-
* WSL's default, and an explicit name pins the filesystem.
|
|
1327
|
-
*/
|
|
1328
|
-
distro: z.string().default(""),
|
|
1329
|
-
/**
|
|
1330
|
-
* Default workdir for relative input; accepts a Linux path, a UNC path, or
|
|
1331
|
-
* `C:\...`. Empty — the default — means the distro user's home, resolved
|
|
1332
|
-
* inside the distro.
|
|
1333
|
-
*/
|
|
1334
|
-
cwd: z.string().default(""),
|
|
1335
|
-
/** Path to `wsl.exe`, used only to resolve the default distro. */
|
|
1336
|
-
wslPath: z.string().default("wsl.exe"),
|
|
1337
|
-
/** UTF-8 byte limit per overwrite-diff side, mirroring the host backend. */
|
|
1338
|
-
diffBasisMaxBytes: z.number().default(10 * 1024 * 1024),
|
|
1339
|
-
/**
|
|
1340
|
-
* Fence mutations by `ctx.sandboxPolicy`, and report the mode through
|
|
1341
|
-
* {@link sandboxMode}. `false` restores the pre-sandbox behaviour exactly —
|
|
1342
|
-
* an unfenced backend that reports `undefined` — for an operator who wants
|
|
1343
|
-
* the old posture and accepts what it means: the model is told these
|
|
1344
|
-
* operations are unconfined.
|
|
1345
|
-
*/
|
|
1346
|
-
sandbox: z.boolean().default(true),
|
|
1347
|
-
/**
|
|
1348
|
-
* Run confined mutations in the session's systemd user scope — the same
|
|
1349
|
-
* runtime the shell executor acquires for the same session, distro,
|
|
1350
|
-
* workspace and policy — instead of a per-policy confined resident. A
|
|
1351
|
-
* missing session ID keeps the providers separate. The kernel enforcement
|
|
1352
|
-
* is the runtime's mount profile; the scope stops when its providers
|
|
1353
|
-
* release it. Requires systemd + `Linger`, like `wsl-shell`'s
|
|
1354
|
-
* `sessionSandbox`; the preflight refuses with the remedy. Off for direct
|
|
1355
|
-
* constructions; on in the shipped preset.
|
|
1356
|
-
*/
|
|
1357
|
-
sessionSandbox: z.union([z.boolean(), z.const("auto")]).default(false),
|
|
1358
|
-
/**
|
|
1359
|
-
* Shadow `/mnt` with an empty tmpfs in every confined profile, hiding the
|
|
1360
|
-
* Windows drive from confined commands — same meaning and same honest
|
|
1361
|
-
* limits as the `wsl-shell` key of the same name (its doc carries the
|
|
1362
|
-
* full story). Confined fs mutations publish through the masked resident;
|
|
1363
|
-
* reads and the share substrate are unaffected.
|
|
1364
|
-
*/
|
|
1365
|
-
maskWindowsDrive: z.boolean().default(false),
|
|
1366
|
-
/**
|
|
1367
|
-
* Refuse any path that leaves the pinned distro. A WSL filesystem is a
|
|
1368
|
-
* whole-Linux view whose `/mnt/c` also reaches the Windows disk, so without
|
|
1369
|
-
* this the backend would silently widen the session far beyond the
|
|
1370
|
-
* workspace the operator selected.
|
|
1371
|
-
*/
|
|
1372
|
-
restrictToDistro: z.boolean().default(true),
|
|
1373
|
-
/**
|
|
1374
|
-
* How deep the in-distro watch scan walks, `1` = the watched directory and
|
|
1375
|
-
* its direct children. `0` — the default — walks the whole tree, which is
|
|
1376
|
-
* what the invalidation contract asks for but a real cost every poll over
|
|
1377
|
-
* a tree containing a `node_modules`; a bound trades that cost for a
|
|
1378
|
-
* documented blind spot: a change below the bound is not seen until
|
|
1379
|
-
* another change above it fires the same callback.
|
|
1380
|
-
*/
|
|
1381
|
-
watchMaxDepth: z.natural().default(0),
|
|
1382
|
-
/**
|
|
1383
|
-
* Which I/O substrate serves the file tools. Only `"agent"` exists — the
|
|
1384
|
-
* resident in-distro agent (`lib/fs-substrate.js`): reads, writes and
|
|
1385
|
-
* identities run where the files live, symlinks and mode bits are native,
|
|
1386
|
-
* and the mutation guard survives to the write's no-replace publication,
|
|
1387
|
-
* kernel-enforced by the confined resident when the policy is confined.
|
|
1388
|
-
* The former `"share"` opt-out — the Windows-side host filesystem stack
|
|
1389
|
-
* over the distro's 9p share — is retired: it was the one model-facing
|
|
1390
|
-
* I/O path that still crossed the share, and the agent has no fallback
|
|
1391
|
-
* that needs it. A profile carrying `"share"` is refused at construction
|
|
1392
|
-
* with the migration (`shareSubstrateRefusal`). `watch()` rides the
|
|
1393
|
-
* in-distro poll loop for the substrate regardless (`lib/watcher.js`) —
|
|
1394
|
-
* it never ran through either substrate. The substrate never changes
|
|
1395
|
-
* `sandboxMode`'s honesty.
|
|
1396
|
-
*/
|
|
1397
|
-
substrate: z.union(["share", "agent"]).default("agent"),
|
|
1398
|
-
});
|
|
1399
|
-
/**
|
|
1400
|
-
* @param ctx - the composition context.
|
|
1401
|
-
* @param config - the validated plugin config.
|
|
1402
|
-
*/
|
|
1403
|
-
constructor(ctx, config) {
|
|
1404
|
-
// The share substrate is refused before any peer work: a profile still
|
|
1405
|
-
// carrying the retired value must fail loudly, with the migration, not
|
|
1406
|
-
// silently serve the one I/O path this provider exists to close.
|
|
1407
|
-
const refusal = shareSubstrateRefusal(config.substrate);
|
|
1408
|
-
if (refusal !== null)
|
|
1409
|
-
throw new Error(refusal.message);
|
|
1410
|
-
super(ctx, config);
|
|
1411
|
-
installMessagesLocale(ctx);
|
|
1412
|
-
this.resolvedDistro = pinnedDistro(config.distro) ?? "";
|
|
1413
|
-
this.resolvedHome = undefined;
|
|
1414
|
-
this.resolvedHomes = new Map();
|
|
1415
|
-
this.defaultMode = ctx.sandboxPolicy.defaultMode;
|
|
1416
|
-
this.agentSubstrateInstance = undefined;
|
|
1417
|
-
this.agentSubstrates = new Map();
|
|
1418
|
-
this.sandbox = new WslSandbox({ wslPath: config.wslPath, maskWindowsDrive: config.maskWindowsDrive });
|
|
1419
|
-
this.agentInstance = undefined;
|
|
1420
|
-
this.agentInstances = new Map();
|
|
1421
|
-
this.sessionRuntimes = sessionRuntimes;
|
|
1422
|
-
this.sessionRuntimeEntries = new Map();
|
|
1423
|
-
this.sessionRuntimeOwner = randomUUID();
|
|
1424
|
-
this.sessionScopeProbe = (argv) => runCapture(argv);
|
|
1425
|
-
this.sessionRuntimePreflight = new Set();
|
|
1426
|
-
this.autoSessionScope = new Map();
|
|
1427
|
-
// The preset's disposer releases the runtime; the shell executor's effect
|
|
1428
|
-
// releases its own reference, so the scope stops after the last one.
|
|
1429
|
-
ctx.effect(() => () => this.disposeSessionRuntimes().catch(() => { }), "wsl fs session runtimes");
|
|
1430
|
-
}
|
|
1431
|
-
/**
|
|
1432
|
-
* The mode this backend fences mutations with, or `undefined` when the
|
|
1433
|
-
* operator turned the fence off. This is the capability fact `dsh-tool-fs`
|
|
1434
|
-
* reads to advertise the escalation fields honestly, so it must disappear
|
|
1435
|
-
* together with the enforcement — never claim a boundary that is not applied.
|
|
1436
|
-
*
|
|
1437
|
-
* @returns the deployment default mode, or `undefined` when unfenced.
|
|
1438
|
-
*/
|
|
1439
|
-
get sandboxMode() {
|
|
1440
|
-
const config = this.config;
|
|
1441
|
-
return config.sandbox ? this.defaultMode : undefined;
|
|
1442
|
-
}
|
|
1443
|
-
/**
|
|
1444
|
-
* The resident agent serving the default/pinned distro's in-distro side
|
|
1445
|
-
* work, created on first use and kept for the provider's lifetime.
|
|
1446
|
-
*
|
|
1447
|
-
* @returns the agent for the default/pinned distro.
|
|
1448
|
-
*/
|
|
1449
|
-
async publicationAgent() {
|
|
1450
|
-
if (this.agentInstance === undefined) {
|
|
1451
|
-
this.agentInstance = sharedAgent(await this.distro());
|
|
1452
|
-
}
|
|
1453
|
-
return this.agentInstance;
|
|
1454
|
-
}
|
|
1455
|
-
/**
|
|
1456
|
-
* The resident agent for one distro. The default/pinned distro keeps the
|
|
1457
|
-
* legacy {@link publicationAgent} cache; every other distro gets its own
|
|
1458
|
-
* entry, because the shared agent is a per-distro process singleton.
|
|
1459
|
-
*
|
|
1460
|
-
* @param distro - the distro name.
|
|
1461
|
-
* @returns the agent for that distro.
|
|
1462
|
-
*/
|
|
1463
|
-
async publicationAgentFor(distro) {
|
|
1464
|
-
if (this.resolvedDistro.length > 0 && distro === this.resolvedDistro)
|
|
1465
|
-
return this.publicationAgent();
|
|
1466
|
-
const cached = this.agentInstances.get(distro);
|
|
1467
|
-
if (cached !== undefined)
|
|
1468
|
-
return cached;
|
|
1469
|
-
const agent = sharedAgent(distro);
|
|
1470
|
-
this.agentInstances.set(distro, agent);
|
|
1471
|
-
return agent;
|
|
1472
|
-
}
|
|
1473
|
-
/**
|
|
1474
|
-
* The agent-backed substrate for the default/pinned distro, built on first
|
|
1475
|
-
* use over the shared resident agent.
|
|
1476
|
-
*
|
|
1477
|
-
* @returns the substrate.
|
|
1478
|
-
*/
|
|
1479
|
-
async agentSubstrate() {
|
|
1480
|
-
const config = this.config;
|
|
1481
|
-
if (this.agentSubstrateInstance === undefined) {
|
|
1482
|
-
this.agentSubstrateInstance = new AgentSubstrate({
|
|
1483
|
-
agent: await this.publicationAgent(),
|
|
1484
|
-
distro: await this.distro(),
|
|
1485
|
-
diffBasisMaxBytes: config.diffBasisMaxBytes,
|
|
1486
|
-
agentFor: (policy) => this.mutationAgent(policy),
|
|
1487
|
-
});
|
|
1488
|
-
}
|
|
1489
|
-
return this.agentSubstrateInstance;
|
|
1490
|
-
}
|
|
1491
|
-
/**
|
|
1492
|
-
* The agent-backed substrate for one distro. The default/pinned distro keeps
|
|
1493
|
-
* the legacy {@link agentSubstrate} accessor (and its test override); every
|
|
1494
|
-
* other distro gets a substrate that mints its own UNC identities and
|
|
1495
|
-
* addresses its own resident.
|
|
1496
|
-
*
|
|
1497
|
-
* @param distro - the distro name.
|
|
1498
|
-
* @returns the substrate for that distro.
|
|
1499
|
-
*/
|
|
1500
|
-
async agentSubstrateFor(distro) {
|
|
1501
|
-
if (this.resolvedDistro.length > 0 && distro === this.resolvedDistro)
|
|
1502
|
-
return this.agentSubstrate();
|
|
1503
|
-
const cached = this.agentSubstrates.get(distro);
|
|
1504
|
-
if (cached !== undefined)
|
|
1505
|
-
return cached;
|
|
1506
|
-
const config = this.config;
|
|
1507
|
-
const substrate = new AgentSubstrate({
|
|
1508
|
-
agent: await this.publicationAgentFor(distro),
|
|
1509
|
-
distro,
|
|
1510
|
-
diffBasisMaxBytes: config.diffBasisMaxBytes,
|
|
1511
|
-
agentFor: (policy) => this.mutationAgent(policy, distro),
|
|
1512
|
-
});
|
|
1513
|
-
this.agentSubstrates.set(distro, substrate);
|
|
1514
|
-
return substrate;
|
|
1515
|
-
}
|
|
1516
|
-
/**
|
|
1517
|
-
* The substrate for one resolved target, following the target's UNC identity.
|
|
1518
|
-
*
|
|
1519
|
-
* @param target - the resolved target.
|
|
1520
|
-
* @returns the substrate for the target's distro.
|
|
1521
|
-
*/
|
|
1522
|
-
async substrateForTarget(target) {
|
|
1523
|
-
return this.agentSubstrateFor(await this.distroForTarget(target));
|
|
1524
|
-
}
|
|
1525
|
-
/**
|
|
1526
|
-
* The persistent session runtime for one confined mutation, when
|
|
1527
|
-
* `sessionSandbox` is on. The key is the shell executor's key for the same
|
|
1528
|
-
* session/policy, so the write and the commands share one agent, one mount
|
|
1529
|
-
* view and one scope; the provider holds a reference until the session ends.
|
|
1530
|
-
*
|
|
1531
|
-
* @param policy - the resolved confined policy.
|
|
1532
|
-
* @param distro - the resolved distro name.
|
|
1533
|
-
* @returns the runtime entry, or undefined when the mode is off.
|
|
1534
|
-
*/
|
|
1535
|
-
sessionRuntimeFor(policy, distro) {
|
|
1536
|
-
const config = this.config;
|
|
1537
|
-
if (!config.sessionSandbox)
|
|
1538
|
-
return undefined;
|
|
1539
|
-
const workspaceRoot = policy.workspaceRoot || config.cwd;
|
|
1540
|
-
const sessionId = policy.sessionId || this.sessionRuntimeOwner;
|
|
1541
|
-
const key = SessionRuntimes.key({ sessionId, distro, workspaceRoot, mode: policy.mode, maskWindowsDrive: config.maskWindowsDrive });
|
|
1542
|
-
const held = this.sessionRuntimeEntries.get(key);
|
|
1543
|
-
if (held !== undefined)
|
|
1544
|
-
return held;
|
|
1545
|
-
const entry = this.sessionRuntimes.acquire({
|
|
1546
|
-
sessionId,
|
|
1547
|
-
distro,
|
|
1548
|
-
wslPath: config.wslPath,
|
|
1549
|
-
workspaceRoot,
|
|
1550
|
-
mode: policy.mode,
|
|
1551
|
-
maskWindowsDrive: config.maskWindowsDrive,
|
|
1552
|
-
});
|
|
1553
|
-
this.sessionRuntimeEntries.set(key, entry);
|
|
1554
|
-
return entry;
|
|
1555
|
-
}
|
|
1556
|
-
/**
|
|
1557
|
-
* Run the session runtime's preflight once per provider. Only success is
|
|
1558
|
-
* cached, so following the remedy does not need an app restart.
|
|
1559
|
-
*
|
|
1560
|
-
* @param distro - the resolved distro name.
|
|
1561
|
-
* @returns resolved once the platform can host the runtime.
|
|
1562
|
-
* @throws {Error} with the remedy when it cannot.
|
|
1563
|
-
*/
|
|
1564
|
-
async ensureSessionRuntimeUsable(distro) {
|
|
1565
|
-
if (this.sessionRuntimePreflight.has(distro))
|
|
1566
|
-
return;
|
|
1567
|
-
const config = this.config;
|
|
1568
|
-
const problem = await probeSessionRuntime({ wslPath: config.wslPath, distro, run: this.sessionScopeProbe });
|
|
1569
|
-
if (problem !== null)
|
|
1570
|
-
throw new Error(problem);
|
|
1571
|
-
await ensureNativeSessionAgent({ wslPath: config.wslPath, distro, setNative: setSessionNativeAgent });
|
|
1572
|
-
this.sessionRuntimePreflight.add(distro);
|
|
1573
|
-
}
|
|
1574
|
-
/**
|
|
1575
|
-
* Whether this provider should use the session runtime for one distro, with
|
|
1576
|
-
* the `auto` downgrade and its bounded re-probe. `true` keeps the refusing
|
|
1577
|
-
* behavior; `false` stays off.
|
|
1578
|
-
*
|
|
1579
|
-
* @param distro - the resolved distro.
|
|
1580
|
-
* @returns whether to acquire the per-session scope.
|
|
1581
|
-
*/
|
|
1582
|
-
async wantsSessionRuntime(distro) {
|
|
1583
|
-
const config = this.config;
|
|
1584
|
-
return sessionRuntimeWanted(config.sessionSandbox, distro, () => this.ensureSessionRuntimeUsable(distro), this.autoSessionScope);
|
|
1585
|
-
}
|
|
1586
|
-
/**
|
|
1587
|
-
* Release every runtime this provider holds. Called from the preset's
|
|
1588
|
-
* dispose effect; public so tests and shutdown paths can await it.
|
|
1589
|
-
*
|
|
1590
|
-
* @returns resolved once every reference is released.
|
|
1591
|
-
*/
|
|
1592
|
-
async disposeSessionRuntimes() {
|
|
1593
|
-
const entries = [...this.sessionRuntimeEntries.values()];
|
|
1594
|
-
this.sessionRuntimeEntries.clear();
|
|
1595
|
-
for (const entry of entries)
|
|
1596
|
-
await this.sessionRuntimes.release(entry.key);
|
|
1597
|
-
}
|
|
1598
|
-
/**
|
|
1599
|
-
* The agent a MUTATION runs on under this resolved policy — stage-two
|
|
1600
|
-
* routing. A confined policy addresses the confined resident whose bwrap
|
|
1601
|
-
* profile binds exactly what the mode grants, so the kernel enforces what
|
|
1602
|
-
* the check decided; an escalated write (`danger-full-access`) or a disabled
|
|
1603
|
-
* sandbox addresses the plain resident, which is what those mean. A distro
|
|
1604
|
-
* without a usable bwrap refuses confined mutations instead of downgrading
|
|
1605
|
-
* them — the same closed failure the command path has.
|
|
1606
|
-
*
|
|
1607
|
-
* @param policy - the resolved file-effect policy, or undefined when the
|
|
1608
|
-
* caller pre-checked.
|
|
1609
|
-
* @param forDistro - the distro the mutation belongs to; derived from the
|
|
1610
|
-
* policy when the caller does not know it.
|
|
1611
|
-
* @returns the agent to publish through.
|
|
1612
|
-
*/
|
|
1613
|
-
async mutationAgent(policy, forDistro) {
|
|
1614
|
-
const config = this.config;
|
|
1615
|
-
const distro = forDistro ?? await this.distroForPolicy(policy);
|
|
1616
|
-
if (!isConfinedMutation({ policy, sandboxEnabled: config.sandbox })) {
|
|
1617
|
-
return this.publicationAgentFor(distro);
|
|
1618
|
-
}
|
|
1619
|
-
// The untyped guard decided this is a confined policy but cannot narrow
|
|
1620
|
-
// the parameter, so the confined shape is asserted once here (type-level
|
|
1621
|
-
// only; `confinedPolicy` is the same value as `policy`).
|
|
1622
|
-
const confinedPolicy = policy;
|
|
1623
|
-
if (!(await this.sandbox.usable(distro))) {
|
|
1624
|
-
// The probe's classified remedy — missing vs present-but-broken, with the
|
|
1625
|
-
// distro's own package family — is what every other refusal surfaces;
|
|
1626
|
-
// this path has the same failure, so it carries the same text.
|
|
1627
|
-
throw new SandboxUnavailableError(confinedPolicy.mode, bwrapFailure(config.wslPath, distro) ?? missingBwrapRemedy(distro));
|
|
1628
|
-
}
|
|
1629
|
-
if (await this.wantsSessionRuntime(distro)) {
|
|
1630
|
-
const runtime = this.sessionRuntimeFor(confinedPolicy, distro);
|
|
1631
|
-
if (runtime !== undefined)
|
|
1632
|
-
return runtime.agent;
|
|
1633
|
-
}
|
|
1634
|
-
return confinedAgent({ distro, wslPath: config.wslPath, policy: confinedPolicy, maskWindowsDrive: config.maskWindowsDrive });
|
|
1635
|
-
}
|
|
1636
|
-
/**
|
|
1637
|
-
* Map a substrate error onto the peer's `FsError`, so the tool layer reads
|
|
1638
|
-
* the same refusal dialect on both substrates. An agent that is out becomes
|
|
1639
|
-
* an I/O error naming the cause — the share backend's "distro is gone" case
|
|
1640
|
-
* is the same availability, but the message says which substrate failed.
|
|
1641
|
-
*
|
|
1642
|
-
* @param error - what the substrate raised.
|
|
1643
|
-
* @returns the error to surface.
|
|
1644
|
-
*/
|
|
1645
|
-
peerError(error) {
|
|
1646
|
-
if (error instanceof FsCodedError) {
|
|
1647
|
-
return new FsError(error.message, error.code, { cause: error });
|
|
1648
|
-
}
|
|
1649
|
-
if (error instanceof SandboxUnavailableError)
|
|
1650
|
-
return new FsError(error.message, "FS_IO_ERROR", { cause: error });
|
|
1651
|
-
const { message, code, cause } = substrateFailure(error);
|
|
1652
|
-
return new FsError(message, code, cause === undefined ? {} : { cause });
|
|
1653
|
-
}
|
|
1654
|
-
/**
|
|
1655
|
-
* One resolved target's Linux path — the substrate's coordinate — falling
|
|
1656
|
-
* back to the display spelling when the identity is not a distro share path.
|
|
1657
|
-
*
|
|
1658
|
-
* @param target - the resolved target.
|
|
1659
|
-
* @returns the absolute Linux path.
|
|
1660
|
-
*/
|
|
1661
|
-
linuxOf(target) {
|
|
1662
|
-
return uncToPosix(target.targetKey)?.linuxPath ?? target.displayPath;
|
|
1663
|
-
}
|
|
1664
|
-
/**
|
|
1665
|
-
* The distro used when no path supplies evidence: the pinned name, WSL's
|
|
1666
|
-
* default, or the default for the automatic modes.
|
|
1667
|
-
*
|
|
1668
|
-
* @returns the distro name.
|
|
1669
|
-
*/
|
|
1670
|
-
async distro() {
|
|
1671
|
-
const config = this.config;
|
|
1672
|
-
if (this.resolvedDistro.length === 0)
|
|
1673
|
-
this.resolvedDistro = await defaultDistro({ wslPath: config.wslPath });
|
|
1674
|
-
return this.resolvedDistro;
|
|
1675
|
-
}
|
|
1676
|
-
/**
|
|
1677
|
-
* The distro one path belongs to: an explicit pin wins; otherwise the path
|
|
1678
|
-
* itself, then the cwd or configured cwd, may name a distro; both absent
|
|
1679
|
-
* falls back to WSL's default.
|
|
1680
|
-
*
|
|
1681
|
-
* @param path - the caller path, in any coordinate system.
|
|
1682
|
-
* @param cwd - the caller's optional cwd override.
|
|
1683
|
-
* @returns the distro name.
|
|
1684
|
-
*/
|
|
1685
|
-
async distroForPath(path, cwd) {
|
|
1686
|
-
const config = this.config;
|
|
1687
|
-
return resolveOperationDistro(config.distro, [path, cwd ?? config.cwd], () => this.distro());
|
|
1688
|
-
}
|
|
1689
|
-
/**
|
|
1690
|
-
* The distro a resolved target belongs to. A UNC identity names it outright;
|
|
1691
|
-
* a host-coordinate target falls back to the configured/default distro.
|
|
1692
|
-
*
|
|
1693
|
-
* @param target - the resolved target.
|
|
1694
|
-
* @returns the distro name.
|
|
1695
|
-
*/
|
|
1696
|
-
async distroForTarget(target) {
|
|
1697
|
-
return uncToPosix(target.targetKey)?.distro ?? this.distroForPath(target.displayPath);
|
|
1698
|
-
}
|
|
1699
|
-
/**
|
|
1700
|
-
* The distro a mutation's policy belongs to: the workspace root is the
|
|
1701
|
-
* strongest evidence, then the configured cwd, then the default.
|
|
1702
|
-
*
|
|
1703
|
-
* @param policy - the resolved policy, when the caller has one.
|
|
1704
|
-
* @returns the distro name.
|
|
1705
|
-
*/
|
|
1706
|
-
async distroForPolicy(policy) {
|
|
1707
|
-
const config = this.config;
|
|
1708
|
-
return resolveOperationDistro(config.distro, [policy?.workspaceRoot, config.cwd], () => this.distro());
|
|
1709
|
-
}
|
|
1710
|
-
/**
|
|
1711
|
-
* Translate one caller path into the world path, enforcing the distro fence.
|
|
1712
|
-
*
|
|
1713
|
-
* @param path - a Linux, UNC or Windows path.
|
|
1714
|
-
* @param cwd - the caller's override of the configured default workdir.
|
|
1715
|
-
* @returns the host path to operate on.
|
|
1716
|
-
*/
|
|
1717
|
-
async worldPath(path, cwd) {
|
|
1718
|
-
const config = this.config;
|
|
1719
|
-
const distro = await this.distroForPath(path, cwd);
|
|
1720
|
-
let base = cwd ?? config.cwd;
|
|
1721
|
-
if (String(base ?? "").trim().length === 0 && isRelativeWorldPath(path)) {
|
|
1722
|
-
// An empty `cwd` means the distro user's home. Only relative input
|
|
1723
|
-
// consults the base at all, which is also the only case that has to pay
|
|
1724
|
-
// for the `wsl.exe` query — an absolute path never does.
|
|
1725
|
-
base = await distroHome(this, distro);
|
|
1726
|
-
}
|
|
1727
|
-
const world = toWorldPath(path, { distro, cwd: base });
|
|
1728
|
-
const refusal = outsideDistroRefusal({ path, world, distro, restrictToDistro: config.restrictToDistro });
|
|
1729
|
-
if (refusal !== null) {
|
|
1730
|
-
// Deliberately NOT `FS_SANDBOX_DENIED`. The file-tool layer turns that code
|
|
1731
|
-
// into a denial marker plus an escalation offer, and no wider permission can
|
|
1732
|
-
// lift this fence: it is a configuration choice, not a sandbox decision.
|
|
1733
|
-
throw new FsError(refusal.message, refusal.code);
|
|
1734
|
-
}
|
|
1735
|
-
return world;
|
|
1736
|
-
}
|
|
1737
|
-
/**
|
|
1738
|
-
* Resolve a path to a target whose `targetKey` is the UNC identity the host
|
|
1739
|
-
* I/O stack uses and whose `displayPath` is the Linux path the model sees.
|
|
1740
|
-
*
|
|
1741
|
-
* @param path - a Linux, UNC or Windows path.
|
|
1742
|
-
* @param opts - optional `cwd` override and `signal`.
|
|
1743
|
-
* @returns the resolved `FsTarget`.
|
|
1744
|
-
*/
|
|
1745
|
-
async resolve(path, opts) {
|
|
1746
|
-
const world = await this.worldPath(path, opts?.cwd);
|
|
1747
|
-
const linux = uncToPosix(world)?.linuxPath ?? windowsToLinuxMount(world);
|
|
1748
|
-
if (linux === undefined)
|
|
1749
|
-
throw new FsError(`cannot serve "${path}" from inside the distro`, "FS_IO_ERROR");
|
|
1750
|
-
const distro = uncToPosix(world)?.distro ?? await this.distroForPath(path, opts?.cwd);
|
|
1751
|
-
try {
|
|
1752
|
-
// The substrate's resolved shape carries plain-string keys; the seam's
|
|
1753
|
-
// branded tokens ride one type-level cast (runtime shape unchanged).
|
|
1754
|
-
return (await (await this.agentSubstrateFor(distro)).resolve(linux, opts?.signal));
|
|
1755
|
-
}
|
|
1756
|
-
catch (error) {
|
|
1757
|
-
throw this.peerError(error);
|
|
1758
|
-
}
|
|
1759
|
-
}
|
|
1760
|
-
/**
|
|
1761
|
-
* Enforce the per-call file-effect policy against one target and return the
|
|
1762
|
-
* EXACT target the mutation must use, so the checked identity is the mutated
|
|
1763
|
-
* one (no check-here-write-there window).
|
|
1764
|
-
*
|
|
1765
|
-
* `read-only` denies outright. `workspace-write` re-resolves the target NOW
|
|
1766
|
-
* (reflecting a symlink ancestor swapped since the tool resolved it), requires
|
|
1767
|
-
* containment under a writable root — the workspace plus the temp area of the
|
|
1768
|
-
* world the workspace lives in — and hands back that fresh target.
|
|
1769
|
-
* `danger-full-access` is the approved escalation and is not fenced. Refusal
|
|
1770
|
-
* is the structured `FS_SANDBOX_DENIED` the tool layer maps to its
|
|
1771
|
-
* model-facing `[sandbox: …]` marker and escalation hint.
|
|
1772
|
-
*
|
|
1773
|
-
* @param target - the resolved target to mutate.
|
|
1774
|
-
* @param sandboxPolicy - the per-call mode and workspace root; omit for the
|
|
1775
|
-
* deployment policy.
|
|
1776
|
-
* @returns the target the mutation must use.
|
|
1777
|
-
* @throws {FsError} with `FS_SANDBOX_DENIED` when the policy refuses it.
|
|
1778
|
-
*/
|
|
1779
|
-
async checkedTarget(target, sandboxPolicy) {
|
|
1780
|
-
const config = this.config;
|
|
1781
|
-
if (!config.sandbox)
|
|
1782
|
-
return target;
|
|
1783
|
-
const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
|
|
1784
|
-
const modeRefusal = mutationModeRefusal(policy.mode, target.displayPath);
|
|
1785
|
-
if (modeRefusal !== null) {
|
|
1786
|
-
throw new FsError(modeRefusal.message, modeRefusal.code);
|
|
1787
|
-
}
|
|
1788
|
-
if (policy.mode !== "workspace-write")
|
|
1789
|
-
return target;
|
|
1790
|
-
const distro = await this.distroForTarget(target);
|
|
1791
|
-
const fresh = await this.resolve(target.targetKey);
|
|
1792
|
-
for (const root of wslWritableRoots(policy, distro)) {
|
|
1793
|
-
if (isWorldPathUnder(fresh.targetKey, root, { distro }))
|
|
1794
|
-
return fresh;
|
|
1795
|
-
}
|
|
1796
|
-
const denial = workspaceWriteDenial(target.displayPath);
|
|
1797
|
-
throw new FsError(denial.message, denial.code);
|
|
1798
|
-
}
|
|
1799
|
-
/**
|
|
1800
|
-
* One target's metadata, answered from the distro.
|
|
1801
|
-
*
|
|
1802
|
-
* @param target - the resolved target.
|
|
1803
|
-
* @param signal - optional cancellation.
|
|
1804
|
-
* @returns the metadata, or undefined when absent.
|
|
1805
|
-
*/
|
|
1806
|
-
async stat(target, signal) {
|
|
1807
|
-
try {
|
|
1808
|
-
return (await (await this.substrateForTarget(target)).stat(target, signal));
|
|
1809
|
-
}
|
|
1810
|
-
catch (error) {
|
|
1811
|
-
throw this.peerError(error);
|
|
1812
|
-
}
|
|
1813
|
-
}
|
|
1814
|
-
/**
|
|
1815
|
-
* No-follow stat one path. The agent substrate answers from the distro,
|
|
1816
|
-
* where a symlink is a first-class entry.
|
|
1817
|
-
*
|
|
1818
|
-
* @param path - a Linux, UNC or Windows path.
|
|
1819
|
-
* @param opts - optional `cwd` override.
|
|
1820
|
-
* @param signal - optional cancellation.
|
|
1821
|
-
* @returns the path info, or undefined when absent.
|
|
1822
|
-
*/
|
|
1823
|
-
async lstat(path, opts, signal) {
|
|
1824
|
-
const world = await this.worldPath(path, opts?.cwd);
|
|
1825
|
-
const linux = uncToPosix(world)?.linuxPath ?? windowsToLinuxMount(world);
|
|
1826
|
-
if (linux === undefined)
|
|
1827
|
-
throw new FsError(`cannot inspect "${path}" from inside the distro`, "FS_IO_ERROR");
|
|
1828
|
-
const distro = uncToPosix(world)?.distro ?? await this.distroForPath(path, opts?.cwd);
|
|
1829
|
-
try {
|
|
1830
|
-
return (await (await this.agentSubstrateFor(distro)).lstat(linux, signal));
|
|
1831
|
-
}
|
|
1832
|
-
catch (error) {
|
|
1833
|
-
throw this.peerError(error);
|
|
1834
|
-
}
|
|
1835
|
-
}
|
|
1836
|
-
/**
|
|
1837
|
-
* Read one whole regular UTF-8 file from the distro.
|
|
1838
|
-
*
|
|
1839
|
-
* @param target - the resolved target.
|
|
1840
|
-
* @param signal - optional cancellation.
|
|
1841
|
-
* @returns the file text.
|
|
1842
|
-
*/
|
|
1843
|
-
async readText(target, signal) {
|
|
1844
|
-
try {
|
|
1845
|
-
return await (await this.substrateForTarget(target)).readText(target, signal);
|
|
1846
|
-
}
|
|
1847
|
-
catch (error) {
|
|
1848
|
-
throw this.peerError(error);
|
|
1849
|
-
}
|
|
1850
|
-
}
|
|
1851
|
-
/**
|
|
1852
|
-
* Stream one whole regular UTF-8 file from the distro.
|
|
1853
|
-
*
|
|
1854
|
-
* @param target - the resolved target.
|
|
1855
|
-
* @param signal - optional cancellation.
|
|
1856
|
-
* @returns the text chunks.
|
|
1857
|
-
*/
|
|
1858
|
-
async streamText(target, signal) {
|
|
1859
|
-
try {
|
|
1860
|
-
return await (await this.substrateForTarget(target)).streamText(target, signal);
|
|
1861
|
-
}
|
|
1862
|
-
catch (error) {
|
|
1863
|
-
throw this.peerError(error);
|
|
1864
|
-
}
|
|
1865
|
-
}
|
|
1866
|
-
/**
|
|
1867
|
-
* Read one whole regular file as raw bytes, bounded.
|
|
1868
|
-
*
|
|
1869
|
-
* @param target - the resolved target.
|
|
1870
|
-
* @param signal - optional cancellation.
|
|
1871
|
-
* @param maxBytes - inclusive byte cap on the content.
|
|
1872
|
-
* @returns the bytes.
|
|
1873
|
-
*/
|
|
1874
|
-
async readBytes(target, signal, maxBytes) {
|
|
1875
|
-
try {
|
|
1876
|
-
return await (await this.substrateForTarget(target)).readBytes(target, signal, maxBytes);
|
|
1877
|
-
}
|
|
1878
|
-
catch (error) {
|
|
1879
|
-
throw this.peerError(error);
|
|
1880
|
-
}
|
|
1881
|
-
}
|
|
1882
|
-
/**
|
|
1883
|
-
* Read one byte window of a regular file.
|
|
1884
|
-
*
|
|
1885
|
-
* @param target - the resolved target.
|
|
1886
|
-
* @param range - the window.
|
|
1887
|
-
* @param signal - optional cancellation.
|
|
1888
|
-
* @returns the window's bytes.
|
|
1889
|
-
*/
|
|
1890
|
-
async readByteRange(target, range, signal) {
|
|
1891
|
-
try {
|
|
1892
|
-
return await (await this.substrateForTarget(target)).readByteRange(target, range, signal);
|
|
1893
|
-
}
|
|
1894
|
-
catch (error) {
|
|
1895
|
-
throw this.peerError(error);
|
|
1896
|
-
}
|
|
1897
|
-
}
|
|
1898
|
-
/**
|
|
1899
|
-
* List one directory level. The substrate's rows already carry Linux display
|
|
1900
|
-
* paths and canonical identities — nothing to rewrite.
|
|
1901
|
-
*
|
|
1902
|
-
* @param target - the resolved directory.
|
|
1903
|
-
* @param signal - optional cancellation.
|
|
1904
|
-
* @returns the directory rows.
|
|
1905
|
-
*/
|
|
1906
|
-
async listDir(target, signal) {
|
|
1907
|
-
try {
|
|
1908
|
-
return (await (await this.substrateForTarget(target)).listDir(target, signal));
|
|
1909
|
-
}
|
|
1910
|
-
catch (error) {
|
|
1911
|
-
throw this.peerError(error);
|
|
1912
|
-
}
|
|
1913
|
-
}
|
|
1914
|
-
/**
|
|
1915
|
-
* Map an absolute host path into this execution world, SYNCHRONOUSLY — the
|
|
1916
|
-
* upstream contract (`FileSystem.processPathFromHostPath`) and what its
|
|
1917
|
-
* consumers rely on: `packages/spill/spill-policy` passes this method as a
|
|
1918
|
-
* plain callback over image attachments, and `packages/api/session-controller`
|
|
1919
|
-
* plus the UI's open/reveal path compare the return value against `undefined`
|
|
1920
|
-
* without awaiting. The mapping is therefore built from facts that are already
|
|
1921
|
-
* known — a UNC host path names its own distro outright; a non-UNC path uses
|
|
1922
|
-
* the pinned/config default once `distro()` has resolved it, and the
|
|
1923
|
-
* configured `cwd`, or the resolved home for a relative path. A call that
|
|
1924
|
-
* would have to ask `wsl.exe` — a cold default distro with no UNC, or a
|
|
1925
|
-
* relative path before the home is known — answers `undefined`, which every
|
|
1926
|
-
* consumer reads as "no mapping", the same answer the ssh provider gives for
|
|
1927
|
-
* a path it cannot map.
|
|
1928
|
-
*
|
|
1929
|
-
* The VALUE is the world spelling the backend keys on (the UNC identity for a
|
|
1930
|
-
* distro path), so the consumers' round trip — map, `resolve`, `processPath`,
|
|
1931
|
-
* compare with the original host path — closes exactly as it does for the
|
|
1932
|
-
* host backend. Real operations are unaffected: they take the async
|
|
1933
|
-
* {@link WslFileSystem.worldPath} and its loud refusals.
|
|
1934
|
-
*
|
|
1935
|
-
* @param hostPath - an absolute host path (a relative one maps only when the
|
|
1936
|
-
* configured `cwd` or a known home gives it a base).
|
|
1937
|
-
* @returns the world path for the same file, or undefined when it cannot be
|
|
1938
|
-
* mapped with what is already known.
|
|
1939
|
-
*/
|
|
1940
|
-
processPathFromHostPath(hostPath) {
|
|
1941
|
-
const config = this.config;
|
|
1942
|
-
const choice = selectDistro({
|
|
1943
|
-
configured: config.distro,
|
|
1944
|
-
candidates: [hostPath, config.cwd],
|
|
1945
|
-
fallback: this.resolvedDistro,
|
|
1946
|
-
});
|
|
1947
|
-
if (choice.distro.length === 0)
|
|
1948
|
-
return undefined;
|
|
1949
|
-
let base = config.cwd;
|
|
1950
|
-
if (String(base ?? "").trim().length === 0 && isRelativeWorldPath(hostPath)) {
|
|
1951
|
-
base = this.resolvedHomes.get(choice.distro) ?? (choice.distro === this.resolvedDistro ? this.resolvedHome : undefined);
|
|
1952
|
-
if (base === undefined)
|
|
1953
|
-
return undefined;
|
|
1954
|
-
}
|
|
1955
|
-
const world = toWorldPath(hostPath, { distro: choice.distro, cwd: base });
|
|
1956
|
-
const refusal = outsideDistroRefusal({ path: hostPath, world, distro: choice.distro, restrictToDistro: config.restrictToDistro });
|
|
1957
|
-
return refusal === null ? world : undefined;
|
|
1958
|
-
}
|
|
1959
|
-
/**
|
|
1960
|
-
* Watch from inside the distro, where the kernel can actually report change:
|
|
1961
|
-
* a long-lived `wsl.exe` poll loop (`lib/watcher.js`) fires the seam's
|
|
1962
|
-
* invalidation callback. The seam asks for coarse invalidation, not events,
|
|
1963
|
-
* so a poll is honest — and creations and deletions are both seen, because
|
|
1964
|
-
* they bump the parent directory's mtime. Replaces the previous flat
|
|
1965
|
-
* refusal (`FS_IO_ERROR`), which was the correct answer over 9p only.
|
|
1966
|
-
*
|
|
1967
|
-
* A target that disappears mid-watch ends the loop with a report through
|
|
1968
|
-
* `changed` — never the armed-but-never-fires silence a missing directory
|
|
1969
|
-
* would otherwise produce. The scan's depth is `watchMaxDepth`.
|
|
1970
|
-
*
|
|
1971
|
-
* @param target - the resolved file or directory to observe.
|
|
1972
|
-
* @param changed - the invalidation callback.
|
|
1973
|
-
* @param signal - cancels initialization; the caller closes an armed watcher.
|
|
1974
|
-
* @returns resolves once active, with the async close function.
|
|
1975
|
-
*/
|
|
1976
|
-
async watch(target, changed, signal) {
|
|
1977
|
-
signal.throwIfAborted();
|
|
1978
|
-
const config = this.config;
|
|
1979
|
-
const parsed = uncToPosix(target.targetKey);
|
|
1980
|
-
if (parsed === undefined) {
|
|
1981
|
-
throw new FsError(`cannot watch "${target.displayPath}": not a path inside the distro`, "FS_IO_ERROR");
|
|
1982
|
-
}
|
|
1983
|
-
const pinned = pinnedDistro(config.distro);
|
|
1984
|
-
const configuredName = pinned ?? (isDefaultDistro(config.distro) ? await this.distro() : undefined);
|
|
1985
|
-
if (configuredName !== undefined) {
|
|
1986
|
-
const refusal = outsideDistroRefusal({
|
|
1987
|
-
path: target.displayPath,
|
|
1988
|
-
world: target.targetKey,
|
|
1989
|
-
distro: configuredName,
|
|
1990
|
-
restrictToDistro: config.restrictToDistro,
|
|
1991
|
-
});
|
|
1992
|
-
if (refusal !== null)
|
|
1993
|
-
throw new FsError(refusal.message, refusal.code);
|
|
1994
|
-
}
|
|
1995
|
-
const distro = parsed.distro;
|
|
1996
|
-
return armDistroWatcher({
|
|
1997
|
-
wslPath: config.wslPath,
|
|
1998
|
-
distro,
|
|
1999
|
-
linuxPath: parsed.linuxPath,
|
|
2000
|
-
onChange: changed,
|
|
2001
|
-
onError: (error) => changed(error),
|
|
2002
|
-
signal,
|
|
2003
|
-
maxDepth: config.watchMaxDepth,
|
|
2004
|
-
});
|
|
2005
|
-
}
|
|
2006
|
-
/**
|
|
2007
|
-
* Fence the write by the per-call policy, then publish through the
|
|
2008
|
-
* substrate. The fence's fresh target is the one checked and written, so a
|
|
2009
|
-
* refusal costs no I/O and cannot be raced by a swapped symlink; the guard
|
|
2010
|
-
* rides the write op, where the agent re-verifies it before the rename;
|
|
2011
|
-
* the confined resident enforces the mount boundary in the kernel.
|
|
2012
|
-
*
|
|
2013
|
-
* @param target - the resolved target.
|
|
2014
|
-
* @param content - the full new file content.
|
|
2015
|
-
* @param expected - the write intent.
|
|
2016
|
-
* @param signal - optional cancellation.
|
|
2017
|
-
* @param sandboxPolicy - the per-call mode and workspace root; omit for the
|
|
2018
|
-
* deployment policy.
|
|
2019
|
-
* @returns the write outcome.
|
|
2020
|
-
*/
|
|
2021
|
-
async writeText(target, content, expected, signal, sandboxPolicy) {
|
|
2022
|
-
const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
|
|
2023
|
-
const fenced = await this.checkedTarget(target, policy);
|
|
2024
|
-
try {
|
|
2025
|
-
return (await (await this.substrateForTarget(fenced)).writeText(fenced, content, expected, signal, policy));
|
|
2026
|
-
}
|
|
2027
|
-
catch (error) {
|
|
2028
|
-
throw this.peerError(error);
|
|
2029
|
-
}
|
|
2030
|
-
}
|
|
2031
|
-
/**
|
|
2032
|
-
* Fence the edit by the same policy, keeping the guard's observable
|
|
2033
|
-
* behaviour.
|
|
2034
|
-
*
|
|
2035
|
-
* @param target - the resolved target.
|
|
2036
|
-
* @param edit - the literal search/replace request.
|
|
2037
|
-
* @param expected - the version guard.
|
|
2038
|
-
* @param signal - optional cancellation.
|
|
2039
|
-
* @param sandboxPolicy - the per-call mode and workspace root; omit for the
|
|
2040
|
-
* deployment policy.
|
|
2041
|
-
* @returns the edit outcome.
|
|
2042
|
-
*/
|
|
2043
|
-
async editText(target, edit, expected, signal, sandboxPolicy) {
|
|
2044
|
-
const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
|
|
2045
|
-
const fenced = await this.checkedTarget(target, policy);
|
|
2046
|
-
try {
|
|
2047
|
-
return (await (await this.substrateForTarget(fenced)).editText(fenced, edit, expected, signal, policy));
|
|
2048
|
-
}
|
|
2049
|
-
catch (error) {
|
|
2050
|
-
throw this.peerError(error);
|
|
2051
|
-
}
|
|
2052
|
-
}
|
|
2053
|
-
/**
|
|
2054
|
-
* Apply parsed hunks (protocol 7): hunk matching and application run
|
|
2055
|
-
* in-process through the peer's own `applyHunks` (the same dialect and
|
|
2056
|
-
* `FS_PATCH_MISMATCH` the peer emits), against the distro's bytes, then
|
|
2057
|
-
* publish through the same guarded atomic write an edit takes.
|
|
2058
|
-
*
|
|
2059
|
-
* @param target - the resolved regular file.
|
|
2060
|
-
* @param hunks - ordered hunks from the caller's patch parse.
|
|
2061
|
-
* @param expected - the version the patch was based on.
|
|
2062
|
-
* @param signal - cancels the patch.
|
|
2063
|
-
* @param sandboxPolicy - the per-call policy; omit for the deployment default.
|
|
2064
|
-
* @returns the pre/post text and the published version.
|
|
2065
|
-
*/
|
|
2066
|
-
async patchText(target, hunks, expected, signal, sandboxPolicy) {
|
|
2067
|
-
const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
|
|
2068
|
-
const fenced = await this.checkedTarget(target, policy);
|
|
2069
|
-
try {
|
|
2070
|
-
return (await (await this.substrateForTarget(fenced)).patchText(fenced, hunks, expected, signal, policy));
|
|
2071
|
-
}
|
|
2072
|
-
catch (error) {
|
|
2073
|
-
throw this.peerError(error);
|
|
2074
|
-
}
|
|
2075
|
-
}
|
|
2076
|
-
/**
|
|
2077
|
-
* Remove one regular file (protocol 7) after fencing the target by the
|
|
2078
|
-
* per-call policy; the guarded removal re-verifies the expected version
|
|
2079
|
-
* distro-side.
|
|
2080
|
-
*
|
|
2081
|
-
* @param target - the resolved file.
|
|
2082
|
-
* @param expected - the version the removal was based on.
|
|
2083
|
-
* @param signal - cancels the removal.
|
|
2084
|
-
* @param sandboxPolicy - the per-call policy; omit for the deployment default.
|
|
2085
|
-
* @returns the bounded pre-removal text basis.
|
|
2086
|
-
*/
|
|
2087
|
-
async deleteFile(target, expected, signal, sandboxPolicy) {
|
|
2088
|
-
const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
|
|
2089
|
-
const fenced = await this.checkedTarget(target, policy);
|
|
2090
|
-
try {
|
|
2091
|
-
return (await (await this.substrateForTarget(fenced)).deleteFile(fenced, expected, signal, policy));
|
|
2092
|
-
}
|
|
2093
|
-
catch (error) {
|
|
2094
|
-
throw this.peerError(error);
|
|
2095
|
-
}
|
|
2096
|
-
}
|
|
2097
|
-
/**
|
|
2098
|
-
* Move one regular file (protocol 7) after fencing BOTH endpoints by the
|
|
2099
|
-
* per-call policy — the destination publishes and the source is removed, so
|
|
2100
|
-
* each must be writable under the same roots.
|
|
2101
|
-
*
|
|
2102
|
-
* @param source - the resolved source.
|
|
2103
|
-
* @param destination - the resolved destination.
|
|
2104
|
-
* @param options - the hunks and the source/destination guards.
|
|
2105
|
-
* @param signal - cancels before publication.
|
|
2106
|
-
* @param sandboxPolicy - the per-call policy; omit for the deployment default.
|
|
2107
|
-
* @returns the bounded source basis and the destination outcome.
|
|
2108
|
-
*/
|
|
2109
|
-
async moveFile(source, destination, options, signal, sandboxPolicy) {
|
|
2110
|
-
const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
|
|
2111
|
-
const fencedSource = await this.checkedTarget(source, policy);
|
|
2112
|
-
const fencedDestination = await this.checkedTarget(destination, policy);
|
|
2113
|
-
try {
|
|
2114
|
-
return (await (await this.substrateForTarget(fencedSource)).moveFile(fencedSource, fencedDestination, options, signal, policy));
|
|
2115
|
-
}
|
|
2116
|
-
catch (error) {
|
|
2117
|
-
throw this.peerError(error);
|
|
2118
|
-
}
|
|
2119
|
-
}
|
|
2120
|
-
}
|
|
1
|
+
/** Public exports for the WSL service providers and compatibility helpers. */
|
|
2
|
+
export { WslShellExecutor } from "./wsl-shell.js";
|
|
3
|
+
export { WslFileSystem } from "./wsl-filesystem.js";
|
|
4
|
+
export { doctorReport } from "./doctor-report.js";
|
|
5
|
+
export { effectiveMaskWindowsDrive } from "./provider-common.js";
|