dsh-wsl-workspace 0.7.2 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -0
- package/README.zh.md +16 -0
- package/TESTING.md +66 -15
- package/lib/client.js +4 -4
- package/lib/client.js.map +1 -1
- package/lib/fs.js +2 -2
- package/lib/index.js +127 -20
- package/lib/index.js.map +1 -1
- package/lib/{links-BQxdJOMy.js → links-DQ8GgpMj.js} +19 -19
- package/lib/links-DQ8GgpMj.js.map +1 -0
- package/lib/shell.js +2 -2
- package/lib/{wsl-CECXiGZH.js → wsl-BTA7XT8X.js} +72 -12
- package/lib/wsl-BTA7XT8X.js.map +1 -0
- package/lib/{wsl-credentials-BJXc9tfi.js → wsl-credentials-gFHTqaiN.js} +2 -2
- package/lib/{wsl-credentials-BJXc9tfi.js.map → wsl-credentials-gFHTqaiN.js.map} +1 -1
- package/lib/wsl-relay.js +1 -1
- package/lib/wsl-search.js +2 -2
- package/package.json +10 -4
- package/src/client/locales.ts +4 -4
- package/src/index.ts +222 -25
- package/src/shared/links.ts +20 -11
- package/src/shared/wsl.ts +99 -15
- package/lib/links-BQxdJOMy.js.map +0 -1
- package/lib/wsl-CECXiGZH.js.map +0 -1
|
@@ -1,9 +1,6 @@
|
|
|
1
|
-
import { isAbsoluteLinuxPath, joinUnc, parseWslUnc } from "./wsl-
|
|
2
|
-
import { execFile } from "node:child_process";
|
|
3
|
-
import { promisify } from "node:util";
|
|
1
|
+
import { execFileResult, isAbsoluteLinuxPath, joinUnc, parseWslUnc, textOf, wslExecutableCandidates } from "./wsl-BTA7XT8X.js";
|
|
4
2
|
|
|
5
3
|
//#region src/shared/links.ts
|
|
6
|
-
const execFileAsync = promisify(execFile);
|
|
7
4
|
/** How many `readlink` calls may be in flight at once. */
|
|
8
5
|
const LINK_RESOLVE_CONCURRENCY = 4;
|
|
9
6
|
/** How long the distribution may take to answer one `readlink` call. */
|
|
@@ -42,20 +39,23 @@ async function resolveLinuxSymlink(uncPath, wslPath = "wsl.exe") {
|
|
|
42
39
|
const unc = parseWslUnc(uncPath);
|
|
43
40
|
if (unc === null || /[\r\n]/.test(unc.linuxPath)) return void 0;
|
|
44
41
|
try {
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
42
|
+
for (const candidate of wslExecutableCandidates(wslPath)) try {
|
|
43
|
+
const output = await execFileResult(candidate, [
|
|
44
|
+
"-d",
|
|
45
|
+
unc.distro,
|
|
46
|
+
"--",
|
|
47
|
+
"readlink",
|
|
48
|
+
"-f",
|
|
49
|
+
unc.linuxPath
|
|
50
|
+
], {
|
|
51
|
+
encoding: "utf8",
|
|
52
|
+
timeout: LINK_RESOLVE_TIMEOUT_MS,
|
|
53
|
+
windowsHide: true
|
|
54
|
+
});
|
|
55
|
+
const target = textOf(output.stdout).trim();
|
|
56
|
+
return isAbsoluteLinuxPath(target) ? joinUnc(unc.distro, target) : void 0;
|
|
57
|
+
} catch {}
|
|
58
|
+
return void 0;
|
|
59
59
|
} catch {
|
|
60
60
|
return void 0;
|
|
61
61
|
}
|
|
@@ -63,4 +63,4 @@ async function resolveLinuxSymlink(uncPath, wslPath = "wsl.exe") {
|
|
|
63
63
|
|
|
64
64
|
//#endregion
|
|
65
65
|
export { resolveLinuxSymlink, resolveLinuxSymlinks };
|
|
66
|
-
//# sourceMappingURL=links-
|
|
66
|
+
//# sourceMappingURL=links-DQ8GgpMj.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"links-DQ8GgpMj.js","names":["resolved: (string | undefined)[]"],"sources":["../src/shared/links.ts"],"sourcesContent":["/**\n * Linux symlink resolution through the owning distribution.\n *\n * The `\\\\wsl.localhost\\<distro>\\…` 9P share lists a Linux symlink entry but\n * cannot resolve its target: `readdir` reports it, and every Windows-side\n * `stat` on it fails (`ENOENT`/`EISDIR`). The distribution resolves the same\n * path trivially, so both halves of this plugin — the skill walk and the\n * filesystem backend — ask it with one short `wsl.exe … readlink -f` call per\n * link.\n *\n * Each link gets its own call on purpose: `wsl.exe` drops the arguments that\n * follow a command (`sh -c 'echo ARGC:$#' sh a b c` answers 0) and its\n * command-line parser truncates an argument containing a double quote, while a\n * bare multi-argument `readlink -f a b c` stops at the first path it cannot\n * resolve and still exits non-zero. A process argument carries any path\n * without quoting, which is what keeps this correct.\n *\n * @module dsh-wsl-workspace/shared/links\n */\n\nimport { execFileResult, textOf, wslExecutableCandidates } from './wsl.ts'\nimport { isAbsoluteLinuxPath, joinUnc, parseWslUnc } from './paths.ts'\n\n/** How many `readlink` calls may be in flight at once. */\nexport const LINK_RESOLVE_CONCURRENCY = 4\n/** How long the distribution may take to answer one `readlink` call. */\nexport const LINK_RESOLVE_TIMEOUT_MS = 10_000\n\n/**\n * Resolve Linux symlinks through the distribution that owns them.\n *\n * Never throws: a link the distribution cannot resolve (a missing component, a\n * stopped distribution, a `readlink` that fails) stays unresolved, and callers\n * keep whatever behaviour they had before this fallback existed.\n *\n * @param uncPaths - the links to resolve, in UNC spelling.\n * @param wslPath - the `wsl.exe` executable (absolute or PATH name).\n * @returns one entry per input, in order: the resolved real path as a UNC\n * path, or `undefined` when the link or the distribution could not answer.\n */\nexport async function resolveLinuxSymlinks(\n uncPaths: readonly string[],\n wslPath = 'wsl.exe',\n): Promise<(string | undefined)[]> {\n const resolved: (string | undefined)[] = uncPaths.map(() => undefined)\n let next = 0\n const workers = Array.from(\n { length: Math.min(LINK_RESOLVE_CONCURRENCY, uncPaths.length) },\n async () => {\n for (let index = next; index < uncPaths.length; index = next) {\n next += 1\n resolved[index] = await resolveLinuxSymlink(uncPaths[index] ?? '', wslPath)\n }\n },\n )\n await Promise.all(workers)\n return resolved\n}\n\n/**\n * Resolve one Linux symlink the share cannot follow.\n * @param uncPath - the link, in UNC spelling.\n * @param wslPath - the `wsl.exe` executable (absolute or PATH name).\n * @returns the real path as a UNC path, or `undefined` when it does not resolve.\n */\nexport async function resolveLinuxSymlink(\n uncPath: string,\n wslPath = 'wsl.exe',\n): Promise<string | undefined> {\n const unc = parseWslUnc(uncPath)\n // `readlink` answers one line, which the caller trims: a line break inside\n // the path itself would come back mangled by that trim.\n if (unc === null || /[\\r\\n]/.test(unc.linuxPath)) return undefined\n try {\n // `execFileResult` is the callback form on purpose: a host that replaces\n // `child_process.execFile` with a plain wrapper (DSH Desktop's\n // `windowsHide` injection) strips the metadata `promisify` needs, and the\n // promisified call would hand back stdout instead of `{ stdout, stderr }`\n // — making this silently return `undefined` for every link (issue #35).\n for (const candidate of wslExecutableCandidates(wslPath)) {\n try {\n const output = await execFileResult(\n candidate,\n ['-d', unc.distro, '--', 'readlink', '-f', unc.linuxPath],\n { encoding: 'utf8', timeout: LINK_RESOLVE_TIMEOUT_MS, windowsHide: true },\n )\n const target = textOf(output.stdout).trim()\n return isAbsoluteLinuxPath(target) ? joinUnc(unc.distro, target) : undefined\n } catch {\n // try the next spelling of wsl.exe\n }\n }\n return undefined\n } catch {\n // Missing intermediate components, an unreadable link, a stopped\n // distribution or a missing `readlink` all land here.\n return undefined\n }\n}\n"],"mappings":";;;;AAwBA,MAAa,2BAA2B;;AAExC,MAAa,0BAA0B;;;;;;;;;;;;;AAcvC,eAAsB,qBACpB,UACA,UAAU,WACuB;CACjC,MAAMA,WAAmC,SAAS,UAAU;CAC5D,IAAI,OAAO;CACX,MAAM,UAAU,MAAM,KACpB,EAAE,QAAQ,KAAK,IAAI,0BAA0B,SAAS,WACtD,YAAY;AACV,OAAK,IAAI,QAAQ,MAAM,QAAQ,SAAS,QAAQ,QAAQ,MAAM;AAC5D,WAAQ;AACR,YAAS,SAAS,MAAM,oBAAoB,SAAS,UAAU,IAAI;;;AAIzE,OAAM,QAAQ,IAAI;AAClB,QAAO;;;;;;;;AAST,eAAsB,oBACpB,SACA,UAAU,WACmB;CAC7B,MAAM,MAAM,YAAY;AAGxB,KAAI,QAAQ,QAAQ,SAAS,KAAK,IAAI,WAAY,QAAO;AACzD,KAAI;AAMF,OAAK,MAAM,aAAa,wBAAwB,SAC9C,KAAI;GACF,MAAM,SAAS,MAAM,eACnB,WACA;IAAC;IAAM,IAAI;IAAQ;IAAM;IAAY;IAAM,IAAI;MAC/C;IAAE,UAAU;IAAQ,SAAS;IAAyB,aAAa;;GAErE,MAAM,SAAS,OAAO,OAAO,QAAQ;AACrC,UAAO,oBAAoB,UAAU,QAAQ,IAAI,QAAQ,UAAU;UAC7D;AAIV,SAAO;SACD;AAGN,SAAO"}
|
package/lib/shell.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { defaultDistroSync, isValidWslUsername, isWindowsPathShaped, joinUnc, parseWslUnc, windowsToMntPath } from "./wsl-
|
|
2
|
-
import { getWorkspaceUsername } from "./wsl-credentials-
|
|
1
|
+
import { defaultDistroSync, isValidWslUsername, isWindowsPathShaped, joinUnc, parseWslUnc, windowsToMntPath } from "./wsl-BTA7XT8X.js";
|
|
2
|
+
import { getWorkspaceUsername } from "./wsl-credentials-gFHTqaiN.js";
|
|
3
3
|
import z from "@deepseek-ai/schemastery";
|
|
4
4
|
import { ShellExecutor } from "@deepseek-ai/dsh-shell";
|
|
5
5
|
import { MAX_TIMER_DELAY_MS, clampTimeout, deadline, timeoutOf } from "@deepseek-ai/dsh-timeout";
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { execFile, execFileSync } from "node:child_process";
|
|
2
|
-
import { promisify } from "node:util";
|
|
3
2
|
|
|
4
3
|
//#region src/shared/paths.ts
|
|
5
4
|
/**
|
|
@@ -144,7 +143,6 @@ function isValidWslUsername(value) {
|
|
|
144
143
|
|
|
145
144
|
//#endregion
|
|
146
145
|
//#region src/shared/wsl.ts
|
|
147
|
-
const execFileAsync = promisify(execFile);
|
|
148
146
|
/** Executable timeout for the short discovery calls. */
|
|
149
147
|
const DISCOVERY_TIMEOUT_MS = 1e4;
|
|
150
148
|
const LXSS_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss";
|
|
@@ -153,12 +151,70 @@ function messageOf(value) {
|
|
|
153
151
|
return value instanceof Error ? value.message : String(value);
|
|
154
152
|
}
|
|
155
153
|
/**
|
|
154
|
+
* Run `execFile` through its callback API and resolve `{ stdout, stderr }`.
|
|
155
|
+
*
|
|
156
|
+
* `util.promisify(execFile)` only resolves that object because `execFile`
|
|
157
|
+
* carries `util.promisify.custom`. A host that replaces
|
|
158
|
+
* `child_process.execFile` with a plain wrapper loses that metadata, and
|
|
159
|
+
* `promisify` then falls back to "resolve the first callback value" — which is
|
|
160
|
+
* stdout itself, so `result.stdout` is `undefined` (issue #35: DSH Desktop
|
|
161
|
+
* injects `windowsHide: true` that way, and `listDistros()` died with
|
|
162
|
+
* `Cannot read properties of undefined (reading 'includes')`).
|
|
163
|
+
*
|
|
164
|
+
* The callback form is what every such wrapper preserves, so this does not
|
|
165
|
+
* depend on how the host patched the module.
|
|
166
|
+
* @param file - the executable.
|
|
167
|
+
* @param args - its arguments.
|
|
168
|
+
* @param options - `execFile` options, including the requested encoding.
|
|
169
|
+
* @returns both streams; the caller narrows them by the encoding it asked for.
|
|
170
|
+
*/
|
|
171
|
+
function execFileResult(file, args, options) {
|
|
172
|
+
return new Promise((settle, fail) => {
|
|
173
|
+
execFile(file, [...args], options, (error, stdout, stderr) => {
|
|
174
|
+
if (error !== null && error !== void 0) {
|
|
175
|
+
fail(error);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
settle({
|
|
179
|
+
stdout,
|
|
180
|
+
stderr
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
/** Read a captured stream as text, whichever way the encoding arrived. */
|
|
186
|
+
function textOf(stream) {
|
|
187
|
+
return typeof stream === "string" ? stream : stream.toString("utf8");
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* The `wsl.exe` spellings to try, in order.
|
|
191
|
+
*
|
|
192
|
+
* The bare name relies on `PATH`. A host whose `PATH` omits `System32` can run
|
|
193
|
+
* every other part of this plugin — `listDir`/`check` go through the
|
|
194
|
+
* `\\wsl.localhost\…` share and never spawn anything — while `listDistros`
|
|
195
|
+
* reports that WSL is missing, which is what issue #36 describes. The
|
|
196
|
+
* absolute fallback removes that failure mode.
|
|
197
|
+
* @param wslPath - the configured executable.
|
|
198
|
+
* @returns the candidates, without duplicates.
|
|
199
|
+
*/
|
|
200
|
+
function wslExecutableCandidates(wslPath) {
|
|
201
|
+
if (wslPath !== "wsl.exe") return [wslPath];
|
|
202
|
+
const root = process.env.SystemRoot ?? process.env.windir;
|
|
203
|
+
if (root === void 0 || root === "") return [wslPath];
|
|
204
|
+
const absolute = `${root.replace(/[\\/]+$/, "")}\\System32\\wsl.exe`;
|
|
205
|
+
return [wslPath, absolute];
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
156
208
|
* Decode `wsl.exe -l -q` output. Newer builds emit UTF-8; most emit UTF-16LE
|
|
157
|
-
* with NUL bytes interleaved — the NUL probe picks the right one.
|
|
209
|
+
* with NUL bytes interleaved — the NUL probe picks the right one. A host that
|
|
210
|
+
* handed back something other than the captured stream is reported as such
|
|
211
|
+
* instead of throwing `Cannot read properties of undefined`.
|
|
158
212
|
* @param buffer - the raw captured output.
|
|
159
213
|
* @returns the decoded text.
|
|
160
214
|
*/
|
|
161
215
|
function decodeWslOutput(buffer) {
|
|
216
|
+
if (typeof buffer === "string") return buffer;
|
|
217
|
+
if (!(buffer instanceof Uint8Array)) throw new Error(`wsl-workspace: expected captured output, got ${typeof buffer}`);
|
|
162
218
|
return buffer.includes(0) ? buffer.toString("utf16le") : buffer.toString("utf8");
|
|
163
219
|
}
|
|
164
220
|
/**
|
|
@@ -167,16 +223,20 @@ function decodeWslOutput(buffer) {
|
|
|
167
223
|
* @returns distribution names, blank lines dropped.
|
|
168
224
|
*/
|
|
169
225
|
async function listDistros(wslPath = "wsl.exe") {
|
|
226
|
+
const candidates = wslExecutableCandidates(wslPath);
|
|
170
227
|
let stdout;
|
|
171
|
-
|
|
172
|
-
|
|
228
|
+
let lastError;
|
|
229
|
+
for (const candidate of candidates) try {
|
|
230
|
+
const result = await execFileResult(candidate, ["-l", "-q"], {
|
|
173
231
|
encoding: "buffer",
|
|
174
232
|
timeout: DISCOVERY_TIMEOUT_MS
|
|
175
233
|
});
|
|
176
234
|
stdout = result.stdout;
|
|
235
|
+
break;
|
|
177
236
|
} catch (error) {
|
|
178
|
-
|
|
237
|
+
lastError = error;
|
|
179
238
|
}
|
|
239
|
+
if (stdout === void 0) throw new Error(`wsl-workspace: cannot list WSL distributions (tried ${candidates.join(" and ")}: ${messageOf(lastError)}); is WSL installed?`);
|
|
180
240
|
return decodeWslOutput(stdout).split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
|
|
181
241
|
}
|
|
182
242
|
/**
|
|
@@ -187,21 +247,21 @@ async function listDistros(wslPath = "wsl.exe") {
|
|
|
187
247
|
*/
|
|
188
248
|
async function defaultDistro() {
|
|
189
249
|
try {
|
|
190
|
-
const value = await
|
|
250
|
+
const value = await execFileResult("reg.exe", [
|
|
191
251
|
"query",
|
|
192
252
|
LXSS_KEY,
|
|
193
253
|
"/v",
|
|
194
254
|
"DefaultDistribution"
|
|
195
255
|
], { timeout: DISCOVERY_TIMEOUT_MS });
|
|
196
|
-
const guid = /DefaultDistribution\s+REG_SZ\s+(\{[0-9a-fA-F-]+\})/i.exec(value.stdout)?.[1];
|
|
256
|
+
const guid = /DefaultDistribution\s+REG_SZ\s+(\{[0-9a-fA-F-]+\})/i.exec(textOf(value.stdout))?.[1];
|
|
197
257
|
if (guid === void 0) return void 0;
|
|
198
|
-
const name = await
|
|
258
|
+
const name = await execFileResult("reg.exe", [
|
|
199
259
|
"query",
|
|
200
260
|
`${LXSS_KEY}\\${guid}`,
|
|
201
261
|
"/v",
|
|
202
262
|
"DistributionName"
|
|
203
263
|
], { timeout: DISCOVERY_TIMEOUT_MS });
|
|
204
|
-
const distro = /DistributionName\s+REG_SZ\s+(.+)/i.exec(name.stdout)?.[1]?.trim();
|
|
264
|
+
const distro = /DistributionName\s+REG_SZ\s+(.+)/i.exec(textOf(name.stdout))?.[1]?.trim();
|
|
205
265
|
return distro === void 0 || distro === "" ? void 0 : distro;
|
|
206
266
|
} catch {
|
|
207
267
|
return void 0;
|
|
@@ -244,5 +304,5 @@ function defaultDistroSync() {
|
|
|
244
304
|
}
|
|
245
305
|
|
|
246
306
|
//#endregion
|
|
247
|
-
export { canonicalWindowsPath, defaultDistro, defaultDistroSync, isAbsoluteLinuxPath, isValidWslUsername, isWindowsPathShaped, joinUnc, listDistros, mntToWindowsPath, normalizeLinuxPath, parseWslUnc, uncToLinux, windowsToMntPath };
|
|
248
|
-
//# sourceMappingURL=wsl-
|
|
307
|
+
export { canonicalWindowsPath, defaultDistro, defaultDistroSync, execFileResult, isAbsoluteLinuxPath, isValidWslUsername, isWindowsPathShaped, joinUnc, listDistros, mntToWindowsPath, normalizeLinuxPath, parseWslUnc, textOf, uncToLinux, windowsToMntPath, wslExecutableCandidates };
|
|
308
|
+
//# sourceMappingURL=wsl-BTA7XT8X.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wsl-BTA7XT8X.js","names":["stdout: Buffer | string | undefined","lastError: unknown","syncDefault: string | undefined"],"sources":["../src/shared/paths.ts","../src/shared/wsl.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 * Canonical Windows drive path for store keys and cross-realm identity:\n * separators unified to `\\`, trailing separator stripped, and the WHOLE path\n * lowercased — Windows paths compare case-insensitively, and the workspace\n * registry may realpath a different casing than the caller spelled (8.3 or\n * on-disk casing), so the store key must collide across casings.\n * @param path - candidate Windows drive path.\n * @returns the canonical form, or `null` when not drive-shaped.\n */\nexport function canonicalWindowsPath(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(/\\\\$/, '').toLowerCase()\n return `${(match[1] ?? '').toLowerCase()}:\\\\${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","/**\n * WSL discovery helpers (host side): enumerate installed distributions\n * through `wsl.exe -l -q` and read the default distribution from the Lxss\n * registry key. `wsl.exe` output is UTF-16LE on most builds, so decoding\n * sniffs for NUL bytes before choosing an encoding.\n * @module dsh-wsl-workspace/shared/wsl\n */\n\nimport { execFile, execFileSync } from 'node:child_process'\nimport type { ExecFileOptions } from 'node:child_process'\n\n/** Executable timeout for the short discovery calls. */\nconst DISCOVERY_TIMEOUT_MS = 10_000\n\nconst LXSS_KEY = 'HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Lxss'\n\n/** Human text for an unknown rejection. */\nfunction messageOf(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/** One `execFile` outcome: the two streams, as `encoding` asked for them. */\nexport interface ExecFileResult {\n stdout: Buffer | string\n stderr: Buffer | string\n}\n\n/**\n * Run `execFile` through its callback API and resolve `{ stdout, stderr }`.\n *\n * `util.promisify(execFile)` only resolves that object because `execFile`\n * carries `util.promisify.custom`. A host that replaces\n * `child_process.execFile` with a plain wrapper loses that metadata, and\n * `promisify` then falls back to \"resolve the first callback value\" — which is\n * stdout itself, so `result.stdout` is `undefined` (issue #35: DSH Desktop\n * injects `windowsHide: true` that way, and `listDistros()` died with\n * `Cannot read properties of undefined (reading 'includes')`).\n *\n * The callback form is what every such wrapper preserves, so this does not\n * depend on how the host patched the module.\n * @param file - the executable.\n * @param args - its arguments.\n * @param options - `execFile` options, including the requested encoding.\n * @returns both streams; the caller narrows them by the encoding it asked for.\n */\nexport function execFileResult(\n file: string,\n args: readonly string[],\n options: ExecFileOptions,\n): Promise<ExecFileResult> {\n // `settle`/`fail` rather than `resolve`/`reject`, matching\n // `src/host/wsl-search.ts`; `scripts/verify-lib.mjs` reads a bare\n // `resolve(` call as an unbound `node:path` export.\n return new Promise<ExecFileResult>((settle, fail) => {\n execFile(file, [...args], options, (error, stdout, stderr) => {\n if (error !== null && error !== undefined) {\n fail(error)\n return\n }\n settle({ stdout, stderr })\n })\n })\n}\n\n/** Read a captured stream as text, whichever way the encoding arrived. */\nexport function textOf(stream: Buffer | string): string {\n return typeof stream === 'string' ? stream : stream.toString('utf8')\n}\n\n/**\n * The `wsl.exe` spellings to try, in order.\n *\n * The bare name relies on `PATH`. A host whose `PATH` omits `System32` can run\n * every other part of this plugin — `listDir`/`check` go through the\n * `\\\\wsl.localhost\\…` share and never spawn anything — while `listDistros`\n * reports that WSL is missing, which is what issue #36 describes. The\n * absolute fallback removes that failure mode.\n * @param wslPath - the configured executable.\n * @returns the candidates, without duplicates.\n */\nexport function wslExecutableCandidates(wslPath: string): string[] {\n if (wslPath !== 'wsl.exe') return [wslPath]\n const root = process.env.SystemRoot ?? process.env.windir\n if (root === undefined || root === '') return [wslPath]\n const absolute = `${root.replace(/[\\\\/]+$/, '')}\\\\System32\\\\wsl.exe`\n return [wslPath, absolute]\n}\n\n/**\n * Decode `wsl.exe -l -q` output. Newer builds emit UTF-8; most emit UTF-16LE\n * with NUL bytes interleaved — the NUL probe picks the right one. A host that\n * handed back something other than the captured stream is reported as such\n * instead of throwing `Cannot read properties of undefined`.\n * @param buffer - the raw captured output.\n * @returns the decoded text.\n */\nexport function decodeWslOutput(buffer: Buffer | string): string {\n if (typeof buffer === 'string') return buffer\n if (!(buffer instanceof Uint8Array)) {\n throw new Error(`wsl-workspace: expected captured output, got ${typeof buffer}`)\n }\n return buffer.includes(0) ? buffer.toString('utf16le') : buffer.toString('utf8')\n}\n\n/**\n * List installed WSL distributions in `wsl.exe` order.\n * @param wslPath - the `wsl.exe` executable (absolute or PATH name).\n * @returns distribution names, blank lines dropped.\n */\nexport async function listDistros(wslPath = 'wsl.exe'): Promise<string[]> {\n const candidates = wslExecutableCandidates(wslPath)\n let stdout: Buffer | string | undefined\n let lastError: unknown\n for (const candidate of candidates) {\n try {\n const result = await execFileResult(candidate, ['-l', '-q'], {\n encoding: 'buffer',\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n stdout = result.stdout\n break\n } catch (error) {\n lastError = error\n }\n }\n if (stdout === undefined) {\n throw new Error(\n `wsl-workspace: cannot list WSL distributions (tried ${candidates.join(' and ')}: ${messageOf(lastError)}); is WSL installed?`,\n )\n }\n return decodeWslOutput(stdout)\n .split(/\\r?\\n/)\n .map(line => line.trim())\n .filter(line => line.length > 0)\n}\n\n/**\n * Read the user's default distribution from the Lxss registry. Non-fatal:\n * returns `undefined` when the value is absent or unreadable (the caller\n * falls back to list order).\n * @returns the default distribution name, or `undefined`.\n */\nexport async function defaultDistro(): Promise<string | undefined> {\n try {\n const value = await execFileResult('reg.exe', ['query', LXSS_KEY, '/v', 'DefaultDistribution'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const guid = /DefaultDistribution\\s+REG_SZ\\s+(\\{[0-9a-fA-F-]+\\})/i.exec(textOf(value.stdout))?.[1]\n if (guid === undefined) return undefined\n const name = await execFileResult('reg.exe', ['query', `${LXSS_KEY}\\\\${guid}`, '/v', 'DistributionName'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const distro = /DistributionName\\s+REG_SZ\\s+(.+)/i.exec(textOf(name.stdout))?.[1]?.trim()\n return distro === undefined || distro === '' ? undefined : distro\n } catch {\n return undefined\n }\n}\n\n/** Module-level cache for {@link defaultDistroSync} (one registry read per process). */\nlet syncDefaultResolved = false\nlet syncDefault: string | undefined\n\n/**\n * Synchronous variant of {@link defaultDistro} for executors that must\n * resolve a distribution inside a synchronous plan step. Cached after the\n * first read; non-fatal (returns `undefined` when the registry is\n * unreadable, letting the caller fail loud with its own message).\n * @returns the default distribution name, or `undefined`.\n */\nexport function defaultDistroSync(): string | undefined {\n if (syncDefaultResolved) return syncDefault\n syncDefaultResolved = true\n try {\n const value = execFileSync('reg.exe', ['query', LXSS_KEY, '/v', 'DefaultDistribution'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const guid = /DefaultDistribution\\s+REG_SZ\\s+(\\{[0-9a-fA-F-]+\\})/i.exec(String(value))?.[1]\n if (guid === undefined) return undefined\n const name = execFileSync('reg.exe', ['query', `${LXSS_KEY}\\\\${guid}`, '/v', 'DistributionName'], {\n timeout: DISCOVERY_TIMEOUT_MS,\n })\n const distro = /DistributionName\\s+REG_SZ\\s+(.+)/i.exec(String(name))?.[1]?.trim()\n syncDefault = distro === undefined || distro === '' ? undefined : distro\n } catch {\n syncDefault = undefined\n }\n return syncDefault\n}\n"],"mappings":";;;;;;;;AAMA,MAAM,qBAAqB;;AAE3B,MAAM,kBAAkB;;AAGxB,MAAM,YAAY,CAAC,oBAAoB;;;;;;;;AAiBvC,SAAgB,YAAY,KAAkC;CAC5D,MAAM,aAAa,IAAI,QAAQ,OAAO,KAAK,QAAQ,UAAU;AAC7D,KAAI,CAAC,WAAW,WAAW,MAAO,QAAO;CACzC,MAAM,WAAW,WAAW,MAAM,GAAG,MAAM;CAC3C,MAAM,QAAQ,SAAS,MAAM,IAAI;AACjC,KAAI,CAAC,UAAU,SAAS,MAAO,QAAO;CACtC,MAAM,SAAS,SAAS,MAAM;AAC9B,KAAI,WAAW,GAAI,QAAO;CAC1B,MAAM,OAAO,SAAS,MAAM,GAAG,QAAO,YAAW,QAAQ,SAAS;AAClE,QAAO;EAAE;EAAQ,WAAW,IAAI,KAAK,KAAK;;;;;;;;;;;AAoB5C,SAAgB,WAAW,SAAyB;CAClD,MAAM,QAAQ,YAAY;AAC1B,KAAI,UAAU,KACZ,OAAM,IAAI,MAAM,mBAAmB,QAAQ;AAE7C,QAAO,MAAM;;;;;;;;AASf,SAAgB,mBAAmB,MAAsB;CACvD,MAAM,YAAY,KAAK,QAAQ,QAAQ;AACvC,QAAO,cAAc,MAAM,MAAM,UAAU,QAAQ,OAAO;;;;;;;AAQ5D,SAAgB,oBAAoB,MAAuB;AACzD,QAAO,KAAK,WAAW,QAAQ,CAAC,KAAK,SAAS;;;;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c, parseWslUnc } from "./wsl-BTA7XT8X.js";
|
|
2
2
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { homedir } from "node:os";
|
|
@@ -99,4 +99,4 @@ function listWorkspaceKeys() {
|
|
|
99
99
|
|
|
100
100
|
//#endregion
|
|
101
101
|
export { canonicalWslUnc, getWindowsWorkspace, getWorkspaceUsername, listWorkspaceKeys, registerWindowsWorkspace, setWorkspaceUsername };
|
|
102
|
-
//# sourceMappingURL=wsl-credentials-
|
|
102
|
+
//# sourceMappingURL=wsl-credentials-gFHTqaiN.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wsl-credentials-
|
|
1
|
+
{"version":3,"file":"wsl-credentials-gFHTqaiN.js","names":["parsed: unknown","entry: WorkspaceEntry"],"sources":["../src/shared/wsl-credentials.ts"],"sourcesContent":["/**\n * Per-workspace WSL credentials (host side only). The dialog stores the\n * optional Linux username of a WSL workspace under the harness home; the\n * per-session env contributor and the WSL shell executor read it back so\n * `wsl.exe -u <username>` can run commands as that user. Keys are canonical\n * UNC workspace paths. This module touches node builtins, so the browser\n * half never imports it.\n * @module dsh-wsl-workspace/shared/wsl-credentials\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport { canonicalWindowsPath, isValidWslUsername, joinUnc, parseWslUnc } from './paths.ts'\n\n/** One workspace's stored credentials. */\ninterface WorkspaceEntry {\n /** The Linux user bash runs as inside the distribution (absent = distro default). */\n username?: string\n /**\n * The WSL distribution of a Windows-drive workspace (`/mnt/<drive>` path).\n * 9P cannot serve drvfs mounts, so such workspaces register under their\n * Windows drive path; this entry is what the per-session env contributor\n * uses to hand a distro to the shell executor.\n */\n distro?: string\n}\n\n/** The stored form: canonical UNC or Windows drive workspace path → credentials. */\ntype WorkspaceStore = Record<string, WorkspaceEntry>\n\n/** The store file lives under the harness home so both host halves share it. */\nfunction storePath(): string {\n const dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh')\n return join(dshHome, 'wsl-workspaces.json')\n}\n\n/** Read the store; a missing or corrupt file reads as empty (never throws). */\nfunction readStore(): WorkspaceStore {\n try {\n const parsed: unknown = JSON.parse(readFileSync(storePath(), 'utf8'))\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {}\n return parsed as WorkspaceStore\n } catch {\n return {}\n }\n}\n\n/**\n * Canonicalize any accepted WSL UNC spelling into the store's key form.\n * @param path - candidate workspace path (either UNC host form).\n * @returns the canonical UNC path, or null when the path is not a WSL UNC.\n */\nexport function canonicalWslUnc(path: string): string | null {\n const parsed = parseWslUnc(path)\n return parsed === null ? null : joinUnc(parsed.distro, parsed.linuxPath)\n}\n\n/**\n * Read the stored username for a WSL workspace.\n * @param uncPath - the workspace path (any accepted WSL UNC spelling).\n * @returns the username, or undefined when none is stored.\n */\nexport function getWorkspaceUsername(uncPath: string): string | undefined {\n const key = canonicalWslUnc(uncPath)\n if (key === null) return undefined\n const username = readStore()[key]?.username\n return username === undefined || username === '' ? undefined : username\n}\n\n/**\n * Store (or clear) the username of a WSL workspace.\n * @param uncPath - the workspace path (any accepted WSL UNC spelling).\n * @param username - the username; empty or undefined clears the stored value.\n */\nexport function setWorkspaceUsername(uncPath: string, username: string | undefined): void {\n const key = canonicalWslUnc(uncPath)\n if (key === null) throw new Error('wsl-workspace: workspace path is not a WSL UNC path')\n const store = readStore()\n if (username === undefined || username.trim() === '') {\n delete store[key]\n } else {\n const trimmed = username.trim()\n if (!isValidWslUsername(trimmed)) {\n throw new Error('wsl-workspace: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\n }\n store[key] = { username: trimmed }\n }\n const path = storePath()\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(store, null, 2) + '\\n', 'utf8')\n}\n\n/**\n * Register the WSL distribution (and optional Linux username) of a\n * Windows-drive workspace (`/mnt/<drive>` path). Keys are canonical Windows\n * drive paths; the per-session env contributor reads the entry back so\n * `wsl.exe -d <distro>` can run when the session cwd is a drive path.\n * @param winPath - the Windows drive path (any spelling).\n * @param distro - the WSL distribution the workspace belongs to.\n * @param username - optional Linux username (distro default when absent).\n */\nexport function registerWindowsWorkspace(winPath: string, distro: string, username: string | undefined): void {\n const key = canonicalWindowsPath(winPath)\n if (key === null) throw new Error('wsl-workspace: workspace path is not a Windows drive path')\n const entry: WorkspaceEntry = { distro }\n if (username !== undefined && username.trim() !== '') {\n const trimmed = username.trim()\n if (!isValidWslUsername(trimmed)) {\n throw new Error('wsl-workspace: username must match the Linux username pattern [A-Za-z_][A-Za-z0-9_.-]*')\n }\n entry.username = trimmed\n }\n const store = readStore()\n store[key] = entry\n const path = storePath()\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(store, null, 2) + '\\n', 'utf8')\n}\n\n/**\n * Read the stored credentials of a Windows-drive workspace.\n * @param winPath - the Windows drive path (any spelling).\n * @returns the stored entry, or undefined when none is registered.\n */\nexport function getWindowsWorkspace(winPath: string): WorkspaceEntry | undefined {\n const key = canonicalWindowsPath(winPath)\n if (key === null) return undefined\n return readStore()[key]\n}\n\n/** Every stored workspace key (canonical UNC and Windows drive paths). */\nexport function listWorkspaceKeys(): string[] {\n return Object.keys(readStore())\n}\n"],"mappings":";;;;;;;AAgCA,SAAS,YAAoB;CAC3B,MAAM,UAAU,QAAQ,IAAI,YAAY,KAAK,WAAW;AACxD,QAAO,KAAK,SAAS;;;AAIvB,SAAS,YAA4B;AACnC,KAAI;EACF,MAAMA,SAAkB,KAAK,MAAM,aAAa,aAAa;AAC7D,MAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,QAAS,QAAO;AACnF,SAAO;SACD;AACN,SAAO;;;;;;;;AASX,SAAgB,gBAAgB,MAA6B;CAC3D,MAAM,SAAS,YAAY;AAC3B,QAAO,WAAW,OAAO,OAAO,QAAQ,OAAO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1,4 @@
|
|
|
1
|
-
import { defaultDistroSync, isValidWslUsername, parseWslUnc, windowsToMntPath } from "./wsl-
|
|
1
|
+
import { defaultDistroSync, isValidWslUsername, parseWslUnc, windowsToMntPath } from "./wsl-BTA7XT8X.js";
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
3
|
|
|
4
4
|
//#region src/host/wsl-relay.ts
|
package/lib/wsl-search.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { defaultDistroSync, isAbsoluteLinuxPath, parseWslUnc, windowsToMntPath } from "./wsl-
|
|
2
|
-
import { getWorkspaceUsername } from "./wsl-credentials-
|
|
1
|
+
import { defaultDistroSync, isAbsoluteLinuxPath, parseWslUnc, windowsToMntPath } from "./wsl-BTA7XT8X.js";
|
|
2
|
+
import { getWorkspaceUsername } from "./wsl-credentials-gFHTqaiN.js";
|
|
3
3
|
import z from "@deepseek-ai/schemastery";
|
|
4
4
|
import { posix } from "node:path";
|
|
5
5
|
import { execFile } from "node:child_process";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-wsl-workspace",
|
|
3
3
|
"description": "WSL workspace support for DeepSeek Harness: add a WSL workspace from the web GUI and run the whole agent session (bash + file tools) inside the WSL distribution, VS Code Remote-WSL style. No toolchain install inside WSL required.",
|
|
4
|
-
"version": "0.7.
|
|
4
|
+
"version": "0.7.4",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -45,7 +45,9 @@
|
|
|
45
45
|
"0.1.2-rc.1": "compatible",
|
|
46
46
|
"0.1.3-alpha.2": "compatible",
|
|
47
47
|
"0.1.5-rc.1": "compatible",
|
|
48
|
-
"0.1.5-rc.2": "compatible"
|
|
48
|
+
"0.1.5-rc.2": "compatible",
|
|
49
|
+
"0.1.7-rc.1": "compatible",
|
|
50
|
+
"0.1.7-rc.2": "compatible"
|
|
49
51
|
}
|
|
50
52
|
}
|
|
51
53
|
},
|
|
@@ -68,6 +70,7 @@
|
|
|
68
70
|
],
|
|
69
71
|
"peerDependencies": {
|
|
70
72
|
"@deepseek-ai/cordis": "*",
|
|
73
|
+
"@deepseek-ai/cordis-plugin-include": "*",
|
|
71
74
|
"@deepseek-ai/dsh-fs": "*",
|
|
72
75
|
"@deepseek-ai/dsh-fs-local": "*",
|
|
73
76
|
"@deepseek-ai/dsh-sandbox": "*",
|
|
@@ -76,10 +79,12 @@
|
|
|
76
79
|
"@deepseek-ai/dsh-timeout": "*",
|
|
77
80
|
"@deepseek-ai/dsh-tool-fs-search": "*",
|
|
78
81
|
"@deepseek-ai/dsh-tools": "*",
|
|
79
|
-
"@deepseek-ai/schemastery": "*"
|
|
82
|
+
"@deepseek-ai/schemastery": "*",
|
|
83
|
+
"js-yaml": "*"
|
|
80
84
|
},
|
|
81
85
|
"peerDependenciesMeta": {
|
|
82
86
|
"@deepseek-ai/cordis": { "optional": true },
|
|
87
|
+
"@deepseek-ai/cordis-plugin-include": { "optional": true },
|
|
83
88
|
"@deepseek-ai/dsh-fs": { "optional": true },
|
|
84
89
|
"@deepseek-ai/dsh-fs-local": { "optional": true },
|
|
85
90
|
"@deepseek-ai/dsh-sandbox": { "optional": true },
|
|
@@ -88,7 +93,8 @@
|
|
|
88
93
|
"@deepseek-ai/dsh-timeout": { "optional": true },
|
|
89
94
|
"@deepseek-ai/dsh-tool-fs-search": { "optional": true },
|
|
90
95
|
"@deepseek-ai/dsh-tools": { "optional": true },
|
|
91
|
-
"@deepseek-ai/schemastery": { "optional": true }
|
|
96
|
+
"@deepseek-ai/schemastery": { "optional": true },
|
|
97
|
+
"js-yaml": { "optional": true }
|
|
92
98
|
},
|
|
93
99
|
"files": [
|
|
94
100
|
"lib",
|
package/src/client/locales.ts
CHANGED
|
@@ -41,8 +41,8 @@ export const zh: Record<string, string> = {
|
|
|
41
41
|
'help.compat.versionLabel': '插件版本',
|
|
42
42
|
'help.compat.unknown': '未能读取版本与兼容声明(宿主端没有响应)',
|
|
43
43
|
'help.compat.body': '上方是这份构建声明兼容的 DSH 版本,每一条都在隔离实例上实测过(独立 DSH_HOME、依赖固定到该版本、跑满十项门禁)。\n插件在运行时自动识别 DSH 版本并选用对应的 API;两边都不支持时会明确报错,而不是留下一个空工作区。\n版本不在列表里通常仍然可用,但未经验证。',
|
|
44
|
-
'help.news.title': '本次更新(0.7.
|
|
45
|
-
'help.news.body': '
|
|
44
|
+
'help.news.title': '本次更新(0.7.4)',
|
|
45
|
+
'help.news.body': '在 DSH Desktop 上对话框又能用了(issue #35、#36)。Desktop 宿主会在插件加载之前包装 child_process:装上普通的 exec / execFile 包装函数,再用 syncBuiltinESMExports() 把它们回写到内建模块。\n这份 execFile 上没有 util.promisify.custom,于是 promisify(execFile) 退回通用实现——它只用回调的第一个参数 resolve——结果每次调用拿到的 result.stdout 都是 undefined。发行版查询去读它就抛 Cannot read properties of undefined (reading \'includes\'),前端把异常吞掉、渲染出一个空的发行版列表:对话框能打开、下拉框里却一个发行版都没有,也创建不出工作区;而同一台机器上 wsl.exe -l -q 在终端里列得好好的,看上去像"插件找不到 WSL2"。\n三处调用(列发行版、默认发行版、符号链接解析)现在都改用 execFile 的回调形式,任何包装都改不了这个签名,输出再由 textOf 统一取文本。\nwsl.exe 的查找改成候选列表:先试 PATH 上的 wsl.exe,再试绝对路径 %SystemRoot%\\System32\\wsl.exe;都失败时报出试过的每一个候选以及各自的原因,而不是从解码器里冒出一个类型错误。\n新增 tests/exec-shape.mjs:复刻 Desktop 的包装形态(分别带与不带 --import 起一个探针进程),断言被包装的形态确实是坏的、新助手是对的,并把真实的三个函数在两种形态下各跑一遍;它注册为 Run-Checks 里的 exec-shape 检查,免得以后又被改回 promisify。',
|
|
46
46
|
'help.usage.title': '用法与特性',
|
|
47
47
|
'help.usage.body': '点击侧边栏底部的 W 按钮 → 选发行版 → 输入或浏览 Linux 路径 → 检查 → 创建并打开。\n创建出的会话里,bash 与文件工具都落在该发行版内,模型看到的路径全是 Linux 路径;Windows 盘可从会话内通过 /mnt/<盘符> 访问。\n四种模式(标准 / PTC / 极简 / 创造)各有 WSL 变体,在模式选择器里直接选即可,名字形如 WSL · Standard mode(标准模式)。\n用户名可选,等价于 wsl.exe -u <用户名>,只改变 bash 与 persistent-bash 的运行身份;文件工具走 Windows 侧共享,不受它影响。\n技能目录从会话 cwd 最近的 .git 祖先开始向下扫描 .dsh/skills 与 .agents/skills(含嵌套项目),上限 4 层目录 / 64 个技能目录 / 4096 个已访问目录,并按扫描根缓存 10 秒。9P 解不开的符号链接交给发行版 readlink 解析出真实路径(每次查找最多 32 条)后继续扫描,链接进来的项目与它下面的嵌套项目都能扫到。\n目录不再冻结:对 UNC 关闭文件监视之后,插件每 3 秒重查一次已发布的技能目录、并比对每个技能文件的修改时间与大小,所以新增、删除与改写都会在下一个回合生效;完整重新发现每 30 秒一次,用于找到此前不存在的技能目录(技能正文始终实时读取)。\n文件搜索由发行版内的 grep / glob 提供,源预设没有这两个工具的模式(极简)不会多出来:grep 用 GNU grep -E(\\d、\\w、(?i) 可用,环视与反向引用不支持),跳过隐藏项与 node_modules,不读 .gitignore;glob 用 GNU find 列文件、按 gitignore 风格匹配(* 不跨目录、** 跨、{a,b}、前导 ! 取反),按修改时间从旧到新排序。\n文件工具在链接处按真实路径工作,并按真实路径判策略:链接指向工作区外就等于工作区外。\nbash 由 PTY 承载的持久 shell 提供:登录环境、起始目录就是会话工作区,cd / export / venv / 后台任务跨调用保留(它取代了原先一次性 bash)。\n需要可跟踪的后台任务时用 bash_background:它立刻返回 job id,job_list / job_output(增量读取)/ job_kill 都作用于它;bash 本身没有 run_in_background 参数,传了会被忽略。job id 只在本次 DSH 进程内唯一,重启后会重新编号,引用前先用 job_list 确认。\nbash 与文件工具的 shell 都在发行版内运行、不受 DSH 文件策略约束;文件工具(read/write/edit)受策略约束,工作区内修改模式下只能写工作区内。',
|
|
48
48
|
'help.known.title': '已知问题',
|
|
@@ -89,8 +89,8 @@ export const en: Record<string, string> = {
|
|
|
89
89
|
'help.compat.versionLabel': 'Plugin version',
|
|
90
90
|
'help.compat.unknown': 'Version and compatibility declaration unavailable (the host side did not answer)',
|
|
91
91
|
'help.compat.body': 'The chips above are the DSH releases this build declares, each verified on an isolated instance (own DSH_HOME, dependencies pinned to that release, full check suite).\nThe plugin detects the DSH generation at runtime and picks the matching API; a release exposing neither fails loudly instead of leaving an empty workspace.\nA release outside the list usually still works, but is unverified.',
|
|
92
|
-
'help.news.title': "What's new in 0.7.
|
|
93
|
-
'help.news.body': '
|
|
92
|
+
'help.news.title': "What's new in 0.7.4",
|
|
93
|
+
'help.news.body': 'The dialog works in DSH Desktop again (issues #35, #36). The Desktop host wraps child_process before the plugin loads: it installs plain exec / execFile wrappers and re-exports them with syncBuiltinESMExports().\nThat copy of execFile carries no util.promisify.custom, so promisify(execFile) fell back to the generic implementation, which resolves with the first callback argument only - the stdout string - and result.stdout was undefined on every call.\nThe distro lookup read it and threw "Cannot read properties of undefined (reading \'includes\')"; the frontend caught that and rendered an empty distro picker: the dialog opened, the list stayed empty and no workspace could be created, while wsl.exe -l -q listed the distribution normally in a terminal.\nAll three call sites (list distros, default distro, symlink resolution) now use the callback form of execFile, which no wrapper can reshape; textOf takes the text out of either stream shape.\nThe wsl.exe lookup is a candidate list: wsl.exe on PATH first, then %SystemRoot%\\System32\\wsl.exe, and a failure now names every candidate it tried with the error each produced instead of a type error from inside the decoder.\ntests/exec-shape.mjs reproduces the Desktop wrapper (a probe process with and without --import), asserts the wrapped shape is broken and the new helpers are right, and runs the three real functions through both shapes; it is registered as the exec-shape check in Run-Checks so nobody refactors it back.',
|
|
94
94
|
'help.usage.title': 'Usage and features',
|
|
95
95
|
'help.usage.body': 'Click the W button at the sidebar foot, pick a distribution, type or browse to a Linux path, press Check, then Create & open.\nIn that session the bash tool and the file tools run inside the distribution, so every path the model sees is a Linux path; Windows drives stay reachable as /mnt/<drive>.\nEach mode (Standard / PTC / Minimal / Creator) has a WSL variant in the mode picker, named like WSL · Standard mode.\nThe optional username behaves like wsl.exe -u <user> for bash and persistent-bash; the file tools go through the Windows-side share and are unaffected.\nThe skill catalog is discovered from the nearest .git ancestor of the session cwd downwards (.dsh/skills and .agents/skills, nested projects included), bounded to 4 levels / 64 skill directories / 4096 visited directories, and cached per scan root for 10 seconds.\nA link the share cannot follow is resolved through the distribution (wsl.exe readlink, at most 32 per lookup) and the scan continues at the real path, so a linked-in project and its own nested projects are found too.\nThe catalog is not frozen: published skills directories are re-checked every 3 seconds (skill file mtime + size), so an add, remove or edit appears on the next turn; a 30-second walk finds a skills directory that did not exist before.\nFile search comes from grep / glob inside the distribution, and a mode that mounts no search suite (Minimal) gains none. grep is GNU grep -E (no lookaround or backreferences), skips hidden entries and node_modules, and does not read .gitignore; glob matches gitignore-style patterns here, oldest first.\nThe file tools work at the resolved real path of a link, and the policy is judged there too: a link out of the workspace is an outside write.\n`bash` is a PTY-backed stateful shell: login environment, starting directory the session workspace, and cd / exports / background jobs survive between calls.\nFor a tracked background job use bash_background: it returns a job id immediately, and job_list / job_output (incremental) / job_kill act on it.\n`bash` itself has no run_in_background parameter and ignores one; job ids are unique within this DSH process, so confirm with job_list before acting on one.\nBoth it and the file tools\' shell run inside the distribution, outside the DSH file policy; read/write/edit are inside it, and workspace-write only writes inside the workspace.',
|
|
96
96
|
'help.known.title': 'Known issues',
|