dsh-plugin-wsl-env 0.23.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +9 -5
  3. package/SECURITY.md +10 -0
  4. package/client.js +974 -165
  5. package/cordis.patch.yml +28 -3
  6. package/docs/API.md +2 -1
  7. package/docs/ARCHITECTURE.md +36 -13
  8. package/docs/COMPATIBILITY.md +5 -0
  9. package/docs/CONFIGURATION.md +80 -9
  10. package/docs/CONFIGURATION.zh.md +64 -8
  11. package/docs/DIAGNOSTICS.md +48 -20
  12. package/docs/DIAGNOSTICS.zh.md +36 -14
  13. package/docs/LIMITATIONS.md +36 -9
  14. package/docs/LIMITATIONS.zh.md +26 -7
  15. package/docs/MIGRATION.md +1 -1
  16. package/docs/PEER-PARITY.md +4 -4
  17. package/docs/QUICKSTART.md +42 -12
  18. package/docs/QUICKSTART.zh.md +29 -8
  19. package/docs/README.zh.md +9 -5
  20. package/docs/RELEASING.md +17 -13
  21. package/docs/REQUIREMENTS.zh.md +5 -4
  22. package/docs/UPSTREAM-FSIO-EXPORT.md +5 -4
  23. package/docs/UPSTREAM-PROMPT-ADAPTERS.md +85 -0
  24. package/docs/root-fs-routing.md +1 -1
  25. package/lib/agent-confined.d.ts +7 -1
  26. package/lib/agent-confined.js +3 -3
  27. package/lib/auto-preset.d.ts +27 -0
  28. package/lib/auto-preset.js +40 -3
  29. package/lib/bwrap.d.ts +14 -0
  30. package/lib/bwrap.js +11 -0
  31. package/lib/client-host.d.ts +2 -2
  32. package/lib/client-host.js +2 -2
  33. package/lib/cwd-prompt.d.ts +41 -3
  34. package/lib/cwd-prompt.js +125 -8
  35. package/lib/doctor-report.d.ts +50 -0
  36. package/lib/doctor-report.js +172 -0
  37. package/lib/fs-routing.d.ts +1 -1
  38. package/lib/fs-routing.js +1 -1
  39. package/lib/fs.d.ts +1 -1
  40. package/lib/fs.js +1 -1
  41. package/lib/index.d.ts +6 -1464
  42. package/lib/index.js +5 -2120
  43. package/lib/listing.d.ts +21 -9
  44. package/lib/listing.js +25 -21
  45. package/lib/messages.d.ts +1 -1
  46. package/lib/messages.js +3 -3
  47. package/lib/picker.d.ts +50 -16
  48. package/lib/picker.js +103 -23
  49. package/lib/preflight.d.ts +7 -4
  50. package/lib/preflight.js +27 -13
  51. package/lib/preset-choice.d.ts +22 -3
  52. package/lib/preset-choice.js +36 -3
  53. package/lib/provider-common.d.ts +58 -0
  54. package/lib/provider-common.js +123 -0
  55. package/lib/sandbox-core.d.ts +1 -0
  56. package/lib/sandbox-core.js +4 -2
  57. package/lib/session-runtime.d.ts +7 -1
  58. package/lib/session-runtime.js +9 -2
  59. package/lib/shell.d.ts +1 -1
  60. package/lib/shell.js +1 -1
  61. package/lib/status.d.ts +261 -0
  62. package/lib/status.js +425 -0
  63. package/lib/writable-roots.d.ts +109 -0
  64. package/lib/writable-roots.js +257 -0
  65. package/lib/wsl-doctor-tool.d.ts +8 -0
  66. package/lib/wsl-doctor-tool.js +18 -20
  67. package/lib/wsl-filesystem.d.ts +692 -0
  68. package/lib/wsl-filesystem.js +897 -0
  69. package/lib/wsl-shell.d.ts +742 -0
  70. package/lib/wsl-shell.js +965 -0
  71. package/lib/wsl.d.ts +13 -1
  72. package/lib/wsl.js +16 -1
  73. package/locale/doctor/en.json +3 -2
  74. package/locale/doctor/zh.json +3 -2
  75. package/package.json +12 -4
  76. package/scripts/doctor.mjs +436 -226
  77. package/scripts/profile-preset.mjs +17 -5
@@ -0,0 +1,897 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { randomUUID } from "node:crypto";
3
+ import { LocalFileSystem } from "@deepseek-ai/dsh-fs-local";
4
+ import { FsError } from "@deepseek-ai/dsh-fs";
5
+ import { SandboxUnavailableError } from "@deepseek-ai/dsh-sandbox";
6
+ import { isRelativeWorldPath, isWorldPathUnder, toWorldPath, uncToPosix, windowsToLinuxMount } from "./paths.js";
7
+ import { isConfinedMutation, mutationModeRefusal, outsideDistroRefusal, shareSubstrateRefusal, substrateFailure, workspaceWriteDenial } from "./fs-decisions.js";
8
+ import { isDefaultDistro, pinnedDistro, selectDistro } from "./distro-route.js";
9
+ import { WslSandbox } from "./sandbox.js";
10
+ import { bwrapFailure, missingBwrapRemedy } from "./sandbox-core.js";
11
+ import { armDistroWatcher } from "./watcher.js";
12
+ import { sharedAgent } from "./agent-shared.js";
13
+ import { AgentSubstrate } from "./fs-substrate.js";
14
+ import { FsCodedError } from "./fsio-text.js";
15
+ import { confinedAgent } from "./agent-confined.js";
16
+ import { SessionRuntimes, probeSessionRuntime, sessionRuntimes, setSessionNativeAgent } from "./session-runtime.js";
17
+ import { ensureNativeSessionAgent } from "./native-agent.js";
18
+ import { installMessagesLocale } from "./messages.js";
19
+ import { defaultDistro, runCapture } from "./wsl.js";
20
+ import { validateWritableRootsConfig } from "./writable-roots.js";
21
+ import { distroHome, effectiveWritableRoots, resolveOperationDistro, sessionRuntimeWanted, wslWritableRoots } from "./provider-common.js";
22
+ /**
23
+ * Filesystem backend over a WSL distro's UNC share.
24
+ *
25
+ * Reads, listings, stats and searches reuse the host backend verbatim: the
26
+ * share is a real filesystem to Node, and the packaged ripgrep walks it too.
27
+ * Two things are deliberately replaced.
28
+ *
29
+ * **Resolution** accepts Linux paths (`/home/andy/proj/src/a.ts`) and shows them
30
+ * back as Linux paths, while `targetKey` stays the UNC path the host I/O uses —
31
+ * the seam treats `targetKey` as opaque and reserves `displayPath` for model and
32
+ * UI output, so this rewrite is contract-legal.
33
+ *
34
+ * **Mutation guards are hoisted.** The host backend publishes a guarded
35
+ * *creation* by hard-linking a staged file into place, and the WSL UNC share
36
+ * rejects hard links with `ENOTSUP`; it also refuses `symlink` with `EPERM`.
37
+ * Guarded creation through the share would therefore fail with `FS_IO_ERROR` on
38
+ * the most common write there is — creating a new file. This backend checks the
39
+ * caller's guard itself and then delegates the unguarded publication, which the
40
+ * share does support. The residual window is the same check-then-act race
41
+ * `dsh-fs-sandbox` already documents and accepts.
42
+ *
43
+ * **Publication is replaced.** Unguarded is not enough on its own: the host
44
+ * backend's Windows branch also copies the replaced file's security descriptor
45
+ * and publishes with `ReplaceFileW`, and neither exists on a 9p share — the
46
+ * descriptor read fails every write to an existing file outright. See the
47
+ * constructor for what runs instead.
48
+ */
49
+ export class WslFileSystem extends LocalFileSystem {
50
+ static inject = ["sandboxPolicy"];
51
+ static Config = z.object({
52
+ /**
53
+ * Distro mode: empty/`"auto"` follows the target path, `"default"` forces
54
+ * WSL's default, and an explicit name pins the filesystem.
55
+ */
56
+ distro: z.string().default(""),
57
+ /**
58
+ * Default workdir for relative input; accepts a Linux path, a UNC path, or
59
+ * `C:\...`. Empty — the default — means the distro user's home, resolved
60
+ * inside the distro.
61
+ */
62
+ cwd: z.string().default(""),
63
+ /** Path to `wsl.exe`, used only to resolve the default distro. */
64
+ wslPath: z.string().default("wsl.exe"),
65
+ /** UTF-8 byte limit per overwrite-diff side, mirroring the host backend. */
66
+ diffBasisMaxBytes: z.number().default(10 * 1024 * 1024),
67
+ /**
68
+ * Fence mutations by `ctx.sandboxPolicy`, and report the mode through
69
+ * {@link sandboxMode}. `false` restores the pre-sandbox behaviour exactly —
70
+ * an unfenced backend that reports `undefined` — for an operator who wants
71
+ * the old posture and accepts what it means: the model is told these
72
+ * operations are unconfined.
73
+ */
74
+ sandbox: z.boolean().default(true),
75
+ /**
76
+ * Run confined mutations in the session's systemd user scope — the same
77
+ * runtime the shell executor acquires for the same session, distro,
78
+ * workspace and policy — instead of a per-policy confined resident. A
79
+ * missing session ID keeps the providers separate. The kernel enforcement
80
+ * is the runtime's mount profile; the scope stops when its providers
81
+ * release it. Requires systemd + `Linger`, like `wsl-shell`'s
82
+ * `sessionSandbox`; the preflight refuses with the remedy. Off for direct
83
+ * constructions; on in the shipped preset.
84
+ */
85
+ sessionSandbox: z.union([z.boolean(), z.const("auto")]).default(false),
86
+ /**
87
+ * Shadow `/mnt` with an empty tmpfs in every confined profile, hiding the
88
+ * Windows drive from confined commands — same meaning and same honest
89
+ * limits as the `wsl-shell` key of the same name (its doc carries the
90
+ * full story). Confined fs mutations publish through the masked resident;
91
+ * reads and the share substrate are unaffected.
92
+ */
93
+ maskWindowsDrive: z.boolean().default(false),
94
+ /**
95
+ * Extra directories under `workspace-write`, in distro spelling — the
96
+ * same list and same rules as `wsl-shell`'s key. Confined writes bind
97
+ * them, and the fs fence accepts them; keep the two rows' lists equal so
98
+ * a command and its write see one mount table.
99
+ */
100
+ writableRoots: z.array(z.string()).default([]),
101
+ /**
102
+ * Refuse any path that leaves the pinned distro. A WSL filesystem is a
103
+ * whole-Linux view whose `/mnt/c` also reaches the Windows disk, so without
104
+ * this the backend would silently widen the session far beyond the
105
+ * workspace the operator selected.
106
+ */
107
+ restrictToDistro: z.boolean().default(true),
108
+ /**
109
+ * How deep the in-distro watch scan walks, `1` = the watched directory and
110
+ * its direct children. `0` — the default — walks the whole tree, which is
111
+ * what the invalidation contract asks for but a real cost every poll over
112
+ * a tree containing a `node_modules`; a bound trades that cost for a
113
+ * documented blind spot: a change below the bound is not seen until
114
+ * another change above it fires the same callback.
115
+ */
116
+ watchMaxDepth: z.natural().default(0),
117
+ /**
118
+ * Which I/O substrate serves the file tools. Only `"agent"` exists — the
119
+ * resident in-distro agent (`lib/fs-substrate.js`): reads, writes and
120
+ * identities run where the files live, symlinks and mode bits are native,
121
+ * and the mutation guard survives to the write's no-replace publication,
122
+ * kernel-enforced by the confined resident when the policy is confined.
123
+ * The former `"share"` opt-out — the Windows-side host filesystem stack
124
+ * over the distro's 9p share — is retired: it was the one model-facing
125
+ * I/O path that still crossed the share, and the agent has no fallback
126
+ * that needs it. A profile carrying `"share"` is refused at construction
127
+ * with the migration (`shareSubstrateRefusal`). `watch()` rides the
128
+ * in-distro poll loop for the substrate regardless (`lib/watcher.js`) —
129
+ * it never ran through either substrate. The substrate never changes
130
+ * `sandboxMode`'s honesty.
131
+ */
132
+ substrate: z.union(["share", "agent"]).default("agent"),
133
+ });
134
+ /**
135
+ * @param ctx - the composition context.
136
+ * @param config - the validated plugin config.
137
+ */
138
+ constructor(ctx, config) {
139
+ // The share substrate is refused before any peer work: a profile still
140
+ // carrying the retired value must fail loudly, with the migration, not
141
+ // silently serve the one I/O path this provider exists to close.
142
+ const refusal = shareSubstrateRefusal(config.substrate);
143
+ if (refusal !== null)
144
+ throw new Error(refusal.message);
145
+ super(ctx, config);
146
+ validateWritableRootsConfig(config.writableRoots);
147
+ installMessagesLocale(ctx);
148
+ this.resolvedDistro = pinnedDistro(config.distro) ?? "";
149
+ this.resolvedHome = undefined;
150
+ this.resolvedHomes = new Map();
151
+ this.defaultMode = ctx.sandboxPolicy.defaultMode;
152
+ this.agentSubstrateInstance = undefined;
153
+ this.agentSubstrates = new Map();
154
+ this.sandbox = new WslSandbox({ wslPath: config.wslPath, maskWindowsDrive: config.maskWindowsDrive });
155
+ this.agentInstance = undefined;
156
+ this.agentInstances = new Map();
157
+ this.sessionRuntimes = sessionRuntimes;
158
+ this.sessionRuntimeEntries = new Map();
159
+ this.sessionRuntimeOwner = randomUUID();
160
+ this.sessionScopeProbe = (argv) => runCapture(argv);
161
+ this.writableRootsProbe = (argv) => runCapture(argv);
162
+ this.sessionRuntimePreflight = new Set();
163
+ this.autoSessionScope = new Map();
164
+ // The preset's disposer releases the runtime; the shell executor's effect
165
+ // releases its own reference, so the scope stops after the last one.
166
+ ctx.effect(() => () => this.disposeSessionRuntimes().catch(() => { }), "wsl fs session runtimes");
167
+ }
168
+ /**
169
+ * The mode this backend fences mutations with, or `undefined` when the
170
+ * operator turned the fence off. This is the capability fact `dsh-tool-fs`
171
+ * reads to advertise the escalation fields honestly, so it must disappear
172
+ * together with the enforcement — never claim a boundary that is not applied.
173
+ *
174
+ * @returns the deployment default mode, or `undefined` when unfenced.
175
+ */
176
+ get sandboxMode() {
177
+ const config = this.config;
178
+ return config.sandbox ? this.defaultMode : undefined;
179
+ }
180
+ /**
181
+ * The resident agent serving the default/pinned distro's in-distro side
182
+ * work, created on first use and kept for the provider's lifetime.
183
+ *
184
+ * @returns the agent for the default/pinned distro.
185
+ */
186
+ async publicationAgent() {
187
+ if (this.agentInstance === undefined) {
188
+ this.agentInstance = sharedAgent(await this.distro());
189
+ }
190
+ return this.agentInstance;
191
+ }
192
+ /**
193
+ * The resident agent for one distro. The default/pinned distro keeps the
194
+ * legacy {@link publicationAgent} cache; every other distro gets its own
195
+ * entry, because the shared agent is a per-distro process singleton.
196
+ *
197
+ * @param distro - the distro name.
198
+ * @returns the agent for that distro.
199
+ */
200
+ async publicationAgentFor(distro) {
201
+ if (this.resolvedDistro.length > 0 && distro === this.resolvedDistro)
202
+ return this.publicationAgent();
203
+ const cached = this.agentInstances.get(distro);
204
+ if (cached !== undefined)
205
+ return cached;
206
+ const agent = sharedAgent(distro);
207
+ this.agentInstances.set(distro, agent);
208
+ return agent;
209
+ }
210
+ /**
211
+ * The agent-backed substrate for the default/pinned distro, built on first
212
+ * use over the shared resident agent.
213
+ *
214
+ * @returns the substrate.
215
+ */
216
+ async agentSubstrate() {
217
+ const config = this.config;
218
+ if (this.agentSubstrateInstance === undefined) {
219
+ this.agentSubstrateInstance = new AgentSubstrate({
220
+ agent: await this.publicationAgent(),
221
+ distro: await this.distro(),
222
+ diffBasisMaxBytes: config.diffBasisMaxBytes,
223
+ agentFor: (policy) => this.mutationAgent(policy),
224
+ });
225
+ }
226
+ return this.agentSubstrateInstance;
227
+ }
228
+ /**
229
+ * The agent-backed substrate for one distro. The default/pinned distro keeps
230
+ * the legacy {@link agentSubstrate} accessor (and its test override); every
231
+ * other distro gets a substrate that mints its own UNC identities and
232
+ * addresses its own resident.
233
+ *
234
+ * @param distro - the distro name.
235
+ * @returns the substrate for that distro.
236
+ */
237
+ async agentSubstrateFor(distro) {
238
+ if (this.resolvedDistro.length > 0 && distro === this.resolvedDistro)
239
+ return this.agentSubstrate();
240
+ const cached = this.agentSubstrates.get(distro);
241
+ if (cached !== undefined)
242
+ return cached;
243
+ const config = this.config;
244
+ const substrate = new AgentSubstrate({
245
+ agent: await this.publicationAgentFor(distro),
246
+ distro,
247
+ diffBasisMaxBytes: config.diffBasisMaxBytes,
248
+ agentFor: (policy) => this.mutationAgent(policy, distro),
249
+ });
250
+ this.agentSubstrates.set(distro, substrate);
251
+ return substrate;
252
+ }
253
+ /**
254
+ * The substrate for one resolved target, following the target's UNC identity.
255
+ *
256
+ * @param target - the resolved target.
257
+ * @returns the substrate for the target's distro.
258
+ */
259
+ async substrateForTarget(target) {
260
+ return this.agentSubstrateFor(await this.distroForTarget(target));
261
+ }
262
+ /**
263
+ * The effective extra writable roots for one mutation: the row's
264
+ * `writableRoots` plus the shared policy's `additionalWritableRoots`,
265
+ * resolved to Linux paths and checked once per process. Empty unless the
266
+ * mutation is confined under `workspace-write`.
267
+ *
268
+ * @param distro - the distro the mutation belongs to.
269
+ * @param policy - the per-call file-effect policy, when there is one.
270
+ * @returns the roots every confinement site binds.
271
+ * @throws {SandboxInvalidRootError} when an entry cannot be granted or checked.
272
+ */
273
+ async writableRootsFor(distro, policy, check = true) {
274
+ const config = this.config;
275
+ if (!config.sandbox || policy === undefined || policy.mode !== "workspace-write")
276
+ return [];
277
+ if ((config.writableRoots?.length ?? 0) === 0 && (policy.additionalWritableRoots?.length ?? 0) === 0)
278
+ return [];
279
+ // Only a `~` entry needs the distro home. Policy entries are absolute
280
+ // execution-world paths, and absolute row entries need no probe — which
281
+ // keeps a policy-only grant (the composition tests' case) from spawning
282
+ // `wsl.exe` on a machine that has none.
283
+ const needsHome = (config.writableRoots ?? []).some((root) => root === "~" || root.startsWith("~/"));
284
+ const home = needsHome ? await distroHome(this, distro) : "";
285
+ return effectiveWritableRoots({
286
+ configured: config.writableRoots,
287
+ policy: policy,
288
+ distro,
289
+ home,
290
+ wslPath: config.wslPath,
291
+ run: this.writableRootsProbe,
292
+ check,
293
+ });
294
+ }
295
+ /**
296
+ * The persistent session runtime for one confined mutation, when
297
+ * `sessionSandbox` is on. The key is the shell executor's key for the same
298
+ * session/policy, so the write and the commands share one agent, one mount
299
+ * view and one scope; the provider holds a reference until the session ends.
300
+ *
301
+ * @param policy - the resolved confined policy.
302
+ * @param distro - the resolved distro name.
303
+ * @param writableRoots - the effective extra roots the runtime binds.
304
+ * @returns the runtime entry, or undefined when the mode is off.
305
+ */
306
+ sessionRuntimeFor(policy, distro, writableRoots = []) {
307
+ const config = this.config;
308
+ if (!config.sessionSandbox)
309
+ return undefined;
310
+ const workspaceRoot = policy.workspaceRoot || config.cwd;
311
+ const sessionId = policy.sessionId || this.sessionRuntimeOwner;
312
+ const key = SessionRuntimes.key({ sessionId, distro, workspaceRoot, mode: policy.mode, maskWindowsDrive: config.maskWindowsDrive, writableRoots });
313
+ const held = this.sessionRuntimeEntries.get(key);
314
+ if (held !== undefined)
315
+ return held;
316
+ const entry = this.sessionRuntimes.acquire({
317
+ sessionId,
318
+ distro,
319
+ wslPath: config.wslPath,
320
+ workspaceRoot,
321
+ mode: policy.mode,
322
+ maskWindowsDrive: config.maskWindowsDrive,
323
+ writableRoots,
324
+ });
325
+ this.sessionRuntimeEntries.set(key, entry);
326
+ return entry;
327
+ }
328
+ /**
329
+ * Run the session runtime's preflight once per provider. Only success is
330
+ * cached, so following the remedy does not need an app restart.
331
+ *
332
+ * @param distro - the resolved distro name.
333
+ * @returns resolved once the platform can host the runtime.
334
+ * @throws {Error} with the remedy when it cannot.
335
+ */
336
+ async ensureSessionRuntimeUsable(distro) {
337
+ if (this.sessionRuntimePreflight.has(distro))
338
+ return;
339
+ const config = this.config;
340
+ const problem = await probeSessionRuntime({ wslPath: config.wslPath, distro, run: this.sessionScopeProbe });
341
+ if (problem !== null)
342
+ throw new Error(problem);
343
+ await ensureNativeSessionAgent({ wslPath: config.wslPath, distro, setNative: setSessionNativeAgent });
344
+ this.sessionRuntimePreflight.add(distro);
345
+ }
346
+ /**
347
+ * Whether this provider should use the session runtime for one distro, with
348
+ * the `auto` downgrade and its bounded re-probe. `true` keeps the refusing
349
+ * behavior; `false` stays off.
350
+ *
351
+ * @param distro - the resolved distro.
352
+ * @returns whether to acquire the per-session scope.
353
+ */
354
+ async wantsSessionRuntime(distro) {
355
+ const config = this.config;
356
+ return sessionRuntimeWanted(config.sessionSandbox, distro, () => this.ensureSessionRuntimeUsable(distro), this.autoSessionScope);
357
+ }
358
+ /**
359
+ * Release every runtime this provider holds. Called from the preset's
360
+ * dispose effect; public so tests and shutdown paths can await it.
361
+ *
362
+ * @returns resolved once every reference is released.
363
+ */
364
+ async disposeSessionRuntimes() {
365
+ const entries = [...this.sessionRuntimeEntries.values()];
366
+ this.sessionRuntimeEntries.clear();
367
+ for (const entry of entries)
368
+ await this.sessionRuntimes.release(entry.key);
369
+ }
370
+ /**
371
+ * The agent a MUTATION runs on under this resolved policy — stage-two
372
+ * routing. A confined policy addresses the confined resident whose bwrap
373
+ * profile binds exactly what the mode grants, so the kernel enforces what
374
+ * the check decided; an escalated write (`danger-full-access`) or a disabled
375
+ * sandbox addresses the plain resident, which is what those mean. A distro
376
+ * without a usable bwrap refuses confined mutations instead of downgrading
377
+ * them — the same closed failure the command path has.
378
+ *
379
+ * @param policy - the resolved file-effect policy, or undefined when the
380
+ * caller pre-checked.
381
+ * @param forDistro - the distro the mutation belongs to; derived from the
382
+ * policy when the caller does not know it.
383
+ * @returns the agent to publish through.
384
+ */
385
+ async mutationAgent(policy, forDistro) {
386
+ const config = this.config;
387
+ const distro = forDistro ?? await this.distroForPolicy(policy);
388
+ if (!isConfinedMutation({ policy, sandboxEnabled: config.sandbox })) {
389
+ return this.publicationAgentFor(distro);
390
+ }
391
+ const writableRoots = await this.writableRootsFor(distro, policy);
392
+ // The untyped guard decided this is a confined policy but cannot narrow
393
+ // the parameter, so the confined shape is asserted once here (type-level
394
+ // only; `confinedPolicy` is the same value as `policy`).
395
+ const confinedPolicy = policy;
396
+ if (!(await this.sandbox.usable(distro))) {
397
+ // The probe's classified remedy — missing vs present-but-broken, with the
398
+ // distro's own package family — is what every other refusal surfaces;
399
+ // this path has the same failure, so it carries the same text.
400
+ throw new SandboxUnavailableError(confinedPolicy.mode, bwrapFailure(config.wslPath, distro) ?? missingBwrapRemedy(distro));
401
+ }
402
+ if (await this.wantsSessionRuntime(distro)) {
403
+ const runtime = this.sessionRuntimeFor(confinedPolicy, distro, writableRoots);
404
+ if (runtime !== undefined)
405
+ return runtime.agent;
406
+ }
407
+ return confinedAgent({ distro, wslPath: config.wslPath, policy: confinedPolicy, maskWindowsDrive: config.maskWindowsDrive, writableRoots });
408
+ }
409
+ /**
410
+ * Map a substrate error onto the peer's `FsError`, so the tool layer reads
411
+ * the same refusal dialect on both substrates. An agent that is out becomes
412
+ * an I/O error naming the cause — the share backend's "distro is gone" case
413
+ * is the same availability, but the message says which substrate failed.
414
+ *
415
+ * @param error - what the substrate raised.
416
+ * @returns the error to surface.
417
+ */
418
+ peerError(error) {
419
+ if (error instanceof FsCodedError) {
420
+ return new FsError(error.message, error.code, { cause: error });
421
+ }
422
+ if (error instanceof SandboxUnavailableError)
423
+ return new FsError(error.message, "FS_IO_ERROR", { cause: error });
424
+ const { message, code, cause } = substrateFailure(error);
425
+ return new FsError(message, code, cause === undefined ? {} : { cause });
426
+ }
427
+ /**
428
+ * One resolved target's Linux path — the substrate's coordinate — falling
429
+ * back to the display spelling when the identity is not a distro share path.
430
+ *
431
+ * @param target - the resolved target.
432
+ * @returns the absolute Linux path.
433
+ */
434
+ linuxOf(target) {
435
+ return uncToPosix(target.targetKey)?.linuxPath ?? target.displayPath;
436
+ }
437
+ /**
438
+ * The distro used when no path supplies evidence: the pinned name, WSL's
439
+ * default, or the default for the automatic modes.
440
+ *
441
+ * @returns the distro name.
442
+ */
443
+ async distro() {
444
+ const config = this.config;
445
+ if (this.resolvedDistro.length === 0)
446
+ this.resolvedDistro = await defaultDistro({ wslPath: config.wslPath });
447
+ return this.resolvedDistro;
448
+ }
449
+ /**
450
+ * The distro one path belongs to: an explicit pin wins; otherwise the path
451
+ * itself, then the cwd or configured cwd, may name a distro; both absent
452
+ * falls back to WSL's default.
453
+ *
454
+ * @param path - the caller path, in any coordinate system.
455
+ * @param cwd - the caller's optional cwd override.
456
+ * @returns the distro name.
457
+ */
458
+ async distroForPath(path, cwd) {
459
+ const config = this.config;
460
+ return resolveOperationDistro(config.distro, [path, cwd ?? config.cwd], () => this.distro());
461
+ }
462
+ /**
463
+ * The distro a resolved target belongs to. A UNC identity names it outright;
464
+ * a host-coordinate target falls back to the configured/default distro.
465
+ *
466
+ * @param target - the resolved target.
467
+ * @returns the distro name.
468
+ */
469
+ async distroForTarget(target) {
470
+ return uncToPosix(target.targetKey)?.distro ?? this.distroForPath(target.displayPath);
471
+ }
472
+ /**
473
+ * The distro a mutation's policy belongs to: the workspace root is the
474
+ * strongest evidence, then the configured cwd, then the default.
475
+ *
476
+ * @param policy - the resolved policy, when the caller has one.
477
+ * @returns the distro name.
478
+ */
479
+ async distroForPolicy(policy) {
480
+ const config = this.config;
481
+ return resolveOperationDistro(config.distro, [policy?.workspaceRoot, config.cwd], () => this.distro());
482
+ }
483
+ /**
484
+ * Translate one caller path into the world path, enforcing the distro fence.
485
+ *
486
+ * @param path - a Linux, UNC or Windows path.
487
+ * @param cwd - the caller's override of the configured default workdir.
488
+ * @returns the host path to operate on.
489
+ */
490
+ async worldPath(path, cwd) {
491
+ const config = this.config;
492
+ const distro = await this.distroForPath(path, cwd);
493
+ let base = cwd ?? config.cwd;
494
+ if (String(base ?? "").trim().length === 0 && isRelativeWorldPath(path)) {
495
+ // An empty `cwd` means the distro user's home. Only relative input
496
+ // consults the base at all, which is also the only case that has to pay
497
+ // for the `wsl.exe` query — an absolute path never does.
498
+ base = await distroHome(this, distro);
499
+ }
500
+ const world = toWorldPath(path, { distro, cwd: base });
501
+ const refusal = outsideDistroRefusal({ path, world, distro, restrictToDistro: config.restrictToDistro });
502
+ if (refusal !== null) {
503
+ // Deliberately NOT `FS_SANDBOX_DENIED`. The file-tool layer turns that code
504
+ // into a denial marker plus an escalation offer, and no wider permission can
505
+ // lift this fence: it is a configuration choice, not a sandbox decision.
506
+ throw new FsError(refusal.message, refusal.code);
507
+ }
508
+ return world;
509
+ }
510
+ /**
511
+ * Resolve a path to a target whose `targetKey` is the UNC identity the host
512
+ * I/O stack uses and whose `displayPath` is the Linux path the model sees.
513
+ *
514
+ * @param path - a Linux, UNC or Windows path.
515
+ * @param opts - optional `cwd` override and `signal`.
516
+ * @returns the resolved `FsTarget`.
517
+ */
518
+ async resolve(path, opts) {
519
+ const world = await this.worldPath(path, opts?.cwd);
520
+ const linux = uncToPosix(world)?.linuxPath ?? windowsToLinuxMount(world);
521
+ if (linux === undefined)
522
+ throw new FsError(`cannot serve "${path}" from inside the distro`, "FS_IO_ERROR");
523
+ const distro = uncToPosix(world)?.distro ?? await this.distroForPath(path, opts?.cwd);
524
+ try {
525
+ // The substrate's resolved shape carries plain-string keys; the seam's
526
+ // branded tokens ride one type-level cast (runtime shape unchanged).
527
+ return (await (await this.agentSubstrateFor(distro)).resolve(linux, opts?.signal));
528
+ }
529
+ catch (error) {
530
+ throw this.peerError(error);
531
+ }
532
+ }
533
+ /**
534
+ * Enforce the per-call file-effect policy against one target and return the
535
+ * EXACT target the mutation must use, so the checked identity is the mutated
536
+ * one (no check-here-write-there window).
537
+ *
538
+ * `read-only` denies outright. `workspace-write` re-resolves the target NOW
539
+ * (reflecting a symlink ancestor swapped since the tool resolved it), requires
540
+ * containment under a writable root — the workspace plus the temp area of the
541
+ * world the workspace lives in — and hands back that fresh target.
542
+ * `danger-full-access` is the approved escalation and is not fenced. Refusal
543
+ * is the structured `FS_SANDBOX_DENIED` the tool layer maps to its
544
+ * model-facing `[sandbox: …]` marker and escalation hint.
545
+ *
546
+ * @param target - the resolved target to mutate.
547
+ * @param sandboxPolicy - the per-call mode and workspace root; omit for the
548
+ * deployment policy.
549
+ * @returns the target the mutation must use.
550
+ * @throws {FsError} with `FS_SANDBOX_DENIED` when the policy refuses it.
551
+ */
552
+ async checkedTarget(target, sandboxPolicy) {
553
+ const config = this.config;
554
+ if (!config.sandbox)
555
+ return target;
556
+ const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
557
+ const modeRefusal = mutationModeRefusal(policy.mode, target.displayPath);
558
+ if (modeRefusal !== null) {
559
+ throw new FsError(modeRefusal.message, modeRefusal.code);
560
+ }
561
+ if (policy.mode !== "workspace-write")
562
+ return target;
563
+ const distro = await this.distroForTarget(target);
564
+ // The fence decision needs the roots' spelling, not the one-time physical
565
+ // check: that check belongs to the agent that will actually bind them, and
566
+ // running it here would spawn `wsl.exe` for a decision that may never write.
567
+ const extraRoots = await this.writableRootsFor(distro, policy, false);
568
+ const fresh = await this.resolve(target.targetKey);
569
+ for (const root of wslWritableRoots(policy, distro, extraRoots)) {
570
+ if (isWorldPathUnder(fresh.targetKey, root, { distro }))
571
+ return fresh;
572
+ }
573
+ const denial = workspaceWriteDenial(target.displayPath);
574
+ throw new FsError(denial.message, denial.code);
575
+ }
576
+ /**
577
+ * One target's metadata, answered from the distro.
578
+ *
579
+ * @param target - the resolved target.
580
+ * @param signal - optional cancellation.
581
+ * @returns the metadata, or undefined when absent.
582
+ */
583
+ async stat(target, signal) {
584
+ try {
585
+ return (await (await this.substrateForTarget(target)).stat(target, signal));
586
+ }
587
+ catch (error) {
588
+ throw this.peerError(error);
589
+ }
590
+ }
591
+ /**
592
+ * No-follow stat one path. The agent substrate answers from the distro,
593
+ * where a symlink is a first-class entry.
594
+ *
595
+ * @param path - a Linux, UNC or Windows path.
596
+ * @param opts - optional `cwd` override.
597
+ * @param signal - optional cancellation.
598
+ * @returns the path info, or undefined when absent.
599
+ */
600
+ async lstat(path, opts, signal) {
601
+ const world = await this.worldPath(path, opts?.cwd);
602
+ const linux = uncToPosix(world)?.linuxPath ?? windowsToLinuxMount(world);
603
+ if (linux === undefined)
604
+ throw new FsError(`cannot inspect "${path}" from inside the distro`, "FS_IO_ERROR");
605
+ const distro = uncToPosix(world)?.distro ?? await this.distroForPath(path, opts?.cwd);
606
+ try {
607
+ return (await (await this.agentSubstrateFor(distro)).lstat(linux, signal));
608
+ }
609
+ catch (error) {
610
+ throw this.peerError(error);
611
+ }
612
+ }
613
+ /**
614
+ * Read one whole regular UTF-8 file from the distro.
615
+ *
616
+ * @param target - the resolved target.
617
+ * @param signal - optional cancellation.
618
+ * @returns the file text.
619
+ */
620
+ async readText(target, signal) {
621
+ try {
622
+ return await (await this.substrateForTarget(target)).readText(target, signal);
623
+ }
624
+ catch (error) {
625
+ throw this.peerError(error);
626
+ }
627
+ }
628
+ /**
629
+ * Stream one whole regular UTF-8 file from the distro.
630
+ *
631
+ * @param target - the resolved target.
632
+ * @param signal - optional cancellation.
633
+ * @returns the text chunks.
634
+ */
635
+ async streamText(target, signal) {
636
+ try {
637
+ return await (await this.substrateForTarget(target)).streamText(target, signal);
638
+ }
639
+ catch (error) {
640
+ throw this.peerError(error);
641
+ }
642
+ }
643
+ /**
644
+ * Read one whole regular file as raw bytes, bounded.
645
+ *
646
+ * @param target - the resolved target.
647
+ * @param signal - optional cancellation.
648
+ * @param maxBytes - inclusive byte cap on the content.
649
+ * @returns the bytes.
650
+ */
651
+ async readBytes(target, signal, maxBytes) {
652
+ try {
653
+ return await (await this.substrateForTarget(target)).readBytes(target, signal, maxBytes);
654
+ }
655
+ catch (error) {
656
+ throw this.peerError(error);
657
+ }
658
+ }
659
+ /**
660
+ * Read one byte window of a regular file.
661
+ *
662
+ * @param target - the resolved target.
663
+ * @param range - the window.
664
+ * @param signal - optional cancellation.
665
+ * @returns the window's bytes.
666
+ */
667
+ async readByteRange(target, range, signal) {
668
+ try {
669
+ return await (await this.substrateForTarget(target)).readByteRange(target, range, signal);
670
+ }
671
+ catch (error) {
672
+ throw this.peerError(error);
673
+ }
674
+ }
675
+ /**
676
+ * List one directory level. The substrate's rows already carry Linux display
677
+ * paths and canonical identities — nothing to rewrite.
678
+ *
679
+ * @param target - the resolved directory.
680
+ * @param signal - optional cancellation.
681
+ * @returns the directory rows.
682
+ */
683
+ async listDir(target, signal) {
684
+ try {
685
+ return (await (await this.substrateForTarget(target)).listDir(target, signal));
686
+ }
687
+ catch (error) {
688
+ throw this.peerError(error);
689
+ }
690
+ }
691
+ /**
692
+ * Map an absolute host path into this execution world, SYNCHRONOUSLY — the
693
+ * upstream contract (`FileSystem.processPathFromHostPath`) and what its
694
+ * consumers rely on: `packages/spill/spill-policy` passes this method as a
695
+ * plain callback over image attachments, and `packages/api/session-controller`
696
+ * plus the UI's open/reveal path compare the return value against `undefined`
697
+ * without awaiting. The mapping is therefore built from facts that are already
698
+ * known — a UNC host path names its own distro outright; a non-UNC path uses
699
+ * the pinned/config default once `distro()` has resolved it, and the
700
+ * configured `cwd`, or the resolved home for a relative path. A call that
701
+ * would have to ask `wsl.exe` — a cold default distro with no UNC, or a
702
+ * relative path before the home is known — answers `undefined`, which every
703
+ * consumer reads as "no mapping", the same answer the ssh provider gives for
704
+ * a path it cannot map.
705
+ *
706
+ * The VALUE is the world spelling the backend keys on (the UNC identity for a
707
+ * distro path), so the consumers' round trip — map, `resolve`, `processPath`,
708
+ * compare with the original host path — closes exactly as it does for the
709
+ * host backend. Real operations are unaffected: they take the async
710
+ * {@link WslFileSystem.worldPath} and its loud refusals.
711
+ *
712
+ * @param hostPath - an absolute host path (a relative one maps only when the
713
+ * configured `cwd` or a known home gives it a base).
714
+ * @returns the world path for the same file, or undefined when it cannot be
715
+ * mapped with what is already known.
716
+ */
717
+ processPathFromHostPath(hostPath) {
718
+ const config = this.config;
719
+ const choice = selectDistro({
720
+ configured: config.distro,
721
+ candidates: [hostPath, config.cwd],
722
+ fallback: this.resolvedDistro,
723
+ });
724
+ if (choice.distro.length === 0)
725
+ return undefined;
726
+ let base = config.cwd;
727
+ if (String(base ?? "").trim().length === 0 && isRelativeWorldPath(hostPath)) {
728
+ base = this.resolvedHomes.get(choice.distro) ?? (choice.distro === this.resolvedDistro ? this.resolvedHome : undefined);
729
+ if (base === undefined)
730
+ return undefined;
731
+ }
732
+ const world = toWorldPath(hostPath, { distro: choice.distro, cwd: base });
733
+ const refusal = outsideDistroRefusal({ path: hostPath, world, distro: choice.distro, restrictToDistro: config.restrictToDistro });
734
+ return refusal === null ? world : undefined;
735
+ }
736
+ /**
737
+ * Watch from inside the distro, where the kernel can actually report change:
738
+ * a long-lived `wsl.exe` poll loop (`lib/watcher.js`) fires the seam's
739
+ * invalidation callback. The seam asks for coarse invalidation, not events,
740
+ * so a poll is honest — and creations and deletions are both seen, because
741
+ * they bump the parent directory's mtime. Replaces the previous flat
742
+ * refusal (`FS_IO_ERROR`), which was the correct answer over 9p only.
743
+ *
744
+ * A target that disappears mid-watch ends the loop with a report through
745
+ * `changed` — never the armed-but-never-fires silence a missing directory
746
+ * would otherwise produce. The scan's depth is `watchMaxDepth`.
747
+ *
748
+ * @param target - the resolved file or directory to observe.
749
+ * @param changed - the invalidation callback.
750
+ * @param signal - cancels initialization; the caller closes an armed watcher.
751
+ * @returns resolves once active, with the async close function.
752
+ */
753
+ async watch(target, changed, signal) {
754
+ signal.throwIfAborted();
755
+ const config = this.config;
756
+ const parsed = uncToPosix(target.targetKey);
757
+ if (parsed === undefined) {
758
+ throw new FsError(`cannot watch "${target.displayPath}": not a path inside the distro`, "FS_IO_ERROR");
759
+ }
760
+ const pinned = pinnedDistro(config.distro);
761
+ const configuredName = pinned ?? (isDefaultDistro(config.distro) ? await this.distro() : undefined);
762
+ if (configuredName !== undefined) {
763
+ const refusal = outsideDistroRefusal({
764
+ path: target.displayPath,
765
+ world: target.targetKey,
766
+ distro: configuredName,
767
+ restrictToDistro: config.restrictToDistro,
768
+ });
769
+ if (refusal !== null)
770
+ throw new FsError(refusal.message, refusal.code);
771
+ }
772
+ const distro = parsed.distro;
773
+ return armDistroWatcher({
774
+ wslPath: config.wslPath,
775
+ distro,
776
+ linuxPath: parsed.linuxPath,
777
+ onChange: changed,
778
+ onError: (error) => changed(error),
779
+ signal,
780
+ maxDepth: config.watchMaxDepth,
781
+ });
782
+ }
783
+ /**
784
+ * Fence the write by the per-call policy, then publish through the
785
+ * substrate. The fence's fresh target is the one checked and written, so a
786
+ * refusal costs no I/O and cannot be raced by a swapped symlink; the guard
787
+ * rides the write op, where the agent re-verifies it before the rename;
788
+ * the confined resident enforces the mount boundary in the kernel.
789
+ *
790
+ * @param target - the resolved target.
791
+ * @param content - the full new file content.
792
+ * @param expected - the write intent.
793
+ * @param signal - optional cancellation.
794
+ * @param sandboxPolicy - the per-call mode and workspace root; omit for the
795
+ * deployment policy.
796
+ * @returns the write outcome.
797
+ */
798
+ async writeText(target, content, expected, signal, sandboxPolicy) {
799
+ const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
800
+ const fenced = await this.checkedTarget(target, policy);
801
+ try {
802
+ return (await (await this.substrateForTarget(fenced)).writeText(fenced, content, expected, signal, policy));
803
+ }
804
+ catch (error) {
805
+ throw this.peerError(error);
806
+ }
807
+ }
808
+ /**
809
+ * Fence the edit by the same policy, keeping the guard's observable
810
+ * behaviour.
811
+ *
812
+ * @param target - the resolved target.
813
+ * @param edit - the literal search/replace request.
814
+ * @param expected - the version guard.
815
+ * @param signal - optional cancellation.
816
+ * @param sandboxPolicy - the per-call mode and workspace root; omit for the
817
+ * deployment policy.
818
+ * @returns the edit outcome.
819
+ */
820
+ async editText(target, edit, expected, signal, sandboxPolicy) {
821
+ const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
822
+ const fenced = await this.checkedTarget(target, policy);
823
+ try {
824
+ return (await (await this.substrateForTarget(fenced)).editText(fenced, edit, expected, signal, policy));
825
+ }
826
+ catch (error) {
827
+ throw this.peerError(error);
828
+ }
829
+ }
830
+ /**
831
+ * Apply parsed hunks (protocol 7): hunk matching and application run
832
+ * in-process through the peer's own `applyHunks` (the same dialect and
833
+ * `FS_PATCH_MISMATCH` the peer emits), against the distro's bytes, then
834
+ * publish through the same guarded atomic write an edit takes.
835
+ *
836
+ * @param target - the resolved regular file.
837
+ * @param hunks - ordered hunks from the caller's patch parse.
838
+ * @param expected - the version the patch was based on.
839
+ * @param signal - cancels the patch.
840
+ * @param sandboxPolicy - the per-call policy; omit for the deployment default.
841
+ * @returns the pre/post text and the published version.
842
+ */
843
+ async patchText(target, hunks, expected, signal, sandboxPolicy) {
844
+ const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
845
+ const fenced = await this.checkedTarget(target, policy);
846
+ try {
847
+ return (await (await this.substrateForTarget(fenced)).patchText(fenced, hunks, expected, signal, policy));
848
+ }
849
+ catch (error) {
850
+ throw this.peerError(error);
851
+ }
852
+ }
853
+ /**
854
+ * Remove one regular file (protocol 7) after fencing the target by the
855
+ * per-call policy; the guarded removal re-verifies the expected version
856
+ * distro-side.
857
+ *
858
+ * @param target - the resolved file.
859
+ * @param expected - the version the removal was based on.
860
+ * @param signal - cancels the removal.
861
+ * @param sandboxPolicy - the per-call policy; omit for the deployment default.
862
+ * @returns the bounded pre-removal text basis.
863
+ */
864
+ async deleteFile(target, expected, signal, sandboxPolicy) {
865
+ const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
866
+ const fenced = await this.checkedTarget(target, policy);
867
+ try {
868
+ return (await (await this.substrateForTarget(fenced)).deleteFile(fenced, expected, signal, policy));
869
+ }
870
+ catch (error) {
871
+ throw this.peerError(error);
872
+ }
873
+ }
874
+ /**
875
+ * Move one regular file (protocol 7) after fencing BOTH endpoints by the
876
+ * per-call policy — the destination publishes and the source is removed, so
877
+ * each must be writable under the same roots.
878
+ *
879
+ * @param source - the resolved source.
880
+ * @param destination - the resolved destination.
881
+ * @param options - the hunks and the source/destination guards.
882
+ * @param signal - cancels before publication.
883
+ * @param sandboxPolicy - the per-call policy; omit for the deployment default.
884
+ * @returns the bounded source basis and the destination outcome.
885
+ */
886
+ async moveFile(source, destination, options, signal, sandboxPolicy) {
887
+ const policy = sandboxPolicy ?? this.ctx.sandboxPolicy.resolve();
888
+ const fencedSource = await this.checkedTarget(source, policy);
889
+ const fencedDestination = await this.checkedTarget(destination, policy);
890
+ try {
891
+ return (await (await this.substrateForTarget(fencedSource)).moveFile(fencedSource, fencedDestination, options, signal, policy));
892
+ }
893
+ catch (error) {
894
+ throw this.peerError(error);
895
+ }
896
+ }
897
+ }