dsh-plugin-wsl-env 0.19.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +188 -1
  2. package/README.md +2 -2
  3. package/client.d.ts +5 -0
  4. package/client.js +218 -0
  5. package/cordis.patch.yml +75 -1
  6. package/docs/API.md +1 -0
  7. package/docs/CONFIGURATION.md +48 -5
  8. package/docs/CONFIGURATION.zh.md +15 -1
  9. package/docs/DIAGNOSTICS.md +110 -0
  10. package/docs/DIAGNOSTICS.zh.md +96 -0
  11. package/docs/LIMITATIONS.md +25 -0
  12. package/docs/LIMITATIONS.zh.md +7 -0
  13. package/docs/MIGRATION.md +1 -1
  14. package/docs/QUICKSTART.md +19 -3
  15. package/docs/RELEASING.md +3 -0
  16. package/docs/ROADMAP-1.0.md +49 -4
  17. package/docs/UPSTREAM-FILE-REFERENCE-SEAM.md +5 -0
  18. package/docs/UPSTREAM-OPEN-IN-APP.md +33 -0
  19. package/lib/client-host.d.ts +29 -0
  20. package/lib/client-host.js +29 -0
  21. package/lib/cwd-prompt-tool.d.ts +88 -0
  22. package/lib/cwd-prompt-tool.js +94 -0
  23. package/lib/cwd-prompt.d.ts +166 -0
  24. package/lib/cwd-prompt.js +203 -0
  25. package/lib/doctor-live.d.ts +5 -1
  26. package/lib/doctor-live.js +3 -2
  27. package/lib/index.d.ts +11 -0
  28. package/lib/index.js +10 -8
  29. package/lib/messages.d.ts +238 -0
  30. package/lib/messages.js +292 -0
  31. package/lib/preflight.d.ts +24 -0
  32. package/lib/preflight.js +111 -11
  33. package/lib/sandbox-core.js +7 -14
  34. package/lib/session-scope.js +10 -5
  35. package/lib/shell-env.d.ts +25 -0
  36. package/lib/shell-env.js +56 -0
  37. package/lib/shell.d.ts +3 -1
  38. package/lib/shell.js +3 -1
  39. package/lib/update-check.d.ts +197 -0
  40. package/lib/update-check.js +211 -0
  41. package/lib/wsl-doctor-command.d.ts +105 -0
  42. package/lib/wsl-doctor-command.js +240 -0
  43. package/lib/wsl-doctor-tool.d.ts +214 -0
  44. package/lib/wsl-doctor-tool.js +423 -0
  45. package/locale/doctor/en.json +30 -0
  46. package/locale/doctor/zh.json +30 -0
  47. package/package.json +47 -5
  48. package/scripts/doctor.mjs +1606 -171
@@ -0,0 +1,211 @@
1
+ /**
2
+ * The plugin's update check: notice when a newer release exists, stop there.
3
+ *
4
+ * Upgrading today means re-installing by hand (Plugins page, or
5
+ * `dsh plugin add`) and the harness's own plugin-manager already answers
6
+ * "which versions exist and do they fit this DSH" — `listVersions` resolves
7
+ * dist-tags, deprecation, and the `engines.dsh`/peer compatibility of every
8
+ * candidate against the running DSH. This service makes that answer arrive
9
+ * without the user opening the Versions page first: on a slow timer it asks
10
+ * the host's `pluginManager` for this package's version list and, when the
11
+ * stable channel has moved, publishes one fact. Applying the update stays a
12
+ * user action — a plugin that silently replaces its own code under a running
13
+ * harness is a posture this plugin rejects, and the harness has no HMR, so
14
+ * even a correct swap needs a restart to take effect.
15
+ *
16
+ * Delegation is the whole network story: the check spawns nothing and fetches
17
+ * nothing itself. `pluginManager` is read with `ctx.get`, the sanctioned read
18
+ * for a service this row does not inject — a host without it (or a bundle
19
+ * loaded from a linked checkout, which `listVersions` refuses as
20
+ * `not-updatable` because the mirror is managed by `pnpm run sync:windows`)
21
+ * simply means no check ran, at debug level, never a warning.
22
+ *
23
+ * This is a TypeScript source built to `lib/update-check.js`; edit THIS file
24
+ * and run `pnpm run build` — the artifact under `lib/` is generated, and
25
+ * `pnpm test` fails when it drifts.
26
+ *
27
+ * @module dsh-plugin-wsl-env/update-check
28
+ */
29
+ import z from "@deepseek-ai/schemastery";
30
+ export const name = "wsl-update-check";
31
+ /** The checked package: this plugin, by its npm name. */
32
+ const PACKAGE = "dsh-plugin-wsl-env";
33
+ /** The interval the row ships with. */
34
+ export const DEFAULT_INTERVAL_MS = 24 * 60 * 60 * 1000;
35
+ /** The smallest interval a config may ask for; one check spawns `pnpm view` in the profile. */
36
+ export const MIN_INTERVAL_MS = 60 * 1000;
37
+ export const Config = z.object({
38
+ /** Whether the update check runs at all. */
39
+ enabled: z.boolean().default(true),
40
+ /** How often the registry is asked, in milliseconds; floored at one minute. */
41
+ intervalMs: z.number().default(DEFAULT_INTERVAL_MS),
42
+ });
43
+ /**
44
+ * The module-level fact store. `shellEnv`'s resolver is synchronous by
45
+ * contract, so the timer-fed fact must live somewhere a plain import can read
46
+ * without await — the same posture as the ports snapshot, and the same
47
+ * module-singleton pattern as the shared agent (`lib/agent-shared.js`).
48
+ */
49
+ let fact;
50
+ /**
51
+ * The newest update fact this process has published, or undefined when no
52
+ * check ran, the registry said "up to date", or the last check learned
53
+ * nothing actionable.
54
+ *
55
+ * @returns the fact, for `shellEnv`'s synchronous resolver.
56
+ */
57
+ export function currentUpdateFact() {
58
+ return fact;
59
+ }
60
+ /**
61
+ * Publish (or clear) the update fact. Exported for the tests, which must be
62
+ * able to stage a fact without a host plugin-manager — the same "tests-only"
63
+ * carve-out as `clearNativeBackendCache`.
64
+ *
65
+ * @param next - the fact to publish, or undefined to clear.
66
+ */
67
+ export function setUpdateFact(next) {
68
+ fact = next;
69
+ }
70
+ /**
71
+ * The interval a config asks for, floored at {@link MIN_INTERVAL_MS}. A check
72
+ * spawns `pnpm view` in the profile, so a tight loop would hammer the
73
+ * registry; the floor makes even `0` safe.
74
+ *
75
+ * @param ms - the configured interval, or undefined for the default.
76
+ * @returns the interval the scheduler uses.
77
+ */
78
+ export function clampInterval(ms) {
79
+ return Math.max(ms ?? DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS);
80
+ }
81
+ /**
82
+ * How long after mount the first check waits: two to ten minutes, jittered.
83
+ * The delay keeps the check off the startup path (a cold start must not wait
84
+ * on a registry round-trip) and off the startup stampede of `pnpm` work the
85
+ * profile is already doing.
86
+ *
87
+ * @param random - the randomness source, injectable for tests.
88
+ * @returns the delay in milliseconds.
89
+ */
90
+ export function firstDelayMs(random = Math.random) {
91
+ return 120_000 + random() * 480_000;
92
+ }
93
+ /**
94
+ * Pick the version the fact should name: the stable channel's newest release
95
+ * (`latest` tag) that is still a bundle. Prereleases ship on `next` by the
96
+ * release discipline and never move `latest`, so they are not news; a version
97
+ * that lost the bundle manifest could not be installed as an update. The list
98
+ * is newest-first, so the first match is the newest.
99
+ *
100
+ * @param list - the version list `listVersions` answered with.
101
+ * @returns the target version, or undefined when the stable channel has not moved.
102
+ */
103
+ export function updateTarget(list) {
104
+ return list.versions.find((version) => version.bundle && version.tags.includes("latest"));
105
+ }
106
+ /**
107
+ * Run one check against the host's plugin-manager and publish the fact.
108
+ *
109
+ * Every non-answer is quiet by design: a missing manager, a linked checkout
110
+ * (`not-updatable`), a registry the host cannot reach (`network`), or a stable
111
+ * channel that has not moved all leave the previous fact (or none) standing —
112
+ * an update check must never become the noisiest thing in the app.
113
+ *
114
+ * @param manager - the host plugin-manager, or undefined when the host has none.
115
+ * @returns the published fact, or undefined when the check learned nothing.
116
+ */
117
+ export async function checkForUpdate(manager) {
118
+ if (manager === undefined)
119
+ return undefined;
120
+ let list;
121
+ try {
122
+ list = await manager.listVersions(PACKAGE);
123
+ }
124
+ catch {
125
+ // `listVersions` resolves refusals into its result; a throw means the
126
+ // service itself is broken. The next tick retries; nothing is published.
127
+ return undefined;
128
+ }
129
+ if (list.status !== "listed")
130
+ return undefined;
131
+ const target = updateTarget(list);
132
+ if (target === undefined) {
133
+ setUpdateFact(undefined);
134
+ return undefined;
135
+ }
136
+ const next = {
137
+ installed: list.installed,
138
+ latest: target.version,
139
+ ...(target.publishedAt === undefined ? {} : { publishedAt: target.publishedAt }),
140
+ incompatible: target.incompatible !== undefined,
141
+ ...(target.deprecated === undefined ? {} : { deprecated: target.deprecated }),
142
+ checkedAt: Date.now(),
143
+ };
144
+ setUpdateFact(next);
145
+ return next;
146
+ }
147
+ /**
148
+ * The fact as one line, for the managed `DSH_*` variable and the log. The
149
+ * wording is the same the doctor's section reuses, so "available" never
150
+ * drifts between the two surfaces.
151
+ *
152
+ * @param update - the fact, or undefined.
153
+ * @returns the message, or an empty string when there is nothing to say.
154
+ */
155
+ export function updateFactMessage(update) {
156
+ if (update === undefined)
157
+ return "";
158
+ const marks = [];
159
+ if (update.incompatible)
160
+ marks.push("requires a newer DSH first");
161
+ if (update.deprecated !== undefined)
162
+ marks.push(`deprecated: ${update.deprecated}`);
163
+ const tail = marks.length === 0 ? "" : ` — ${marks.join("; ")}`;
164
+ return `${update.latest} available (installed ${update.installed})${tail}`;
165
+ }
166
+ /**
167
+ * Mount the update check.
168
+ *
169
+ * @param ctx - the cordis context.
170
+ * @param config - the schema-validated plugin config.
171
+ */
172
+ export async function apply(ctx, config = {}) {
173
+ if (!(config.enabled ?? true))
174
+ return;
175
+ const intervalMs = clampInterval(config.intervalMs);
176
+ const debug = (message) => ctx.logger?.debug?.(message);
177
+ const tick = async () => {
178
+ try {
179
+ // The read is the cordis-sanctioned one for a service this row does not
180
+ // inject: `ctx.get` answers undefined when the host has no
181
+ // plugin-manager (a headless harness, a bare composition), where a
182
+ // property read would throw and mark the whole component failed.
183
+ const manager = ctx.get("pluginManager");
184
+ if (manager === undefined) {
185
+ debug("wsl-update-check: the host has no plugin-manager; the check is skipped");
186
+ return;
187
+ }
188
+ const published = await checkForUpdate(manager);
189
+ if (published === undefined) {
190
+ debug("wsl-update-check: no newer stable release (or the registry was unreachable)");
191
+ return;
192
+ }
193
+ debug(`wsl-update-check: ${updateFactMessage(published)}`);
194
+ }
195
+ catch (error) {
196
+ // A check that cannot run is a next tick's business, never a session's
197
+ // error: the timer swallows everything at debug level.
198
+ debug(`wsl-update-check: the check failed (${error?.message ?? error})`);
199
+ }
200
+ };
201
+ const first = setTimeout(() => void tick(), firstDelayMs());
202
+ const repeat = setInterval(() => void tick(), intervalMs);
203
+ first.unref?.();
204
+ repeat.unref?.();
205
+ // Disposing matters: a config hot-reload re-runs apply(), and two live
206
+ // timers would double the registry traffic.
207
+ ctx.effect(() => () => {
208
+ clearTimeout(first);
209
+ clearInterval(repeat);
210
+ });
211
+ }
@@ -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
+ }