dsh-plugin-wsl-env 0.19.0 → 0.21.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 (43) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +2 -2
  3. package/client.d.ts +5 -0
  4. package/client.js +98 -0
  5. package/cordis.patch.yml +66 -1
  6. package/docs/API.md +1 -0
  7. package/docs/CONFIGURATION.md +39 -5
  8. package/docs/CONFIGURATION.zh.md +15 -1
  9. package/docs/DIAGNOSTICS.md +83 -0
  10. package/docs/DIAGNOSTICS.zh.md +73 -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.js +6 -8
  28. package/lib/messages.d.ts +157 -0
  29. package/lib/messages.js +199 -0
  30. package/lib/preflight.d.ts +24 -0
  31. package/lib/preflight.js +111 -11
  32. package/lib/sandbox-core.js +7 -14
  33. package/lib/session-scope.js +10 -5
  34. package/lib/shell-env.d.ts +25 -0
  35. package/lib/shell-env.js +56 -0
  36. package/lib/shell.d.ts +3 -1
  37. package/lib/shell.js +3 -1
  38. package/lib/update-check.d.ts +197 -0
  39. package/lib/update-check.js +211 -0
  40. package/lib/wsl-doctor-tool.d.ts +122 -0
  41. package/lib/wsl-doctor-tool.js +161 -0
  42. package/package.json +43 -5
  43. package/scripts/doctor.mjs +1167 -160
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Distro-native working directory in the model's runtime context: rewrite the
3
+ * `working-directory:current` entry so a distro session reads its directory as
4
+ * the POSIX path its own commands use, not the host UNC spelling.
5
+ *
6
+ * The harness's `working-directory` service prints the session cwd verbatim,
7
+ * which on this deployment is `\\wsl.localhost\<distro>\...` — the coordinate
8
+ * system of the HOST filesystem, and one the model's tools mostly cannot use
9
+ * directly: the shell executor runs inside the distro, where only the POSIX
10
+ * form resolves. The mismatch is invisible to the harness and costs the model
11
+ * a translation step on every path it quotes back, with a wrong-guess failure
12
+ * mode (a UNC path handed to `bash` names nothing).
13
+ *
14
+ * The value reaches the model through TWO renderings, and both must be
15
+ * covered:
16
+ *
17
+ * 1. the system prompt — the entry as `assemble()` resolves it;
18
+ * 2. the per-turn runtime-context snapshot — `refreshContext()` re-resolves
19
+ * the registry providers DIRECTLY, so a waterfall listener on
20
+ * `system-prompt/assemble` never sees it.
21
+ *
22
+ * Both read the same scoped-layer table, where the nearest scope wins a name
23
+ * (`ScopedLayers.merge`). So the primary mechanism is a session-scoped
24
+ * registration UNDER THE SAME NAME: the entry's provider asks the harness's
25
+ * `workingDirectory` service for the CURRENT directory (so a mid-session `cd`
26
+ * still shows) and rewrites every WSL UNC spelling in it to its POSIX form.
27
+ * A root-level waterfall listener stays as defense in depth for the prompt
28
+ * path on a session where the inject seam is unavailable; the rewrite is
29
+ * idempotent, so the two mechanisms compose without interaction.
30
+ *
31
+ * Advisory by construction. The seams are structural (the plugin's own types
32
+ * spell the slices; docs/UPSTREAM-SESSION-NOTICE.md already relies on the
33
+ * sibling `systemPrompt.context()` seam): a harness without them, an agent
34
+ * whose context is not exposed, or a non-WSL workspace degrades to the
35
+ * shipped behavior — no rewrite, no failure. The rewrite touches one display
36
+ * string; it must never fail a model step.
37
+ *
38
+ * This is a TypeScript source built to `lib/cwd-prompt.js`; edit THIS file and
39
+ * run `pnpm run build` — the artifact under `lib/` is generated, and
40
+ * `pnpm test` fails when it drifts.
41
+ *
42
+ * @module dsh-plugin-wsl-env/cwd-prompt
43
+ */
44
+ import z from "@deepseek-ai/schemastery";
45
+ import { isWslUnc, uncToPosix } from "./paths.js";
46
+ export const name = "wsl-cwd-prompt";
47
+ export const Config = z.object({
48
+ /** Whether the runtime-context rewrite runs at all. */
49
+ enabled: z.boolean().default(true),
50
+ });
51
+ /**
52
+ * The context entry name the harness's working-directory service registers.
53
+ * Registering the same name in a session scope shadows it for BOTH renderings
54
+ * (`assemble` and `refreshContext` merge scoped layers over the global one).
55
+ */
56
+ const ENTRY_NAME = "working-directory:current";
57
+ /**
58
+ * Rewrite every JSON-string-quoted WSL UNC path in one text to its POSIX form.
59
+ * The harness writes the cwd through `JSON.stringify`, so the backslashes are
60
+ * ESCAPED inside the quotes (`"\\\\wsl.localhost\\..."` as rendered text):
61
+ * match a JSON string, parse its inner content, and only rewrite when the raw
62
+ * value is a WSL UNC share. A path that parses to anything else (a drive
63
+ * path, another share, already-POSIX text) passes through unchanged, so the
64
+ * rewrite is safe to re-run.
65
+ *
66
+ * @param text - the contribution text.
67
+ * @returns the text with WSL UNC paths in distro coordinates.
68
+ */
69
+ export function rewriteQuotedUnc(text) {
70
+ return String(text).replace(/"((?:[^"\\]|\\.)*)"/gu, (whole, inner) => {
71
+ let raw;
72
+ try {
73
+ // The inner content is a complete JSON string body by construction of
74
+ // the match; a body with an invalid escape fails closed to `whole`.
75
+ raw = JSON.parse(`"${inner}"`);
76
+ }
77
+ catch {
78
+ return whole;
79
+ }
80
+ const parsed = uncToPosix(raw);
81
+ return parsed === undefined ? whole : JSON.stringify(parsed.linuxPath);
82
+ });
83
+ }
84
+ /**
85
+ * The rewritten entry text for one assembly: ask the harness's service for the
86
+ * CURRENT directory (a mid-session `cd` must show), fall back to the session
87
+ * header's original cwd, and translate only WSL UNC spellings. Everything the
88
+ * regex cannot see passes through untouched, so a host session receives the
89
+ * shipped text byte for byte.
90
+ *
91
+ * @param agent - the agent the assembly runs inside.
92
+ * @param workingDirectory - the harness's service, when resolvable.
93
+ * @returns the entry text.
94
+ */
95
+ export function entryText(agent, workingDirectory) {
96
+ const session = agent?.session;
97
+ let directory;
98
+ try {
99
+ directory = session === undefined ? undefined : workingDirectory?.get?.(session);
100
+ }
101
+ catch {
102
+ directory = undefined;
103
+ }
104
+ if (directory === undefined || directory.length === 0)
105
+ directory = session?.header?.cwd ?? "";
106
+ return rewriteQuotedUnc(`Current working directory: ${JSON.stringify(directory)}.`);
107
+ }
108
+ /**
109
+ * Mount the rewrite.
110
+ *
111
+ * @param ctx - the cordis context (the composition root, where the harness's
112
+ * own prompt services register).
113
+ * @param config - the schema-validated plugin config.
114
+ */
115
+ export function apply(ctx, config = {}) {
116
+ const enabled = config.enabled ?? true;
117
+ if (!enabled)
118
+ return;
119
+ const debug = (message) => ctx.logger?.debug?.(message);
120
+ /**
121
+ * Install the session-scoped shadow entry: same name, so it wins the merge;
122
+ * the provider re-reads the current directory on every rendering. Absent on
123
+ * host workspaces (nothing WSL to rewrite) and on agents whose context the
124
+ * harness does not expose (the shipped entry stands).
125
+ *
126
+ * @param agent - the session that just opened.
127
+ */
128
+ const install = (agent) => {
129
+ const cwd = agent.session?.header?.cwd;
130
+ if (cwd === undefined || !isWslUnc(cwd))
131
+ return;
132
+ const agentCtx = agent.ctx;
133
+ if (agentCtx === undefined || typeof agentCtx.inject !== "function")
134
+ return;
135
+ let workingDirectory;
136
+ try {
137
+ const resolved = agentCtx.get?.("workingDirectory");
138
+ if (resolved !== undefined && resolved !== null)
139
+ workingDirectory = /** @type {WorkingDirectorySlice} */ (resolved);
140
+ }
141
+ catch (error) {
142
+ debug(`wsl-cwd-prompt: could not read the workingDirectory service (${error?.message ?? error})`);
143
+ }
144
+ try {
145
+ agentCtx.inject(["systemPrompt"], (scope) => {
146
+ const order = scope.systemPrompt.getContextOrder?.("WORKING_DIRECTORY") ?? 200;
147
+ scope.systemPrompt.context({
148
+ name: ENTRY_NAME,
149
+ order,
150
+ required: true,
151
+ interpolate: false,
152
+ text: (context) => entryText(context?.agent, workingDirectory),
153
+ });
154
+ });
155
+ }
156
+ catch (error) {
157
+ debug(`wsl-cwd-prompt: could not install the shadow entry (${error?.message ?? error})`);
158
+ }
159
+ };
160
+ ctx.on("agent/created", (payload) => {
161
+ // Structural payload: the harness emits { agent } on agent/created.
162
+ const agent = payload?.agent;
163
+ if (agent !== undefined)
164
+ install(agent);
165
+ });
166
+ // Mount order is not a guarantee: a session created during startup can finish
167
+ // before this service mounts and miss the event entirely (dsh-headless does
168
+ // exactly that, and wsl-preflight sweeps for the same reason). `agents` is
169
+ // optional, so read it with `ctx.get`: a property read of an undeclared
170
+ // service throws in cordis 4, and the catch below turns that into a silent
171
+ // no-op — exactly the sweep this block exists to perform.
172
+ try {
173
+ const agents = ctx.get?.("agents");
174
+ for (const agent of agents?.list() ?? [])
175
+ install(agent);
176
+ }
177
+ catch (error) {
178
+ debug(`wsl-cwd-prompt: could not sweep already-live agents: ${error?.message ?? error}`);
179
+ }
180
+ /**
181
+ * Defense in depth for the PROMPT rendering on sessions where the inject
182
+ * seam is unavailable: rewrite the assembled entry in place, then continue
183
+ * the chain. Never throws; an unexpected shape skips the rewrite.
184
+ *
185
+ * @param assembly - the assembly built so far.
186
+ * @param _context - the assembly context (unused).
187
+ * @param next - the waterfall continuation.
188
+ * @returns the downstream assembly.
189
+ */
190
+ const listener = async (assembly, _context, next) => {
191
+ try {
192
+ const entry = assembly?.contexts?.find((candidate) => candidate?.name === ENTRY_NAME);
193
+ if (entry !== undefined && typeof entry.text === "string")
194
+ entry.text = rewriteQuotedUnc(entry.text);
195
+ }
196
+ catch {
197
+ // Display preference, not correctness: skip the rewrite rather than
198
+ // fail the model step this assembly feeds.
199
+ }
200
+ return next();
201
+ };
202
+ ctx.on("system-prompt/assemble", listener);
203
+ }
@@ -18,12 +18,16 @@ import type { AgentStatus } from "./agent.js";
18
18
  export interface DoctorCheck {
19
19
  /** The stable check id, e.g. `agent.handshake`. */
20
20
  id: string;
21
- /** `ok` | `warn` | `fail` | `info`. */
21
+ /** `ok` | `warn` | `fail` | `info` | `skipped`. */
22
22
  status: string;
23
23
  /** The human detail line. */
24
24
  detail?: string;
25
25
  /** The copy-paste remedy, when the status is not `ok`. */
26
26
  remedy?: string;
27
+ /** The distro the check ran against (schema 2, distro-scoped checks). */
28
+ distro?: string;
29
+ /** Whether a `fail` here blocks the first command (schema 2). */
30
+ blocksFirstCommand?: boolean;
27
31
  }
28
32
  /** The doctor's versioned JSON report shape (`schemaVersion`). */
29
33
  export interface DoctorReport {
@@ -21,11 +21,12 @@ export function mergeLiveResidentStatus(report, status) {
21
21
  if (!fresh)
22
22
  return report;
23
23
  const errorLine = status.lastError.length > 0 ? `; lastError: ${status.lastError}` : "";
24
+ // The fresh check's shape fields (distro, blocksFirstCommand) ride through:
25
+ // the merge rewrites the verdict and the evidence, never the schema.
24
26
  const merged = {
25
- id: fresh.id,
27
+ ...fresh,
26
28
  status: status.state === "dead" ? "fail" : status.lastError.length > 0 ? "warn" : fresh.status,
27
29
  detail: `probed: the live resident (pid ${status.pid}, state ${status.state}, deaths ${status.deaths}, pending ${status.pending})${errorLine}; fresh-probe facts: ${fresh.detail ?? ""}`,
28
- ...(fresh.remedy !== undefined ? { remedy: fresh.remedy } : {}),
29
30
  };
30
31
  const checks = report.checks.map((check) => (check === fresh ? merged : check));
31
32
  const summary = { ...report.summary };
package/lib/index.js CHANGED
@@ -59,6 +59,7 @@ import { FsCodedError } from "./fsio-text.js";
59
59
  import { confinedAgent } from "./agent-confined.js";
60
60
  import { SessionRuntimes, probeSessionRuntime, sessionRuntimes, setSessionNativeAgent } from "./session-runtime.js";
61
61
  import { configureAgentBackend, ensureNativeSessionAgent } from "./native-agent.js";
62
+ import { installMessagesLocale, t } from "./messages.js";
62
63
  import { mergeLiveResidentStatus } from "./doctor-live.js";
63
64
  import { spawnSync } from "node:child_process";
64
65
  import { fileURLToPath } from "node:url";
@@ -452,6 +453,7 @@ export class WslShellExecutor extends LocalBashExecutor {
452
453
  constructor(ctx, config) {
453
454
  super(ctx, config);
454
455
  configureAgentBackend(config.agentBackend ?? "auto");
456
+ installMessagesLocale(ctx);
455
457
  this.resolvedDistro = pinnedDistro(config.distro) ?? "";
456
458
  this.resolvedShell = config.shell;
457
459
  this.resolvedShells = new Map();
@@ -888,9 +890,7 @@ export class WslShellExecutor extends LocalBashExecutor {
888
890
  const code = wslErrorCode(result?.stdout?.text, result?.stderr?.text);
889
891
  if (code === undefined)
890
892
  return;
891
- throw new Error(`wsl.exe reported ${code} for distro "${distro}": it is not installed, or not running. ` +
892
- `Start it with \`wsl.exe -d ${distro}\`, check \`wsl.exe -l -v\`, or point \`distro\` at another one. ` +
893
- `This is not a sandbox denial, so running with wider permissions will not help.`);
893
+ throw new Error(t("distroUnavailable", { code, distro }));
894
894
  }
895
895
  /**
896
896
  * Reject a command that ran in the wrong directory.
@@ -908,8 +908,7 @@ export class WslShellExecutor extends LocalBashExecutor {
908
908
  const missing = workdirFailure(result?.stdout?.text, result?.stderr?.text);
909
909
  if (missing === undefined)
910
910
  return;
911
- throw new Error(`wsl.exe could not enter the working directory "${missing}" inside the distro, so the command ran from "/" instead. ` +
912
- `Create it, or point \`cwd\` (or the request's \`workdir\`) at a directory that exists.`);
911
+ throw new Error(t("workdirMissing", { missing }));
913
912
  }
914
913
  /**
915
914
  * Execute one resolved spec inside the distro, confined by the per-call policy
@@ -958,9 +957,7 @@ export class WslShellExecutor extends LocalBashExecutor {
958
957
  throwIfWorkdirInAnotherDistro(workdir, distro) {
959
958
  if (!isAnotherDistrosUnc(workdir, distro))
960
959
  return;
961
- throw new Error(`"${workdir}" names a workspace in another WSL distro, and this profile pins its commands to "${distro}" — ` +
962
- `running them here would act on a different machine's tree. Open a session in that distro, ` +
963
- `or point cwd/workdir at this distro.`);
960
+ throw new Error(t("workdirAnotherDistro", { workdir, distro }));
964
961
  }
965
962
  /**
966
963
  * The agent-backed execution path: one long-lived in-distro process, the
@@ -1295,6 +1292,7 @@ export class WslFileSystem extends LocalFileSystem {
1295
1292
  if (refusal !== null)
1296
1293
  throw new Error(refusal.message);
1297
1294
  super(ctx, config);
1295
+ installMessagesLocale(ctx);
1298
1296
  this.resolvedDistro = pinnedDistro(config.distro) ?? "";
1299
1297
  this.resolvedHome = undefined;
1300
1298
  this.resolvedHomes = new Map();
@@ -0,0 +1,157 @@
1
+ /**
2
+ * The language the plugin's runtime refusal and remedy messages render in,
3
+ * following the harness app's locale setting.
4
+ *
5
+ * The preference lives in the host composition as the `locale` entry's
6
+ * `preference` field (`@deepseek-ai/dsh-client-locale`'s host half declares it
7
+ * volatile), persisted through the host `settings` service. This module reads
8
+ * it through an OPTIONAL `settings` injection — the service belongs to the
9
+ * base bundle, and a profile without it (or a `settings` that never resolves)
10
+ * keeps the English defaults, which is also every test's default. A language
11
+ * switch re-reads on the service's `settings/document-updated` event, so
12
+ * following the remedy or switching language needs no app restart.
13
+ *
14
+ * Only plugin-authored text is cataloged here. The `fs-decisions` refusals and
15
+ * the fsio replica stay byte-identical English — the tool layer matches on
16
+ * those strings (see `src/fs-decisions.ts` and `docs/UPSTREAM-FSIO-EXPORT.md`).
17
+ *
18
+ * This is a TypeScript source built to `lib/messages.js`; edit THIS file and
19
+ * run `pnpm run build` — the artifact under `lib/` is generated, and
20
+ * `pnpm test` fails when it drifts.
21
+ *
22
+ * @module dsh-plugin-wsl-env/messages
23
+ */
24
+ import type { Context } from "@deepseek-ai/cordis";
25
+ /** The languages the catalogs ship. More locales are additive: add a table and widen the resolver. */
26
+ export type MessagesLocale = "en" | "zh";
27
+ /**
28
+ * The message templates, keyed by call site. Each entry owns its parameter
29
+ * shape; the `zh` table is type-checked against the `en` table's key and
30
+ * parameter union, so the two catalogs cannot drift apart silently.
31
+ */
32
+ declare const en: {
33
+ /** `sessionScopeProblem`: systemd is not PID 1 in the distro. */
34
+ sessionScopeNoSystemd: ({ distro }: {
35
+ distro: string;
36
+ }) => string;
37
+ /** `sessionScopeProblem`: `systemctl --user` does not answer. */
38
+ sessionScopeNoUserManager: ({ distro }: {
39
+ distro: string;
40
+ }) => string;
41
+ /** `sessionScopeProblem`: the `systemd-run` binary is missing. */
42
+ sessionScopeNoSystemdRun: ({ distro }: {
43
+ distro: string;
44
+ }) => string;
45
+ /** `sessionScopeProblem`: the user manager would stop with the last session. */
46
+ sessionScopeNoLinger: ({ distro }: {
47
+ distro: string;
48
+ }) => string;
49
+ /**
50
+ * `sessionScopeProblem`: the probe's answer is empty or unrecognized. The
51
+ * caller renders `answer` (the quoted word, or `(nothing)`) and `errorSuffix`
52
+ * (`""` or `": <error>"`) so both languages keep one sentence shape.
53
+ */
54
+ sessionScopeUnknownAnswer: ({ distro, answer, errorSuffix }: {
55
+ distro: string;
56
+ answer: string;
57
+ errorSuffix: string;
58
+ }) => string;
59
+ /** `missingBwrapRemedy` without a detected package family. */
60
+ bwrapMissingGeneric: ({ distro }: {
61
+ distro: string;
62
+ }) => string;
63
+ /** `missingBwrapRemedy` with a family's direct install command. */
64
+ bwrapMissingFamily: ({ distro, direct }: {
65
+ distro: string;
66
+ direct: string;
67
+ }) => string;
68
+ /** `composeBwrapFailure`: bwrap ran and refused — present but unusable. */
69
+ bwrapBroken: ({ distro, output }: {
70
+ distro: string;
71
+ output: string;
72
+ }) => string;
73
+ /** `bwrapInstallHint`: bwrap probed healthy but failed a real command. */
74
+ bwrapRuntimeFailure: ({ distro }: {
75
+ distro: string;
76
+ }) => string;
77
+ /** `composeBwrapFailure`: the unclassified probe's raw output, appended to a remedy. */
78
+ bwrapProbeFailedSuffix: ({ output }: {
79
+ output: string;
80
+ }) => string;
81
+ /** `throwIfDistroUnavailable`: wsl.exe says the distro is gone. */
82
+ distroUnavailable: ({ code, distro }: {
83
+ code: string;
84
+ distro: string;
85
+ }) => string;
86
+ /** `throwIfWorkdirMissing`: `wsl.exe --cd` fell back to `/`. */
87
+ workdirMissing: ({ missing }: {
88
+ missing: string;
89
+ }) => string;
90
+ /** `throwIfWorkdirInAnotherDistro`: the workspace names a pinned-against distro. */
91
+ workdirAnotherDistro: ({ workdir, distro }: {
92
+ workdir: string;
93
+ distro: string;
94
+ }) => string;
95
+ };
96
+ type Catalog = typeof en;
97
+ type MessageKey = keyof Catalog;
98
+ /**
99
+ * The locale the message builders render in.
100
+ *
101
+ * @returns the active catalog language.
102
+ */
103
+ export declare function messagesLocale(): MessagesLocale;
104
+ /**
105
+ * Force the message language. The wiring calls this from the resolved
106
+ * `locale.preference`; tests call it directly and reset afterwards.
107
+ *
108
+ * @param locale - the language to render in.
109
+ */
110
+ export declare function configureMessagesLocale(locale: MessagesLocale): void;
111
+ /**
112
+ * Render one message in the active language, falling back to the English
113
+ * template when the active catalog somehow lacks the key (the catalogs are
114
+ * type-checked against each other, so this guards runtime drift only).
115
+ *
116
+ * The `params` type correlates the parameters with the key: the conditional
117
+ * resolves per call site, so `t("sessionScopeNoLinger", { distro })`
118
+ * typechecks while `t("sessionScopeNoLinger", { missing })` does not. It
119
+ * lives in the JSDoc because a comment between the parameters would have the
120
+ * type-stripping build emit a line with trailing whitespace, which the style
121
+ * gate refuses.
122
+ *
123
+ * @typeParam K - the message key.
124
+ * @param key - the message to render.
125
+ * @param params - the key's parameters, as the template declares them.
126
+ * @returns the rendered message.
127
+ */
128
+ export declare function t<K extends MessageKey>(key: K, params: Catalog[K] extends (first: infer P) => string ? P : never): string;
129
+ /**
130
+ * Map one `locale.preference` value onto a catalog language. The app's
131
+ * language ids are BCP 47-style tags (`zh`, `en`, `ja`, …); the plugin ships
132
+ * zh and en, and every other id renders English.
133
+ *
134
+ * @param preference - the stored preference, or anything else when unset.
135
+ * @returns the catalog language the preference selects.
136
+ */
137
+ export declare function resolveMessagesLocale(preference: unknown): MessagesLocale;
138
+ /**
139
+ * Follow the harness locale for the caller's composition. Every row wires its
140
+ * own injection (the shell executor, the fs provider and the preflight all
141
+ * call this), so a hot-reloaded row re-wires too; the redundant reads converge
142
+ * on the same app-wide preference and the events are rare.
143
+ *
144
+ * The `settings` service is optional — a profile without it (some CLI
145
+ * compositions) keeps English. When it is present, the preference is read once
146
+ * the service resolves and again on every `settings/document-updated` event,
147
+ * which also covers the `locale` entry activating after this row did. A read
148
+ * that throws keeps the previous language: this is presentation, not gating.
149
+ *
150
+ * @param ctx - the row's composition context.
151
+ */
152
+ export declare function installMessagesLocale(ctx: Context): void;
153
+ /**
154
+ * Restore English. Tests only: production wiring is process-wide by design.
155
+ */
156
+ export declare function resetMessagesLocaleForTests(): void;
157
+ export {};
@@ -0,0 +1,199 @@
1
+ /**
2
+ * The language the plugin's runtime refusal and remedy messages render in,
3
+ * following the harness app's locale setting.
4
+ *
5
+ * The preference lives in the host composition as the `locale` entry's
6
+ * `preference` field (`@deepseek-ai/dsh-client-locale`'s host half declares it
7
+ * volatile), persisted through the host `settings` service. This module reads
8
+ * it through an OPTIONAL `settings` injection — the service belongs to the
9
+ * base bundle, and a profile without it (or a `settings` that never resolves)
10
+ * keeps the English defaults, which is also every test's default. A language
11
+ * switch re-reads on the service's `settings/document-updated` event, so
12
+ * following the remedy or switching language needs no app restart.
13
+ *
14
+ * Only plugin-authored text is cataloged here. The `fs-decisions` refusals and
15
+ * the fsio replica stay byte-identical English — the tool layer matches on
16
+ * those strings (see `src/fs-decisions.ts` and `docs/UPSTREAM-FSIO-EXPORT.md`).
17
+ *
18
+ * This is a TypeScript source built to `lib/messages.js`; edit THIS file and
19
+ * run `pnpm run build` — the artifact under `lib/` is generated, and
20
+ * `pnpm test` fails when it drifts.
21
+ *
22
+ * @module dsh-plugin-wsl-env/messages
23
+ */
24
+ /**
25
+ * The message templates, keyed by call site. Each entry owns its parameter
26
+ * shape; the `zh` table is type-checked against the `en` table's key and
27
+ * parameter union, so the two catalogs cannot drift apart silently.
28
+ */
29
+ const en = {
30
+ /** `sessionScopeProblem`: systemd is not PID 1 in the distro. */
31
+ sessionScopeNoSystemd: ({ distro }) => `sessionSandbox needs systemd as PID 1 in "${distro}": set [boot] systemd=true in /etc/wsl.conf, run "wsl --shutdown", and reopen the session.`,
32
+ /** `sessionScopeProblem`: `systemctl --user` does not answer. */
33
+ sessionScopeNoUserManager: ({ distro }) => `sessionSandbox needs a reachable systemd user manager in "${distro}": log in to the distro once, or enable lingering (see the next refusal).`,
34
+ /** `sessionScopeProblem`: the `systemd-run` binary is missing. */
35
+ sessionScopeNoSystemdRun: ({ distro }) => `sessionSandbox needs "systemd-run" in "${distro}"; the distro's systemd package is incomplete or missing.`,
36
+ /** `sessionScopeProblem`: the user manager would stop with the last session. */
37
+ sessionScopeNoLinger: ({ distro }) => `sessionSandbox needs the user manager to outlive a login session: run "loginctl enable-linger $USER" in "${distro}" and retry.`,
38
+ /**
39
+ * `sessionScopeProblem`: the probe's answer is empty or unrecognized. The
40
+ * caller renders `answer` (the quoted word, or `(nothing)`) and `errorSuffix`
41
+ * (`""` or `": <error>"`) so both languages keep one sentence shape.
42
+ */
43
+ sessionScopeUnknownAnswer: ({ distro, answer, errorSuffix }) => `the sessionSandbox preflight in "${distro}" answered ${answer}${errorSuffix}; see docs/adr/0001-session-scoped-sandbox.md.`,
44
+ /** `missingBwrapRemedy` without a detected package family. */
45
+ bwrapMissingGeneric: ({ distro }) => `bwrap is not usable inside distro "${distro}". Install it with ` +
46
+ `"scripts/bootstrap.sh ${distro} --install" (from the package), or install the ` +
47
+ `"bubblewrap" package with the distro's package manager.`,
48
+ /** `missingBwrapRemedy` with a family's direct install command. */
49
+ bwrapMissingFamily: ({ distro, direct }) => `bwrap is not usable inside distro "${distro}". Install it with ` +
50
+ `"scripts/bootstrap.sh ${distro} --install" (from the package), or directly: ` +
51
+ `wsl.exe -d ${distro} -u root -- ${direct}`,
52
+ /** `composeBwrapFailure`: bwrap ran and refused — present but unusable. */
53
+ bwrapBroken: ({ distro, output }) => `bwrap is installed inside distro "${distro}" but failed the usability probe: ${output}. ` +
54
+ `This is usually the kernel (unprivileged user namespaces disabled) or an unusable bwrap build rather than a missing package, so reinstalling will not help. ` +
55
+ `Check \`wsl.exe -d ${distro} --exec bwrap --version\` inside the distro, or set \`sandbox: false\` on the wsl-shell and wsl-fs rows to run unconfined.`,
56
+ /** `bwrapInstallHint`: bwrap probed healthy but failed a real command. */
57
+ bwrapRuntimeFailure: ({ distro }) => `bwrap failed at run time inside distro "${distro}". Check \`bwrap --version\` there, ` +
58
+ `or reinstall it: "scripts/bootstrap.sh ${distro} --install".`,
59
+ /** `composeBwrapFailure`: the unclassified probe's raw output, appended to a remedy. */
60
+ bwrapProbeFailedSuffix: ({ output }) => ` The probe failed with: ${output}`,
61
+ /** `throwIfDistroUnavailable`: wsl.exe says the distro is gone. */
62
+ distroUnavailable: ({ code, distro }) => `wsl.exe reported ${code} for distro "${distro}": it is not installed, or not running. ` +
63
+ `Start it with \`wsl.exe -d ${distro}\`, check \`wsl.exe -l -v\`, or point \`distro\` at another one. ` +
64
+ `This is not a sandbox denial, so running with wider permissions will not help.`,
65
+ /** `throwIfWorkdirMissing`: `wsl.exe --cd` fell back to `/`. */
66
+ workdirMissing: ({ missing }) => `wsl.exe could not enter the working directory "${missing}" inside the distro, so the command ran from "/" instead. ` +
67
+ `Create it, or point \`cwd\` (or the request's \`workdir\`) at a directory that exists.`,
68
+ /** `throwIfWorkdirInAnotherDistro`: the workspace names a pinned-against distro. */
69
+ workdirAnotherDistro: ({ workdir, distro }) => `"${workdir}" names a workspace in another WSL distro, and this profile pins its commands to "${distro}" — ` +
70
+ `running them here would act on a different machine's tree. Open a session in that distro, ` +
71
+ `or point cwd/workdir at this distro.`,
72
+ };
73
+ /** The Chinese catalog; the type keeps every key and parameter in step with `en`. */
74
+ const zh = {
75
+ sessionScopeNoSystemd: ({ distro }) => `sessionSandbox 需要在 "${distro}" 中以 systemd 作为 PID 1:在 /etc/wsl.conf 中设置 [boot] systemd=true,运行 "wsl --shutdown",然后重新打开会话。`,
76
+ sessionScopeNoUserManager: ({ distro }) => `sessionSandbox 需要能访问 "${distro}" 中的 systemd 用户管理器:先在发行版中登录一次,或启用 lingering(见下一条拒绝说明)。`,
77
+ sessionScopeNoSystemdRun: ({ distro }) => `sessionSandbox 需要 "${distro}" 中存在 "systemd-run";该发行版的 systemd 软件包不完整或缺失。`,
78
+ sessionScopeNoLinger: ({ distro }) => `sessionSandbox 需要用户管理器在登录会话结束后继续存活:在 "${distro}" 中运行 "loginctl enable-linger $USER",然后重试。`,
79
+ sessionScopeUnknownAnswer: ({ distro, answer, errorSuffix }) => `"${distro}" 中的 sessionSandbox 预检应答为 ${answer}${errorSuffix};参见 docs/adr/0001-session-scoped-sandbox.md。`,
80
+ bwrapMissingGeneric: ({ distro }) => `bwrap 在发行版 "${distro}" 中不可用。请用 "scripts/bootstrap.sh ${distro} --install"(随包提供)安装,` +
81
+ `或用发行版的包管理器安装 "bubblewrap" 软件包。`,
82
+ bwrapMissingFamily: ({ distro, direct }) => `bwrap 在发行版 "${distro}" 中不可用。请用 "scripts/bootstrap.sh ${distro} --install"(随包提供)安装,` +
83
+ `或直接执行:wsl.exe -d ${distro} -u root -- ${direct}`,
84
+ bwrapBroken: ({ distro, output }) => `bwrap 已安装在发行版 "${distro}" 中,但未通过可用性探测:${output}。` +
85
+ `这通常是内核原因(未特权用户命名空间被禁用)或 bwrap 构建不可用,而不是缺少软件包,重新安装不会有帮助。` +
86
+ `请在发行版内检查 \`wsl.exe -d ${distro} --exec bwrap --version\`,或将 wsl-shell 与 wsl-fs 行设为 \`sandbox: false\` 以无隔离运行。`,
87
+ bwrapRuntimeFailure: ({ distro }) => `bwrap 在发行版 "${distro}" 中运行时失败。请在该发行版内检查 \`bwrap --version\`,` +
88
+ `或重新安装:"scripts/bootstrap.sh ${distro} --install"。`,
89
+ bwrapProbeFailedSuffix: ({ output }) => `(探测失败输出:${output})`,
90
+ distroUnavailable: ({ code, distro }) => `wsl.exe 对发行版 "${distro}" 报告了 ${code}:该发行版未安装或未在运行。` +
91
+ `用 \`wsl.exe -d ${distro}\` 启动它,用 \`wsl.exe -l -v\` 检查,或将 \`distro\` 指向另一个发行版。` +
92
+ `这不是沙箱拒绝,放宽权限也不会有帮助。`,
93
+ workdirMissing: ({ missing }) => `wsl.exe 无法进入发行版中的工作目录 "${missing}",命令改从 "/" 运行。` +
94
+ `请创建该目录,或将 \`cwd\`(或请求的 \`workdir\`)指向一个已存在的目录。`,
95
+ workdirAnotherDistro: ({ workdir, distro }) => `"${workdir}" 指向另一个 WSL 发行版中的工作区,而本 profile 将命令固定在 "${distro}" —— ` +
96
+ `在这里运行会作用于另一台机器的目录树。请在该发行版中打开会话,或将 cwd/workdir 指向本发行版。`,
97
+ };
98
+ /** The active language; English until a settings service reports otherwise. */
99
+ let current = "en";
100
+ /**
101
+ * The locale the message builders render in.
102
+ *
103
+ * @returns the active catalog language.
104
+ */
105
+ export function messagesLocale() {
106
+ return current;
107
+ }
108
+ /**
109
+ * Force the message language. The wiring calls this from the resolved
110
+ * `locale.preference`; tests call it directly and reset afterwards.
111
+ *
112
+ * @param locale - the language to render in.
113
+ */
114
+ export function configureMessagesLocale(locale) {
115
+ current = locale;
116
+ }
117
+ /**
118
+ * Render one message in the active language, falling back to the English
119
+ * template when the active catalog somehow lacks the key (the catalogs are
120
+ * type-checked against each other, so this guards runtime drift only).
121
+ *
122
+ * The `params` type correlates the parameters with the key: the conditional
123
+ * resolves per call site, so `t("sessionScopeNoLinger", { distro })`
124
+ * typechecks while `t("sessionScopeNoLinger", { missing })` does not. It
125
+ * lives in the JSDoc because a comment between the parameters would have the
126
+ * type-stripping build emit a line with trailing whitespace, which the style
127
+ * gate refuses.
128
+ *
129
+ * @typeParam K - the message key.
130
+ * @param key - the message to render.
131
+ * @param params - the key's parameters, as the template declares them.
132
+ * @returns the rendered message.
133
+ */
134
+ export function t(key, params) {
135
+ // Key and parameter parity between the catalogs is the type system's job
136
+ // (`zh` is `typeof en`), so the lookup needs no runtime fallback.
137
+ const template = current === "zh" ? zh[key] : en[key];
138
+ return template(params);
139
+ }
140
+ /**
141
+ * Map one `locale.preference` value onto a catalog language. The app's
142
+ * language ids are BCP 47-style tags (`zh`, `en`, `ja`, …); the plugin ships
143
+ * zh and en, and every other id renders English.
144
+ *
145
+ * @param preference - the stored preference, or anything else when unset.
146
+ * @returns the catalog language the preference selects.
147
+ */
148
+ export function resolveMessagesLocale(preference) {
149
+ return typeof preference === "string" && /^zh/iu.test(preference) ? "zh" : "en";
150
+ }
151
+ /**
152
+ * Follow the harness locale for the caller's composition. Every row wires its
153
+ * own injection (the shell executor, the fs provider and the preflight all
154
+ * call this), so a hot-reloaded row re-wires too; the redundant reads converge
155
+ * on the same app-wide preference and the events are rare.
156
+ *
157
+ * The `settings` service is optional — a profile without it (some CLI
158
+ * compositions) keeps English. When it is present, the preference is read once
159
+ * the service resolves and again on every `settings/document-updated` event,
160
+ * which also covers the `locale` entry activating after this row did. A read
161
+ * that throws keeps the previous language: this is presentation, not gating.
162
+ *
163
+ * @param ctx - the row's composition context.
164
+ */
165
+ export function installMessagesLocale(ctx) {
166
+ if (typeof ctx.inject !== "function")
167
+ return;
168
+ ctx.inject(["settings"], (scope) => {
169
+ // Narrow once to the shape this module reads; see `SettingsScope`.
170
+ const view = scope;
171
+ const settings = view.settings;
172
+ if (settings?.describe === undefined)
173
+ return;
174
+ const read = () => {
175
+ try {
176
+ const row = settings.describe().find((entry) => entry.ns === "locale");
177
+ if (row === undefined)
178
+ return;
179
+ // The descriptor's value is the entry's projected volatile form —
180
+ // `{ preference?: string }` for the locale entry.
181
+ const preference = row.value?.preference;
182
+ configureMessagesLocale(resolveMessagesLocale(preference));
183
+ }
184
+ catch {
185
+ // A describe failure must never fail a row's load; keep the last language.
186
+ }
187
+ };
188
+ read();
189
+ // The event name lives in the host's own `Events` augmentation, which this
190
+ // plugin's typings do not carry; widen the registration to a plain string.
191
+ view.on("settings/document-updated", () => read());
192
+ });
193
+ }
194
+ /**
195
+ * Restore English. Tests only: production wiring is process-wide by design.
196
+ */
197
+ export function resetMessagesLocaleForTests() {
198
+ current = "en";
199
+ }