dsh-plugin-wsl-env 0.24.0 → 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 (59) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +6 -3
  3. package/SECURITY.md +10 -0
  4. package/cordis.patch.yml +4 -0
  5. package/docs/ARCHITECTURE.md +28 -9
  6. package/docs/CONFIGURATION.md +43 -0
  7. package/docs/CONFIGURATION.zh.md +36 -0
  8. package/docs/DIAGNOSTICS.md +4 -2
  9. package/docs/DIAGNOSTICS.zh.md +3 -1
  10. package/docs/LIMITATIONS.md +17 -4
  11. package/docs/LIMITATIONS.zh.md +11 -3
  12. package/docs/MIGRATION.md +1 -1
  13. package/docs/PEER-PARITY.md +4 -4
  14. package/docs/QUICKSTART.md +12 -5
  15. package/docs/QUICKSTART.zh.md +8 -2
  16. package/docs/README.zh.md +6 -3
  17. package/docs/RELEASING.md +17 -13
  18. package/docs/REQUIREMENTS.zh.md +3 -2
  19. package/docs/UPSTREAM-FSIO-EXPORT.md +5 -4
  20. package/docs/UPSTREAM-PROMPT-ADAPTERS.md +85 -0
  21. package/docs/root-fs-routing.md +1 -1
  22. package/lib/agent-confined.d.ts +7 -1
  23. package/lib/agent-confined.js +3 -3
  24. package/lib/bwrap.d.ts +14 -0
  25. package/lib/bwrap.js +11 -0
  26. package/lib/cwd-prompt.d.ts +41 -3
  27. package/lib/cwd-prompt.js +125 -8
  28. package/lib/doctor-report.d.ts +50 -0
  29. package/lib/doctor-report.js +172 -0
  30. package/lib/fs-routing.d.ts +1 -1
  31. package/lib/fs-routing.js +1 -1
  32. package/lib/fs.d.ts +1 -1
  33. package/lib/fs.js +1 -1
  34. package/lib/index.d.ts +6 -1464
  35. package/lib/index.js +5 -2120
  36. package/lib/messages.d.ts +1 -1
  37. package/lib/messages.js +3 -3
  38. package/lib/preflight.d.ts +7 -4
  39. package/lib/preflight.js +27 -13
  40. package/lib/provider-common.d.ts +58 -0
  41. package/lib/provider-common.js +123 -0
  42. package/lib/sandbox-core.d.ts +1 -0
  43. package/lib/sandbox-core.js +4 -2
  44. package/lib/session-runtime.d.ts +7 -1
  45. package/lib/session-runtime.js +9 -2
  46. package/lib/shell.d.ts +1 -1
  47. package/lib/shell.js +1 -1
  48. package/lib/writable-roots.d.ts +109 -0
  49. package/lib/writable-roots.js +257 -0
  50. package/lib/wsl-doctor-tool.js +2 -2
  51. package/lib/wsl-filesystem.d.ts +692 -0
  52. package/lib/wsl-filesystem.js +897 -0
  53. package/lib/wsl-shell.d.ts +742 -0
  54. package/lib/wsl-shell.js +965 -0
  55. package/lib/wsl.d.ts +1 -1
  56. package/lib/wsl.js +1 -1
  57. package/package.json +4 -3
  58. package/scripts/doctor.mjs +1 -1
  59. package/scripts/profile-preset.mjs +17 -5
package/lib/messages.d.ts CHANGED
@@ -146,7 +146,7 @@ declare const en: {
146
146
  doctorDigestFixPrefix: ({ remedy }: {
147
147
  remedy: string;
148
148
  }) => string;
149
- /** `wsl_doctor` digest: the ready note (how to attach the full report). */
149
+ /** `wsl_doctor` digest: the ready note; the report is not a promise about a call. */
150
150
  doctorDigestNoteReady: () => string;
151
151
  /** `wsl_doctor` digest: the blocked note (the rerun is the re-verification). */
152
152
  doctorDigestNoteBlocked: () => string;
package/lib/messages.js CHANGED
@@ -96,8 +96,8 @@ const en = {
96
96
  doctorTallySkipped: ({ n }) => `${n} skipped`,
97
97
  /** `wsl_doctor` digest: the remedy prefix under a failed check. */
98
98
  doctorDigestFixPrefix: ({ remedy }) => ` fix: ${remedy}`,
99
- /** `wsl_doctor` digest: the ready note (how to attach the full report). */
100
- doctorDigestNoteReady: () => "the first command should succeed; run the CLI (pnpm run doctor --bundle <path>) for the attachable file",
99
+ /** `wsl_doctor` digest: the ready note; the report is not a promise about a call. */
100
+ doctorDigestNoteReady: () => "ready covers the checks in this run; it does not promise every command will succeed",
101
101
  /** `wsl_doctor` digest: the blocked note (the rerun is the re-verification). */
102
102
  doctorDigestNoteBlocked: () => "apply each remedy above, then call this tool again — the re-run is the re-verification",
103
103
  /** `wsl_doctor` digest: the blocked summary tail; `noneBlocking` is the fixed clause. */
@@ -143,7 +143,7 @@ const zh = {
143
143
  doctorTallyInfo: ({ n }) => `信息 ${n}`,
144
144
  doctorTallySkipped: ({ n }) => `跳过 ${n}`,
145
145
  doctorDigestFixPrefix: ({ remedy }) => ` 修复: ${remedy}`,
146
- doctorDigestNoteReady: () => "首条命令应能成功;如需可附加的报告文件,运行 CLI(pnpm run doctor --bundle <path>)",
146
+ doctorDigestNoteReady: () => "ready 只覆盖本次检查,不保证每条命令都能成功",
147
147
  doctorDigestNoteBlocked: () => "应用上方每条修复,然后再次调用本工具——重跑即复核",
148
148
  doctorDigestBlockedTail: ({ blockers, warnings, skipped, note }) => `阻断项:${blockers};${warnings} 个警告,${skipped} 个跳过腿——均不阻断;${note}`,
149
149
  };
@@ -14,8 +14,9 @@
14
14
  * The same probes also run once at plugin load (`startup`, on by default) so an
15
15
  * install-plus-restart already carries the verdict in the log — the pinned or
16
16
  * WSL-default distro — before the first session opens. A session on that distro
17
- * repeats only the runtime-context entry; other distros keep the session-open
18
- * check unchanged.
17
+ * repeats only a failing verdict as the runtime-context entry; a ready verdict
18
+ * stays in the log, because "the prerequisite is usable" is not an action the
19
+ * model needs to take. Other distros keep the session-open check unchanged.
19
20
  *
20
21
  * Advisory by construction. A preflight that cannot run (no WSL, a wedged
21
22
  * `wsl.exe`) degrades to a log line; it must never fail a session that has not
@@ -55,7 +56,8 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
55
56
  * against the pinned or WSL-default distro, so the verdict is in the log
56
57
  * before any session opens. Sessions on other distros are still checked at
57
58
  * open, and a session announcement for a message the load pass already
58
- * logged skips the duplicate log line but keeps its runtime-context entry.
59
+ * logged skips the duplicate log line; a failing verdict still lands as the
60
+ * session's runtime-context entry.
59
61
  */
60
62
  startup: z<boolean, boolean, "defined">;
61
63
  }>>, Schemastery.ObjectT<NoInfer<{
@@ -81,7 +83,8 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
81
83
  * against the pinned or WSL-default distro, so the verdict is in the log
82
84
  * before any session opens. Sessions on other distros are still checked at
83
85
  * open, and a session announcement for a message the load pass already
84
- * logged skips the duplicate log line but keeps its runtime-context entry.
86
+ * logged skips the duplicate log line; a failing verdict still lands as the
87
+ * session's runtime-context entry.
85
88
  */
86
89
  startup: z<boolean, boolean, "defined">;
87
90
  }>>, "plain">;
package/lib/preflight.js CHANGED
@@ -14,8 +14,9 @@
14
14
  * The same probes also run once at plugin load (`startup`, on by default) so an
15
15
  * install-plus-restart already carries the verdict in the log — the pinned or
16
16
  * WSL-default distro — before the first session opens. A session on that distro
17
- * repeats only the runtime-context entry; other distros keep the session-open
18
- * check unchanged.
17
+ * repeats only a failing verdict as the runtime-context entry; a ready verdict
18
+ * stays in the log, because "the prerequisite is usable" is not an action the
19
+ * model needs to take. Other distros keep the session-open check unchanged.
19
20
  *
20
21
  * Advisory by construction. A preflight that cannot run (no WSL, a wedged
21
22
  * `wsl.exe`) degrades to a log line; it must never fail a session that has not
@@ -60,12 +61,22 @@ export const Config = z.object({
60
61
  * against the pinned or WSL-default distro, so the verdict is in the log
61
62
  * before any session opens. Sessions on other distros are still checked at
62
63
  * open, and a session announcement for a message the load pass already
63
- * logged skips the duplicate log line but keeps its runtime-context entry.
64
+ * logged skips the duplicate log line; a failing verdict still lands as the
65
+ * session's runtime-context entry.
64
66
  */
65
67
  startup: z.boolean().default(true),
66
68
  });
67
69
  /** Distros whose stale-scope sweep has already run in this process. */
68
70
  const sweptDistros = new Set();
71
+ /** The one instruction a blocked remedy needs; the model must not install packages unasked. */
72
+ const OPERATOR = "operator action: ask the user before running a remedy";
73
+ /**
74
+ * Mark a blocked verdict's remedy as user-owned action.
75
+ *
76
+ * @param message - the composed problem and remedy.
77
+ * @returns the model-facing sentence.
78
+ */
79
+ const blocked = (message) => `${message.replace(/[.\s]+$/u, "")} (${OPERATOR}).`;
69
80
  /**
70
81
  * Stop `dsh-wsl-*.scope` units a crashed app left behind. A scope is stale
71
82
  * when its cgroup has no `wsl-agent.sh`; a live agent means another session
@@ -99,18 +110,20 @@ export async function apply(ctx, config = {}) {
99
110
  const wslPath = config.wslPath ?? "wsl.exe";
100
111
  const warn = (message) => ctx.logger?.warn?.(message);
101
112
  /**
102
- * Publish one advisory: the log line always, plus — when the harness exposes
103
- * the agent's `systemPrompt` — a session-scoped runtime-context entry, so the
104
- * warning is visible to the session instead of only in the app log. DSH
105
- * 0.2.1 has no toast/notice seam; docs/UPSTREAM-SESSION-NOTICE.md records the
106
- * ask, and the runtime context is the available visible channel today.
113
+ * Publish one advisory: the log line always, plus — when the verdict is
114
+ * blocked and the harness exposes the agent's `systemPrompt` — a
115
+ * session-scoped runtime-context entry, so the failure is visible to the
116
+ * session instead of only in the app log. A ready verdict is log-only: it is
117
+ * not an action and does not belong in the model's context.
107
118
  *
108
119
  * @param agent - the session that just opened.
109
120
  * @param message - the advisory, remedy included.
110
- * @param level - `warn` for a blocked environment (the historical shape); `info` for the ready line, which is confirmation, not a complaint.
121
+ * @param level - `warn` for a blocked environment; `info` for the ready line, which is confirmation, not a complaint.
111
122
  */
112
123
  const announce = (agent, message, level = "warn") => {
113
124
  announceLog(message, level);
125
+ if (level !== "warn")
126
+ return;
114
127
  const agentCtx = agent.ctx;
115
128
  if (agentCtx === undefined || typeof agentCtx.inject !== "function")
116
129
  return;
@@ -123,7 +136,7 @@ export async function apply(ctx, config = {}) {
123
136
  ctx.logger?.debug?.(`wsl-preflight: could not publish the notice to the session (${error?.message ?? error})`);
124
137
  }
125
138
  };
126
- /** Messages the load pass already logged; a session announcement repeats only the entry. */
139
+ /** Messages the load pass already logged; a session announcement repeats only a blocked entry. */
127
140
  const startupLogged = new Set();
128
141
  /**
129
142
  * The log-only half of {@link announce}: a blocked environment warns, a ready
@@ -183,14 +196,14 @@ export async function apply(ctx, config = {}) {
183
196
  const flight = (async () => {
184
197
  const usable = await bwrapUsable({ wslPath, distro });
185
198
  if (!usable) {
186
- return { message: `wsl-preflight: ${bwrapFailure(wslPath, distro) ?? missingBwrapRemedy(distro)}`, level: "warn" };
199
+ return { message: blocked(`wsl-preflight: ${bwrapFailure(wslPath, distro) ?? missingBwrapRemedy(distro)}`), level: "warn" };
187
200
  }
188
201
  if (!(config.sessionSandbox ?? true)) {
189
202
  return { message: `wsl-preflight: ready — bwrap is usable inside "${distro}" (the session scope is not checked: sessionSandbox: false)`, level: "info" };
190
203
  }
191
204
  const sessionProblem = await probeSession(distro);
192
205
  if (sessionProblem !== undefined) {
193
- return { message: `wsl-preflight: ${sessionProblem}`, level: "warn" };
206
+ return { message: blocked(`wsl-preflight: ${sessionProblem}`), level: "warn" };
194
207
  }
195
208
  return { message: `wsl-preflight: ready — bwrap and the session scope are usable inside "${distro}"`, level: "info" };
196
209
  })();
@@ -241,7 +254,8 @@ export async function apply(ctx, config = {}) {
241
254
  * The load pass: run the same probes once at mount — install + restart,
242
255
  * before any session — against the pinned or WSL-default distro, and log the
243
256
  * verdict. A session announcement for the same message then skips the
244
- * duplicate log line but keeps its runtime-context entry. Advisory like every
257
+ * duplicate log line; a blocked verdict still lands as the runtime-context
258
+ * entry. Advisory like every
245
259
  * other arm: an unreachable distro degrades to a debug line.
246
260
  */
247
261
  const startupCheck = async () => {
@@ -0,0 +1,58 @@
1
+ import type { SandboxExecutionPolicy } from "@deepseek-ai/dsh-sandbox";
2
+ interface DistroHomeOwner {
3
+ config: unknown;
4
+ resolvedDistro: string;
5
+ resolvedHome: string | undefined;
6
+ resolvedHomes: Map<string, string>;
7
+ }
8
+ /**
9
+ * The configured default workdir, or an empty string when the operator left it
10
+ * unset. `cwd` is a volatile field on both providers, so it is read through
11
+ * `.get()`, and it may be absent entirely.
12
+ */
13
+ export declare function configuredCwd(config: {
14
+ cwd?: {
15
+ get(): string | undefined;
16
+ };
17
+ }): string;
18
+ /**
19
+ * The distro user's home as a Linux path, cached on the provider instance whose
20
+ * `distro`/`wslPath` config it belongs to.
21
+ */
22
+ export declare function distroHome(owner: DistroHomeOwner, distro: string): Promise<string>;
23
+ /**
24
+ * Translate workspace-write grants into the vocabulary used by the target
25
+ * filesystem. WSL workspaces receive distro-local temporary and extra roots;
26
+ * Windows workspaces retain the upstream grant.
27
+ */
28
+ export declare function wslWritableRoots(policy: SandboxExecutionPolicy, distro: string, linuxExtraRoots: readonly string[]): string[];
29
+ /**
30
+ * Resolve configured and policy-provided roots for one distro, then verify
31
+ * their physical directories before they are bound into a confinement profile.
32
+ */
33
+ export declare function effectiveWritableRoots(input: {
34
+ configured?: readonly string[] | undefined;
35
+ policy?: SandboxExecutionPolicy | undefined;
36
+ distro: string;
37
+ home: string;
38
+ wslPath: string;
39
+ signal?: AbortSignal | undefined;
40
+ run?: ((argv: string[]) => Promise<string>) | undefined;
41
+ check?: boolean;
42
+ }): Promise<string[]>;
43
+ /** Whether confined profiles shadow `/mnt`, with the explicit stance winning. */
44
+ export declare function effectiveMaskWindowsDrive(config: {
45
+ interopVisibility?: "visible" | "masked" | "disabled";
46
+ maskWindowsDrive?: boolean;
47
+ }): boolean;
48
+ /** Resolve the distro for an operation from its configuration and candidates. */
49
+ export declare function resolveOperationDistro(configured: string, candidates: ReadonlyArray<string | undefined>, probeDefault: () => Promise<string>): Promise<string>;
50
+ /**
51
+ * Choose the session runtime policy for one distro, retrying an automatic
52
+ * failed probe after its short cache expires.
53
+ */
54
+ export declare function sessionRuntimeWanted(value: boolean | "auto", distro: string, ensure: () => Promise<void>, cache: Map<string, {
55
+ usable: boolean;
56
+ checkedAt: number;
57
+ }>): Promise<boolean>;
58
+ export {};
@@ -0,0 +1,123 @@
1
+ import { canonicalPath, SandboxInvalidRootError, writableRoots } from "@deepseek-ai/dsh-sandbox";
2
+ import { isWslUnc, posixToUnc, toLinuxPath } from "./paths.js";
3
+ import { distroOfUnc, isDefaultDistro, pinnedDistro } from "./distro-route.js";
4
+ import { linuxHomePath } from "./wsl.js";
5
+ import { WritableRootError, ensureWritableRoots, resolveWritableRoots } from "./writable-roots.js";
6
+ const AUTO_SCOPE_RECHECK_MS = 60_000;
7
+ /**
8
+ * The configured default workdir, or an empty string when the operator left it
9
+ * unset. `cwd` is a volatile field on both providers, so it is read through
10
+ * `.get()`, and it may be absent entirely.
11
+ */
12
+ export function configuredCwd(config) {
13
+ return String(config.cwd?.get?.() ?? "").trim();
14
+ }
15
+ /**
16
+ * The distro user's home as a Linux path, cached on the provider instance whose
17
+ * `distro`/`wslPath` config it belongs to.
18
+ */
19
+ export async function distroHome(owner, distro) {
20
+ const cached = owner.resolvedHomes.get(distro);
21
+ if (cached !== undefined)
22
+ return cached;
23
+ if (owner.resolvedHome !== undefined && owner.resolvedDistro.length > 0 && distro === owner.resolvedDistro) {
24
+ owner.resolvedHomes.set(distro, owner.resolvedHome);
25
+ return owner.resolvedHome;
26
+ }
27
+ const config = owner.config;
28
+ const home = await linuxHomePath(distro, { wslPath: config.wslPath });
29
+ owner.resolvedHomes.set(distro, home);
30
+ if (owner.resolvedDistro.length > 0 && distro === owner.resolvedDistro)
31
+ owner.resolvedHome = home;
32
+ return home;
33
+ }
34
+ /**
35
+ * Translate workspace-write grants into the vocabulary used by the target
36
+ * filesystem. WSL workspaces receive distro-local temporary and extra roots;
37
+ * Windows workspaces retain the upstream grant.
38
+ */
39
+ export function wslWritableRoots(policy, distro, linuxExtraRoots) {
40
+ if (policy.mode !== "workspace-write")
41
+ return [];
42
+ const roots = new Set([canonicalPath(policy.workspaceRoot)]);
43
+ if (isWslUnc(policy.workspaceRoot)) {
44
+ roots.add(canonicalPath(posixToUnc(distro, "/tmp")));
45
+ for (const root of linuxExtraRoots)
46
+ roots.add(canonicalPath(posixToUnc(distro, root)));
47
+ }
48
+ else {
49
+ for (const root of writableRoots(policy))
50
+ roots.add(root);
51
+ }
52
+ return [...roots];
53
+ }
54
+ /**
55
+ * Resolve configured and policy-provided roots for one distro, then verify
56
+ * their physical directories before they are bound into a confinement profile.
57
+ */
58
+ export async function effectiveWritableRoots(input) {
59
+ try {
60
+ const roots = resolveWritableRoots({
61
+ configured: input.configured,
62
+ policy: input.policy?.additionalWritableRoots,
63
+ home: input.home,
64
+ distro: input.distro,
65
+ workspaceRoot: toLinuxPath(input.policy?.workspaceRoot ?? input.home),
66
+ });
67
+ if (input.check !== false) {
68
+ await ensureWritableRoots({ wslPath: input.wslPath, distro: input.distro, roots, signal: input.signal, ...(input.run === undefined ? {} : { run: input.run }) });
69
+ }
70
+ return roots;
71
+ }
72
+ catch (error) {
73
+ if (error instanceof WritableRootError)
74
+ throw new SandboxInvalidRootError(error.root, error.reason);
75
+ throw error;
76
+ }
77
+ }
78
+ /** Whether confined profiles shadow `/mnt`, with the explicit stance winning. */
79
+ export function effectiveMaskWindowsDrive(config) {
80
+ if (config.interopVisibility !== undefined)
81
+ return config.interopVisibility !== "visible";
82
+ return config.maskWindowsDrive === true;
83
+ }
84
+ /** Resolve the distro for an operation from its configuration and candidates. */
85
+ export async function resolveOperationDistro(configured, candidates, probeDefault) {
86
+ const pinned = pinnedDistro(configured);
87
+ if (pinned !== undefined)
88
+ return pinned;
89
+ if (!isDefaultDistro(configured)) {
90
+ for (const candidate of candidates) {
91
+ const named = distroOfUnc(candidate);
92
+ if (named !== undefined)
93
+ return named;
94
+ }
95
+ }
96
+ return probeDefault();
97
+ }
98
+ /**
99
+ * Choose the session runtime policy for one distro, retrying an automatic
100
+ * failed probe after its short cache expires.
101
+ */
102
+ export async function sessionRuntimeWanted(value, distro, ensure, cache) {
103
+ if (value === false)
104
+ return false;
105
+ if (value === true) {
106
+ await ensure();
107
+ return true;
108
+ }
109
+ const cached = cache.get(distro);
110
+ if (cached?.usable === true)
111
+ return true;
112
+ if (cached !== undefined && Date.now() - cached.checkedAt < AUTO_SCOPE_RECHECK_MS)
113
+ return false;
114
+ try {
115
+ await ensure();
116
+ cache.set(distro, { usable: true, checkedAt: Date.now() });
117
+ return true;
118
+ }
119
+ catch {
120
+ cache.set(distro, { usable: false, checkedAt: Date.now() });
121
+ return false;
122
+ }
123
+ }
@@ -118,6 +118,7 @@ export interface WslSandboxCoreInstance {
118
118
  }, options: {
119
119
  distro: string;
120
120
  signal?: AbortSignal | undefined;
121
+ writableRoots?: readonly string[] | undefined;
121
122
  }) => Promise<WslConfined>;
122
123
  }
123
124
  /**
@@ -277,7 +277,9 @@ export function createSandboxCore({ SandboxUnavailableError }) {
277
277
  * @param argv - the argv to run INSIDE the distro (shell, its flags, command).
278
278
  * @param policy - the resolved confined policy (`mode` is never
279
279
  * `danger-full-access`; the caller does not confine that case at all).
280
- * @param options - the distro to run in and optional cancellation.
280
+ * @param options - the distro to run in, optional cancellation, and the
281
+ * resolved extra writable roots (already Linux paths, filtered and
282
+ * physically checked by the provider).
281
283
  * @returns the wrapped argv plus the settlement-classification facts, in the
282
284
  * seam's `ConfinedArgv` shape.
283
285
  * @throws SandboxUnavailableError when the distro has no usable `bwrap`, so a
@@ -289,7 +291,7 @@ export function createSandboxCore({ SandboxUnavailableError }) {
289
291
  throw new SandboxUnavailableError(policy.mode, bwrapFailure(this.wslPath, distro) ?? missingBwrapRemedy(distro));
290
292
  }
291
293
  const workspaceRoot = toLinuxPath(policy.workspaceRoot);
292
- const prefix = bwrapArgvPrefix({ ...policy, workspaceRoot }, { maskWindowsDrive: this.maskWindowsDrive });
294
+ const prefix = bwrapArgvPrefix({ ...policy, workspaceRoot }, { maskWindowsDrive: this.maskWindowsDrive, writableRoots: options.writableRoots });
293
295
  return {
294
296
  argv: [...prefix, ...argv],
295
297
  enforcement: ENFORCEMENT,
@@ -55,6 +55,12 @@ interface SessionRuntimeRequest {
55
55
  mode: string;
56
56
  /** Shadow `/mnt` in the runtime's mount profile. */
57
57
  maskWindowsDrive?: boolean;
58
+ /**
59
+ * Extra Linux roots to bind read-write in the runtime's profile. The
60
+ * providers resolved, filtered and checked them; they are part of the key
61
+ * because the mount table is fixed for the runtime's lifetime.
62
+ */
63
+ writableRoots?: readonly string[];
58
64
  /** The agent's client lease; 0 disables. */
59
65
  leaseMs?: number;
60
66
  }
@@ -134,7 +140,7 @@ export declare class SessionRuntimes {
134
140
  * @param request - the runtime request.
135
141
  * @returns the registry key.
136
142
  */
137
- static key(request: Pick<SessionRuntimeRequest, "distro" | "workspaceRoot" | "mode" | "maskWindowsDrive" | "sessionId">): string;
143
+ static key(request: Pick<SessionRuntimeRequest, "distro" | "workspaceRoot" | "mode" | "maskWindowsDrive" | "sessionId" | "writableRoots">): string;
138
144
  /**
139
145
  * Acquire the runtime for one key, creating it on first use.
140
146
  *
@@ -146,7 +146,14 @@ export class SessionRuntimes {
146
146
  * @returns the registry key.
147
147
  */
148
148
  static key(request) {
149
- return [request.sessionId ?? "", request.distro, request.workspaceRoot, request.mode, request.maskWindowsDrive === true ? "masked" : "visible"].join("\u0000");
149
+ return [
150
+ request.sessionId ?? "",
151
+ request.distro,
152
+ request.workspaceRoot,
153
+ request.mode,
154
+ request.maskWindowsDrive === true ? "masked" : "visible",
155
+ (request.writableRoots ?? []).join("\u0000"),
156
+ ].join("\u0000");
150
157
  }
151
158
  /**
152
159
  * Acquire the runtime for one key, creating it on first use.
@@ -165,7 +172,7 @@ export class SessionRuntimes {
165
172
  const unit = sessionScopeUnit(request.distro, this.token());
166
173
  const prefix = sessionScopePrefix(unit);
167
174
  if (request.mode !== "danger-full-access") {
168
- prefix.push(...bwrapArgvPrefix({ mode: request.mode, workspaceRoot: toLinuxPath(request.workspaceRoot) }, { maskWindowsDrive: request.maskWindowsDrive, realTmp: true, pidNamespace: false }));
175
+ prefix.push(...bwrapArgvPrefix({ mode: request.mode, workspaceRoot: toLinuxPath(request.workspaceRoot) }, { maskWindowsDrive: request.maskWindowsDrive, realTmp: true, pidNamespace: false, writableRoots: request.writableRoots }));
169
176
  }
170
177
  const agent = this.spawnAgent({
171
178
  distro: request.distro,
package/lib/shell.d.ts CHANGED
@@ -9,4 +9,4 @@
9
9
  *
10
10
  * @module dsh-plugin-wsl-env/shell
11
11
  */
12
- export { WslShellExecutor as default, WslShellExecutor } from "./index.js";
12
+ export { WslShellExecutor as default, WslShellExecutor } from "./wsl-shell.js";
package/lib/shell.js CHANGED
@@ -9,4 +9,4 @@
9
9
  *
10
10
  * @module dsh-plugin-wsl-env/shell
11
11
  */
12
- export { WslShellExecutor as default, WslShellExecutor } from "./index.js";
12
+ export { WslShellExecutor as default, WslShellExecutor } from "./wsl-shell.js";
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The extra directories a WSL confinement grants read-write under
3
+ * `workspace-write`, and the one-time check that they are usable.
4
+ *
5
+ * `workspace-write` grants the session workspace and the distro's temp areas —
6
+ * nothing under the user's home. Toolchains do not stay inside the workspace:
7
+ * npm writes `~/.npm`, pnpm writes its store under `~/.local/share/pnpm`,
8
+ * cargo writes `~/.cargo/registry`, and a linked Git worktree writes the
9
+ * shared `.git` directory. This module turns the operator's grants (the plugin
10
+ * rows' `writableRoots` plus the shared policy's `additionalWritableRoots`)
11
+ * into the Linux paths the bwrap profile binds.
12
+ *
13
+ * ## Why the roots are filtered
14
+ *
15
+ * A grant is bound rw into the distro's mount table. If the bound path could
16
+ * be replaced by a symlink after the check, the next command would bind the
17
+ * link's target — the classic grant-redirection escape. The model can write
18
+ * only the workspace and the temp areas, so a grant whose parent is writable
19
+ * is not merely redundant, it is a redirection risk. Candidates already
20
+ * writable (inside the workspace, `/tmp` or `/dev/shm`) and candidates nested
21
+ * inside another grant are therefore dropped, not bound. Every effective root
22
+ * has a read-only parent, which is what makes the one-time physical-path
23
+ * check below sufficient for the model threat model.
24
+ *
25
+ * This module is peer-free so the rules are unit-testable in a bare checkout;
26
+ * `lib/provider-common.js` converts {@link WritableRootError} into the peer's
27
+ * `SandboxInvalidRootError` at the call sites.
28
+ *
29
+ * This is a TypeScript source built to `lib/writable-roots.js`; edit THIS file
30
+ * and run `pnpm run build` — the artifact under `lib/` is generated, and
31
+ * `pnpm test` fails when it drifts.
32
+ *
33
+ * @module dsh-plugin-wsl-env/writable-roots
34
+ */
35
+ /** A configured grant that cannot be used, with the reason the model-facing error carries. */
36
+ export declare class WritableRootError extends Error {
37
+ /** The entry as configured (or the policy's spelling). */
38
+ readonly root: string;
39
+ /** Why it was refused. */
40
+ readonly reason: string;
41
+ /**
42
+ * @param root - the entry as configured.
43
+ * @param reason - the model-facing reason.
44
+ */
45
+ constructor(root: string, reason: string);
46
+ }
47
+ /** The inputs of {@link resolveWritableRoots}. */
48
+ export interface WritableRootsInput {
49
+ /** The plugin rows' `writableRoots` (distro paths; `~` expands to the distro home). */
50
+ configured?: readonly string[] | undefined;
51
+ /** The shared policy's `additionalWritableRoots` (UNC of this distro, or Linux paths). */
52
+ policy?: readonly string[] | undefined;
53
+ /** The resolved distro user's home, for `~` and `~/...` entries. */
54
+ home: string;
55
+ /** The distro the workspace belongs to, for the UNC check and the embedded error text. */
56
+ distro: string;
57
+ /** The workspace root in Linux form; grants inside it are already writable. */
58
+ workspaceRoot: string;
59
+ }
60
+ /**
61
+ * Validate the shape of a row's `writableRoots` before any distro is known.
62
+ * Called from the providers' constructors so a typo fails at boot instead of
63
+ * at the first command.
64
+ *
65
+ * @param values - the configured entries, if present.
66
+ * @throws {Error} naming the first entry that is not a distro path.
67
+ */
68
+ export declare function validateWritableRootsConfig(values: readonly string[] | undefined): void;
69
+ /**
70
+ * Turn the configured and policy grants into the effective Linux roots.
71
+ *
72
+ * Entries already writable (inside the workspace, `/tmp` or `/dev/shm`) and
73
+ * entries nested inside another grant are dropped: they add no permission, and
74
+ * binding them would let the model redirect the bind through a symlink. The
75
+ * rest are deduplicated, sorted and returned.
76
+ *
77
+ * @param input - the configured grants, policy grants, home and workspace.
78
+ * @returns the effective roots, in deterministic order.
79
+ * @throws {WritableRootError} for an entry that names another world or is malformed.
80
+ */
81
+ export declare function resolveWritableRoots(input: WritableRootsInput): string[];
82
+ /** The argv of the one-time physical-directory check, exported for tests and diagnostics. */
83
+ export declare function writableRootsCheckArgv(wslPath: string, distro: string, roots: readonly string[]): string[];
84
+ /**
85
+ * Check once per process that every effective root exists, is readable and is
86
+ * its own physical directory. A missing root reports the operator-facing
87
+ * failure instead of letting bwrap die with an opaque mount error; a symlinked
88
+ * root is refused with the physical-path rule the peer's extra-root contract
89
+ * uses.
90
+ *
91
+ * A success is remembered for the process lifetime: the effective roots have
92
+ * read-only parents, so the model cannot replace them, and the common roots
93
+ * (`~/.npm`, `~/.cache`, …) are stable. A failed check is not remembered, so a
94
+ * directory the operator creates while the app runs is believed next time.
95
+ *
96
+ * @param options - the `wsl.exe` path, distro, effective roots and optional run override.
97
+ * @returns resolved when every root is usable.
98
+ * @throws {WritableRootError} naming the first unusable root.
99
+ */
100
+ export declare function ensureWritableRoots(options: {
101
+ wslPath: string;
102
+ distro: string;
103
+ roots: readonly string[];
104
+ signal?: AbortSignal | undefined;
105
+ /** The runner, overridable in tests; defaults to the shared capture. */
106
+ run?: (argv: string[]) => Promise<string>;
107
+ }): Promise<void>;
108
+ /** Test hook: forget the remembered checks. */
109
+ export declare function resetWritableRootsChecks(): void;