dsh-wsl-workspace 0.1.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.
@@ -0,0 +1,105 @@
1
+ //#region src/shared/paths.ts
2
+ /** The two UNC hosts WSL exposes a distribution's filesystem under. */
3
+ const UNC_HOSTS = ["wsl.localhost", "wsl$"];
4
+ /**
5
+ * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2
6
+ * `\\wsl.localhost\<distro>\<linux>` form, the legacy `\\wsl$\<distro>\<linux>`
7
+ * interop form, and forward-slash spellings of either.
8
+ * @param raw - candidate absolute path.
9
+ * @returns the parsed target, or null when the path is not a WSL UNC.
10
+ */
11
+ function parseWslUnc(raw) {
12
+ const normalized = raw.replace(/\\/g, "/").replace(/\/\/+/g, "//");
13
+ if (!normalized.startsWith("//")) return null;
14
+ const segments = normalized.slice(2).split("/");
15
+ const host = (segments[0] ?? "").toLowerCase();
16
+ if (!UNC_HOSTS.includes(host)) return null;
17
+ const distro = segments[1] ?? "";
18
+ if (distro === "") return null;
19
+ return {
20
+ distro,
21
+ linuxPath: `/${segments.slice(2).filter((segment) => segment.length > 0).join("/")}`
22
+ };
23
+ }
24
+ /**
25
+ * Normalize a Linux absolute path for the Host: collapse repeated slashes and
26
+ * strip a trailing slash (root becomes `/`).
27
+ * @param path - absolute Linux path.
28
+ * @returns the normalized path.
29
+ */
30
+ function normalizeLinuxPath(path) {
31
+ const collapsed = path.replace(/\/+/g, "/");
32
+ return collapsed === "/" ? "/" : collapsed.replace(/\/$/, "");
33
+ }
34
+ /**
35
+ * Whether a path is an absolute, non-empty Linux path.
36
+ * @param path - candidate.
37
+ * @returns whether it starts with `/` and contains no NUL.
38
+ */
39
+ function isAbsoluteLinuxPath(path) {
40
+ return path.startsWith("/") && !path.includes("\0");
41
+ }
42
+ /**
43
+ * Join a distro and a Linux absolute path into the WSL2 UNC form used as the
44
+ * workspace identity (`\\wsl.localhost\<distro>\<linux>`, backslash segments).
45
+ * @param distro - distro name.
46
+ * @param linuxPath - absolute Linux path (leading `/`).
47
+ * @returns the UNC path.
48
+ */
49
+ function joinUnc(distro, linuxPath) {
50
+ if (!isAbsoluteLinuxPath(linuxPath)) throw new Error(`wsl-workspace: cannot map a non-absolute Linux path "${linuxPath}" to UNC`);
51
+ if (distro === "" || distro === "." || distro === ".." || /[\\/]/.test(distro)) throw new Error(`wsl-workspace: invalid distribution name "${distro}"`);
52
+ const normalized = linuxPath.replace(/\/+/g, "/").replace(/\/$/, "");
53
+ const windowsSegments = (normalized.startsWith("/") ? normalized.slice(1) : normalized).replace(/\//g, "\\");
54
+ return `\\\\wsl.localhost\\${distro}${windowsSegments === "" ? "" : `\\${windowsSegments}`}`;
55
+ }
56
+ /**
57
+ * Translate a Windows drive path to the drvfs mount path WSL distributions
58
+ * conventionally expose it at (`C:\foo` → `/mnt/c/foo`). Only single-letter
59
+ * drives under `/mnt` are mapped; custom mount points are out of scope.
60
+ * @param path - the candidate Windows path.
61
+ * @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.
62
+ */
63
+ function windowsToMntPath(path) {
64
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(path);
65
+ if (match === null) return null;
66
+ const rest = (match[2] ?? "").replace(/\\/g, "/").replace(/\/+/g, "/").replace(/\/$/, "");
67
+ return `/mnt/${(match[1] ?? "").toLowerCase()}${rest === "" ? "" : `/${rest}`}`;
68
+ }
69
+ /**
70
+ * Translate a `/mnt/<drive>/…` path back to its Windows drive path.
71
+ * @param linuxPath - the candidate Linux path.
72
+ * @returns the `X:\…` drive path, or `null` when the path is not a drvfs mount.
73
+ */
74
+ function mntToWindowsPath(linuxPath) {
75
+ const match = /^\/mnt\/([a-zA-Z])(?:\/(.*))?$/.exec(linuxPath);
76
+ if (match === null) return null;
77
+ const rest = (match[2] ?? "").replace(/\//g, "\\");
78
+ return `${(match[1] ?? "").toUpperCase()}:\\${rest}`;
79
+ }
80
+ /**
81
+ * True when a value is a Windows-shaped path (drive or UNC), which is how
82
+ * the shell executor decides the WSLENV `/p` translation flag: only Windows
83
+ * path values need translation when they cross into the Linux process.
84
+ * @param value - the environment value to classify.
85
+ * @returns whether the value looks like a Windows path.
86
+ */
87
+ function isWindowsPathShaped(value) {
88
+ return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
89
+ }
90
+ /** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */
91
+ const WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
92
+ /**
93
+ * Whether a value is a safe Linux username for `wsl.exe -u`. The check is
94
+ * strict on purpose: a value starting with `-` could be parsed as a wsl.exe
95
+ * option instead of a username.
96
+ * @param value - candidate username.
97
+ * @returns whether it matches the Linux username shape.
98
+ */
99
+ function isValidWslUsername(value) {
100
+ return WSL_USERNAME_PATTERN.test(value);
101
+ }
102
+ //#endregion
103
+ export { mntToWindowsPath as a, windowsToMntPath as c, joinUnc as i, isValidWslUsername as n, normalizeLinuxPath as o, isWindowsPathShaped as r, parseWslUnc as s, isAbsoluteLinuxPath as t };
104
+
105
+ //# sourceMappingURL=paths-DBaSmi7x.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paths-DBaSmi7x.js","names":[],"sources":["../src/shared/paths.ts"],"sourcesContent":["/**\n * WSL path helpers shared by the client and host halves. Pure and\n * dependency-free so both planes can import them without a runtime edge.\n */\n\n/** WSL2 default loopback bridge host: `\\\\wsl.localhost\\<distro>\\...`. */\nconst WSL_LOCALHOST_HOST = 'wsl.localhost'\n/** Legacy WSL interop host: `\\\\wsl$\\<distro>\\...`. */\nconst WSL_LEGACY_HOST = 'wsl$'\n\n/** The two UNC hosts WSL exposes a distribution's filesystem under. */\nconst UNC_HOSTS = [WSL_LOCALHOST_HOST, WSL_LEGACY_HOST]\n\n/** One WSL workspace coordinate parsed out of a UNC path. */\nexport interface WslUncTarget {\n /** Distro name (e.g. `Ubuntu`) as `wsl -l -q` reports it. */\n readonly distro: string\n /** Normalized absolute Linux path (leading `/`; no trailing slash except root). */\n readonly linuxPath: string\n}\n\n/**\n * Parse a WSL UNC path into its distro and Linux path. Accepts the WSL2\n * `\\\\wsl.localhost\\<distro>\\<linux>` form, the legacy `\\\\wsl$\\<distro>\\<linux>`\n * interop form, and forward-slash spellings of either.\n * @param raw - candidate absolute path.\n * @returns the parsed target, or null when the path is not a WSL UNC.\n */\nexport function parseWslUnc(raw: string): WslUncTarget | null {\n const normalized = raw.replace(/\\\\/g, '/').replace(/\\/\\/+/g, '//')\n if (!normalized.startsWith('//')) return null\n const segments = normalized.slice(2).split('/')\n const host = (segments[0] ?? '').toLowerCase()\n if (!UNC_HOSTS.includes(host)) return null\n const distro = segments[1] ?? ''\n if (distro === '') return null\n const rest = segments.slice(2).filter(segment => segment.length > 0)\n return { distro, linuxPath: `/${rest.join('/')}` }\n}\n\n/**\n * Whether a path resolves into a WSL distro through either UNC form.\n * @param raw - candidate absolute path.\n * @returns whether the path parses as a WSL UNC.\n */\nexport function isWslUnc(raw: string): boolean {\n return parseWslUnc(raw) !== null\n}\n\n/**\n * Translate a WSL UNC path to the absolute Linux path a process inside the\n * distribution can open. Throws on non-WSL input: callers rely on this\n * conversion to hand paths to the Linux world, so a silent pass-through\n * would hand a Windows path to bash.\n * @param uncPath - a path {@link parseWslUnc} accepts.\n * @returns the absolute Linux path.\n */\nexport function uncToLinux(uncPath: string): string {\n const parts = parseWslUnc(uncPath)\n if (parts === null) {\n throw new Error(`wsl-workspace: \"${uncPath}\" is not a WSL UNC path`)\n }\n return parts.linuxPath\n}\n\n/**\n * Normalize a Linux absolute path for the Host: collapse repeated slashes and\n * strip a trailing slash (root becomes `/`).\n * @param path - absolute Linux path.\n * @returns the normalized path.\n */\nexport function normalizeLinuxPath(path: string): string {\n const collapsed = path.replace(/\\/+/g, '/')\n return collapsed === '/' ? '/' : collapsed.replace(/\\/$/, '')\n}\n\n/**\n * Whether a path is an absolute, non-empty Linux path.\n * @param path - candidate.\n * @returns whether it starts with `/` and contains no NUL.\n */\nexport function isAbsoluteLinuxPath(path: string): boolean {\n return path.startsWith('/') && !path.includes('\\0')\n}\n\n/**\n * Join a distro and a Linux absolute path into the WSL2 UNC form used as the\n * workspace identity (`\\\\wsl.localhost\\<distro>\\<linux>`, backslash segments).\n * @param distro - distro name.\n * @param linuxPath - absolute Linux path (leading `/`).\n * @returns the UNC path.\n */\nexport function joinUnc(distro: string, linuxPath: string): string {\n if (!isAbsoluteLinuxPath(linuxPath)) {\n throw new Error(`wsl-workspace: cannot map a non-absolute Linux path \"${linuxPath}\" to UNC`)\n }\n // Defense in depth: a distribution name with separators or dot-dirs would\n // escape the `\\\\wsl.localhost\\` share structure (the host route validates\n // wire-supplied names too; every other caller passes through here).\n if (distro === '' || distro === '.' || distro === '..' || /[\\\\/]/.test(distro)) {\n throw new Error(`wsl-workspace: invalid distribution name \"${distro}\"`)\n }\n const normalized = linuxPath.replace(/\\/+/g, '/').replace(/\\/$/, '')\n const withoutLeading = normalized.startsWith('/') ? normalized.slice(1) : normalized\n const windowsSegments = withoutLeading.replace(/\\//g, '\\\\')\n const suffix = windowsSegments === '' ? '' : `\\\\${windowsSegments}`\n return `\\\\\\\\wsl.localhost\\\\${distro}${suffix}`\n}\n\n/**\n * Translate a Windows drive path to the drvfs mount path WSL distributions\n * conventionally expose it at (`C:\\foo` → `/mnt/c/foo`). Only single-letter\n * drives under `/mnt` are mapped; custom mount points are out of scope.\n * @param path - the candidate Windows path.\n * @returns the `/mnt/<drive>/…` path, or `null` for non-drive paths.\n */\nexport function windowsToMntPath(path: string): string | null {\n const match = /^([A-Za-z]):[\\\\/](.*)$/.exec(path)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/\\/$/, '')\n return `/mnt/${(match[1] ?? '').toLowerCase()}${rest === '' ? '' : `/${rest}`}`\n}\n\n/**\n * Translate a `/mnt/<drive>/…` path back to its Windows drive path.\n * @param linuxPath - the candidate Linux path.\n * @returns the `X:\\…` drive path, or `null` when the path is not a drvfs mount.\n */\nexport function mntToWindowsPath(linuxPath: string): string | null {\n const match = /^\\/mnt\\/([a-zA-Z])(?:\\/(.*))?$/.exec(linuxPath)\n if (match === null) return null\n const rest = (match[2] ?? '').replace(/\\//g, '\\\\')\n return `${(match[1] ?? '').toUpperCase()}:\\\\${rest}`\n}\n\n/**\n * True when a value is a Windows-shaped path (drive or UNC), which is how\n * the shell executor decides the WSLENV `/p` translation flag: only Windows\n * path values need translation when they cross into the Linux process.\n * @param value - the environment value to classify.\n * @returns whether the value looks like a Windows path.\n */\nexport function isWindowsPathShaped(value: string): boolean {\n return /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\n/** Linux username shape for `wsl.exe -u`: starts with a letter or underscore, then letters/digits/`_`/`.`/`-` (max 64). */\nconst WSL_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/\n\n/**\n * Whether a value is a safe Linux username for `wsl.exe -u`. The check is\n * strict on purpose: a value starting with `-` could be parsed as a wsl.exe\n * option instead of a username.\n * @param value - candidate username.\n * @returns whether it matches the Linux username shape.\n */\nexport function isValidWslUsername(value: string): boolean {\n return WSL_USERNAME_PATTERN.test(value)\n}\n"],"mappings":";;AAWA,MAAM,YAAY,CAAC,iBAAoB,MAAe;;;;;;;;AAiBtD,SAAgB,YAAY,KAAkC;CAC5D,MAAM,aAAa,IAAI,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,UAAU,IAAI;CACjE,IAAI,CAAC,WAAW,WAAW,IAAI,GAAG,OAAO;CACzC,MAAM,WAAW,WAAW,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG;CAC9C,MAAM,QAAQ,SAAS,MAAM,GAAA,CAAI,YAAY;CAC7C,IAAI,CAAC,UAAU,SAAS,IAAI,GAAG,OAAO;CACtC,MAAM,SAAS,SAAS,MAAM;CAC9B,IAAI,WAAW,IAAI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,iCAAiC,KAAK,SAAS;CAC7D,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,QAAQ,MAAM,MAAM,GAAA,CAAI,QAAQ,OAAO,IAAI;CACjD,OAAO,IAAI,MAAM,MAAM,GAAA,CAAI,YAAY,EAAE,KAAK;AAChD;;;;;;;;AASA,SAAgB,oBAAoB,OAAwB;CAC1D,OAAO,kBAAkB,KAAK,KAAK,KAAK,MAAM,WAAW,MAAM;AACjE;;AAGA,MAAM,uBAAuB;;;;;;;;AAS7B,SAAgB,mBAAmB,OAAwB;CACzD,OAAO,qBAAqB,KAAK,KAAK;AACxC"}
package/lib/shell.js ADDED
@@ -0,0 +1,382 @@
1
+ import { c as windowsToMntPath, i as joinUnc, n as isValidWslUsername, r as isWindowsPathShaped, s as parseWslUnc } from "./paths-DBaSmi7x.js";
2
+ import { a as getWorkspaceUsername, n as defaultDistroSync } from "./wsl-GjkUifnx.js";
3
+ import z from "@deepseek-ai/schemastery";
4
+ import { ShellExecutor } from "@deepseek-ai/dsh-shell";
5
+ import { MAX_TIMER_DELAY_MS, clampTimeout, deadline, timeoutOf } from "@deepseek-ai/dsh-timeout";
6
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/usingCtx.js
7
+ function _usingCtx() {
8
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
9
+ var n = Error();
10
+ return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
11
+ }, e = {}, n = [];
12
+ function using(r, e) {
13
+ if (null != e) {
14
+ if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
15
+ if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
16
+ if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
17
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
18
+ t && (o = function o() {
19
+ try {
20
+ t.call(e);
21
+ } catch (r) {
22
+ return Promise.reject(r);
23
+ }
24
+ }), n.push({
25
+ v: e,
26
+ d: o,
27
+ a: r
28
+ });
29
+ } else r && n.push({
30
+ d: e,
31
+ a: r
32
+ });
33
+ return e;
34
+ }
35
+ return {
36
+ e,
37
+ u: using.bind(null, !1),
38
+ a: using.bind(null, !0),
39
+ d: function d() {
40
+ var o, t = this.e, s = 0;
41
+ function next() {
42
+ for (; o = n.pop();) try {
43
+ if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
44
+ if (o.d) {
45
+ var r = o.d.call(o.v);
46
+ if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
47
+ } else s |= 1;
48
+ } catch (r) {
49
+ return err(r);
50
+ }
51
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
52
+ if (t !== e) throw t;
53
+ }
54
+ function err(n) {
55
+ return t = t !== e ? new r(n, t) : n, next();
56
+ }
57
+ return next();
58
+ }
59
+ };
60
+ }
61
+ //#endregion
62
+ //#region src/shell.ts
63
+ /**
64
+ * Model-friendly environment overrides (same set `dsh-bash-local` hardcodes):
65
+ * disable colors, pagers, and interactive terminal features that would garble
66
+ * tool output. These values cross into the Linux process through WSLENV.
67
+ */
68
+ const ENV_OVERRIDES = {
69
+ NO_COLOR: "1",
70
+ TERM: "dumb",
71
+ PAGER: "cat",
72
+ GIT_PAGER: "cat"
73
+ };
74
+ /** Default SIGTERM→SIGKILL grace period (matches `dsh-bash-local`). */
75
+ const DEFAULT_GRACE_MS = 3e3;
76
+ /** Default per-stream spill cap (matches `dsh-bash-local`). */
77
+ const DEFAULT_MAX_SPILL_BYTES = 64 * 1024 * 1024;
78
+ /** Project a settled collect-mode reader into the final CollectedOutput shape. */
79
+ function finalOutput(reader) {
80
+ const read = reader.readFrom(0);
81
+ return {
82
+ text: read.text,
83
+ truncated: read.lossy,
84
+ ...read.spillPath !== void 0 ? { spillPath: read.spillPath } : {}
85
+ };
86
+ }
87
+ function assertPositiveFinite(name, value) {
88
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`wsl-shell: ${name} must be a positive finite number`);
89
+ }
90
+ /**
91
+ * Reject a resolved configuration this executor could not run with, so a
92
+ * stored value is refused where it is written instead of failing at the next
93
+ * command.
94
+ * @param config - the schema-validated configuration.
95
+ * @throws Error naming the field that cannot be used.
96
+ */
97
+ function assertServiceableWslConfig(config) {
98
+ const resolved = config;
99
+ assertPositiveFinite("timeoutMs", resolved.timeoutMs);
100
+ assertPositiveFinite("maxTimeoutMs", resolved.maxTimeoutMs);
101
+ assertPositiveFinite("maxOutputBytes", resolved.maxOutputBytes);
102
+ assertPositiveFinite("maxSpillBytes", resolved.maxSpillBytes);
103
+ assertPositiveFinite("graceMs", resolved.graceMs);
104
+ if (resolved.graceMs > MAX_TIMER_DELAY_MS) throw new Error(`wsl-shell: graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`);
105
+ if (resolved.distro !== void 0 && resolved.distro.trim() === "") throw new Error("wsl-shell: distro must be a non-empty distribution name");
106
+ if (resolved.username !== void 0 && resolved.username !== "" && !isValidWslUsername(resolved.username)) throw new Error("wsl-shell: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*");
107
+ }
108
+ /**
109
+ * WSL bash executor over the LOCAL subprocess service: `wsl.exe` is a Windows
110
+ * executable, so the Windows-side spawn, bounded output, spill files, and
111
+ * process-group termination are the local subprocess seam's mechanics; this
112
+ * executor supplies the Linux-world argv, cwd translation, and WSLENV.
113
+ */
114
+ var WslShellExecutor = class WslShellExecutor extends ShellExecutor {
115
+ static inject = ["subprocess"];
116
+ static Config = z.object({
117
+ cwd: z.string(),
118
+ distro: z.string(),
119
+ username: z.string(),
120
+ wslPath: z.string().default("wsl.exe"),
121
+ loginShell: z.boolean().default(true),
122
+ timeoutMs: z.number().default(12e4),
123
+ maxTimeoutMs: z.number().default(6e5),
124
+ maxOutputBytes: z.number().default(64e3),
125
+ maxSpillBytes: z.number().default(DEFAULT_MAX_SPILL_BYTES),
126
+ graceMs: z.number().default(DEFAULT_GRACE_MS)
127
+ });
128
+ resolved;
129
+ /** Validated config (schemastery applied the defaults before construction). */
130
+ get config() {
131
+ return this.resolved;
132
+ }
133
+ constructor(ctx, config) {
134
+ super(ctx);
135
+ const entry = config;
136
+ assertServiceableWslConfig(entry);
137
+ this.resolved = entry;
138
+ }
139
+ /**
140
+ * Resolve a request into a fully-specified spec: fill `workdir` from
141
+ * `config.cwd`, and `timeoutMs` from `config.timeoutMs`, capped at
142
+ * `config.maxTimeoutMs`. The tool layer calls this before
143
+ * {@link run}/{@link start}, so those methods receive explicit values.
144
+ */
145
+ resolve(request) {
146
+ const timeoutMs = clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, "wsl-shell: request.timeoutMs");
147
+ const stdoutMaxBytes = request.stdoutMaxBytes ?? this.config.maxOutputBytes;
148
+ assertPositiveFinite("request.stdoutMaxBytes", stdoutMaxBytes);
149
+ return {
150
+ command: request.command,
151
+ workdir: request.workdir ?? this.config.cwd ?? process.cwd(),
152
+ timeoutMs,
153
+ stdoutMaxBytes,
154
+ ...request.signal ? { signal: request.signal } : {},
155
+ ...request.stdin !== void 0 ? { stdin: request.stdin } : {},
156
+ ...request.env !== void 0 ? { env: request.env } : {},
157
+ ...request.dshEnv !== void 0 ? { dshEnv: request.dshEnv } : {},
158
+ sandboxPolicy: request.sandboxPolicy
159
+ };
160
+ }
161
+ /**
162
+ * Translate a resolved spec into the Linux execution plan. Fails loud on a
163
+ * workdir that names neither the WSL world (UNC or Linux path) nor a
164
+ * Windows drive path (reached through `/mnt/<drive>`).
165
+ * @param spec - the resolved execution spec.
166
+ * @returns the translated plan, including the complete argv.
167
+ */
168
+ plan(spec) {
169
+ const workdir = spec.workdir;
170
+ let distro;
171
+ let linuxCwd;
172
+ let windowsCwd;
173
+ let username;
174
+ const unc = parseWslUnc(workdir);
175
+ if (unc !== null) {
176
+ distro = unc.distro;
177
+ linuxCwd = unc.linuxPath;
178
+ windowsCwd = process.env.SystemRoot ?? process.cwd();
179
+ username = this.resolveUser(spec, joinUnc(unc.distro, unc.linuxPath));
180
+ } else if (workdir.startsWith("/")) {
181
+ distro = this.resolveDistro(spec);
182
+ linuxCwd = workdir;
183
+ windowsCwd = process.cwd();
184
+ username = this.resolveUser(spec, void 0);
185
+ } else {
186
+ const mnt = windowsToMntPath(workdir);
187
+ if (mnt === null) throw new Error(`wsl-shell: workdir "${workdir}" is not in the WSL execution world`);
188
+ distro = this.resolveDistro(spec);
189
+ linuxCwd = mnt;
190
+ windowsCwd = workdir;
191
+ username = this.resolveUser(spec, void 0);
192
+ }
193
+ const env = this.withWslEnv(spec);
194
+ const argv = [
195
+ this.config.wslPath,
196
+ "-d",
197
+ distro,
198
+ ...username !== void 0 && username !== "" ? ["-u", username] : [],
199
+ "--cd",
200
+ linuxCwd,
201
+ "-e",
202
+ "bash",
203
+ this.config.loginShell ? "-lc" : "-c",
204
+ spec.command
205
+ ];
206
+ return {
207
+ distro,
208
+ linuxCwd,
209
+ windowsCwd,
210
+ env,
211
+ argv
212
+ };
213
+ }
214
+ /**
215
+ * Resolve the distribution for a workdir that carries none. The chain:
216
+ * the calling session's distribution (`DSH_WSL_DISTRO`, contributed by the
217
+ * host half from the session's UNC workspace cwd — the common case for a
218
+ * model passing a Linux `workdir`), then the configured `distro`, then the
219
+ * host's default distribution (cached registry read) as a last resort for
220
+ * plugin-driven calls with no session. Fails loud when every source is
221
+ * absent rather than guessing a distro the path does not belong to.
222
+ * @param spec - the resolved execution spec (its dshEnv carries the session fact).
223
+ * @returns the distribution name.
224
+ */
225
+ resolveDistro(spec) {
226
+ const fromEnv = spec.dshEnv?.DSH_WSL_DISTRO;
227
+ if (fromEnv !== void 0 && fromEnv !== "") return fromEnv;
228
+ const configured = this.config.distro;
229
+ if (configured !== void 0 && configured !== "") return configured;
230
+ const fallback = defaultDistroSync();
231
+ if (fallback !== void 0) return fallback;
232
+ throw new Error("wsl-shell: Linux workdir carries no distribution; no session DSH_WSL_DISTRO, distro config, or default distribution is available");
233
+ }
234
+ /**
235
+ * Resolve the Linux user bash runs as. The chain: the calling session's
236
+ * workspace user (`DSH_WSL_USER`, contributed by the host half), then the
237
+ * workspace's stored username when the workdir is a UNC path, then the
238
+ * configured `username`. Absent everywhere, the distribution's default
239
+ * user runs. Invalid values are skipped (they were validated on write;
240
+ * the guard is defense in depth).
241
+ * @param spec - the resolved execution spec (its dshEnv carries the session fact).
242
+ * @param uncKey - canonical UNC key of the workdir when it is a UNC path.
243
+ * @returns the username, or undefined for the distro default user.
244
+ */
245
+ resolveUser(spec, uncKey) {
246
+ const candidates = [
247
+ spec.dshEnv?.DSH_WSL_USER,
248
+ uncKey === void 0 ? void 0 : getWorkspaceUsername(uncKey),
249
+ this.config.username
250
+ ];
251
+ for (const candidate of candidates) if (candidate !== void 0 && candidate !== "" && isValidWslUsername(candidate)) return candidate;
252
+ }
253
+ /**
254
+ * Merge the caller env layers and inject `WSLENV` so the Windows-side
255
+ * values reach the Linux process. Windows-path-shaped values get the `/p`
256
+ * translation flag (they become `/mnt/<drive>/…` inside WSL); the ambient
257
+ * `WSLENV` value is preserved and extended.
258
+ * @param spec - the resolved execution spec.
259
+ * @returns the explicit environment map for the spawn.
260
+ */
261
+ withWslEnv(spec) {
262
+ const env = {
263
+ ...ENV_OVERRIDES,
264
+ ...spec.env,
265
+ ...spec.dshEnv
266
+ };
267
+ const flags = [];
268
+ for (const [key, value] of Object.entries(env)) {
269
+ if (key.toUpperCase() === "WSLENV") continue;
270
+ flags.push(isWindowsPathShaped(value) ? `${key}/p` : key);
271
+ }
272
+ env.WSLENV = [process.env.WSLENV, flags.join(":")].filter((part) => part !== void 0 && part !== "").join(":");
273
+ return env;
274
+ }
275
+ /** Map a plan onto a fully-specified subprocess spawn. */
276
+ spawnSpec(plan, spec, stdoutMaxBytes, signal) {
277
+ const collect = (maxBytes) => ({
278
+ maxBytes,
279
+ spill: { maxBytes: this.config.maxSpillBytes }
280
+ });
281
+ return {
282
+ argv: plan.argv,
283
+ cwd: plan.windowsCwd,
284
+ stdio: {
285
+ stdin: spec.stdin !== void 0 ? { data: spec.stdin } : "ignore",
286
+ stdout: collect(stdoutMaxBytes),
287
+ stderr: collect(this.config.maxOutputBytes)
288
+ },
289
+ graceMs: this.config.graceMs,
290
+ signal,
291
+ env: plan.env
292
+ };
293
+ }
294
+ /** The collect-mode readers this executor requested (present by construction). */
295
+ static collected(handle) {
296
+ const { stdout, stderr } = handle.collected;
297
+ /* v8 ignore start -- collect dispositions expose both readers by the seam contract; defensive. */
298
+ if (stdout === void 0 || stderr === void 0) throw new Error("wsl-shell: subprocess implementation dropped a requested collect stream");
299
+ /* v8 ignore stop */
300
+ return {
301
+ stdout,
302
+ stderr
303
+ };
304
+ }
305
+ /** Run one command in the foreground. */
306
+ async run(spec) {
307
+ try {
308
+ var _usingCtx$1 = _usingCtx();
309
+ const plan = this.plan(spec);
310
+ const d = _usingCtx$1.u(deadline(spec.signal, spec.timeoutMs, "WSL_BASH_TIMEOUT"));
311
+ const handle = this.ctx.subprocess.spawn(this.spawnSpec(plan, spec, spec.stdoutMaxBytes, d.signal));
312
+ const outcome = await handle.done;
313
+ const collected = WslShellExecutor.collected(handle);
314
+ const timedOut = timeoutOf(d.signal, "WSL_BASH_TIMEOUT") !== void 0;
315
+ const aborted = d.signal.aborted && !timedOut;
316
+ return {
317
+ ...outcome,
318
+ timedOut,
319
+ aborted,
320
+ timeoutMs: spec.timeoutMs,
321
+ stdout: finalOutput(collected.stdout),
322
+ stderr: finalOutput(collected.stderr)
323
+ };
324
+ } catch (_) {
325
+ _usingCtx$1.e = _;
326
+ } finally {
327
+ _usingCtx$1.d();
328
+ }
329
+ }
330
+ /** Start one command in the background and return its live handle. */
331
+ start(spec) {
332
+ const plan = this.plan(spec);
333
+ const running = this.ctx.subprocess.spawn(this.spawnSpec(plan, spec, this.config.maxOutputBytes, spec.signal));
334
+ const collected = WslShellExecutor.collected(running);
335
+ let spawnFailureNote;
336
+ const consumeSpawnFailure = () => {
337
+ const note = spawnFailureNote ?? "";
338
+ spawnFailureNote = void 0;
339
+ return note;
340
+ };
341
+ let stdoutOffset = 0;
342
+ let stderrOffset = 0;
343
+ const proc = {
344
+ status: "running",
345
+ exitCode: null,
346
+ signal: null,
347
+ done: running.done.then((outcome) => {
348
+ if (proc.status === "running") proc.status = spec.signal?.aborted === true || outcome.signal !== null ? "killed" : "completed";
349
+ proc.exitCode = outcome.exitCode;
350
+ proc.signal = outcome.signal;
351
+ }, (error) => {
352
+ proc.status = "killed";
353
+ spawnFailureNote = `spawn failed: ${String(error)}`;
354
+ }),
355
+ readOutput: () => {
356
+ const out = collected.stdout.readFrom(stdoutOffset);
357
+ const err = collected.stderr.readFrom(stderrOffset);
358
+ stdoutOffset = out.nextOffset;
359
+ stderrOffset = err.nextOffset;
360
+ const errText = err.text.length > 0 ? err.text : consumeSpawnFailure();
361
+ const separator = out.text.length > 0 && !out.text.endsWith("\n") ? "\n" : "";
362
+ return {
363
+ delta: out.text + (errText.length > 0 ? `${separator}[stderr]\n${errText}` : ""),
364
+ lossy: out.lossy || err.lossy,
365
+ ...out.spillPath !== void 0 ? { stdoutSpillPath: out.spillPath } : {},
366
+ ...err.spillPath !== void 0 ? { stderrSpillPath: err.spillPath } : {}
367
+ };
368
+ },
369
+ kill: () => {
370
+ if (proc.status !== "running") return false;
371
+ proc.status = "killed";
372
+ running.terminate();
373
+ return true;
374
+ }
375
+ };
376
+ return proc;
377
+ }
378
+ };
379
+ //#endregion
380
+ export { WslShellExecutor, WslShellExecutor as default, assertServiceableWslConfig };
381
+
382
+ //# sourceMappingURL=shell.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell.js","names":[],"sources":["../src/shell.ts"],"sourcesContent":["/**\n * WSL Service Provider for the `ctx.shell` capability seam. Every command\n * runs inside one WSL distribution as `wsl.exe -d <distro> [-u <user>]\n * --cd <linux cwd> -e bash -lc <command>`, so the model-facing bash dialect\n * matches the execution world exactly — the \"like direct calls\" experience\n * of a WSL workspace session.\n *\n * The executor is a fresh implementation modeled on\n * `@deepseek-ai/dsh-bash-local` (same deadline fusion, bounded collect,\n * background adaptation) but does NOT register the shared `shell` settings\n * namespace: the host composition already registers it through its own\n * executor, and a second registration from a preset realm would collide.\n * Configuration rides the preset row instead.\n * @module dsh-wsl-workspace/shell\n */\n\nimport { Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport { ShellExecutor } from '@deepseek-ai/dsh-shell'\nimport type {\n CollectedOutput,\n ShellExecRequest,\n ShellExecSpec,\n ShellProcess,\n ShellProcessRead,\n ShellRunResult,\n} from '@deepseek-ai/dsh-shell'\nimport type {\n SubprocessCollect,\n SubprocessHandle,\n SubprocessOutputReader,\n SubprocessSpawnSpec,\n} from '@deepseek-ai/dsh-subprocess'\nimport { clampTimeout, deadline, MAX_TIMER_DELAY_MS, timeoutOf } from '@deepseek-ai/dsh-timeout'\nimport {\n isWindowsPathShaped,\n isValidWslUsername,\n joinUnc,\n parseWslUnc,\n windowsToMntPath,\n} from './shared/paths.ts'\nimport { getWorkspaceUsername } from './shared/wsl-credentials.ts'\nimport { defaultDistroSync } from './shared/wsl.ts'\n\n/**\n * Model-friendly environment overrides (same set `dsh-bash-local` hardcodes):\n * disable colors, pagers, and interactive terminal features that would garble\n * tool output. These values cross into the Linux process through WSLENV.\n */\nconst ENV_OVERRIDES = {\n NO_COLOR: '1',\n TERM: 'dumb',\n PAGER: 'cat',\n GIT_PAGER: 'cat',\n} as const\n\n/** Default SIGTERM→SIGKILL grace period (matches `dsh-bash-local`). */\nconst DEFAULT_GRACE_MS = 3_000\n\n/** Default per-stream spill cap (matches `dsh-bash-local`). */\nconst DEFAULT_MAX_SPILL_BYTES = 64 * 1024 * 1024\n\n/** Plugin config (all optional — `static Config` supplies the defaults). */\nexport interface Config {\n /** Default working directory (a WSL UNC or Linux path); per-call workdir wins. */\n cwd?: string\n /**\n * Default distribution used only when a call's workdir carries no distro\n * (UNC workdirs always do; Linux/Windows drive workdirs do not).\n */\n distro?: string\n /**\n * Linux user bash runs as when the call carries no per-workspace user\n * (`wsl.exe -u <username>`); undefined/empty = the distro default user.\n */\n username?: string\n /** The `wsl.exe` executable (absolute path or PATH name). */\n wslPath?: string\n /** Start bash as a login shell (`-lc`) so user profile PATHs (nvm, cargo…) load. */\n loginShell?: boolean\n /** Default foreground timeout in milliseconds. */\n timeoutMs?: number\n /** Upper bound for per-call timeout overrides. */\n maxTimeoutMs?: number\n /** Per-stream in-memory output cap; overflow spills to a temp file. */\n maxOutputBytes?: number\n /** Per-stream spill-file cap; larger streams retain only their in-memory tail. */\n maxSpillBytes?: number\n /** Grace period for kill escalation and inherited pipes; at most `MAX_TIMER_DELAY_MS`. */\n graceMs?: number\n}\n\n/** The shape after schemastery applied the defaults. */\ntype ResolvedConfig = Required<Omit<Config, 'cwd' | 'distro' | 'username'>> & Pick<Config, 'cwd' | 'distro' | 'username'>\n\n/** Project a settled collect-mode reader into the final CollectedOutput shape. */\nfunction finalOutput(reader: SubprocessOutputReader): CollectedOutput {\n const read = reader.readFrom(0)\n return {\n text: read.text,\n truncated: read.lossy,\n ...read.spillPath !== undefined ? { spillPath: read.spillPath } : {},\n }\n}\n\nfunction assertPositiveFinite(name: string, value: number): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`wsl-shell: ${name} must be a positive finite number`)\n }\n}\n\n/**\n * Reject a resolved configuration this executor could not run with, so a\n * stored value is refused where it is written instead of failing at the next\n * command.\n * @param config - the schema-validated configuration.\n * @throws Error naming the field that cannot be used.\n */\nexport function assertServiceableWslConfig(config: Config): void {\n const resolved = config as ResolvedConfig\n assertPositiveFinite('timeoutMs', resolved.timeoutMs)\n assertPositiveFinite('maxTimeoutMs', resolved.maxTimeoutMs)\n assertPositiveFinite('maxOutputBytes', resolved.maxOutputBytes)\n assertPositiveFinite('maxSpillBytes', resolved.maxSpillBytes)\n assertPositiveFinite('graceMs', resolved.graceMs)\n if (resolved.graceMs > MAX_TIMER_DELAY_MS) {\n throw new Error(`wsl-shell: graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`)\n }\n if (resolved.distro !== undefined && resolved.distro.trim() === '') {\n throw new Error('wsl-shell: distro must be a non-empty distribution name')\n }\n if (resolved.username !== undefined && resolved.username !== '' && !isValidWslUsername(resolved.username)) {\n throw new Error('wsl-shell: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\n }\n}\n\n/** One translated execution plan: the Linux world coordinates plus the argv. */\ninterface WslPlan {\n /** Distribution the command runs in. */\n distro: string\n /** Linux working directory handed to `wsl.exe --cd`. */\n linuxCwd: string\n /** A valid Windows directory for the `wsl.exe` process itself. */\n windowsCwd: string\n /** Environment map (ENV_OVERRIDES + caller env + dshEnv) with WSLENV set. */\n env: Record<string, string>\n /** Full argv to hand to `ctx.subprocess`. */\n argv: readonly string[]\n}\n\n/**\n * WSL bash executor over the LOCAL subprocess service: `wsl.exe` is a Windows\n * executable, so the Windows-side spawn, bounded output, spill files, and\n * process-group termination are the local subprocess seam's mechanics; this\n * executor supplies the Linux-world argv, cwd translation, and WSLENV.\n */\nexport class WslShellExecutor extends ShellExecutor {\n static inject = ['subprocess']\n\n static Config: z<Config> = z.object({\n cwd: z.string(),\n distro: z.string(),\n username: z.string(),\n wslPath: z.string().default('wsl.exe'),\n loginShell: z.boolean().default(true),\n timeoutMs: z.number().default(120_000),\n maxTimeoutMs: z.number().default(600_000),\n maxOutputBytes: z.number().default(64_000),\n maxSpillBytes: z.number().default(DEFAULT_MAX_SPILL_BYTES),\n graceMs: z.number().default(DEFAULT_GRACE_MS),\n })\n\n private readonly resolved: ResolvedConfig\n\n /** Validated config (schemastery applied the defaults before construction). */\n get config(): ResolvedConfig {\n return this.resolved\n }\n\n constructor(ctx: Context, config: Config) {\n super(ctx)\n const entry = config as ResolvedConfig\n assertServiceableWslConfig(entry)\n this.resolved = entry\n }\n\n /**\n * Resolve a request into a fully-specified spec: fill `workdir` from\n * `config.cwd`, and `timeoutMs` from `config.timeoutMs`, capped at\n * `config.maxTimeoutMs`. The tool layer calls this before\n * {@link run}/{@link start}, so those methods receive explicit values.\n */\n resolve(request: ShellExecRequest): ShellExecSpec {\n const timeoutMs = clampTimeout(\n request.timeoutMs,\n this.config.timeoutMs,\n this.config.maxTimeoutMs,\n 'wsl-shell: request.timeoutMs',\n )\n const stdoutMaxBytes = request.stdoutMaxBytes ?? this.config.maxOutputBytes\n assertPositiveFinite('request.stdoutMaxBytes', stdoutMaxBytes)\n return {\n command: request.command,\n workdir: request.workdir ?? this.config.cwd ?? process.cwd(),\n timeoutMs,\n stdoutMaxBytes,\n ...request.signal ? { signal: request.signal } : {},\n ...request.stdin !== undefined ? { stdin: request.stdin } : {},\n ...request.env !== undefined ? { env: request.env } : {},\n ...request.dshEnv !== undefined ? { dshEnv: request.dshEnv } : {},\n sandboxPolicy: request.sandboxPolicy,\n }\n }\n\n /**\n * Translate a resolved spec into the Linux execution plan. Fails loud on a\n * workdir that names neither the WSL world (UNC or Linux path) nor a\n * Windows drive path (reached through `/mnt/<drive>`).\n * @param spec - the resolved execution spec.\n * @returns the translated plan, including the complete argv.\n */\n private plan(spec: ShellExecSpec): WslPlan {\n const workdir = spec.workdir\n let distro: string\n let linuxCwd: string\n let windowsCwd: string\n let username: string | undefined\n const unc = parseWslUnc(workdir)\n if (unc !== null) {\n distro = unc.distro\n linuxCwd = unc.linuxPath\n // The `wsl.exe` process itself needs a plain Windows directory: its own\n // cwd is irrelevant (`--cd` sets the Linux side), and spawning with a\n // UNC cwd is a documented Node/Windows edge. SystemRoot always exists.\n windowsCwd = process.env.SystemRoot ?? process.cwd()\n username = this.resolveUser(spec, joinUnc(unc.distro, unc.linuxPath))\n } else if (workdir.startsWith('/')) {\n distro = this.resolveDistro(spec)\n linuxCwd = workdir\n windowsCwd = process.cwd()\n username = this.resolveUser(spec, undefined)\n } else {\n const mnt = windowsToMntPath(workdir)\n if (mnt === null) {\n throw new Error(`wsl-shell: workdir \"${workdir}\" is not in the WSL execution world`)\n }\n distro = this.resolveDistro(spec)\n linuxCwd = mnt\n windowsCwd = workdir\n username = this.resolveUser(spec, undefined)\n }\n const env = this.withWslEnv(spec)\n const argv = [\n this.config.wslPath,\n '-d', distro,\n ...(username !== undefined && username !== '' ? ['-u', username] : []),\n '--cd', linuxCwd,\n '-e', 'bash',\n this.config.loginShell ? '-lc' : '-c',\n spec.command,\n ]\n return { distro, linuxCwd, windowsCwd, env, argv }\n }\n\n /**\n * Resolve the distribution for a workdir that carries none. The chain:\n * the calling session's distribution (`DSH_WSL_DISTRO`, contributed by the\n * host half from the session's UNC workspace cwd — the common case for a\n * model passing a Linux `workdir`), then the configured `distro`, then the\n * host's default distribution (cached registry read) as a last resort for\n * plugin-driven calls with no session. Fails loud when every source is\n * absent rather than guessing a distro the path does not belong to.\n * @param spec - the resolved execution spec (its dshEnv carries the session fact).\n * @returns the distribution name.\n */\n private resolveDistro(spec: ShellExecSpec): string {\n const fromEnv = spec.dshEnv?.DSH_WSL_DISTRO\n if (fromEnv !== undefined && fromEnv !== '') return fromEnv\n const configured = this.config.distro\n if (configured !== undefined && configured !== '') return configured\n const fallback = defaultDistroSync()\n if (fallback !== undefined) return fallback\n throw new Error(\n 'wsl-shell: Linux workdir carries no distribution; no session DSH_WSL_DISTRO, distro config, '\n + 'or default distribution is available',\n )\n }\n\n /**\n * Resolve the Linux user bash runs as. The chain: the calling session's\n * workspace user (`DSH_WSL_USER`, contributed by the host half), then the\n * workspace's stored username when the workdir is a UNC path, then the\n * configured `username`. Absent everywhere, the distribution's default\n * user runs. Invalid values are skipped (they were validated on write;\n * the guard is defense in depth).\n * @param spec - the resolved execution spec (its dshEnv carries the session fact).\n * @param uncKey - canonical UNC key of the workdir when it is a UNC path.\n * @returns the username, or undefined for the distro default user.\n */\n private resolveUser(spec: ShellExecSpec, uncKey: string | undefined): string | undefined {\n const candidates = [\n spec.dshEnv?.DSH_WSL_USER,\n uncKey === undefined ? undefined : getWorkspaceUsername(uncKey),\n this.config.username,\n ]\n for (const candidate of candidates) {\n if (candidate !== undefined && candidate !== '' && isValidWslUsername(candidate)) return candidate\n }\n return undefined\n }\n\n /**\n * Merge the caller env layers and inject `WSLENV` so the Windows-side\n * values reach the Linux process. Windows-path-shaped values get the `/p`\n * translation flag (they become `/mnt/<drive>/…` inside WSL); the ambient\n * `WSLENV` value is preserved and extended.\n * @param spec - the resolved execution spec.\n * @returns the explicit environment map for the spawn.\n */\n private withWslEnv(spec: ShellExecSpec): Record<string, string> {\n const env: Record<string, string> = { ...ENV_OVERRIDES, ...spec.env, ...spec.dshEnv }\n const flags: string[] = []\n for (const [key, value] of Object.entries(env)) {\n if (key.toUpperCase() === 'WSLENV') continue\n flags.push(isWindowsPathShaped(value) ? `${key}/p` : key)\n }\n const ambient = process.env.WSLENV\n const merged = [ambient, flags.join(':')].filter(part => part !== undefined && part !== '').join(':')\n env.WSLENV = merged\n return env\n }\n\n /** Map a plan onto a fully-specified subprocess spawn. */\n private spawnSpec(plan: WslPlan, spec: ShellExecSpec, stdoutMaxBytes: number, signal: AbortSignal | undefined): SubprocessSpawnSpec {\n const collect = (maxBytes: number): SubprocessCollect =>\n ({ maxBytes, spill: { maxBytes: this.config.maxSpillBytes } })\n return {\n argv: plan.argv,\n cwd: plan.windowsCwd,\n stdio: {\n stdin: spec.stdin !== undefined ? { data: spec.stdin } : 'ignore',\n stdout: collect(stdoutMaxBytes),\n stderr: collect(this.config.maxOutputBytes),\n },\n graceMs: this.config.graceMs,\n signal,\n env: plan.env,\n }\n }\n\n /** The collect-mode readers this executor requested (present by construction). */\n private static collected(handle: SubprocessHandle): { stdout: SubprocessOutputReader; stderr: SubprocessOutputReader } {\n const { stdout, stderr } = handle.collected\n /* v8 ignore start -- collect dispositions expose both readers by the seam contract; defensive. */\n if (stdout === undefined || stderr === undefined) {\n throw new Error('wsl-shell: subprocess implementation dropped a requested collect stream')\n }\n /* v8 ignore stop */\n return { stdout, stderr }\n }\n\n /** Run one command in the foreground. */\n async run(spec: ShellExecSpec): Promise<ShellRunResult> {\n const plan = this.plan(spec)\n using d = deadline(spec.signal, spec.timeoutMs, 'WSL_BASH_TIMEOUT')\n const handle = this.ctx.subprocess.spawn(this.spawnSpec(plan, spec, spec.stdoutMaxBytes, d.signal))\n const outcome = await handle.done\n const collected = WslShellExecutor.collected(handle)\n // Only this executor's timeout reason counts as timedOut; outer deadlines count as aborts.\n const timedOut = timeoutOf(d.signal, 'WSL_BASH_TIMEOUT') !== undefined\n const aborted = d.signal.aborted && !timedOut\n return {\n ...outcome,\n timedOut,\n aborted,\n timeoutMs: spec.timeoutMs,\n stdout: finalOutput(collected.stdout),\n stderr: finalOutput(collected.stderr),\n }\n }\n\n /** Start one command in the background and return its live handle. */\n start(spec: ShellExecSpec): ShellProcess {\n const plan = this.plan(spec)\n // Background runs ignore timeoutMs; callers stop them through kill() or spec.signal.\n const running = this.ctx.subprocess.spawn(this.spawnSpec(plan, spec, this.config.maxOutputBytes, spec.signal))\n const collected = WslShellExecutor.collected(running)\n\n // A spawn failure produces no process output, so the subprocess service has\n // nothing to buffer; the note is delivered exactly once through the read path.\n let spawnFailureNote: string | undefined\n const consumeSpawnFailure = (): string => {\n const note = spawnFailureNote ?? ''\n spawnFailureNote = undefined\n return note\n }\n\n let stdoutOffset = 0\n let stderrOffset = 0\n const proc: ShellProcess = {\n status: 'running',\n exitCode: null,\n signal: null,\n done: running.done.then((outcome) => {\n if (proc.status === 'running') {\n proc.status = spec.signal?.aborted === true || outcome.signal !== null ? 'killed' : 'completed'\n }\n proc.exitCode = outcome.exitCode\n proc.signal = outcome.signal\n }, (error: unknown) => {\n proc.status = 'killed'\n spawnFailureNote = `spawn failed: ${String(error)}`\n }),\n readOutput: (): ShellProcessRead => {\n const out = collected.stdout.readFrom(stdoutOffset)\n const err = collected.stderr.readFrom(stderrOffset)\n stdoutOffset = out.nextOffset\n stderrOffset = err.nextOffset\n const errText = err.text.length > 0 ? err.text : consumeSpawnFailure()\n const separator = out.text.length > 0 && !out.text.endsWith('\\n') ? '\\n' : ''\n const delta = out.text\n + (errText.length > 0 ? `${separator}[stderr]\\n${errText}` : '')\n return {\n delta,\n lossy: out.lossy || err.lossy,\n ...out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {},\n ...err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {},\n }\n },\n kill: (): boolean => {\n if (proc.status !== 'running') return false\n proc.status = 'killed'\n running.terminate()\n return true\n },\n }\n return proc\n }\n}\n\nexport default WslShellExecutor\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,gBAAgB;CACpB,UAAU;CACV,MAAM;CACN,OAAO;CACP,WAAW;AACb;;AAGA,MAAM,mBAAmB;;AAGzB,MAAM,0BAA0B,KAAK,OAAO;;AAoC5C,SAAS,YAAY,QAAiD;CACpE,MAAM,OAAO,OAAO,SAAS,CAAC;CAC9B,OAAO;EACL,MAAM,KAAK;EACX,WAAW,KAAK;EAChB,GAAG,KAAK,cAAc,KAAA,IAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;CACrE;AACF;AAEA,SAAS,qBAAqB,MAAc,OAAqB;CAC/D,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GACtC,MAAM,IAAI,MAAM,cAAc,KAAK,kCAAkC;AAEzE;;;;;;;;AASA,SAAgB,2BAA2B,QAAsB;CAC/D,MAAM,WAAW;CACjB,qBAAqB,aAAa,SAAS,SAAS;CACpD,qBAAqB,gBAAgB,SAAS,YAAY;CAC1D,qBAAqB,kBAAkB,SAAS,cAAc;CAC9D,qBAAqB,iBAAiB,SAAS,aAAa;CAC5D,qBAAqB,WAAW,SAAS,OAAO;CAChD,IAAI,SAAS,UAAU,oBACrB,MAAM,IAAI,MAAM,8CAA8C,oBAAoB;CAEpF,IAAI,SAAS,WAAW,KAAA,KAAa,SAAS,OAAO,KAAK,MAAM,IAC9D,MAAM,IAAI,MAAM,yDAAyD;CAE3E,IAAI,SAAS,aAAa,KAAA,KAAa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