dsh-plugin-wsl-env 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/messages.js CHANGED
@@ -69,6 +69,39 @@ 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
+ /** `wsl_doctor` digest: the verdict line. `verdict` is the report's own `ready`/`blocked`. */
73
+ doctorDigestVerdict: ({ verdict }) => `wsl doctor verdict: ${verdict}`,
74
+ /** `wsl_doctor` digest: the host-wide group heading. */
75
+ doctorDigestHostLabel: () => "(host — Windows and global checks)",
76
+ /** `wsl_doctor` digest: the heading for checks the run's scope never executed. */
77
+ doctorDigestNotRunLabel: () => "(not run in this scope)",
78
+ /** `wsl_doctor` digest: marks which distro group is the session's own. */
79
+ doctorDigestSessionLabel: ({ name }) => `${name} (this session's distro)`,
80
+ /** `wsl_doctor` digest: one summary line for the checks the run's scope never executed; `reason` says why (the run's scope profile). */
81
+ doctorDigestSkipRow: ({ n, reason, ids }) => `[SKIP] not run in this scope — ${reason} (${n}): ${ids}`,
82
+ /** `wsl_doctor` digest: the scope reason for a quick run's skip line. */
83
+ doctorSkipReasonQuick: () => "the quick profile covers first-command prerequisites only",
84
+ /** `wsl_doctor` digest: the scope reason for a section-filtered run's skip line. */
85
+ doctorSkipReasonSections: ({ sections }) => `the run covered only: ${sections}`,
86
+ /** `wsl_doctor` digest: the scope reason when the report recorded none. */
87
+ doctorSkipReasonGeneric: () => "no scope recorded for this report",
88
+ /** `wsl_doctor` digest: one line per check a failed prerequisite gated out; `reason` names the blocker. */
89
+ doctorSkipGated: ({ id, reason }) => `[SKIP] ${id} — skipped: ${reason}`,
90
+ /** `wsl_doctor` digest: per-group tallies, one entry per non-zero status. */
91
+ doctorTallyOk: ({ n }) => `${n} ok`,
92
+ doctorTallyWarn: ({ n }) => `${n} warn`,
93
+ doctorTallyFail: ({ n }) => `${n} fail`,
94
+ doctorTallyUnknown: ({ n }) => `${n} unknown`,
95
+ doctorTallyInfo: ({ n }) => `${n} info`,
96
+ doctorTallySkipped: ({ n }) => `${n} skipped`,
97
+ /** `wsl_doctor` digest: the remedy prefix under a failed check. */
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",
101
+ /** `wsl_doctor` digest: the blocked note (the rerun is the re-verification). */
102
+ doctorDigestNoteBlocked: () => "apply each remedy above, then call this tool again — the re-run is the re-verification",
103
+ /** `wsl_doctor` digest: the blocked summary tail; `noneBlocking` is the fixed clause. */
104
+ doctorDigestBlockedTail: ({ blockers, warnings, skipped, note }) => `blocked by: ${blockers}; ${warnings} warning(s), ${skipped} skipped leg(s) — none blocking; ${note}`,
72
105
  };
73
106
  /** The Chinese catalog; the type keeps every key and parameter in step with `en`. */
74
107
  const zh = {
@@ -94,6 +127,25 @@ const zh = {
94
127
  `请创建该目录,或将 \`cwd\`(或请求的 \`workdir\`)指向一个已存在的目录。`,
95
128
  workdirAnotherDistro: ({ workdir, distro }) => `"${workdir}" 指向另一个 WSL 发行版中的工作区,而本 profile 将命令固定在 "${distro}" —— ` +
96
129
  `在这里运行会作用于另一台机器的目录树。请在该发行版中打开会话,或将 cwd/workdir 指向本发行版。`,
130
+ doctorDigestVerdict: ({ verdict }) => `wsl doctor 裁决:${verdict}`,
131
+ doctorDigestHostLabel: () => "(宿主——Windows 与全局检查)",
132
+ doctorDigestNotRunLabel: () => "(不在本次范围)",
133
+ doctorDigestSessionLabel: ({ name }) => `${name}(当前会话的 distro)`,
134
+ doctorDigestSkipRow: ({ n, reason, ids }) => `[SKIP] 不在本次范围——${reason}(${n}):${ids}`,
135
+ doctorSkipReasonQuick: () => "quick 档只探首条命令的前置项",
136
+ doctorSkipReasonSections: ({ sections }) => `本次只运行了这些分区:${sections}`,
137
+ doctorSkipReasonGeneric: () => "报告未记录运行范围",
138
+ doctorSkipGated: ({ id, reason }) => `[SKIP] ${id}——被前置阻断:${reason}`,
139
+ doctorTallyOk: ({ n }) => `通过 ${n}`,
140
+ doctorTallyWarn: ({ n }) => `警告 ${n}`,
141
+ doctorTallyFail: ({ n }) => `失败 ${n}`,
142
+ doctorTallyUnknown: ({ n }) => `未知 ${n}`,
143
+ doctorTallyInfo: ({ n }) => `信息 ${n}`,
144
+ doctorTallySkipped: ({ n }) => `跳过 ${n}`,
145
+ doctorDigestFixPrefix: ({ remedy }) => ` 修复: ${remedy}`,
146
+ doctorDigestNoteReady: () => "首条命令应能成功;如需可附加的报告文件,运行 CLI(pnpm run doctor --bundle <path>)",
147
+ doctorDigestNoteBlocked: () => "应用上方每条修复,然后再次调用本工具——重跑即复核",
148
+ doctorDigestBlockedTail: ({ blockers, warnings, skipped, note }) => `阻断项:${blockers};${warnings} 个警告,${skipped} 个跳过腿——均不阻断;${note}`,
97
149
  };
98
150
  /** The active language; English until a settings service reports otherwise. */
99
151
  let current = "en";
@@ -160,9 +212,20 @@ export function resolveMessagesLocale(preference) {
160
212
  * which also covers the `locale` entry activating after this row did. A read
161
213
  * that throws keeps the previous language: this is presentation, not gating.
162
214
  *
215
+ * A browser whose user never picked a language in Settings has NO persisted
216
+ * `locale.preference` — its Chinese UI came from the navigator's provisional
217
+ * match, which the Host settings never record. For that case the fallback
218
+ * reads the process's ICU default locale (Electron: the OS UI language), so
219
+ * a zh-CN Windows with a provisional-Chinese UI still renders Chinese. An
220
+ * explicit Settings choice always wins over the fallback.
221
+ *
163
222
  * @param ctx - the row's composition context.
164
223
  */
165
224
  export function installMessagesLocale(ctx) {
225
+ // Provisional fallback first: the settings read below is asynchronous (it
226
+ // waits for the injection), and the OS language is the best guess until a
227
+ // stored preference replaces it.
228
+ configureMessagesLocale(hostFallbackLocale());
166
229
  if (typeof ctx.inject !== "function")
167
230
  return;
168
231
  ctx.inject(["settings"], (scope) => {
@@ -174,8 +237,12 @@ export function installMessagesLocale(ctx) {
174
237
  const read = () => {
175
238
  try {
176
239
  const row = settings.describe().find((entry) => entry.ns === "locale");
177
- if (row === undefined)
240
+ if (row === undefined) {
241
+ // No stored preference (the provisional-UI case): the OS fallback
242
+ // stands. It was already applied above; keep it.
243
+ configureMessagesLocale(hostFallbackLocale());
178
244
  return;
245
+ }
179
246
  // The descriptor's value is the entry's projected volatile form —
180
247
  // `{ preference?: string }` for the locale entry.
181
248
  const preference = row.value?.preference;
@@ -197,3 +264,29 @@ export function installMessagesLocale(ctx) {
197
264
  export function resetMessagesLocaleForTests() {
198
265
  current = "en";
199
266
  }
267
+ /**
268
+ * The no-settings fallback: the process's ICU default locale, which in the
269
+ * desktop app follows the OS UI language (a zh-CN Windows yields `zh-CN`).
270
+ * Under Node's small-icu builds this is `en-US`, which maps to English — the
271
+ * previous default. Exported for tests.
272
+ *
273
+ * @returns {"en" | "zh"} the language the OS-level locale selects.
274
+ */
275
+ export function hostFallbackLocale() {
276
+ try {
277
+ return localeFromTag(Intl.DateTimeFormat().resolvedOptions().locale);
278
+ }
279
+ catch {
280
+ return "en";
281
+ }
282
+ }
283
+ /**
284
+ * Map one BCP 47-style tag onto a catalog language: `zh*` renders Chinese,
285
+ * everything else English.
286
+ *
287
+ * @param tag - the locale tag (may be empty).
288
+ * @returns {"en" | "zh"} the catalog language the tag selects.
289
+ */
290
+ function localeFromTag(tag) {
291
+ return /^zh/iu.test(tag) ? "zh" : "en";
292
+ }
@@ -0,0 +1,105 @@
1
+ export declare const name = "wsl-doctor-command";
2
+ /**
3
+ * No required inject: a headless deployment has no commands registry, and a
4
+ * required inject would fail the whole composition mount over a surface this
5
+ * row cannot use. The registry resolves per mount through the optional
6
+ * `ctx.get` (cordis answers undefined for an absent name; a `get` needs no
7
+ * inject), with a plain property as the test seam — the same shape the
8
+ * `wsl_doctor` tool uses for its optional collector.
9
+ */
10
+ export declare const inject: string[];
11
+ /** The host commands registry slice this row consumes. */
12
+ export interface CommandsRegistrySlice {
13
+ register: (definition: WslDoctorCommandDefinition) => unknown;
14
+ }
15
+ /** The invocation face the registry hands a handler. */
16
+ export interface WslDoctorCommandInvocation {
17
+ /** The receiving agent, when the command ran against a session. */
18
+ agent?: unknown;
19
+ /** Everything after the command name, separator whitespace trimmed. */
20
+ rawInput: string;
21
+ /** The dispatcher's abort signal; cancelling stops awaiting and kills the child. */
22
+ signal?: AbortSignal;
23
+ }
24
+ /** The command definition face this row registers. */
25
+ export interface WslDoctorCommandDefinition {
26
+ name: string;
27
+ description: string;
28
+ input?: {
29
+ hint: string;
30
+ };
31
+ handler: (invocation: WslDoctorCommandInvocation) => Promise<WslDoctorCommandResult>;
32
+ }
33
+ /** The settled result the adapter renders detached from model history. */
34
+ export interface WslDoctorCommandResult {
35
+ kind: "success" | "error";
36
+ text: string;
37
+ }
38
+ /** The context slice this service consumes. */
39
+ export type WslDoctorCommandContext = {
40
+ /** The commands registry, when the deployment has a command adapter. */
41
+ commands?: CommandsRegistrySlice;
42
+ /** The harness's cwd service, used to name the session's distro. */
43
+ workingDirectory?: {
44
+ ensure: (agent: unknown, signal?: unknown) => Promise<string>;
45
+ };
46
+ /** Optional cordis-style lookup: how production resolves both without an inject. */
47
+ get?: (name: string) => unknown;
48
+ /** The test seam: a provided CLI runner replaces the real subprocess. */
49
+ doctorCli?: DoctorCliRunner;
50
+ };
51
+ /** The CLI runner seam: argv in (node-less — the runner owns the runtime), JSON text out. */
52
+ export type DoctorCliRunner = (argv: string[], signal?: AbortSignal) => Promise<string>;
53
+ /** The parsed `/wsl-doctor` line. */
54
+ export interface ParsedDoctorInput {
55
+ /** quick → `--quick`; full → no flag; section → `--sections <name>`. */
56
+ mode: "quick" | "full" | "section";
57
+ /** The section name, when `mode` is `"section"`. */
58
+ section?: string;
59
+ /** The explicit distro, or empty to resolve from the session's cwd. */
60
+ distro: string;
61
+ }
62
+ /** The doctor CLI this row spawns, resolved from the built module's package root. */
63
+ export declare const DOCTOR_SCRIPT: string;
64
+ /** The usage text a grammar violation settles with. */
65
+ export declare const USAGE: string;
66
+ /**
67
+ * Parse the raw input after the command name. Tokens: one mode word or
68
+ * section name, plus an optional `--distro <name>` / `--distro=<name>`; a
69
+ * second bare token is accepted as the distro name.
70
+ *
71
+ * @param rawInput - everything after the command name.
72
+ * @returns the parsed mode, optional section, and optional distro.
73
+ * @throws when a token matches nothing — the caller settles usage text.
74
+ */
75
+ export declare function parseDoctorInput(rawInput: string): ParsedDoctorInput;
76
+ /**
77
+ * The default CLI runner: spawn the standalone doctor as a host subprocess.
78
+ * `process.execPath` is the Electron binary inside the harness, so
79
+ * `ELECTRON_RUN_AS_NODE=1` turns it into plain node for the child; under a
80
+ * plain node runtime the variable is ignored. Exit code 1 is a *blocked
81
+ * verdict*, which is a successful diagnosis — the JSON on stdout still parses;
82
+ * only a spawn failure or unparseable output is an infrastructure error.
83
+ *
84
+ * @param argv - flags after the script path (no node, no script — added here).
85
+ * @param signal - the dispatcher's abort signal; abort kills the child.
86
+ * @returns the CLI's stdout (one JSON report).
87
+ */
88
+ export declare function runDoctorCli(argv: string[], signal?: AbortSignal): Promise<string>;
89
+ /**
90
+ * Format the CLI's JSON report into the itemized text the UI renders — the
91
+ * same digest the `wsl_doctor` tool returns, so both surfaces itemize every
92
+ * check identically.
93
+ *
94
+ * @param json - the CLI's stdout, one versioned JSON report.
95
+ * @param distro - the distro the run named, for the session-distro markers.
96
+ * @returns the rendered report text.
97
+ */
98
+ export declare function formatDoctorReport(json: string, distro: string): string;
99
+ /**
100
+ * Mount the command.
101
+ *
102
+ * @param ctx - the cordis context (the composition root, where the commands
103
+ * registry and the harness cwd service are reachable).
104
+ */
105
+ export declare function apply(ctx: WslDoctorCommandContext): Promise<void>;
@@ -0,0 +1,240 @@
1
+ /**
2
+ * The `/wsl-doctor` UI command: the human runs the environment doctor through
3
+ * the command plane — the browser button drops a `/wsl-doctor` line, the
4
+ * commands registry executes it against a session, and the settled text
5
+ * renders in the UI detached from model history. No model turn happens: the
6
+ * command and its output add no tokens and never enter a request (the
7
+ * `dsh-commands` contract), which is the point — the diagnosis must not
8
+ * depend on the plugin's model-facing runtime being healthy.
9
+ *
10
+ * The handler does NOT collect the report in-process. It spawns the
11
+ * standalone doctor CLI (`scripts/doctor.mjs --json`) as a host subprocess:
12
+ * the CLI loads no peer dependency and no host service (its two peer-tainted
13
+ * imports are inlined and drift-pinned by test), so a diagnosis answers even
14
+ * when the plugin's own module graph is the thing that is broken. Formatting
15
+ * reuses `digestReport`/`renderDigest` from the tool module so the UI command
16
+ * and the model tool present identical itemized output.
17
+ *
18
+ * Grammar: `/wsl-doctor [quick|full|<section>] [--distro <name>]` — an empty
19
+ * line means quick. Without an explicit distro the session's own working
20
+ * directory names the distro; when that also fails, the CLI's effective
21
+ * configuration decides (the shipped preset's `auto` probes every installed
22
+ * distro). Unknown tokens settle as a direct command error with usage text.
23
+ *
24
+ * This is a TypeScript source built to `lib/wsl-doctor-command.js`; edit THIS
25
+ * file and run `pnpm run build` — the artifact under `lib/` is generated, and
26
+ * `pnpm test` fails when it drifts.
27
+ *
28
+ * @module dsh-plugin-wsl-env/wsl-doctor-command
29
+ */
30
+ import { spawn } from "node:child_process";
31
+ import { dirname, resolve } from "node:path";
32
+ import { fileURLToPath } from "node:url";
33
+ import { distroOfUnc } from "./distro-route.js";
34
+ import { digestReport, renderDigest, SECTIONS } from "./wsl-doctor-tool.js";
35
+ export const name = "wsl-doctor-command";
36
+ /**
37
+ * No required inject: a headless deployment has no commands registry, and a
38
+ * required inject would fail the whole composition mount over a surface this
39
+ * row cannot use. The registry resolves per mount through the optional
40
+ * `ctx.get` (cordis answers undefined for an absent name; a `get` needs no
41
+ * inject), with a plain property as the test seam — the same shape the
42
+ * `wsl_doctor` tool uses for its optional collector.
43
+ */
44
+ export const inject = [];
45
+ /** The doctor CLI this row spawns, resolved from the built module's package root. */
46
+ export const DOCTOR_SCRIPT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "doctor.mjs");
47
+ /** The usage text a grammar violation settles with. */
48
+ export const USAGE = "用法:/wsl-doctor [quick|full|<section>] [--distro <名称>]\n" +
49
+ "section ∈ " + SECTIONS.join(" | ") + ";空输入等价 quick。省略 --distro 时用当前会话的工作目录推断 distro。";
50
+ /**
51
+ * Parse the raw input after the command name. Tokens: one mode word or
52
+ * section name, plus an optional `--distro <name>` / `--distro=<name>`; a
53
+ * second bare token is accepted as the distro name.
54
+ *
55
+ * @param rawInput - everything after the command name.
56
+ * @returns the parsed mode, optional section, and optional distro.
57
+ * @throws when a token matches nothing — the caller settles usage text.
58
+ */
59
+ export function parseDoctorInput(rawInput) {
60
+ const parsed = { mode: "quick", distro: "" };
61
+ const tokens = rawInput.trim().split(/\s+/).filter((token) => token.length > 0);
62
+ let expectingDistro = false;
63
+ for (const token of tokens) {
64
+ if (expectingDistro) {
65
+ parsed.distro = token;
66
+ expectingDistro = false;
67
+ continue;
68
+ }
69
+ if (token === "--distro") {
70
+ expectingDistro = true;
71
+ continue;
72
+ }
73
+ if (token.startsWith("--distro=")) {
74
+ parsed.distro = token.slice("--distro=".length);
75
+ continue;
76
+ }
77
+ if (token === "quick" || token === "full") {
78
+ parsed.mode = token;
79
+ continue;
80
+ }
81
+ if (SECTIONS.includes(token)) {
82
+ parsed.mode = "section";
83
+ parsed.section = token;
84
+ continue;
85
+ }
86
+ if (parsed.distro.length === 0) {
87
+ parsed.distro = token;
88
+ continue;
89
+ }
90
+ throw new Error(`无法识别的参数:${token}`);
91
+ }
92
+ if (expectingDistro)
93
+ throw new Error("--distro 需要一个名称");
94
+ return parsed;
95
+ }
96
+ /**
97
+ * The default CLI runner: spawn the standalone doctor as a host subprocess.
98
+ * `process.execPath` is the Electron binary inside the harness, so
99
+ * `ELECTRON_RUN_AS_NODE=1` turns it into plain node for the child; under a
100
+ * plain node runtime the variable is ignored. Exit code 1 is a *blocked
101
+ * verdict*, which is a successful diagnosis — the JSON on stdout still parses;
102
+ * only a spawn failure or unparseable output is an infrastructure error.
103
+ *
104
+ * @param argv - flags after the script path (no node, no script — added here).
105
+ * @param signal - the dispatcher's abort signal; abort kills the child.
106
+ * @returns the CLI's stdout (one JSON report).
107
+ */
108
+ export function runDoctorCli(argv, signal) {
109
+ return new Promise((resolvePromise, rejectPromise) => {
110
+ const child = spawn(process.execPath, [DOCTOR_SCRIPT, ...argv], {
111
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
112
+ windowsHide: true,
113
+ stdio: ["ignore", "pipe", "pipe"],
114
+ signal,
115
+ });
116
+ let stdout = "";
117
+ let stderr = "";
118
+ child.stdout?.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
119
+ child.stderr?.on("data", (chunk) => { stderr += chunk.toString("utf8"); });
120
+ child.on("error", (error) => rejectPromise(error));
121
+ child.on("close", (code) => {
122
+ const text = stdout.trim();
123
+ if (text.startsWith("{")) {
124
+ resolvePromise(text);
125
+ return;
126
+ }
127
+ rejectPromise(new Error(`doctor CLI 未能给出报告(exit ${code ?? "signal"})${stderr.trim().length > 0 ? `:${stderr.trim().slice(0, 400)}` : ""}`));
128
+ });
129
+ });
130
+ }
131
+ /**
132
+ * Resolve the commands registry: the provided `commands` service through the
133
+ * optional `ctx.get`, else the plain property (the test seam). Absent means a
134
+ * headless deployment — the row stays a no-op instead of failing the mount.
135
+ *
136
+ * @param ctx - the cordis context the row mounted in.
137
+ * @returns the registry, or undefined when the deployment has no command adapter.
138
+ */
139
+ function resolveCommands(ctx) {
140
+ if (typeof ctx.get === "function") {
141
+ const provided = ctx.get("commands");
142
+ if (provided !== undefined && provided !== null && typeof provided.register === "function") {
143
+ return provided; // the provided service's contract is this module's `register` slice
144
+ }
145
+ }
146
+ return ctx.commands;
147
+ }
148
+ /**
149
+ * Resolve the distro an invocation targets: the explicit `--distro` wins;
150
+ * otherwise the receiving agent's working directory names a distro when it is
151
+ * a WSL UNC path; otherwise empty — the CLI's effective configuration decides
152
+ * (the shipped preset's `auto` probes every installed distro).
153
+ *
154
+ * @param ctx - the cordis context (for the cwd service).
155
+ * @param invocation - the registry's invocation face.
156
+ * @param distro - the explicitly requested distro, possibly empty.
157
+ * @returns the distro name, possibly empty.
158
+ */
159
+ async function resolveDistro(ctx, invocation, distro) {
160
+ if (distro.length > 0)
161
+ return distro;
162
+ if (invocation.agent === undefined)
163
+ return "";
164
+ // The cwd service resolves through `ctx.get` in production (no inject, no
165
+ // proxy throw); the plain property is the test seam's face.
166
+ const cwdService = typeof ctx.get === "function"
167
+ ? ctx.get("workingDirectory") // the service's contract is this module's `ensure` slice; narrowed below
168
+ : ctx.workingDirectory;
169
+ if (cwdService === undefined || typeof cwdService.ensure !== "function")
170
+ return "";
171
+ try {
172
+ const cwd = await cwdService.ensure(invocation.agent, invocation.signal);
173
+ return distroOfUnc(cwd) ?? "";
174
+ }
175
+ catch {
176
+ // A cwd that cannot resolve (no session, unreadable directory) must not
177
+ // fail the diagnosis: the CLI's own target selection is the fallback.
178
+ return "";
179
+ }
180
+ }
181
+ /**
182
+ * Format the CLI's JSON report into the itemized text the UI renders — the
183
+ * same digest the `wsl_doctor` tool returns, so both surfaces itemize every
184
+ * check identically.
185
+ *
186
+ * @param json - the CLI's stdout, one versioned JSON report.
187
+ * @param distro - the distro the run named, for the session-distro markers.
188
+ * @returns the rendered report text.
189
+ */
190
+ export function formatDoctorReport(json, distro) {
191
+ const report = JSON.parse(json);
192
+ const digest = digestReport(report, distro.length > 0 ? distro : undefined);
193
+ return renderDigest(digest);
194
+ }
195
+ /**
196
+ * Mount the command.
197
+ *
198
+ * @param ctx - the cordis context (the composition root, where the commands
199
+ * registry and the harness cwd service are reachable).
200
+ */
201
+ export async function apply(ctx) {
202
+ const commands = resolveCommands(ctx);
203
+ // No command adapter: nothing to register, nothing to fail. The doctor CLI
204
+ // (`pnpm run doctor`) stays the surface for headless deployments.
205
+ if (commands === undefined)
206
+ return;
207
+ // The test seam is a plain object: read `doctorCli` only when the cordis
208
+ // property proxy is absent, or the read itself throws ("cannot get property
209
+ // ... without inject") — the same guard the tool module uses for `doctor`.
210
+ const runCli = typeof ctx.get !== "function" && typeof ctx.doctorCli === "function" ? ctx.doctorCli : runDoctorCli;
211
+ commands.register({
212
+ name: "wsl-doctor",
213
+ description: "运行 WSL 环境诊断(独立 doctor CLI):结果直接显示在此,不进入模型对话。省略参数为快速诊断。",
214
+ input: { hint: "[quick|full|<section>] [--distro <名称>]" },
215
+ handler: async (invocation) => {
216
+ let parsed;
217
+ try {
218
+ parsed = parseDoctorInput(invocation.rawInput);
219
+ }
220
+ catch (error) {
221
+ return { kind: "error", text: `${error instanceof Error ? error.message : String(error)}\n\n${USAGE}` };
222
+ }
223
+ const distro = await resolveDistro(ctx, invocation, parsed.distro);
224
+ const argv = ["--json"];
225
+ if (parsed.mode === "quick")
226
+ argv.push("--quick");
227
+ if (parsed.mode === "section" && parsed.section !== undefined)
228
+ argv.push("--sections", parsed.section);
229
+ if (distro.length > 0)
230
+ argv.push("--distro", distro);
231
+ try {
232
+ const json = await runCli(argv, invocation.signal);
233
+ return { kind: "success", text: formatDoctorReport(json, distro) };
234
+ }
235
+ catch (error) {
236
+ return { kind: "error", text: `doctor 运行失败:${error instanceof Error ? error.message : String(error)}` };
237
+ }
238
+ },
239
+ });
240
+ }
@@ -61,15 +61,25 @@ export interface DoctorReportLike {
61
61
  distro?: string;
62
62
  }>;
63
63
  summary?: Record<string, number>;
64
+ /** The run's scope when the report is quick or section-filtered. */
65
+ scope?: {
66
+ sections: string[];
67
+ quick: boolean;
68
+ };
64
69
  }
65
- /** The cordis context slice this service consumes. */
70
+ /** The doctor report collector: distro plus run scope in, report out. */
71
+ export type DoctorCollector = (distro: string, options?: {
72
+ quick?: boolean;
73
+ sections?: readonly string[];
74
+ }) => Promise<DoctorReportLike>;
75
+ /** The context slice this service consumes. */
66
76
  export type WslDoctorToolContext = {
67
77
  tools: ToolRegistrySlice;
68
78
  workingDirectory: WorkingDirectoryToolSlice;
69
79
  /** Optional cordis-style lookup: how production resolves `doctor` without an inject. */
70
80
  get?: (name: string) => unknown;
71
81
  /** The in-process collector: a provided `doctor` service, or the test seam's fake. */
72
- doctor?: (distro: string) => Promise<DoctorReportLike>;
82
+ doctor?: DoctorCollector;
73
83
  };
74
84
  /** The tool's config: the row takes no options. */
75
85
  export interface WslDoctorToolConfig {
@@ -81,6 +91,32 @@ export interface FailingCheck {
81
91
  id: string;
82
92
  detail: string;
83
93
  remedy: string;
94
+ /** The distro the failing check ran in; absent for host-wide checks. */
95
+ distro?: string;
96
+ }
97
+ /** Per-distro tallies: what was tested in each distro and how it came out. */
98
+ export interface DistroTally {
99
+ name: string;
100
+ ok: number;
101
+ warn: number;
102
+ fail: number;
103
+ unknown: number;
104
+ info: number;
105
+ skipped: number;
106
+ /** This distro is the session's own — the run's primary subject. */
107
+ session?: boolean;
108
+ /** The distro's own verdict when the report carried one. */
109
+ verdict?: string;
110
+ }
111
+ /** One check as the itemized listing carries it: what was tested and how it came out. */
112
+ export interface CheckItem {
113
+ id: string;
114
+ /** The check's display name; falls back to the id when the report omits it. */
115
+ title: string;
116
+ status: string;
117
+ detail: string;
118
+ distro?: string;
119
+ remedy?: string;
84
120
  }
85
121
  /** The tool's result: the doctor's verdict, condensed for the model. */
86
122
  export interface DoctorDigest {
@@ -89,6 +125,23 @@ export interface DoctorDigest {
89
125
  failing: FailingCheck[];
90
126
  warningCount: number;
91
127
  skippedCount: number;
128
+ /** Per-section tallies for the checks the report carried, in SECTIONS order. */
129
+ sections: Array<{
130
+ section: string;
131
+ ok: number;
132
+ warn: number;
133
+ fail: number;
134
+ unknown: number;
135
+ }>;
136
+ /** Per-distro tallies in first-appearance order — the grouped summary. */
137
+ distros: DistroTally[];
138
+ /** Every check the report carried, in report order — the itemized listing. */
139
+ items: CheckItem[];
140
+ /** The scope the report answers for (quick profile or a section subset). */
141
+ scope?: {
142
+ sections: string[];
143
+ quick: boolean;
144
+ };
92
145
  distroVerdicts: Array<{
93
146
  name: string;
94
147
  verdict: string;
@@ -96,19 +149,58 @@ export interface DoctorDigest {
96
149
  }>;
97
150
  note: string;
98
151
  }
152
+ /**
153
+ * The section a check id belongs to. Mirrors `sectionOf` in
154
+ * `scripts/doctor.mjs` (the CLI's `--sections` filter reads that one); the
155
+ * parity is pinned by a test in `test/wsl-doctor-tool.test.mjs`, so a check
156
+ * cannot move sections on one side without the other noticing.
157
+ * @param id - the check id.
158
+ * @returns the section name.
159
+ */
160
+ export declare function sectionOf(id: string): "host" | "sandbox" | "session" | "conf" | "net" | "agent";
161
+ /** The sections in report order, matching the doctor CLI's SECTIONS list. */
162
+ export declare const SECTIONS: string[];
163
+ /** The detail a scope-filtered skip row carries; the marker the renderer buckets on. */
164
+ export declare const SCOPE_SKIP_DETAIL = "not run in this scope";
165
+ /** The detail prefix a CLI-gated skip row carries (the blocker follows it). */
166
+ export declare const SKIP_DETAIL_PREFIX = "skipped: ";
167
+ /**
168
+ * Every check id the doctor can emit — the CLI's whole probing surface,
169
+ * including the ids that only appear conditionally (`distro.present` for a
170
+ * configured-but-missing distro, `fix.git-trust` for a `--fix` run) and the
171
+ * `tools.*` ids the optional-tool loop constructs. The itemized listing uses
172
+ * this to show the checks a scoped (quick or section) run did NOT execute as
173
+ * explicit `[SKIP]` rows instead of silently dropping them; the parity test
174
+ * in `test/wsl-doctor-tool.test.mjs` re-extracts the ids from the CLI source
175
+ * and fails when the catalog drifts. A full run carries no scope, so a
176
+ * conditional id whose trigger never fired (no distro is missing, no
177
+ * `--fix`) also surfaces there under the generic `no scope recorded`
178
+ * reason — for those ids the honest reading is "did not fire", not
179
+ * "out of scope".
180
+ */
181
+ export declare const CHECK_CATALOG: readonly string[];
99
182
  /**
100
183
  * Digest one doctor report down to what the model acts on: the verdict, the
101
- * blockers, and every failing check with its copy-paste remedy. Warnings and
184
+ * blockers, every failing check with its copy-paste remedy, and the
185
+ * per-section tallies that make the passed checks visible (a bare verdict
186
+ * says nothing about what was tested — the sections do). Warnings and
102
187
  * skipped legs count but do not list — the report's own ids name them when
103
188
  * the model asks.
104
189
  * @param report - the collected (and live-merged) doctor report.
190
+ * @param sessionDistro - the distro this session runs in, when known; the
191
+ * matching tally is flagged so the rendered summary can name it.
105
192
  * @returns the digest.
106
193
  */
107
- export declare function digestReport(report: DoctorReportLike): DoctorDigest;
194
+ export declare function digestReport(report: DoctorReportLike, sessionDistro?: string): DoctorDigest;
108
195
  /**
109
- * Render the digest as the tool's text output: one verdict line, one line
110
- * per failing check with its remedy. The model narrates this; keeping it
111
- * plain text keeps the transcript readable.
196
+ * Render the digest as the tool's text output, in the style of a regular
197
+ * diagnostic tool: one verdict line, then an itemized listing — every check
198
+ * the report carried, grouped by distro, each with an explicit status marker
199
+ * (`[OK]` / `[WARN]` / `[FAIL]` / `[INFO]` / `[SKIP]` / `[??]`), its name and
200
+ * what it found. A failed check carries its copy-paste remedy on the next
201
+ * line; a warned check carries its detail, which is already the remedy's
202
+ * context. The model narrates this; keeping it plain text keeps the
203
+ * transcript readable.
112
204
  * @param digest - the digested report.
113
205
  * @returns the multi-line text.
114
206
  */