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
package/lib/status.js ADDED
@@ -0,0 +1,425 @@
1
+ /**
2
+ * The sidebar panel's diagnostic route (`GET`/`POST /api/wsl-env/status`).
3
+ *
4
+ * The panel is a status/config surface, and the authoritative environment
5
+ * verdict is the doctor's. A browser plugin cannot reach a plugin-private Host
6
+ * method (the Client Remote assembly fixes its namespaces at build time), but
7
+ * it can reach an **authenticated exact Fetch route** on the `/api` channel:
8
+ * `ctx.connection.fetch.register` is the same seam the shipped Session-log and
9
+ * file routes use, it admits only the owner Peer, and it needs no generated
10
+ * wire schema. This row therefore publishes two answers:
11
+ *
12
+ * - `GET /api/wsl-env/status` — the installed distros (from `wsl.exe -l -q`,
13
+ * which starts nothing) plus the last successful verdict per distro,
14
+ * restored from the store below;
15
+ * - `GET /api/wsl-env/status?distro=<name>` — one distro's quick doctor
16
+ * report, digested to the same shape the `/wsl-doctor` command renders;
17
+ * - `POST /api/wsl-env/status?distro=<name>` — the panel's repair action: a
18
+ * full doctor run with `--fix-owned`, which sweeps stale session scopes
19
+ * and purges a broken agent cache, then re-verifies both and answers with
20
+ * the same digest plus the `fix.*` rows. Nothing outside the plugin's own
21
+ * state is touched (no packages, no Windows git config), so the panel
22
+ * stays a diagnostic surface that can heal its own residue.
23
+ *
24
+ * The doctor runs as the standalone CLI subprocess, exactly as the command row
25
+ * runs it, so a diagnosis still answers when the plugin's own module graph is
26
+ * what is broken. Runs are cached per distro for `cacheMs`; `refresh=1` drops
27
+ * the entry. A check is only ever started by an explicit click in the panel:
28
+ * probing a stopped distro boots it, which a page load must not do to every
29
+ * installed distro.
30
+ *
31
+ * The last result per distro — success or failure — is persisted to
32
+ * `$DSH_HOME/cache/dsh-plugin-wsl-env/status.json` (falling back to `~/.dsh`),
33
+ * so a page reload or an app restart still shows what the last check found and
34
+ * when. `source` records whether that run came from an explicit panel action
35
+ * or from the page-load background refresh; a failed background run overwrites
36
+ * the stored result exactly as it was observed. Results are never labeled
37
+ * expired: the timestamp is the timestamp, and the row's check button is the
38
+ * next step. Writing is best-effort — a read-only home degrades to the
39
+ * in-memory cache rather than failing the diagnosis.
40
+ *
41
+ * This is a TypeScript source built to `lib/status.js`; edit THIS file and run
42
+ * `pnpm run build` — the artifact under `lib/` is generated, and `pnpm test`
43
+ * fails when it drifts.
44
+ *
45
+ * @module dsh-plugin-wsl-env/status
46
+ */
47
+ import z from "@deepseek-ai/schemastery";
48
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
49
+ import { homedir } from "node:os";
50
+ import { dirname, join } from "node:path";
51
+ import { listDistros, listRunningDistros } from "./wsl.js";
52
+ import { digestReport, sectionOf } from "./wsl-doctor-tool.js";
53
+ import { runDoctorCli } from "./wsl-doctor-command.js";
54
+ export const name = "wsl-status";
55
+ /** The one route the panel fetches; it must live under the `/api` channel. */
56
+ export const STATUS_PATH = "/api/wsl-env/status";
57
+ /** The on-disk schema version. */
58
+ const STORE_VERSION = 1;
59
+ /**
60
+ * Where the last successful results live: the harness home's cache directory,
61
+ * falling back to `~/.dsh` when the Host process names no home. The panel's
62
+ * guidance must survive a page reload and an app restart; an in-memory cache
63
+ * cannot, because the page's own reload drops the browser state and a plugin
64
+ * reload drops the process state.
65
+ * @returns the absolute path of the status store.
66
+ */
67
+ function defaultStatePath() {
68
+ const configured = (process.env.DSH_HOME ?? "").trim();
69
+ const home = configured.length > 0 ? configured : join(homedir(), ".dsh");
70
+ return join(home, "cache", "dsh-plugin-wsl-env", "status.json");
71
+ }
72
+ export const Config = z.object({
73
+ /** How long one distro's quick verdict stays fresh, in milliseconds. */
74
+ cacheMs: z.natural().default(15_000),
75
+ /** Deadline for one scoped quick doctor run, in milliseconds. */
76
+ timeoutMs: z.natural().min(1).default(90_000),
77
+ /** `wsl.exe` to list the distros; keep in step with the providers' `wslPath`. */
78
+ wslPath: z.string().default("wsl.exe"),
79
+ });
80
+ /**
81
+ * Read the status store. A missing, unreadable or malformed file is no
82
+ * guidance at all: the handler starts empty and the next check rewrites it.
83
+ * @param path - the store path; empty disables persistence.
84
+ * @returns the parsed store, or undefined.
85
+ */
86
+ function readStored(path) {
87
+ if (path.length === 0)
88
+ return undefined;
89
+ try {
90
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
91
+ if (parsed.version !== STORE_VERSION || parsed.distros === null || typeof parsed.distros !== "object")
92
+ return undefined;
93
+ return { version: STORE_VERSION, distros: parsed.distros };
94
+ }
95
+ catch {
96
+ return undefined;
97
+ }
98
+ }
99
+ /**
100
+ * Write the last successful verdicts atomically. A read-only or missing home
101
+ * must not fail the diagnosis that produced them, so a write error is
102
+ * swallowed: the in-memory answer still reaches the panel.
103
+ * @param path - the store path; empty disables persistence.
104
+ * @param verdicts - the verdicts to persist, keyed by distro.
105
+ */
106
+ function writeStored(path, verdicts) {
107
+ if (path.length === 0)
108
+ return;
109
+ const distros = {};
110
+ for (const [distro, entry] of verdicts) {
111
+ const stored = { ...entry.view };
112
+ delete stored.cached;
113
+ distros[distro] = stored;
114
+ }
115
+ try {
116
+ mkdirSync(dirname(path), { recursive: true });
117
+ const temporary = `${path}.tmp`;
118
+ writeFileSync(temporary, `${JSON.stringify({ version: STORE_VERSION, distros }, null, 2)}\n`, { mode: 0o600 });
119
+ renameSync(temporary, path);
120
+ }
121
+ catch {
122
+ // Best effort: the result is still served from memory.
123
+ }
124
+ }
125
+ /**
126
+ * Build the JSON response for one request.
127
+ * @param body - the JSON-serializable value.
128
+ * @param status - the HTTP status.
129
+ * @returns a JSON response.
130
+ */
131
+ function json(body, status = 200) {
132
+ return Response.json(body, { status, headers: { "cache-control": "no-store" } });
133
+ }
134
+ /**
135
+ * Count the statuses the report actually produced for this distro, leaving
136
+ * out the digest's synthetic "not run in this scope" catalog rows.
137
+ * @param findings - the report's rows, already stripped of `fix.*` rows.
138
+ * @returns the per-status totals.
139
+ */
140
+ function countsOf(findings) {
141
+ const actual = findings.filter((item) => item.distro !== "(not run)");
142
+ const count = (status) => actual.filter((item) => item.status === status).length;
143
+ return {
144
+ ok: count("ok"),
145
+ warn: count("warn"),
146
+ fail: count("fail"),
147
+ info: count("info"),
148
+ skipped: count("skipped"),
149
+ unknown: count("unknown"),
150
+ };
151
+ }
152
+ /**
153
+ * Digest one parsed doctor report into the panel's shape.
154
+ * @param digest - the shared digest the command and the tool render.
155
+ * @param distro - the distro the report answers for.
156
+ * @param now - the run's timestamp.
157
+ * @param repaired - whether the run was the full `--fix-owned` action.
158
+ * @param source - who started the run.
159
+ * @returns the panel view.
160
+ */
161
+ function viewOf(digest, distro, now, repaired, source) {
162
+ // The fix rows are the repair's own narration, not findings about the
163
+ // environment: keep them out of the failure/warning lists so a repair does
164
+ // not double-list its work, and surface them separately.
165
+ // The digest also carries synthetic skip rows for catalog ids the report
166
+ // never emitted (`fix.git-trust` on a quiet run): only the fix rows the
167
+ // doctor actually produced are repairs.
168
+ const fixes = digest.items.filter((item) => item.id.startsWith("fix.") && item.status !== "skipped");
169
+ const findings = digest.items.filter((item) => !item.id.startsWith("fix."));
170
+ // Which findings the plugin-owned repair can actually act on. A repair
171
+ // button that cannot apply is worse than no button: the user sees warnings,
172
+ // clicks "修复", and nothing changes. The cache only explains a failed
173
+ // handshake when the cache is the finding — otherwise the handshake needs a
174
+ // reinstall or a resync, not a purge.
175
+ // A broken cache is `warn` under `agentBackend: auto` and `fail` under
176
+ // `native`; both are plugin-owned and repairable by the purge.
177
+ const cacheBroken = findings.some((item) => item.id === "agent.cache" && (item.status === "warn" || item.status === "fail"));
178
+ const repairable = findings
179
+ .filter((item) => (item.id === "runtime.scopes" && item.status === "warn")
180
+ || (item.id === "agent.cache" && (item.status === "warn" || item.status === "fail"))
181
+ || (item.id === "agent.handshake" && item.status === "fail" && cacheBroken))
182
+ .map((item) => item.id);
183
+ // Every executed check, in report order, grouped later by section. The
184
+ // synthetic catalog rows and the repair's own `fix.*` narration are not
185
+ // findings about this distro, so they stay out.
186
+ const checkRows = findings
187
+ .filter((item) => item.scopeSkip !== true)
188
+ .map((item) => ({
189
+ id: item.id,
190
+ title: item.title,
191
+ status: item.status,
192
+ detail: item.detail,
193
+ ...(item.remedy === undefined ? {} : { remedy: item.remedy }),
194
+ section: sectionOf(item.id),
195
+ }));
196
+ return {
197
+ distro,
198
+ verdict: digest.verdict === "ready" ? "ready" : "blocked",
199
+ repaired,
200
+ repairs: repaired
201
+ ? fixes.map((item) => ({
202
+ id: item.id,
203
+ title: item.title,
204
+ status: item.status,
205
+ detail: item.detail,
206
+ ...(item.remedy === undefined ? {} : { remedy: item.remedy }),
207
+ }))
208
+ : [],
209
+ repairable,
210
+ checkedAt: now,
211
+ cached: false,
212
+ source,
213
+ failures: digest.failing
214
+ .filter((check) => !check.id.startsWith("fix."))
215
+ .map((check) => ({ id: check.id, detail: check.detail, remedy: check.remedy })),
216
+ warnings: findings
217
+ .filter((item) => item.status === "warn")
218
+ .map((item) => ({
219
+ id: item.id,
220
+ detail: item.detail,
221
+ ...(item.remedy === undefined ? {} : { remedy: item.remedy }),
222
+ })),
223
+ // Count the rows this run actually answered. The digest's synthetic
224
+ // "not run in this scope" rows describe the catalog, not this distro, and
225
+ // a repair's own `fix.*` rows are narration — both stay out.
226
+ counts: countsOf(findings),
227
+ sections: digest.sections,
228
+ checks: checkRows,
229
+ notRun: digest.scope === undefined ? 0 : digest.notRun,
230
+ blockers: digest.blockers,
231
+ };
232
+ }
233
+ /**
234
+ * Build the route handler.
235
+ *
236
+ * One handler owns one cache, so the row registers exactly one instance and an
237
+ * unload drops every verdict with it.
238
+ *
239
+ * @param options - the distro, runner, and cache seams.
240
+ * @returns the request handler.
241
+ */
242
+ export function createStatusHandler(options) {
243
+ const now = options.now ?? (() => Date.now());
244
+ const statePath = options.statePath ?? defaultStatePath();
245
+ const verdicts = new Map();
246
+ let list;
247
+ // Restore the last successful results before the first request. The stored
248
+ // view is the panel's shape; the fields later releases may have added are
249
+ // defaulted so an older store still renders instead of failing the load.
250
+ for (const [distro, view] of Object.entries(readStored(statePath)?.distros ?? {})) {
251
+ if (view === null || typeof view !== "object" || view.distro !== distro || typeof view.checkedAt !== "number")
252
+ continue;
253
+ verdicts.set(distro, {
254
+ at: view.checkedAt,
255
+ view: {
256
+ ...view,
257
+ repairs: Array.isArray(view.repairs) ? view.repairs : [],
258
+ repairable: Array.isArray(view.repairable) ? view.repairable : [],
259
+ failures: Array.isArray(view.failures) ? view.failures : [],
260
+ warnings: Array.isArray(view.warnings) ? view.warnings : [],
261
+ counts: view.counts ?? { ok: 0, warn: 0, fail: 0, info: 0, skipped: 0, unknown: 0 },
262
+ sections: Array.isArray(view.sections) ? view.sections : [],
263
+ checks: Array.isArray(view.checks) ? view.checks : [],
264
+ notRun: typeof view.notRun === "number" ? view.notRun : 0,
265
+ blockers: Array.isArray(view.blockers) ? view.blockers : [],
266
+ source: view.source === "background" ? "background" : "user",
267
+ cached: false,
268
+ },
269
+ });
270
+ }
271
+ /**
272
+ * Mark a stored or fresh answer for transport. The view's own `checkedAt`
273
+ * and `source` are the truth about the run; `cached` only says whether this
274
+ * response re-ran the doctor.
275
+ * @param view - the view to present.
276
+ * @param cached - whether the answer came from the cache.
277
+ * @returns the presented view.
278
+ */
279
+ const present = (view, cached) => ({ ...view, cached });
280
+ const installed = async (refresh) => {
281
+ if (!refresh && list !== undefined && now() - list.at < options.cacheMs)
282
+ return list.names;
283
+ const names = await options.distros();
284
+ list = { at: now(), names };
285
+ return names;
286
+ };
287
+ const check = async (distro, refresh, repair = false, source = "user") => {
288
+ const cached = verdicts.get(distro);
289
+ // A failure is a fact of this moment: it is kept for the list and the
290
+ // store, but a plain GET re-runs instead of serving it as fresh.
291
+ if (!refresh && cached !== undefined && cached.view.verdict !== "error" && now() - cached.at < options.cacheMs)
292
+ return present(cached.view, true);
293
+ const at = now();
294
+ let view;
295
+ try {
296
+ // A repair needs a full run: `--fix` refuses a scoped one because a
297
+ // scoped report cannot re-verify what it did not probe. `--fix-owned`
298
+ // keeps the loop on plugin-owned state (scopes, agent cache) — the panel
299
+ // never installs packages or rewrites Windows-owned configuration.
300
+ const argv = repair
301
+ ? ["--json", "--fix", "--fix-owned", "--distro", distro]
302
+ : ["--json", "--quick", "--distro", distro];
303
+ const raw = await options.runCli(argv, undefined, options.timeoutMs);
304
+ const report = JSON.parse(raw);
305
+ view = viewOf(digestReport(report, distro), distro, at, repair, source);
306
+ }
307
+ catch (error) {
308
+ view = {
309
+ distro,
310
+ verdict: "error",
311
+ repaired: false,
312
+ repairs: [],
313
+ repairable: [],
314
+ checkedAt: at,
315
+ cached: false,
316
+ source,
317
+ failures: [],
318
+ warnings: [],
319
+ counts: { ok: 0, warn: 0, fail: 0, info: 0, skipped: 0, unknown: 0 },
320
+ sections: [],
321
+ checks: [],
322
+ notRun: 0,
323
+ blockers: [],
324
+ error: error?.message ?? String(error),
325
+ };
326
+ }
327
+ // Persist the result exactly as observed, failure included: a failed
328
+ // background refresh must overwrite the last good result rather than
329
+ // leave a stale success on screen. The store keeps the truth; the panel
330
+ // shows the error and offers the retry.
331
+ verdicts.set(distro, { at, view });
332
+ writeStored(statePath, verdicts);
333
+ return present(view, false);
334
+ };
335
+ return async (request) => {
336
+ if (request.method !== "GET" && request.method !== "POST")
337
+ return json({ error: "只支持 GET 与 POST" }, 405);
338
+ const url = new URL(request.url);
339
+ const repair = request.method === "POST";
340
+ const refresh = url.searchParams.get("refresh") === "1";
341
+ const requested = url.searchParams.get("distro");
342
+ let names;
343
+ try {
344
+ names = await installed(repair || refresh);
345
+ }
346
+ catch (error) {
347
+ return json({ error: `无法读取发行版清单:${error?.message ?? String(error)}` }, 502);
348
+ }
349
+ if (requested === null || requested === "") {
350
+ if (repair)
351
+ return json({ error: "修复需要指定发行版" }, 400);
352
+ // The running list bounds the panel's background refresh: only a
353
+ // distro that is already up may be re-checked without the user asking,
354
+ // because a probe boots a stopped one. A failed read means no refresh.
355
+ let running = [];
356
+ try {
357
+ running = (await options.running?.() ?? []).filter((name) => names.includes(name));
358
+ }
359
+ catch {
360
+ running = [];
361
+ }
362
+ const reply = {
363
+ distros: names,
364
+ running,
365
+ cached: [...verdicts.entries()]
366
+ .filter(([distro]) => names.includes(distro))
367
+ .map(([, entry]) => present(entry.view, true)),
368
+ };
369
+ return json(reply);
370
+ }
371
+ if (!names.includes(requested))
372
+ return json({ error: `未知发行版:${requested}` }, 400);
373
+ const background = !repair && url.searchParams.get("background") === "1";
374
+ return json(await check(requested, refresh || repair, repair, background ? "background" : "user"));
375
+ };
376
+ }
377
+ /**
378
+ * Resolve the row's config into handler options.
379
+ *
380
+ * The seams live in {@link StatusHandlerOptions} (and are exercised by the
381
+ * handler tests). Reading them off the Context would be wrong twice over: a
382
+ * Cordis context property accessor throws for a name that was not injected
383
+ * ("cannot get property ... without inject"), which silently broke route
384
+ * registration once already, and a plugin has no business inventing service
385
+ * names.
386
+ *
387
+ * @param config - the schema-validated config.
388
+ * @returns handler options.
389
+ */
390
+ function optionsFor(config) {
391
+ const wslPath = config.wslPath ?? "wsl.exe";
392
+ return {
393
+ cacheMs: config.cacheMs ?? 15_000,
394
+ timeoutMs: config.timeoutMs ?? 90_000,
395
+ distros: () => listDistros({ wslPath }),
396
+ running: () => listRunningDistros({ wslPath }),
397
+ runCli: runDoctorCli,
398
+ };
399
+ }
400
+ /**
401
+ * Mount the row: register the route once the Host connection is available.
402
+ *
403
+ * A composition without `connection` (headless, ACP) leaves the row inert —
404
+ * the same posture the other surface rows take.
405
+ *
406
+ * @param ctx - the cordis context.
407
+ * @param config - the schema-validated config.
408
+ */
409
+ export function apply(ctx, config = {}) {
410
+ if (typeof ctx.inject !== "function")
411
+ return;
412
+ ctx.inject(["connection"], (scope) => {
413
+ const connection = scope.connection ?? scope.get?.("connection");
414
+ if (connection === undefined)
415
+ return;
416
+ const handler = createStatusHandler(optionsFor(config));
417
+ const dispose = connection.fetch.register({
418
+ path: STATUS_PATH,
419
+ methods: ["GET", "POST"],
420
+ requestBody: "buffered",
421
+ fetch: handler,
422
+ });
423
+ scope.effect?.(() => () => { void dispose(); }, `wsl-status: ${STATUS_PATH}`);
424
+ });
425
+ }
@@ -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;