dsh-plugin-wsl-env 0.26.0 → 0.26.2

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 (52) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/README.md +55 -158
  3. package/SUPPORT.md +2 -2
  4. package/SUPPORT.zh.md +2 -2
  5. package/docs/ARCHITECTURE.md +21 -5
  6. package/docs/ARCHITECTURE.zh.md +17 -4
  7. package/docs/CONFIGURATION.md +7 -9
  8. package/docs/CONFIGURATION.zh.md +6 -7
  9. package/docs/DIAGNOSTICS.md +21 -0
  10. package/docs/DIAGNOSTICS.zh.md +15 -0
  11. package/docs/LIMITATIONS.md +13 -1
  12. package/docs/LIMITATIONS.zh.md +12 -2
  13. package/docs/MIGRATION.md +4 -1
  14. package/docs/MIGRATION.zh.md +4 -1
  15. package/docs/PEER-PARITY.md +16 -0
  16. package/docs/QUICKSTART.md +22 -15
  17. package/docs/QUICKSTART.zh.md +19 -16
  18. package/docs/README.zh.md +59 -146
  19. package/docs/RELEASING.md +2 -2
  20. package/docs/REQUIREMENTS.zh.md +2 -2
  21. package/docs/ROADMAP-1.0.md +1 -1
  22. package/docs/VALUE.md +27 -0
  23. package/docs/VALUE.zh.md +27 -0
  24. package/docs/screenshots/with-plugin.png +0 -0
  25. package/docs/screenshots/with-plugin.svg +59 -0
  26. package/docs/screenshots/with-plugin.zh.png +0 -0
  27. package/docs/screenshots/with-plugin.zh.svg +56 -0
  28. package/docs/screenshots/without-plugin.png +0 -0
  29. package/docs/screenshots/without-plugin.svg +50 -0
  30. package/docs/screenshots/without-plugin.zh.png +0 -0
  31. package/docs/screenshots/without-plugin.zh.svg +45 -0
  32. package/lib/doctor-report.js +8 -1
  33. package/lib/git-exec.d.ts +39 -7
  34. package/lib/git-exec.js +151 -18
  35. package/lib/listing.d.ts +17 -0
  36. package/lib/listing.js +20 -0
  37. package/lib/messages.d.ts +27 -0
  38. package/lib/messages.js +26 -2
  39. package/lib/peer-versions.d.ts +53 -0
  40. package/lib/peer-versions.js +137 -0
  41. package/lib/picker.js +33 -19
  42. package/lib/search-exec.d.ts +45 -9
  43. package/lib/search-exec.js +152 -20
  44. package/lib/subprocess.d.ts +4 -1
  45. package/lib/subprocess.js +16 -3
  46. package/lib/update-check.d.ts +2 -2
  47. package/lib/update-check.js +2 -2
  48. package/lib/wsl-doctor-command.js +2 -1
  49. package/lib/wsl.d.ts +21 -0
  50. package/lib/wsl.js +24 -0
  51. package/package.json +9 -2
  52. package/scripts/doctor.mjs +148 -22
package/lib/git-exec.js CHANGED
@@ -25,19 +25,71 @@
25
25
  * The agent being out is the fallback cue, exactly as `search-exec.ts`:
26
26
  * `spawnFallback` (the caller's one-shot `wsl.exe` handle) is consulted
27
27
  * lazily inside `done`, and from that point the facade proxies the delegate
28
- * verbatim. Cancellation shares one channel: the caller's `signal` and
29
- * `kill()` abort the agent exec, settling `done` as killed.
28
+ * verbatim unless its relay named a broken program or directory. Cancellation
29
+ * shares one channel: the caller's `signal` and `kill()` abort the agent
30
+ * exec, settling `done` as killed.
31
+ *
32
+ * ## Failure surfacing: a broken distro must not look like "no changes"
33
+ *
34
+ * `GitRunner` reads git's own exit codes and stderr; a rejection from
35
+ * `handle.done` is an opaque snapshot failure the model cannot act on. The
36
+ * agent's two local failures therefore become git's own dialect instead:
37
+ *
38
+ * - A `SpawnError` means the agent could not start the program. The native
39
+ * agent reports both a missing executable and a missing working directory
40
+ * that way, without naming either — so the synthesized message names both
41
+ * and the install remedy, at exit 127 (a shell's command-not-found; never
42
+ * `1`, which several git subcommands use for a normal negative answer, nor
43
+ * `128`, which `GitRunner` reads as "not a repository").
44
+ * - A `CwdError` names the directory that could not be entered. It becomes
45
+ * git's fatal class — `fatal: cannot change to '<path>': No such file or
46
+ * directory` at exit 128 — which is exactly what `git -C <missing>` itself
47
+ * prints.
48
+ *
49
+ * Neither failure falls back to the one-shot path. A missing program would
50
+ * only produce the relay's `execvpe(git) failed` at exit `1`, and a missing
51
+ * directory is worse: `wsl.exe --cd` does not fail on it — it warns, runs in
52
+ * `/`, and exits 0 — where `git` then answers "not a git repository", which
53
+ * the snapshot reads as a clean, empty result. The one-shot delegate is
54
+ * post-processed for both relay markers, so the agent being out cannot turn a
55
+ * broken environment into a silent "no changes" either. Other failures still
56
+ * propagate through `done` as rejections.
57
+ *
58
+ * A discovery call's absolute-path answer is translated on BOTH transports:
59
+ * the one-shot delegate's stdout is taken over and passed through
60
+ * `translateDiscoveryOutput` exactly as the agent's result is, so change
61
+ * review sees the same UNC paths whether or not the resident is up.
30
62
  *
31
63
  * Pure shaping over injected collaborators, unit-testable without a distro.
32
64
  *
33
65
  * This is a TypeScript source built to `lib/git-exec.js`; edit THIS file and
34
- * run `pnpm run build` — the artifact under `lib/` is generated, and
35
- * `pnpm test` fails when it drifts.
66
+ * run `pnpm run build` — the artifact under `lib/` is generated, and `pnpm test`
67
+ * fails when it drifts.
36
68
  *
37
69
  * @module dsh-plugin-wsl-env/git-exec
38
70
  */
39
- import { AgentUnavailableError } from "./agent-errors.js";
71
+ import { AgentUnavailableError, CwdError, SpawnError } from "./agent-errors.js";
72
+ import { t } from "./messages.js";
40
73
  import { translateDiscoveryOutput } from "./git-route.js";
74
+ import { execProgramFailure, workdirFailure } from "./wsl.js";
75
+ /** The exit code a shell reports for a command it could not run. */
76
+ const COMMAND_NOT_FOUND_EXIT = 127;
77
+ /**
78
+ * git's fatal-error exit code. A directory that cannot be entered is what
79
+ * `git -C <missing>` itself reports this way, so the synthesized line speaks
80
+ * git's own dialect rather than inventing a code.
81
+ */
82
+ const GIT_FATAL_EXIT = 128;
83
+ /**
84
+ * The stderr one snapshot settles with when its working directory is gone:
85
+ * git's own fatal line, then the directory's remedy.
86
+ *
87
+ * @param linuxPath - the directory the agent could not enter.
88
+ * @returns the stderr text.
89
+ */
90
+ function workdirFailureText(linuxPath) {
91
+ return `fatal: cannot change to '${linuxPath}': No such file or directory\n${t("gitWorkdirMissing", { path: linuxPath })}`;
92
+ }
41
93
  /**
42
94
  * Run one git command through the agent and present it as a git-snapshot
43
95
  * handle.
@@ -46,7 +98,7 @@ import { translateDiscoveryOutput } from "./git-route.js";
46
98
  * @returns the snapshot handle (`done`, `collected`, `kill`).
47
99
  */
48
100
  export function gitExecutionHandle({ agent, cwd, argv, env, stdin, caps, distro, discovery, signal, spawnFallback }) {
49
- const state = { delegate: undefined, stdout: undefined, stderr: undefined };
101
+ const state = { delegate: undefined, stdout: undefined, stderr: undefined, lossy: { stdout: false, stderr: false } };
50
102
  const controller = new AbortController();
51
103
  if (signal?.aborted)
52
104
  controller.abort(signal.reason);
@@ -61,13 +113,86 @@ export function gitExecutionHandle({ agent, cwd, argv, env, stdin, caps, distro,
61
113
  return {
62
114
  readFrom(from) {
63
115
  const buffer = state[slot] ?? Buffer.alloc(0);
64
- const lossy = buffer.length > cap;
116
+ const lossy = state.lossy[slot] || buffer.length > cap;
65
117
  const visible = lossy ? buffer.subarray(0, cap) : buffer;
66
118
  const start = Math.min(from, visible.length);
67
119
  return { text: visible.subarray(start).toString("utf8"), lossy, nextOffset: visible.length };
68
120
  },
69
121
  };
70
122
  };
123
+ /**
124
+ * Settle on a synthesized failure: drop any delegate so `collected` serves
125
+ * the buffers this facade owns.
126
+ *
127
+ * @param exitCode - git's dialect exit code for the failure.
128
+ * @param stderr - the model-facing diagnostic, remedy included.
129
+ * @returns the settled outcome.
130
+ */
131
+ const settleFailure = (exitCode, stderr) => {
132
+ state.delegate = undefined;
133
+ state.stdout = Buffer.alloc(0);
134
+ state.stderr = Buffer.from(stderr, "utf8");
135
+ state.lossy = { stdout: false, stderr: false };
136
+ return { exitCode, signal: null };
137
+ };
138
+ /**
139
+ * The 127 result for a program the distro could not start.
140
+ *
141
+ * @param detail - the agent's or the relay's own spawn diagnostic.
142
+ * @returns the settled outcome.
143
+ */
144
+ const settleProgramMissing = (detail) => settleFailure(COMMAND_NOT_FOUND_EXIT, t("gitProgramMissing", { distro, detail }));
145
+ /**
146
+ * The fatal result for a directory the distro could not enter.
147
+ *
148
+ * @param linuxPath - the directory that could not be entered.
149
+ * @returns the settled outcome.
150
+ */
151
+ const settleWorkdirMissing = (linuxPath) => settleFailure(GIT_FATAL_EXIT, workdirFailureText(linuxPath));
152
+ /**
153
+ * Take the delegated discovery call's streams over so their stdout gets the
154
+ * SAME UNC translation the agent path applies. The one-shot transport runs
155
+ * the same distro git, so an untranslated answer would hand the caller
156
+ * Linux absolute paths that only resolve correctly on the agent transport —
157
+ * a transport-dependent change review. The delegate's per-stream cut flags
158
+ * are carried into this facade's readers rather than flattened.
159
+ *
160
+ * @param delegate - the settled one-shot handle.
161
+ */
162
+ const takeOverDiscoveryOutput = (delegate) => {
163
+ const stdout = delegate.collected.stdout?.readFrom(0);
164
+ const stderr = delegate.collected.stderr?.readFrom(0);
165
+ state.delegate = undefined;
166
+ state.stdout = translateDiscoveryOutput(distro, Buffer.from(stdout?.text ?? "", "utf8"));
167
+ state.stderr = Buffer.from(stderr?.text ?? "", "utf8");
168
+ state.lossy = { stdout: stdout?.lossy === true, stderr: stderr?.lossy === true };
169
+ };
170
+ /**
171
+ * Delegate one agent-unavailable request to the one-shot handle, translating
172
+ * the relay's missing-directory warning and missing-program line into the
173
+ * same explicit failures the agent path produces. Any other delegated
174
+ * outcome passes through verbatim (its collected streams stay the
175
+ * delegate's).
176
+ *
177
+ * @returns the settled outcome.
178
+ */
179
+ const settleDelegate = async () => {
180
+ const delegate = spawnFallback();
181
+ state.delegate = delegate;
182
+ const outcome = await delegate.done;
183
+ if (outcome.exitCode === null)
184
+ return outcome;
185
+ const text = delegate.collected.stderr?.readFrom(0).text ?? "";
186
+ const missingDir = workdirFailure("", text);
187
+ if (missingDir !== undefined)
188
+ return settleWorkdirMissing(missingDir);
189
+ const relayFailure = execProgramFailure("", text);
190
+ if (relayFailure !== undefined)
191
+ return settleProgramMissing(relayFailure);
192
+ if (discovery)
193
+ takeOverDiscoveryOutput(delegate);
194
+ return outcome;
195
+ };
71
196
  const handle = {
72
197
  get collected() {
73
198
  if (state.delegate !== undefined)
@@ -78,21 +203,29 @@ export function gitExecutionHandle({ agent, cwd, argv, env, stdin, caps, distro,
78
203
  let result;
79
204
  try {
80
205
  result = await agent.exec({ cwd, argv, env, stdin, maxOutputBytes: wireCap, signal: controller.signal });
81
- state.stdout = discovery ? translateDiscoveryOutput(distro ?? "", result.stdout) : result.stdout;
206
+ state.stdout = discovery ? translateDiscoveryOutput(distro, result.stdout) : result.stdout;
82
207
  state.stderr = result.stderr;
83
208
  }
84
209
  catch (error) {
85
- if (!(error instanceof AgentUnavailableError)) {
86
- if (controller.signal.aborted) {
87
- // Our kill() or the caller's cancellation: the killed outcome the
88
- // one-shot path reports, not a failure.
89
- return { exitCode: null, signal: "SIGTERM" };
90
- }
91
- throw error;
210
+ if (controller.signal.aborted) {
211
+ // Our kill() or the caller's cancellation: the killed outcome the
212
+ // one-shot path reports, not a failure.
213
+ return { exitCode: null, signal: "SIGTERM" };
214
+ }
215
+ if (error instanceof CwdError) {
216
+ // The directory is gone: git's own fatal dialect, so the snapshot
217
+ // reports the path instead of rejecting as a provider failure.
218
+ return settleWorkdirMissing(error.linuxPath);
92
219
  }
93
- const delegate = spawnFallback();
94
- state.delegate = delegate;
95
- return delegate.done;
220
+ if (error instanceof SpawnError) {
221
+ // The agent could not start the program. The native agent reports
222
+ // both a missing executable and a missing workdir this way, so the
223
+ // message names both and the remedy makes it actionable.
224
+ return settleProgramMissing(error.message);
225
+ }
226
+ if (!(error instanceof AgentUnavailableError))
227
+ throw error;
228
+ return await settleDelegate();
96
229
  }
97
230
  return { exitCode: result.exitCode, signal: null };
98
231
  })(),
package/lib/listing.d.ts CHANGED
@@ -111,6 +111,23 @@ export declare function boundedInsert<T extends {
111
111
  * @returns the argv for the agent or a `wsl.exe --exec` launch.
112
112
  */
113
113
  export declare function dirListingArgv(linuxDir: string): string[];
114
+ /**
115
+ * The distro-side argv one picker directory is created with.
116
+ *
117
+ * The target is named in ABSOLUTE form even though the agent path also sets a
118
+ * working directory: `wsl.exe --cd <missing>` does not fail — it warns, runs
119
+ * the command in `/` and exits 0 — so a relative `mkdir -- <name>` on the
120
+ * one-shot fallback would create `/name` while the picker reports the UNC
121
+ * target as created (when the distro user can write `/`, e.g. a root-default
122
+ * image). The absolute path makes the target independent of the directory the
123
+ * transport actually entered; the agent path keeps the same argv, and its
124
+ * `cwd` still supplies the existence check.
125
+ *
126
+ * @param linuxParent - the absolute Linux parent directory.
127
+ * @param name - the validated single path segment to create.
128
+ * @returns the argv for the agent or a `wsl.exe --exec` launch.
129
+ */
130
+ export declare function distroMkdirArgv(linuxParent: string, name: string): string[];
114
131
  /**
115
132
  * Parse one `find -print0` listing into the picker's rows.
116
133
  *
package/lib/listing.js CHANGED
@@ -148,6 +148,26 @@ export function boundedInsert(window, candidate, keep) {
148
148
  export function dirListingArgv(linuxDir) {
149
149
  return ["find", "-L", linuxDir, "-maxdepth", "1", "-mindepth", "1", "-type", "d", "-print0"];
150
150
  }
151
+ /**
152
+ * The distro-side argv one picker directory is created with.
153
+ *
154
+ * The target is named in ABSOLUTE form even though the agent path also sets a
155
+ * working directory: `wsl.exe --cd <missing>` does not fail — it warns, runs
156
+ * the command in `/` and exits 0 — so a relative `mkdir -- <name>` on the
157
+ * one-shot fallback would create `/name` while the picker reports the UNC
158
+ * target as created (when the distro user can write `/`, e.g. a root-default
159
+ * image). The absolute path makes the target independent of the directory the
160
+ * transport actually entered; the agent path keeps the same argv, and its
161
+ * `cwd` still supplies the existence check.
162
+ *
163
+ * @param linuxParent - the absolute Linux parent directory.
164
+ * @param name - the validated single path segment to create.
165
+ * @returns the argv for the agent or a `wsl.exe --exec` launch.
166
+ */
167
+ export function distroMkdirArgv(linuxParent, name) {
168
+ const base = linuxParent.endsWith("/") ? linuxParent : `${linuxParent}/`;
169
+ return ["mkdir", "--", `${base}${name}`];
170
+ }
151
171
  /**
152
172
  * Parse one `find -print0` listing into the picker's rows.
153
173
  *
package/lib/messages.d.ts CHANGED
@@ -92,6 +92,33 @@ declare const en: {
92
92
  workdir: string;
93
93
  distro: string;
94
94
  }) => string;
95
+ /**
96
+ * `search-exec`: the agent could not start the search program. The native
97
+ * agent cannot tell a missing executable from a missing directory, so both
98
+ * causes and the install remedy are named.
99
+ */
100
+ searchProgramMissing: ({ program, distro, detail }: {
101
+ program: string;
102
+ distro: string;
103
+ detail: string;
104
+ }) => string;
105
+ /** `search-exec`: the working directory a search asked for does not exist. */
106
+ searchWorkdirMissing: ({ path }: {
107
+ path: string;
108
+ }) => string;
109
+ /**
110
+ * `git-exec`: the agent could not start git. The native agent cannot tell a
111
+ * missing executable from a missing directory, so both causes and the
112
+ * install remedy are named.
113
+ */
114
+ gitProgramMissing: ({ distro, detail }: {
115
+ distro: string;
116
+ detail: string;
117
+ }) => string;
118
+ /** `git-exec`: the working directory a git snapshot asked for does not exist. */
119
+ gitWorkdirMissing: ({ path }: {
120
+ path: string;
121
+ }) => string;
95
122
  /**
96
123
  * `auto-preset`: a distro workspace is recorded as Windows access (9p), so
97
124
  * the session runs the host preset. The model-facing half of the reminder;
package/lib/messages.js CHANGED
@@ -69,6 +69,24 @@ const en = {
69
69
  workdirAnotherDistro: ({ workdir, distro }) => `"${workdir}" names a workspace in another WSL distro, and this profile pins its commands to "${distro}" — ` +
70
70
  `running them here would act on a different machine's tree. Open a session in that distro, ` +
71
71
  `or point cwd/workdir at this distro.`,
72
+ /**
73
+ * `search-exec`: the agent could not start the search program. The native
74
+ * agent cannot tell a missing executable from a missing directory, so both
75
+ * causes and the install remedy are named.
76
+ */
77
+ searchProgramMissing: ({ program, distro, detail }) => `${program} could not be started inside distro "${distro}" (${detail}). Commands run with wsl.exe's default PATH, so a user-local install under ~/.local/bin is invisible, and the search directory may also be gone. ` +
78
+ `Install ripgrep with "scripts/bootstrap.sh ${distro} --install" (from the package), or with the distro's own package manager.`,
79
+ /** `search-exec`: the working directory a search asked for does not exist. */
80
+ searchWorkdirMissing: ({ path }) => `The search directory "${path}" does not exist inside the distro. Create it, or point the session's working directory at a directory that exists.`,
81
+ /**
82
+ * `git-exec`: the agent could not start git. The native agent cannot tell a
83
+ * missing executable from a missing directory, so both causes and the
84
+ * install remedy are named.
85
+ */
86
+ gitProgramMissing: ({ distro, detail }) => `git could not be started inside distro "${distro}" (${detail}). Commands run with wsl.exe's default PATH, so a user-local install under ~/.local/bin is invisible, and the snapshot directory may also be gone. ` +
87
+ `Install git with "scripts/bootstrap.sh ${distro} --install" (from the package), or with the distro's own package manager.`,
88
+ /** `git-exec`: the working directory a git snapshot asked for does not exist. */
89
+ gitWorkdirMissing: ({ path }) => `The git snapshot directory "${path}" does not exist inside the distro. Create it, or point the session's working directory at a directory that exists.`,
72
90
  /**
73
91
  * `auto-preset`: a distro workspace is recorded as Windows access (9p), so
74
92
  * the session runs the host preset. The model-facing half of the reminder;
@@ -99,7 +117,7 @@ const en = {
99
117
  /** `wsl_doctor` digest: one summary line for the checks the run's scope never executed; `reason` says why (the run's scope profile). */
100
118
  doctorDigestSkipRow: ({ n, reason, ids }) => `[SKIP] not run in this scope — ${reason} (${n}): ${ids}`,
101
119
  /** `wsl_doctor` digest: the scope reason for a quick run's skip line. */
102
- doctorSkipReasonQuick: () => "the quick profile covers first-command prerequisites only",
120
+ doctorSkipReasonQuick: () => "the quick profile covers the prerequisites and the optional tools only",
103
121
  /** `wsl_doctor` digest: the scope reason for a section-filtered run's skip line. */
104
122
  doctorSkipReasonSections: ({ sections }) => `the run covered only: ${sections}`,
105
123
  /** `wsl_doctor` digest: the scope reason when the report recorded none. */
@@ -146,6 +164,12 @@ const zh = {
146
164
  `请创建该目录,或将 \`cwd\`(或请求的 \`workdir\`)指向一个已存在的目录。`,
147
165
  workdirAnotherDistro: ({ workdir, distro }) => `"${workdir}" 指向另一个 WSL 发行版中的工作区,而本 profile 将命令固定在 "${distro}" —— ` +
148
166
  `在这里运行会作用于另一台机器的目录树。请在该发行版中打开会话,或将 cwd/workdir 指向本发行版。`,
167
+ searchProgramMissing: ({ program, distro, detail }) => `无法在发行版 "${distro}" 内启动 ${program}(${detail})。命令使用 wsl.exe 给出的默认 PATH,因此安装在 ~/.local/bin 下的用户级版本不可见;搜索目录也可能已不存在。` +
168
+ `请用 "scripts/bootstrap.sh ${distro} --install"(随包提供)安装 ripgrep,或使用该发行版自己的包管理器。`,
169
+ searchWorkdirMissing: ({ path }) => `搜索目录 "${path}" 在发行版中不存在。请创建它,或将会话的工作目录指向一个已存在的目录。`,
170
+ gitProgramMissing: ({ distro, detail }) => `无法在发行版 "${distro}" 内启动 git(${detail})。命令使用 wsl.exe 给出的默认 PATH,因此安装在 ~/.local/bin 下的用户级版本不可见;快照目录也可能已不存在。` +
171
+ `请用 "scripts/bootstrap.sh ${distro} --install"(随包提供)安装 git,或使用该发行版自己的包管理器。`,
172
+ gitWorkdirMissing: ({ path }) => `git 快照目录 "${path}" 在发行版中不存在。请创建它,或将会话的工作目录指向一个已存在的目录。`,
149
173
  hostModeWindowsAccess: ({ cwd, distro }) => `工作区 "${cwd}" 位于 WSL 发行版 "${distro}" 内,但被记录为 Windows 访问工作区,` +
150
174
  `因此本会话运行在宿主(Windows)环境:命令经 PowerShell 执行,文件访问经过 9p 共享,发行版的 Linux 工具链不可用。` +
151
175
  `不要在此假设 Linux 命令、路径或工具;如需在发行版内运行,须由操作者以 WSL preset 在本工作区新开会话。`,
@@ -160,7 +184,7 @@ const zh = {
160
184
  doctorDigestNotRunLabel: () => "(不在本次范围)",
161
185
  doctorDigestSessionLabel: ({ name }) => `${name}(当前会话的 distro)`,
162
186
  doctorDigestSkipRow: ({ n, reason, ids }) => `[SKIP] 不在本次范围——${reason}(${n}):${ids}`,
163
- doctorSkipReasonQuick: () => "quick 档只探首条命令的前置项",
187
+ doctorSkipReasonQuick: () => "quick 档只探前置项与可选工具",
164
188
  doctorSkipReasonSections: ({ sections }) => `本次只运行了这些分区:${sections}`,
165
189
  doctorSkipReasonGeneric: () => "报告未记录运行范围",
166
190
  doctorSkipGated: ({ id, reason }) => `[SKIP] ${id}——被前置阻断:${reason}`,
@@ -0,0 +1,53 @@
1
+ /** The private env contract between an in-app spawner and `scripts/doctor.mjs`. */
2
+ export declare const DOCTOR_PEERS_ENV = "DSH_WSL_DOCTOR_PEERS";
3
+ /**
4
+ * The version declared by the nearest `package.json` above a resolved file.
5
+ *
6
+ * Exported for the coverage suite: the walk's two failure arms (a malformed
7
+ * manifest, and the filesystem root) are not reachable with real peers.
8
+ * @param file - one resolved module file.
9
+ * @returns the version, or undefined when no readable manifest declares one.
10
+ */
11
+ export declare function versionAbove(file: string): string | undefined;
12
+ /**
13
+ * Resolve one peer's version the way this process loads it.
14
+ *
15
+ * Exported for the coverage suite: a peer that does not export
16
+ * `./package.json` exercises the entry-file fallback.
17
+ *
18
+ * `require.resolve` runs through the host's profile resolution when there is
19
+ * one, so a linked plugin sees the installation's copies and a plain process
20
+ * sees whatever `node_modules` it would actually import. The package's
21
+ * `./package.json` export is preferred because it names the version directly;
22
+ * a package that does not export it still resolves by its entry file.
23
+ *
24
+ * @param require - the anchored resolver.
25
+ * @param name - the peer package.
26
+ * @returns the resolved version, or undefined when the peer is absent.
27
+ */
28
+ export declare function resolvedPeerVersion(require: NodeJS.Require, name: string): string | undefined;
29
+ /**
30
+ * The peer versions this process resolves.
31
+ *
32
+ * Deliberately uncached: a harness upgrade or a plugin-manager reload changes
33
+ * the answer, and one doctor spawn costs one small resolve per peer.
34
+ *
35
+ * @returns a name → version map; empty when the manifest or the peers are
36
+ * unreadable.
37
+ */
38
+ export declare function resolvedPeerVersions(): Record<string, string>;
39
+ /**
40
+ * Overlay the resolved peer set on one doctor child environment.
41
+ *
42
+ * The variable is set even when the map is empty: its **presence** is what
43
+ * tells the doctor that an in-app process already attempted resolution, so a
44
+ * peer missing from the map means "the host could not resolve it" and must be
45
+ * reported as unchecked — not looked up again in the plugin's physical tree,
46
+ * which may hold a stale copy. Absent means the standalone CLI, which has no
47
+ * host resolution and keeps its own lookup.
48
+ *
49
+ * @param env - the base environment (normally a copy of `process.env`).
50
+ * @param versions - the map; defaults to {@link resolvedPeerVersions}.
51
+ * @returns the child environment to spawn with.
52
+ */
53
+ export declare function withHostPeerVersions(env: NodeJS.ProcessEnv, versions?: Record<string, string>): NodeJS.ProcessEnv;
@@ -0,0 +1,137 @@
1
+ /**
2
+ * The peer set the spawning host process resolved, handed to the doctor CLI.
3
+ *
4
+ * The doctor is a separate process on purpose (see `scripts/doctor.mjs`), and
5
+ * a separate Node process resolves bare imports with Node's own lookup only.
6
+ * That is the wrong answer for a linked plugin: the host installs a profile
7
+ * resolution that projects a linked plugin's declared peers onto the
8
+ * installation's single copies, so the doctor's `createRequire` from the
9
+ * plugin directory can land on an unrelated `node_modules` above the mirror
10
+ * (or on nothing at all) while the plugin itself loads the host's copies.
11
+ * This module reads what the plugin process actually resolves — the same
12
+ * `createRequire` lookup, already intercepted by the host when one is
13
+ * installed — and passes it to the child in {@link DOCTOR_PEERS_ENV}. The
14
+ * variable's presence, not its size, is the signal: the map can be partial or
15
+ * empty (a peer the host could not resolve), and the doctor still treats it as
16
+ * authoritative instead of looking the missing peer up again beside the
17
+ * plugin. The standalone CLI, which has no host and therefore no variable,
18
+ * keeps its own lookup and reports peers it cannot see as unchecked.
19
+ *
20
+ * This is a TypeScript source built to `lib/peer-versions.js`; edit THIS file
21
+ * and run `pnpm run build` — the artifact under `lib/` is generated, and
22
+ * `pnpm test` fails when it drifts.
23
+ *
24
+ * @module dsh-plugin-wsl-env/peer-versions
25
+ */
26
+ import { readFileSync } from "node:fs";
27
+ import { createRequire } from "node:module";
28
+ import { dirname, join } from "node:path";
29
+ import { fileURLToPath } from "node:url";
30
+ /** The private env contract between an in-app spawner and `scripts/doctor.mjs`. */
31
+ export const DOCTOR_PEERS_ENV = "DSH_WSL_DOCTOR_PEERS";
32
+ /** The installed plugin root (`lib/`'s parent), the anchor for its own manifest. */
33
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
34
+ /**
35
+ * The peer names this package declares, in manifest order.
36
+ * @returns the names; an unreadable manifest lists none.
37
+ */
38
+ function peerNames() {
39
+ try {
40
+ // The manifest is this package's own file; the shape is the declaration it ships.
41
+ const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
42
+ return Object.keys(manifest.peerDependencies ?? {});
43
+ }
44
+ catch {
45
+ return [];
46
+ }
47
+ }
48
+ /**
49
+ * The version declared by the nearest `package.json` above a resolved file.
50
+ *
51
+ * Exported for the coverage suite: the walk's two failure arms (a malformed
52
+ * manifest, and the filesystem root) are not reachable with real peers.
53
+ * @param file - one resolved module file.
54
+ * @returns the version, or undefined when no readable manifest declares one.
55
+ */
56
+ export function versionAbove(file) {
57
+ let directory = dirname(file);
58
+ for (;;) {
59
+ try {
60
+ // A peer's manifest is its declaration file; only the version string is read.
61
+ const manifest = JSON.parse(readFileSync(join(directory, "package.json"), "utf8"));
62
+ return typeof manifest.version === "string" ? manifest.version : undefined;
63
+ }
64
+ catch {
65
+ const parent = dirname(directory);
66
+ if (parent === directory)
67
+ return undefined;
68
+ directory = parent;
69
+ }
70
+ }
71
+ }
72
+ /**
73
+ * Resolve one peer's version the way this process loads it.
74
+ *
75
+ * Exported for the coverage suite: a peer that does not export
76
+ * `./package.json` exercises the entry-file fallback.
77
+ *
78
+ * `require.resolve` runs through the host's profile resolution when there is
79
+ * one, so a linked plugin sees the installation's copies and a plain process
80
+ * sees whatever `node_modules` it would actually import. The package's
81
+ * `./package.json` export is preferred because it names the version directly;
82
+ * a package that does not export it still resolves by its entry file.
83
+ *
84
+ * @param require - the anchored resolver.
85
+ * @param name - the peer package.
86
+ * @returns the resolved version, or undefined when the peer is absent.
87
+ */
88
+ export function resolvedPeerVersion(require, name) {
89
+ try {
90
+ return versionAbove(require.resolve(`${name}/package.json`));
91
+ }
92
+ catch {
93
+ // Fall through to the entry file; not every package exports its manifest.
94
+ }
95
+ try {
96
+ return versionAbove(require.resolve(name));
97
+ }
98
+ catch {
99
+ return undefined;
100
+ }
101
+ }
102
+ /**
103
+ * The peer versions this process resolves.
104
+ *
105
+ * Deliberately uncached: a harness upgrade or a plugin-manager reload changes
106
+ * the answer, and one doctor spawn costs one small resolve per peer.
107
+ *
108
+ * @returns a name → version map; empty when the manifest or the peers are
109
+ * unreadable.
110
+ */
111
+ export function resolvedPeerVersions() {
112
+ const require = createRequire(join(ROOT, "package.json"));
113
+ const versions = {};
114
+ for (const name of peerNames()) {
115
+ const version = resolvedPeerVersion(require, name);
116
+ if (version !== undefined)
117
+ versions[name] = version;
118
+ }
119
+ return versions;
120
+ }
121
+ /**
122
+ * Overlay the resolved peer set on one doctor child environment.
123
+ *
124
+ * The variable is set even when the map is empty: its **presence** is what
125
+ * tells the doctor that an in-app process already attempted resolution, so a
126
+ * peer missing from the map means "the host could not resolve it" and must be
127
+ * reported as unchecked — not looked up again in the plugin's physical tree,
128
+ * which may hold a stale copy. Absent means the standalone CLI, which has no
129
+ * host resolution and keeps its own lookup.
130
+ *
131
+ * @param env - the base environment (normally a copy of `process.env`).
132
+ * @param versions - the map; defaults to {@link resolvedPeerVersions}.
133
+ * @returns the child environment to spawn with.
134
+ */
135
+ export function withHostPeerVersions(env, versions = resolvedPeerVersions()) {
136
+ return { ...env, [DOCTOR_PEERS_ENV]: JSON.stringify(versions) };
137
+ }
package/lib/picker.js CHANGED
@@ -53,10 +53,10 @@ import { join, resolve } from "node:path";
53
53
  import z from "@deepseek-ai/schemastery";
54
54
  import { DirectoryPicker, DirectoryPickerError } from "@deepseek-ai/dsh-host-directory-picker";
55
55
  import { UNC_PROVIDER_ROOT, distroRoot, isProviderRoot, isWslUnc, uncToPosix } from "./paths.js";
56
- import { breadcrumbs, boundedInsert, dirListingArgv, fullyQualified, parseDirListing } from "./listing.js";
56
+ import { breadcrumbs, boundedInsert, dirListingArgv, distroMkdirArgv, fullyQualified, parseDirListing } from "./listing.js";
57
57
  import { listDistros, linuxHome, runCapture } from "./wsl.js";
58
58
  import { sharedAgent } from "./agent-shared.js";
59
- import { AgentUnavailableError } from "./agent-errors.js";
59
+ import { AgentUnavailableError, CwdError, SpawnError } from "./agent-errors.js";
60
60
  /** How long a resolved distro list stays fresh before it is queried again. */
61
61
  const DEFAULT_DISTRO_CACHE_MS = 5_000;
62
62
  /**
@@ -412,13 +412,21 @@ export class WslDirectoryPicker extends DirectoryPicker {
412
412
  stdout = result.stdout;
413
413
  }
414
414
  catch (error) {
415
- if (!(error instanceof AgentUnavailableError))
416
- throw error;
417
- try {
418
- stdout = await runCapture([this.config.wslPath, "-d", parsed.distro, "--cd", linuxDir, "--exec", ...dirListingArgv(linuxDir)], signal);
415
+ if (error instanceof AgentUnavailableError) {
416
+ try {
417
+ stdout = await runCapture([this.config.wslPath, "-d", parsed.distro, "--cd", linuxDir, "--exec", ...dirListingArgv(linuxDir)], signal);
418
+ }
419
+ catch (fallbackError) {
420
+ throw new DirectoryPickerError("directory-unreadable", target, `cannot list "${target}": ${messageOf(fallbackError)}`);
421
+ }
422
+ }
423
+ else if (error instanceof CwdError || error instanceof SpawnError) {
424
+ // The agent could not enter the directory (or start the program): a
425
+ // picker failure with the path, not an opaque provider error.
426
+ throw new DirectoryPickerError("directory-unreadable", target, `cannot list "${target}": ${messageOf(error)}`);
419
427
  }
420
- catch (fallbackError) {
421
- throw new DirectoryPickerError("directory-unreadable", target, `cannot list "${target}": ${messageOf(fallbackError)}`);
428
+ else {
429
+ throw error;
422
430
  }
423
431
  }
424
432
  return parseDirListing(stdout, linuxDir, target, this.config.maxEntries);
@@ -524,7 +532,7 @@ export class WslDirectoryPicker extends DirectoryPicker {
524
532
  const parsed = uncToPosix(parent);
525
533
  const linuxParent = parsed.linuxPath.length > 0 ? parsed.linuxPath : "/";
526
534
  try {
527
- const result = await sharedAgent(parsed.distro).exec({ cwd: linuxParent, argv: ["mkdir", "--", name], timeoutMs: 10_000 });
535
+ const result = await sharedAgent(parsed.distro).exec({ cwd: linuxParent, argv: distroMkdirArgv(linuxParent, name), timeoutMs: 10_000 });
528
536
  if (result.exitCode === 0)
529
537
  return target;
530
538
  const detail = result.stderr.toString("utf8");
@@ -535,18 +543,24 @@ export class WslDirectoryPicker extends DirectoryPicker {
535
543
  catch (error) {
536
544
  if (error instanceof DirectoryPickerError)
537
545
  throw error;
538
- if (!(error instanceof AgentUnavailableError))
539
- throw error;
540
- try {
541
- await runCapture([this.config.wslPath, "-d", parsed.distro, "--cd", linuxParent, "--exec", "mkdir", "--", name]);
542
- return target;
546
+ if (error instanceof AgentUnavailableError) {
547
+ try {
548
+ // Absolute target: a `--cd` that silently fell back to `/` must not
549
+ // turn this into a creation somewhere else.
550
+ await runCapture([this.config.wslPath, "-d", parsed.distro, "--cd", linuxParent, "--exec", ...distroMkdirArgv(linuxParent, name)]);
551
+ return target;
552
+ }
553
+ catch (fallbackError) {
554
+ const message = messageOf(fallbackError);
555
+ if (/File exists/i.test(message))
556
+ throw new DirectoryPickerError("directory-exists", target, `${target} already exists`);
557
+ throw new DirectoryPickerError("directory-create-failed", target, `cannot create "${target}": ${message}`);
558
+ }
543
559
  }
544
- catch (fallbackError) {
545
- const message = messageOf(fallbackError);
546
- if (/File exists/i.test(message))
547
- throw new DirectoryPickerError("directory-exists", target, `${target} already exists`);
548
- throw new DirectoryPickerError("directory-create-failed", target, `cannot create "${target}": ${message}`);
560
+ if (error instanceof CwdError || error instanceof SpawnError) {
561
+ throw new DirectoryPickerError("directory-create-failed", target, `cannot create "${target}": ${messageOf(error)}`);
549
562
  }
563
+ throw error;
550
564
  }
551
565
  }
552
566
  }