From cd8687043f426cf78140c85784f04282bbe2e0bc Mon Sep 17 00:00:00 2001 From: magalz Date: Sat, 21 Nov 2026 15:21:36 -0300 Subject: [PATCH 1/7] Detect the official DeepSeek Harness dsh.cmd launcher on Windows The CLI installer writes dsh.cmd, but discovery only looked for dsh.exe. Normalize the official batch shim into the executable, argument prefix and environment the launcher declares, keeping the argument-array spawn sites unchanged. The parser accepts only the official layout, binds the Electron entry to the owning installation, checks both files on disk, and leaves other shims to the node_modules fallback. --- runtime/commands.ts | 79 ++++++++- tests/windows-command-discovery.test.ts | 224 ++++++++++++++++++++++++ 2 files changed, 296 insertions(+), 7 deletions(-) create mode 100644 tests/windows-command-discovery.test.ts diff --git a/runtime/commands.ts b/runtime/commands.ts index 112f0d5..54e1cba 100644 --- a/runtime/commands.ts +++ b/runtime/commands.ts @@ -1,6 +1,14 @@ -import { access, readdir, stat } from "node:fs/promises"; +import { access, readdir, readFile, stat } from "node:fs/promises"; import { constants } from "node:fs"; -import { delimiter, dirname, isAbsolute, join } from "node:path"; +import { + basename, + delimiter, + dirname, + isAbsolute, + join, + resolve, + sep, +} from "node:path"; import { homedir } from "node:os"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; @@ -95,6 +103,51 @@ async function direct( return null; } +const WINDOWS_DSH_SHIM = + /^\s*"%~dp0\\?([^"%\r\n]+\.exe)"\s+--expose-internals\s+"%~dp0\\?([^"%\r\n]+\.(?:c|m)?js)"\s+%\*\s*$/i; + +/** + * The launcher installed by the official DeepSeek Harness CLI is a .cmd shim + * that delegates to an Electron executable. Worker sessions spawn with + * `shell: false`, which cannot run a batch file on Windows. Normalize the shim + * into the executable, argument prefix and environment the installer declares, + * so every existing argument-array spawn site works unchanged. + */ +async function windowsShimCommand(path: string): Promise { + let text: string; + try { + text = await readFile(path, "utf8"); + } catch { + return null; + } + // Only a line that fully matches the official launcher shape counts. A + // comment or echo that merely mentions the flag cannot shadow the real line. + let match: RegExpMatchArray | null = null; + for (const line of text.split(/\r?\n/)) { + match = line.match(WINDOWS_DSH_SHIM); + if (match) break; + } + if (!match) return null; + const base = dirname(path); + const command = resolve(base, match[1]); + const script = resolve(base, match[2]); + // Bind the entry to the installation that owns the executable, so a changed + // .exe cannot keep a saved worker approval for the same script identity. + if (basename(command).toLowerCase() !== "deepseek harness.exe") return null; + const appAsar = join(dirname(command), "resources", "app.asar"); + if (!script.toLowerCase().startsWith((appAsar + sep).toLowerCase())) + return null; + // A leftover shim from an uninstall must not look "installed", and must not + // block the node_modules fallback in the same directory. + if (!(await exists(command)) || !(await exists(appAsar))) return null; + return { + command, + prefix: ["--expose-internals", script], + identity: script, + env: { ELECTRON_RUN_AS_NODE: "1" }, + }; +} + async function cursorRuntime(): Promise { const root = join(homedir(), "AppData", "Local", "cursor-agent", "versions"); try { @@ -227,19 +280,31 @@ export async function findCommand( .filter(Boolean), ), ]; + const extensions = + process.platform === "win32" + ? name === "dsh" + ? [".exe", ".cmd"] + : [".exe"] + : [""]; for (const dir of dirs) { const names = name === "cursor" ? ["cursor-agent", "agent"] : [name]; for (const candidate of names) { - const path = join( - dir, - candidate + (process.platform === "win32" ? ".exe" : ""), - ); - if ((await exists(path)) && (await stat(path)).isFile()) + for (const extension of extensions) { + const path = join(dir, candidate + extension); + if (!((await exists(path)) && (await stat(path)).isFile())) continue; + // A batch shim cannot be passed to spawn with `shell: false`. + if (extension !== ".exe") { + const normalized = + name === "dsh" ? await windowsShimCommand(path) : null; + if (normalized) return normalized; + continue; + } return { command: path, prefix: [], ...(name === "cursor" ? { env: { CURSOR_INVOKED_AS: "agent" } } : {}), }; + } } const packageEntry = name === "memtrace" diff --git a/tests/windows-command-discovery.test.ts b/tests/windows-command-discovery.test.ts new file mode 100644 index 0000000..cffceee --- /dev/null +++ b/tests/windows-command-discovery.test.ts @@ -0,0 +1,224 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { commandIdentity, findCommand } from "../runtime/commands"; + +// Byte-for-byte shape of the launcher written by the official DSH installer, +// including CRLF and the real relative depths from resources/runtime/cli/bin. +const officialShim = [ + "@echo off", + "setlocal DisableDelayedExpansion", + 'set "ELECTRON_RUN_AS_NODE=1"', + '"%~dp0..\\..\\..\\..\\DeepSeek Harness.exe" --expose-internals "%~dp0..\\..\\..\\app.asar\\dsh\\node_modules\\@deepseek-ai\\dsh-desktop-host\\lib\\cli.js" %*', + "exit /b %errorlevel%", + "", +].join("\r\n"); + +async function fixture(t: test.TestContext) { + const root = await mkdtemp(join(tmpdir(), "memcode-win-discovery-")); + t.after(() => rm(root, { recursive: true, force: true })); + const install = join(root, "install"); + const bin = join(install, "resources", "runtime", "cli", "bin"); + await mkdir(bin, { recursive: true }); + const exe = join(install, "DeepSeek Harness.exe"); + const asar = join(install, "resources", "app.asar"); + await writeFile(exe, "fixture-only"); + await writeFile(asar, "fixture-only"); + const script = join( + install, + "resources", + "app.asar", + "dsh", + "node_modules", + "@deepseek-ai", + "dsh-desktop-host", + "lib", + "cli.js", + ); + const before = process.env.PATH; + process.env.PATH = bin; + t.after(() => { + if (before === undefined) delete process.env.PATH; + else process.env.PATH = before; + }); + return { root, install, bin, exe, asar, script }; +} + +test( + "the real dsh.cmd layout is normalized for argument-array spawn", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + + const command = await findCommand("dsh"); + assert.ok(command, "the .cmd launcher must be discovered"); + assert.equal(command.command, f.exe); + assert.deepEqual(command.prefix, ["--expose-internals", f.script]); + assert.equal(command.env?.ELECTRON_RUN_AS_NODE, "1"); + assert.equal(commandIdentity(command), f.script); + }, +); + +test( + "a real dsh.exe in the same directory still wins over the dsh.cmd launcher", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + const exe = join(f.bin, "dsh.exe"); + await writeFile(exe, "fixture-only"); + + const command = await findCommand("dsh"); + assert.equal(command?.command, exe); + assert.deepEqual(command?.prefix, []); + }, +); + +test( + "an unrelated .cmd is never handed to a shell:false spawn", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), "@echo off\r\nfixture-only\r\n"); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "a rem line containing --expose-internals cannot spoof the launcher", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile( + join(f.bin, "dsh.cmd"), + `@echo off\r\nrem "C:\\evil.exe" --expose-internals "a.js"\r\n${officialShim}`, + ); + + const command = await findCommand("dsh"); + assert.equal(command?.command, f.exe); + assert.deepEqual(command?.prefix, ["--expose-internals", f.script]); + }, +); + +test( + "an executable with a different name cannot borrow the DSH launcher identity", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.install, "Other.exe"), "fixture-only"); + await writeFile( + join(f.bin, "dsh.cmd"), + officialShim.replace("DeepSeek Harness.exe", "Other.exe"), + ); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "an entry outside the installation's app.asar is rejected", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile( + join(f.bin, "dsh.cmd"), + officialShim.replace( + "app.asar\\dsh\\node_modules\\@deepseek-ai\\dsh-desktop-host\\lib\\cli.js", + "other\\cli.js", + ), + ); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "a shim from an incomplete installation without app.asar is ignored", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + await rm(f.asar); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "an echo mentioning the flag cannot shadow the real launcher line", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile( + join(f.bin, "dsh.cmd"), + `@echo off\r\necho "%~dp0..\\..\\..\\..\\Other.exe" --expose-internals "x.js" %*\r\n${officialShim}`, + ); + + const command = await findCommand("dsh"); + assert.equal(command?.command, f.exe); + assert.deepEqual(command?.prefix, ["--expose-internals", f.script]); + }, +); + +test( + "a leftover shim whose executable is gone is ignored", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + await rm(f.exe); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "an npm-style cmd shim cannot displace the node_modules fallback", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile( + join(f.bin, "dsh.cmd"), + '"%~dp0\\node.exe" --expose-internals "%~dp0\\node_modules\\@deepseek-ai\\dsh\\lib\\bin.js" %*\r\n', + ); + const fallback = join( + f.bin, + "node_modules", + "@deepseek-ai", + "dsh", + "lib", + "bin.js", + ); + await mkdir(join(f.bin, "node_modules", "@deepseek-ai", "dsh", "lib"), { + recursive: true, + }); + await writeFile(fallback, ""); + + const command = await findCommand("dsh"); + assert.equal(command?.command, process.execPath); + assert.deepEqual(command?.prefix, [fallback]); + }, +); + +test( + "between PATH directories the first entry wins, even when it only has a .cmd", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + const other = join(f.root, "other"); + await mkdir(other, { recursive: true }); + const otherExe = join(other, "dsh.exe"); + await writeFile(otherExe, "fixture-only"); + + process.env.PATH = `${f.bin};${other}`; + assert.equal((await findCommand("dsh"))?.command, f.exe); + + process.env.PATH = `${other};${f.bin}`; + assert.equal((await findCommand("dsh"))?.command, otherExe); + }, +); From 98fa75401a69795b28c77c5432f3d5ab848d827e Mon Sep 17 00:00:00 2001 From: magalz Date: Sat, 21 Nov 2026 16:38:55 -0300 Subject: [PATCH 2/7] fix: keep extensionless PATH commands discoverable outside Windows Shim normalization ran for every extension other than .exe. On Linux the extension list is [""], so each PATH executable entered that branch and was skipped unless a node_modules fallback existed; git, gh and shell lookups could return null. Normalize only .cmd files so native executables reach the direct return. --- runtime/commands.ts | 2 +- tests/linux-command-discovery.test.ts | 39 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 tests/linux-command-discovery.test.ts diff --git a/runtime/commands.ts b/runtime/commands.ts index 54e1cba..c01d4e9 100644 --- a/runtime/commands.ts +++ b/runtime/commands.ts @@ -293,7 +293,7 @@ export async function findCommand( const path = join(dir, candidate + extension); if (!((await exists(path)) && (await stat(path)).isFile())) continue; // A batch shim cannot be passed to spawn with `shell: false`. - if (extension !== ".exe") { + if (extension === ".cmd") { const normalized = name === "dsh" ? await windowsShimCommand(path) : null; if (normalized) return normalized; diff --git a/tests/linux-command-discovery.test.ts b/tests/linux-command-discovery.test.ts new file mode 100644 index 0000000..0d6e899 --- /dev/null +++ b/tests/linux-command-discovery.test.ts @@ -0,0 +1,39 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { findCommand } from "../runtime/commands"; + +async function linuxPathFixture(t: test.TestContext, names: string[]) { + const root = await mkdtemp(join(tmpdir(), "memcode-linux-discovery-")); + t.after(() => rm(root, { recursive: true, force: true })); + const commands = new Map(); + for (const name of names) { + const path = join(root, name); + await writeFile(path, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + commands.set(name, path); + } + const beforePath = process.env.PATH; + const beforePlatform = Object.getOwnPropertyDescriptor(process, "platform"); + process.env.PATH = root; + // findCommand reads process.platform directly. Stub it so this regression is + // observable on a Windows development machine as well as on Linux CI. + Object.defineProperty(process, "platform", { + value: "linux", + configurable: true, + }); + t.after(() => { + if (beforePlatform) + Object.defineProperty(process, "platform", beforePlatform); + if (beforePath === undefined) delete process.env.PATH; + else process.env.PATH = beforePath; + }); + return commands; +} + +test("extensionless PATH executables are discovered on Linux", async (t) => { + const commands = await linuxPathFixture(t, ["git", "gh", "dsh"]); + for (const [name, path] of commands) + assert.deepEqual(await findCommand(name), { command: path, prefix: [] }); +}); From 3b782074a55c8188f0d316f9829e171eb8f9e2fd Mon Sep 17 00:00:00 2001 From: magalz Date: Sat, 21 Nov 2026 17:47:21 -0300 Subject: [PATCH 3/7] fix: rediscover saved dsh identities inside app.asar A GUI launch without the installer's launcher directory on PATH could not reuse an approved dsh runtime: its saved identity points inside app.asar, which ordinary filesystem access cannot read. Reconstruct the Electron command from the owning executable and archive before the configured-path existence check, sharing the validation used for the .cmd shim. Reject non-canonical paths so an identity cannot traverse into another installation. --- runtime/commands.ts | 71 ++++++++++++++++----- tests/windows-command-discovery.test.ts | 83 ++++++++++++++++++++++++- 2 files changed, 138 insertions(+), 16 deletions(-) diff --git a/runtime/commands.ts b/runtime/commands.ts index c01d4e9..7243235 100644 --- a/runtime/commands.ts +++ b/runtime/commands.ts @@ -6,6 +6,7 @@ import { dirname, isAbsolute, join, + normalize, resolve, sep, } from "node:path"; @@ -106,6 +107,58 @@ async function direct( const WINDOWS_DSH_SHIM = /^\s*"%~dp0\\?([^"%\r\n]+\.exe)"\s+--expose-internals\s+"%~dp0\\?([^"%\r\n]+\.(?:c|m)?js)"\s+%\*\s*$/i; +async function dshInstallCommand( + executable: string, + script: string, +): Promise { + // Bind the entry to the installation that owns the executable, so a changed + // .exe cannot keep a saved worker approval for the same script identity. + if (basename(executable).toLowerCase() !== "deepseek harness.exe") + return null; + const appAsar = join(dirname(executable), "resources", "app.asar"); + if (!script.toLowerCase().startsWith((appAsar + sep).toLowerCase())) + return null; + // A leftover shim from an uninstall must not look "installed", and must not + // block the node_modules fallback in the same directory. + if (!(await exists(executable)) || !(await exists(appAsar))) return null; + return { + command: executable, + prefix: ["--expose-internals", script], + identity: script, + env: { ELECTRON_RUN_AS_NODE: "1" }, + }; +} + +/** + * A saved dsh identity points inside the installer's app.asar, which ordinary + * filesystem access cannot read. Rebuild the command from the owning + * installation before the configured-path existence check rejects it. + */ +async function savedArchiveCommand( + name: string, + configured: string, +): Promise { + if (name !== "dsh" || process.platform !== "win32" || !isAbsolute(configured)) + return null; + const normalized = normalize(configured); + // A saved identity must be the exact entry the shim resolved. Reject `..` + // segments that would redirect an approved identity to another installation. + if (normalized.toLowerCase() !== configured.toLowerCase()) return null; + const parts = normalized.split(sep); + const archive = parts.findLastIndex( + (part) => part.toLowerCase() === "app.asar", + ); + if ( + archive < 2 || + parts[archive - 1]?.toLowerCase() !== "resources" || + archive === parts.length - 1 || + !/\.(?:c|m)?js$/i.test(parts[parts.length - 1]) + ) + return null; + const install = parts.slice(0, archive - 1).join(sep); + return dshInstallCommand(join(install, "DeepSeek Harness.exe"), normalized); +} + /** * The launcher installed by the official DeepSeek Harness CLI is a .cmd shim * that delegates to an Electron executable. Worker sessions spawn with @@ -131,21 +184,7 @@ async function windowsShimCommand(path: string): Promise { const base = dirname(path); const command = resolve(base, match[1]); const script = resolve(base, match[2]); - // Bind the entry to the installation that owns the executable, so a changed - // .exe cannot keep a saved worker approval for the same script identity. - if (basename(command).toLowerCase() !== "deepseek harness.exe") return null; - const appAsar = join(dirname(command), "resources", "app.asar"); - if (!script.toLowerCase().startsWith((appAsar + sep).toLowerCase())) - return null; - // A leftover shim from an uninstall must not look "installed", and must not - // block the node_modules fallback in the same directory. - if (!(await exists(command)) || !(await exists(appAsar))) return null; - return { - command, - prefix: ["--expose-internals", script], - identity: script, - env: { ELECTRON_RUN_AS_NODE: "1" }, - }; + return dshInstallCommand(command, script); } async function cursorRuntime(): Promise { @@ -250,6 +289,8 @@ export async function findCommand( options: MacCommandOptions & { platform?: NodeJS.Platform } = {}, ): Promise { if (configured) { + const archived = await savedArchiveCommand(name, configured); + if (archived) return archived; if (!isAbsolute(configured) || !(await exists(configured))) return null; if (/\.(cjs|mjs|js)$/i.test(configured)) return { diff --git a/tests/windows-command-discovery.test.ts b/tests/windows-command-discovery.test.ts index cffceee..64cd71e 100644 --- a/tests/windows-command-discovery.test.ts +++ b/tests/windows-command-discovery.test.ts @@ -2,7 +2,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join, normalize, relative, sep } from "node:path"; import { commandIdentity, findCommand } from "../runtime/commands"; // Byte-for-byte shape of the launcher written by the official DSH installer, @@ -222,3 +222,84 @@ test( assert.equal((await findCommand("dsh"))?.command, otherExe); }, ); + +async function withoutLauncherInPath(t: test.TestContext) { + const f = await fixture(t); + const elsewhere = join(f.root, "empty-path"); + await mkdir(elsewhere, { recursive: true }); + process.env.PATH = elsewhere; + return f; +} + +test( + "a saved app.asar identity rediscovers the harness without the launcher directory in PATH", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await withoutLauncherInPath(t); + assert.equal( + await findCommand("dsh"), + null, + "the installer's launcher directory must be absent", + ); + + const command = await findCommand("dsh", f.script); + assert.ok(command, "the saved identity must rediscover the installation"); + assert.equal(command.command, f.exe); + assert.deepEqual(command.prefix, ["--expose-internals", f.script]); + assert.equal(commandIdentity(command), f.script); + assert.equal(command.env?.ELECTRON_RUN_AS_NODE, "1"); + }, +); + +test( + "a saved archive identity is only reconstructed from a still matching installation", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await withoutLauncherInPath(t); + assert.equal( + await findCommand("codex", f.script), + null, + "another harness must not inherit the dsh archive identity", + ); + + await rm(f.exe); + assert.equal(await findCommand("dsh", f.script), null); + await writeFile(f.exe, "fixture-only"); + + await rm(f.asar); + assert.equal(await findCommand("dsh", f.script), null); + }, +); + +test( + "a configured executable path keeps its direct-command behavior", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await withoutLauncherInPath(t); + assert.equal((await findCommand("dsh", f.exe))?.command, f.exe); + }, +); + +test( + "a saved archive identity cannot traverse into another installation", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await withoutLauncherInPath(t); + const other = join(f.root, "other"); + const otherScript = join( + other, + "resources", + "app.asar", + "dsh", + "cli.js", + ); + await mkdir(join(other, "resources"), { recursive: true }); + await writeFile(join(other, "DeepSeek Harness.exe"), "fixture-only"); + await writeFile(join(other, "resources", "app.asar"), "fixture-only"); + + const from = dirname(f.script); + const forged = from + sep + relative(from, otherScript); + assert.equal(normalize(forged), otherScript); + assert.equal(await findCommand("dsh", forged), null); + }, +); From 5853e83edf0cb7cba0ba56f7871d5331cec1b1c3 Mon Sep 17 00:00:00 2001 From: magalz Date: Sat, 21 Nov 2026 19:31:19 -0300 Subject: [PATCH 4/7] fix(dsh): detect custom ACP profiles, sync desktop providers, and guide CLI setup --- runtime/agents/acp-models.ts | 40 +- runtime/agents/cursor.ts | 36 +- runtime/agents/standard-acp.ts | 43 +- runtime/agents/types.ts | 1 + runtime/app.ts | 190 ++++++- runtime/catalog.ts | 58 ++- runtime/commands.ts | 78 ++- runtime/dsh-desktop.ts | 294 +++++++++++ runtime/dsh-migration.ts | 713 +++++++++++++++++++++++++++ runtime/dsh-profiles.ts | 250 ++++++++++ runtime/dsh-yaml.ts | 595 ++++++++++++++++++++++ runtime/local.ts | 4 +- runtime/mac-commands.ts | 4 +- runtime/review-agent.ts | 27 +- runtime/worker-connections.ts | 59 ++- runtime/workers.ts | 19 +- src/components/Dialogs.tsx | 32 ++ src/components/DshSetupFlow.tsx | 699 ++++++++++++++++++++++++++ src/components/ModelSelect.tsx | 22 +- src/components/Select.tsx | 164 ++++-- src/components/WorkerAssignment.tsx | 12 + src/components/WorkerConnections.tsx | 149 ++++-- src/shared.ts | 103 ++++ src/styles-connections.css | 266 ++++++++++ src/styles-select.css | 12 + src/tauri.ts | 8 + tests/connections.test.ts | 157 ++++-- tests/dsh-desktop.test.ts | 198 ++++++++ tests/dsh-migration.test.ts | 459 +++++++++++++++++ tests/dsh-profiles.test.ts | 157 ++++++ tests/review-agent.test.ts | 38 ++ tests/standard-acp.test.ts | 127 ++++- 32 files changed, 4856 insertions(+), 158 deletions(-) create mode 100644 runtime/dsh-desktop.ts create mode 100644 runtime/dsh-migration.ts create mode 100644 runtime/dsh-profiles.ts create mode 100644 runtime/dsh-yaml.ts create mode 100644 src/components/DshSetupFlow.tsx create mode 100644 tests/dsh-desktop.test.ts create mode 100644 tests/dsh-migration.test.ts create mode 100644 tests/dsh-profiles.test.ts diff --git a/runtime/agents/acp-models.ts b/runtime/agents/acp-models.ts index 31f6b67..d5bcbb5 100644 --- a/runtime/agents/acp-models.ts +++ b/runtime/agents/acp-models.ts @@ -5,21 +5,49 @@ type Json = Record; const rows = (value: unknown): Json[] => Array.isArray(value) ? value.filter(row => row && typeof row === "object") : []; const configs = (session: Json) => rows(session.configOptions); const modelConfig = (session: Json) => configs(session).find(option => option.category === "model" || option.id === "model"); -function choices(option?: Json): Json[] { - return rows(option?.options).flatMap(row => Array.isArray(row.options) ? choices(row) : [row]); +function choices(option?: Json, group?: string): Json[] { + return rows(option?.options).flatMap((row) => { + if (Array.isArray(row.options)) { + const nextGroup = + typeof row.name === "string" + ? row.name + : typeof row.group === "string" + ? row.group + : group; + return choices(row, nextGroup); + } + const leafGroup = typeof row.group === "string" ? row.group : group; + return [leafGroup !== undefined ? { ...row, group: leafGroup } : row]; + }); } /** Opaque ACP IDs come from this installed provider. No guessed model names. */ export function standardACPCatalog(session: Json): ModelOption[] { const option = modelConfig(session); const current = option?.currentValue ?? session.models?.currentModelId; - const offered = option ? choices(option).map(row => ({ id: row.value, label: row.name ?? row.label })) - : rows(session.models?.availableModels).map(row => ({ id: row.modelId, label: row.name })); + const offered = option + ? choices(option).map((row) => ({ + id: row.value, + label: row.name ?? row.label, + group: row.group, + })) + : rows(session.models?.availableModels).map((row) => ({ + id: row.modelId, + label: row.name, + group: row.group, + })); const seen = new Set(); - return offered.flatMap(row => { + return offered.flatMap((row) => { if (typeof row.id !== "string" || !row.id || row.id.length > 256 || seen.has(row.id)) return []; seen.add(row.id); - return [{ id: row.id, label: typeof row.label === "string" ? row.label : row.id, source: "acp" as const, isDefault: row.id === current }]; + const group = typeof row.group === "string" && row.group ? row.group : undefined; + return [{ + id: row.id, + label: typeof row.label === "string" ? row.label : row.id, + ...(group ? { group } : {}), + source: "acp" as const, + isDefault: row.id === current, + }]; }); } diff --git a/runtime/agents/cursor.ts b/runtime/agents/cursor.ts index a762a17..97534a3 100644 --- a/runtime/agents/cursor.ts +++ b/runtime/agents/cursor.ts @@ -192,17 +192,43 @@ export function startStandardACPSession(transport: ACPTransport, options: AgentS return runCursorSession(options, undefined, transport); } -export async function probeStandardACPCatalog(transport: ACPTransport, command: Command): Promise { +export async function probeStandardACPCatalog( + transport: ACPTransport, + command: Command, + probeOptions?: { strictStdout?: boolean }, +): Promise { const cwd = await mkdtemp(join(tmpdir(), `memcode-${transport.id}-catalog-`)); let models: ModelOption[] = []; + let inspected = false; + let stdoutNoiseError: string | undefined; try { - const session = runCursorSession({ command, cwd, env: childEnv(), model: "", effort: "low", prompt: "", briefPath: "", toolArgs: [], - onEvent: () => {}, requestInput: async () => ({ cancelled: true }), - }, result => { models = standardACPCatalog(result); }, transport); - const timer = setTimeout(() => { void session.stop(); }, 15000); + const session = runCursorSession({ + command, + cwd, + env: childEnv(), + model: "", + effort: "low", + prompt: "", + briefPath: "", + toolArgs: [], + onEvent: (event) => { + if (probeOptions?.strictStdout && event.type === "error" && !stdoutNoiseError) { + stdoutNoiseError = event.message; + } + }, + requestInput: async () => ({ cancelled: true }), + }, (result) => { + inspected = true; + models = standardACPCatalog(result); + }, transport); + const timer = setTimeout(() => { void session.stop(); }, 25000); try { const result = await session.completion; if (result.exitCode !== 0) throw Error(result.error || `${transport.name}'s model catalog did not respond.`); + if (probeOptions?.strictStdout) { + if (stdoutNoiseError) throw Error(stdoutNoiseError); + if (!inspected) throw Error(`${transport.name}'s model catalog did not respond cleanly.`); + } } finally { clearTimeout(timer); } return models; } finally { diff --git a/runtime/agents/standard-acp.ts b/runtime/agents/standard-acp.ts index 70a2762..0b68e85 100644 --- a/runtime/agents/standard-acp.ts +++ b/runtime/agents/standard-acp.ts @@ -1,14 +1,26 @@ import { probeStandardACPCatalog, startStandardACPSession, type ACPTransport } from "./cursor"; import type { AgentSessionOptions } from "./types"; import type { Command } from "../commands"; +import { normalizeDshProfile } from "../dsh-profiles"; import { join } from "node:path"; import { writeFile } from "node:fs/promises"; export type StandardHarness = "copilot" | "dsh"; -export function standardTransport(id: StandardHarness, options?: Pick): ACPTransport { +export function standardTransport( + id: StandardHarness, + options?: Partial>, +): ACPTransport { return id === "copilot" - ? { id, name: "GitHub Copilot", args: ["--acp", "--stdio", ...(options ? ["--effort", options.effort] : [])] } - : { id, name: "DeepSeek Harness", args: ["--profile", "acp"] }; + ? { + id, + name: "GitHub Copilot", + args: ["--acp", "--stdio", ...(options?.effort ? ["--effort", options.effort] : [])], + } + : { + id, + name: "DeepSeek Harness", + args: ["--profile", normalizeDshProfile(options?.dshProfile)], + }; } export function startStandardSession(id: StandardHarness, options: AgentSessionOptions) { if (options.localModel) throw Error("The local-model override currently supports Codex with Ollama."); @@ -18,12 +30,25 @@ export function startStandardSession(id: StandardHarness, options: AgentSessionO env: { ...options.env, ...(id === "dsh" ? { DSH_PERMISSION_MODE: options.permissionMode === "full-access" ? "danger-full-access" : "workspace-write" } : {}) }, }); } -export function probeStandardCatalog(id: StandardHarness, command: Command) { - return probeStandardACPCatalog(standardTransport(id), command); +export function probeStandardCatalog( + id: StandardHarness, + command: Command, + dshProfile?: string, + options?: { strictStdout?: boolean }, +) { + return probeStandardACPCatalog( + standardTransport(id, id === "dsh" ? { dshProfile } : undefined), + command, + options, + ); } /** Separate reviewer process, no MCP servers, shell, edits or agent tools. */ -export async function readonlyACPTransport(id: StandardHarness, capsule: string): Promise { +export async function readonlyACPTransport( + id: StandardHarness, + capsule: string, + dshProfile?: string, +): Promise { if (id === "copilot") return { id, name: "GitHub Copilot", args: ["--acp", "--stdio", "--available-tools=view", "--disable-builtin-mcps", "--no-custom-instructions", "--no-auto-update"], }; @@ -39,5 +64,9 @@ export function apply(ctx) { { id: "sandbox-policy", config: { mode: "read-only", workspaceRoot: capsule } }, { insert: [{ id: "memcode-readonly-review", name: plugin }] }, ]), { mode: 0o600 }); - return { id, name: "DeepSeek Harness", args: ["--profile", "acp", "--patch", patch] }; + return { + id, + name: "DeepSeek Harness", + args: ["--profile", normalizeDshProfile(dshProfile), "--patch", patch], + }; } diff --git a/runtime/agents/types.ts b/runtime/agents/types.ts index 5972f00..c504a3e 100644 --- a/runtime/agents/types.ts +++ b/runtime/agents/types.ts @@ -42,6 +42,7 @@ export interface AgentSessionOptions { contextConfig?: string; toolArgs: string[]; localModel?: boolean; + dshProfile?: string; permissionMode?: import("../../src/permissions").PermissionMode; onEvent(event: AgentEvent): void; requestInput( diff --git a/runtime/app.ts b/runtime/app.ts index 820bdbd..9905e95 100644 --- a/runtime/app.ts +++ b/runtime/app.ts @@ -11,10 +11,11 @@ import { randomUUID } from "node:crypto"; import { z } from "zod"; import { newRunbook } from "../src/runbook"; import { repoRelativePath } from "./context/source"; -import type { AppState, Project, WorkItem } from "../src/shared"; +import type { AppState, DshSetupStatus, Project, WorkItem } from "../src/shared"; import { maxWorkerSlots } from "../src/worker-slots"; import { isActive } from "../src/domain"; import { LocalStore, exists, findCommand, git, now, within } from "./local"; +import { findDesktopApp } from "./commands"; import { observePersistence } from "./persistence"; import { MemtraceEngine } from "./memtrace"; import { ensureProjectRepository } from "./project-repository"; @@ -26,7 +27,19 @@ import { reconcileArtifacts } from "./artifact-catalog"; import { WorkerManager } from "./workers"; import { PreviewManager } from "./preview"; import { localURL } from "./urls"; -import { discoverHarnesses } from "./catalog"; +import { discoverHarnesses, invalidateHarnessCache } from "./catalog"; +import { probeStandardCatalog } from "./agents/standard-acp"; +import { + createDshAcpProfile, + inspectDshProfiles, + normalizeDshProfile, +} from "./dsh-profiles"; +import { inspectDshDesktopCli, installDshDesktopCli } from "./dsh-desktop"; +import { + applyDshMigration, + diffDshDesktopModels, + dryRunDshMigration, +} from "./dsh-migration"; import { planDefinedStory, readRoutingCalibration, readRoutingLanguage } from "./story-route"; import { qualificationRequestFingerprint } from "./qualification"; import { registerPlanning } from "./planning"; @@ -773,7 +786,7 @@ export async function createRuntime( const measurement = { ...current, scope: current.scope?.slice() }; const measuredRequest = qualificationRequestFingerprint(measurement); const [installed, evidence, calibration, languageModel] = await Promise.all([ - discover(), + discover(false, undefined, { dshProfile: store.state.settings.dshProfile }), engine.qualify( epicAnalysisProject(project(measurement.projectId), measurement), measurement, @@ -820,9 +833,168 @@ export async function createRuntime( host.call("installation_show_applications", {}), ); register("connection:refresh-catalog", z.undefined(), async () => { - await discoverHarnesses(true); + await discoverHarnesses(true, undefined, { + dshProfile: store.state.settings.dshProfile, + }); return store.runtime(); }); + const dshSetupStatus = async (): Promise => { + const [command, desktopAppPath, profiles] = await Promise.all([ + findCommand("dsh"), + findDesktopApp("dsh"), + inspectDshProfiles(store.state.settings.dshProfile), + ]); + const desktopCli = desktopAppPath + ? await inspectDshDesktopCli(desktopAppPath) + : undefined; + return { + cliInstalled: !!command, + cliPath: command?.command ?? null, + desktopAppPath: desktopAppPath ?? null, + ...(desktopCli ? { desktopCli } : {}), + ...profiles, + }; + }; + const assertNoActiveDshWorker = () => { + if ( + store.state.tasks.some( + (item) => !item.example && item.harness === "dsh" && isActive(item), + ) + ) + throw new Error( + "Stop active DeepSeek Harness workers before changing its CLI, profile, or model setup.", + ); + }; + const resolveDshTargetProfile = async (targetProfile?: string) => + targetProfile?.trim() + ? normalizeDshProfile(targetProfile) + : (await inspectDshProfiles(store.state.settings.dshProfile)).activeProfile; + register("dsh:setup-status", z.undefined(), () => dshSetupStatus()); + register("dsh:install-cli", z.undefined(), async () => { + assertNoActiveDshWorker(); + const desktopAppPath = await findDesktopApp("dsh"); + if (!desktopAppPath) + throw new Error("DeepSeek Harness Desktop was not found on this computer."); + const installed = await installDshDesktopCli(desktopAppPath); + invalidateHarnessCache("dsh"); + const [status, runtime] = await Promise.all([ + dshSetupStatus(), + store.runtime(), + ]); + return { + installed: installed.installed, + ...(installed.needsDesktopMenu !== undefined + ? { needsDesktopMenu: installed.needsDesktopMenu } + : {}), + message: installed.message, + status, + runtime, + }; + }); + register( + "dsh:create-profile", + z.object({ name: nonempty.max(64) }).strict(), + async ({ name }) => { + assertNoActiveDshWorker(); + const normalized = normalizeDshProfile(name); + const command = await findCommand("dsh"); + if (!command) + throw new Error( + "Install the DeepSeek Harness CLI before creating an ACP profile.", + ); + const profile = await createDshAcpProfile(command, normalized); + store.state.settings.dshProfile = profile; + await changed(); + invalidateHarnessCache("dsh"); + const [status, runtime] = await Promise.all([ + dshSetupStatus(), + store.runtime(), + ]); + return { profile, status, runtime }; + }, + ); + register( + "dsh:select-profile", + z.object({ name: nonempty.max(64) }).strict(), + async ({ name }) => { + assertNoActiveDshWorker(); + const profile = normalizeDshProfile(name); + const info = await inspectDshProfiles(profile); + if (info.activeProfileIssue === "missing") + throw new Error(`DeepSeek Harness profile "${profile}" does not exist.`); + if (info.activeProfileIssue === "non-acp") + throw new Error( + `DeepSeek Harness profile "${profile}" is not an ACP profile.`, + ); + store.state.settings.dshProfile = profile; + await changed(); + invalidateHarnessCache("dsh"); + const [status, runtime] = await Promise.all([ + dshSetupStatus(), + store.runtime(), + ]); + return { profile, status, runtime }; + }, + ); + register( + "dsh:desktop-diff", + z.object({ targetProfile: z.string().max(64).optional() }).strict(), + async ({ targetProfile }) => + diffDshDesktopModels(await resolveDshTargetProfile(targetProfile)), + ); + register( + "dsh:dry-run-migrate", + z + .object({ + targetProfile: z.string().max(64).optional(), + selectedIds: z.array(nonempty.max(200)).max(200), + }) + .strict(), + async ({ targetProfile, selectedIds }) => { + const command = await findCommand("dsh"); + if (!command) + throw new Error( + "Install the DeepSeek Harness CLI before testing Desktop model migration.", + ); + const profile = await resolveDshTargetProfile(targetProfile); + return dryRunDshMigration(command, profile, selectedIds, { + probe: (p, cmd) => + probeStandardCatalog("dsh", cmd, p, { strictStdout: true }), + }); + }, + ); + register( + "dsh:apply-migrate", + z + .object({ + targetProfile: z.string().max(64).optional(), + selectedIds: z.array(nonempty.max(200)).max(200), + }) + .strict(), + async ({ targetProfile, selectedIds }) => { + assertNoActiveDshWorker(); + const command = await findCommand("dsh"); + if (!command) + throw new Error( + "Install the DeepSeek Harness CLI before importing Desktop models.", + ); + const profile = await resolveDshTargetProfile(targetProfile); + const applied = await applyDshMigration(command, profile, selectedIds, { + probe: (p, cmd) => + probeStandardCatalog("dsh", cmd, p, { strictStdout: true }), + }); + invalidateHarnessCache("dsh"); + const runtime = await store.runtime(); + return { + ok: applied.ok, + targetProfile: profile, + appliedIds: applied.appliedIds, + failed: applied.failed, + models: applied.models, + runtime, + }; + }, + ); register("connection:guide", z.object({ harness }).strict(), ({ harness }) => host.call("open_worker_setup", { harness }), ); @@ -1043,6 +1215,7 @@ export async function createRuntime( speechEndpoint: z.string().max(1000), speech: speechSettingsSchema.optional(), defaultHarness: harness, + dshProfile: z.string().max(64).optional(), model: z.string().max(200), localModel: z.boolean(), maxWorkers: z.number().int().min(1).max(maxWorkerSlots), @@ -1113,10 +1286,19 @@ export async function createRuntime( // reconnect resets the owner lifecycle so the next project can open it. if (settings.memtracePath !== store.state.settings.memtracePath) await engine.reconnect(); + const dshProfile = + settings.dshProfile === undefined + ? store.state.settings.dshProfile + : settings.dshProfile.trim() + ? normalizeDshProfile(settings.dshProfile) + : undefined; + if (dshProfile !== store.state.settings.dshProfile) + invalidateHarnessCache("dsh"); // A Settings dialog opened before a worker-default or handoff choice must not erase it. store.state.settings = { ...store.state.settings, ...settings, + dshProfile, speech: settings.speech ?? store.state.settings.speech, contextAssistant: settings.contextAssistant ?? store.state.settings.contextAssistant, diff --git a/runtime/catalog.ts b/runtime/catalog.ts index 4c418f9..350471a 100644 --- a/runtime/catalog.ts +++ b/runtime/catalog.ts @@ -3,6 +3,7 @@ import { probeClaudeCatalog } from "./agents/claude"; import { codexCatalogGeneration } from "./agents/codex-models"; import { probeCursorCatalog } from "./agents/cursor"; import { probeStandardCatalog } from "./agents/standard-acp"; +import { inspectDshProfiles } from "./dsh-profiles"; import { commandIdentity, findCommand, @@ -15,7 +16,15 @@ import { type ModelOption, } from "../src/shared"; -const cached = new Map }>(); +const cached = new Map< + Harness, + { expires: number; generation: number; profile?: string; value: Promise } +>(); + +export function invalidateHarnessCache(id?: Harness): void { + if (id) cached.delete(id); + else cached.clear(); +} let cursorCache: { identity: string; expires: number; models: Promise } | undefined; function cursorModels(command: NonNullable>>, refresh: boolean) { @@ -28,7 +37,13 @@ function cursorModels(command: NonNullable { +type DshInspection = Awaited>; + +async function discoverOne( + id: Harness, + refresh: boolean, + dshInfo?: DshInspection, +): Promise { const [command, desktopAppPath] = await Promise.all([findCommand(id), findDesktopApp(id)]); let models: ModelOption[] = []; let allModelsDenied = false; @@ -39,7 +54,10 @@ async function discoverOne(id: Harness, refresh: boolean): Promise []); + if (command && id === "copilot") + models = await probeStandardCatalog(id, command).catch(() => []); + if (command && id === "dsh") + models = await probeStandardCatalog(id, command, dshInfo?.activeProfile).catch(() => []); return { id, name: harnessNames[id], @@ -47,6 +65,12 @@ async function discoverOne(id: Harness, refresh: boolean): Promise profile.name), + activeProfile: dshInfo.activeProfile, + } + : {}), models, ...(allModelsDenied ? { allModelsDenied } : {}), note: command @@ -58,14 +82,34 @@ async function discoverOne(id: Harness, refresh: boolean): Promise { +export async function discoverHarnesses( + refresh = false, + only?: Harness, + options?: { dshProfile?: string }, +): Promise { const ids: Harness[] = only ? [only] : ["codex", "claude", "cursor", "copilot", "dsh"]; - return Promise.all(ids.map((id) => { + return Promise.all(ids.map(async (id) => { + const dshInfo = + id === "dsh" + ? await inspectDshProfiles(options?.dshProfile).catch(() => undefined) + : undefined; + const profile = dshInfo?.activeProfile; const existing = cached.get(id); const generation = id === "codex" ? codexCatalogGeneration : 0; - if (existing && existing.generation === generation && (!refresh || existing.expires === Infinity) && Date.now() < existing.expires) + if ( + existing && + existing.generation === generation && + existing.profile === profile && + (!refresh || existing.expires === Infinity) && + Date.now() < existing.expires + ) return existing.value; - const entry = { expires: Infinity, generation, value: discoverOne(id, refresh) }; + const entry = { + expires: Infinity, + generation, + profile, + value: discoverOne(id, refresh, dshInfo), + }; cached.set(id, entry); void entry.value.then(() => { entry.expires = Date.now() + 60000; }, () => { cached.delete(id); }); return entry.value; diff --git a/runtime/commands.ts b/runtime/commands.ts index 112f0d5..127cce0 100644 --- a/runtime/commands.ts +++ b/runtime/commands.ts @@ -29,11 +29,81 @@ export function commandIdentity(command: Command): string { } export async function findDesktopApp( name: string, - options: MacCommandOptions & { platform?: NodeJS.Platform } = {}, + options: MacCommandOptions & { + platform?: NodeJS.Platform; + windowsCandidates?: readonly string[]; + } = {}, ): Promise { - return (options.platform ?? process.platform) === "darwin" - ? findMacDesktopApp(name, options) - : null; + const platform = options.platform ?? process.platform; + if (platform === "darwin") return findMacDesktopApp(name, options); + if (platform !== "win32" || name !== "dsh") return null; + + const env = options.environment ?? process.env; + const localAppData = env.LOCALAPPDATA ?? join(options.home ?? homedir(), "AppData", "Local"); + const programFiles = env.ProgramFiles ?? "C:\\Program Files"; + const candidates = options.windowsCandidates ?? [ + join(localAppData, "Programs", "DeepSeek Harness", "DeepSeek Harness.exe"), + join(programFiles, "DeepSeek Harness", "DeepSeek Harness.exe"), + ]; + for (const exePath of candidates) { + try { + if ((await stat(exePath)).isFile() && (await exists(join(dirname(exePath), "resources", "app.asar")))) { + return exePath; + } + } catch { + /* Candidate installation is absent. */ + } + } + return null; +} + +function expandWindowsEnvVars(raw: string, env: NodeJS.ProcessEnv): string { + const lookup = new Map(); + for (const [k, v] of Object.entries(env)) { + if (v !== undefined) lookup.set(k.toLowerCase(), v); + } + return raw.replace(/%([^%]+)%/g, (match, name: string) => lookup.get(name.toLowerCase()) ?? match); +} + +export async function refreshWindowsUserPath(): Promise { + if (process.platform !== "win32") return []; + try { + const regExe = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "reg.exe"); + const { stdout } = await promisify(execFile)( + regExe, + ["query", "HKCU\\Environment", "/v", "Path"], + { shell: false, windowsHide: true, timeout: 5000, encoding: "utf8" }, + ); + const match = /^\s*Path\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(stdout); + if (!match) return []; + + const discovered = expandWindowsEnvVars(match[1], process.env) + .split(delimiter) + .map((entry) => entry.replace(/^"|"$/g, "").trim()) + .filter(Boolean); + + const pathKey = Object.keys(process.env).find((k) => k.toLowerCase() === "path") ?? "PATH"; + const existing = (process.env[pathKey] ?? "") + .split(delimiter) + .map((entry) => entry.replace(/^"|"$/g, "").trim()) + .filter(Boolean); + const seen = new Set(existing.map((entry) => entry.toLowerCase())); + const added: string[] = []; + for (const dir of discovered) { + const lower = dir.toLowerCase(); + if (!seen.has(lower)) { + seen.add(lower); + existing.push(dir); + added.push(dir); + } + } + if (added.length > 0) { + process.env[pathKey] = existing.join(delimiter); + } + return added; + } catch { + return []; + } } export async function exists(path: string): Promise { try { diff --git a/runtime/dsh-desktop.ts b/runtime/dsh-desktop.ts new file mode 100644 index 0000000..8bbb7b3 --- /dev/null +++ b/runtime/dsh-desktop.ts @@ -0,0 +1,294 @@ +import { execFile } from "node:child_process"; +import { stat } from "node:fs/promises"; +import { delimiter, dirname, join } from "node:path"; +import { promisify } from "node:util"; +import type { DshDesktopCliInfo } from "../src/shared"; +import { childEnv, exists, refreshWindowsUserPath } from "./commands"; + +const execFileAsync = promisify(execFile); +const FINGERPRINT_RE = /^[a-f0-9]{64}$/i; +const SCRUB_ENV_RE = /KEY|SECRET|TOKEN|PASSWORD|^NODE_OPTIONS$|^NODE_PATH$/i; + +interface DesktopCliPaths { + isMac: boolean; + bundledNode: string; + commandManagerPath: string; + launcherPath: string; +} + +interface CommandManagerResponse { + ok: boolean; + code?: string; + message?: string; + state?: { + fingerprint?: unknown; + managed?: unknown; + available?: unknown; + activeCommand?: unknown; + launcher?: unknown; + directory?: unknown; + }; +} + +function resolveResourcesDir(desktopAppPath: string): { resourcesDir: string; isMac: boolean } { + const isMac = /\.app(?:[\\/]?)$/i.test(desktopAppPath) || process.platform === "darwin"; + const clean = desktopAppPath.replace(/[\\/]+$/, ""); + return { + isMac, + resourcesDir: isMac ? join(clean, "Contents", "Resources") : join(dirname(clean), "resources"), + }; +} + +function scrubbedCliEnv(): NodeJS.ProcessEnv { + const env = childEnv(); + for (const key of Object.keys(env)) { + if (SCRUB_ENV_RE.test(key)) delete env[key]; + } + return env; +} + +async function isFile(path: string): Promise { + try { + return (await stat(path)).isFile(); + } catch { + return false; + } +} + +async function resolveDesktopCliPaths(desktopAppPath: string): Promise { + const { resourcesDir, isMac } = resolveResourcesDir(desktopAppPath); + const nodeNames = process.platform === "win32" ? ["node.exe", "node"] : ["node"]; + let bundledNode: string | null = null; + for (const sub of ["runtime", ""]) { + for (const nodeName of nodeNames) { + const candidate = sub + ? join(resourcesDir, sub, "primary-runtime", "dependencies", "node", "bin", nodeName) + : join(resourcesDir, "primary-runtime", "dependencies", "node", "bin", nodeName); + if (await isFile(candidate)) { + bundledNode = candidate; + break; + } + } + if (bundledNode) break; + } + if (!bundledNode) { + return "DeepSeek Harness Desktop bundled Node runtime was not found."; + } + + const commandManagerPath = join(resourcesDir, "runtime", "cli", "command-manager.js"); + if (!(await isFile(commandManagerPath))) { + return "DeepSeek Harness Desktop CLI manager was not found."; + } + + const launcherCandidates = isMac && process.platform !== "win32" + ? [join(resourcesDir, "runtime", "cli", "bin", "dsh")] + : [ + join(resourcesDir, "runtime", "cli", "bin", "dsh.cmd"), + join(resourcesDir, "runtime", "cli", "bin", "dsh"), + ]; + let launcherPath: string | null = null; + for (const candidate of launcherCandidates) { + if (await exists(candidate)) { + launcherPath = candidate; + break; + } + } + if (!launcherPath) { + return "DeepSeek Harness Desktop CLI launcher was not found."; + } + + return { isMac, bundledNode, commandManagerPath, launcherPath }; +} + +async function runCommandManager( + paths: DesktopCliPaths, + args: string[], +): Promise<{ parsed: CommandManagerResponse | null; errorMessage?: string }> { + let stdout = ""; + let stderr = ""; + let thrownMessage: string | undefined; + try { + const result = await execFileAsync(paths.bundledNode, [paths.commandManagerPath, ...args], { + shell: false, + windowsHide: true, + timeout: 15_000, + encoding: "utf8", + env: scrubbedCliEnv(), + }); + stdout = result.stdout ?? ""; + stderr = result.stderr ?? ""; + } catch (error) { + const err = error as { stdout?: string; stderr?: string; message?: string }; + stdout = typeof err.stdout === "string" ? err.stdout : ""; + stderr = typeof err.stderr === "string" ? err.stderr : ""; + thrownMessage = err.message; + } + + const lines = stdout + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean); + for (let i = lines.length - 1; i >= 0; i--) { + try { + const candidate = JSON.parse(lines[i]) as CommandManagerResponse; + if (candidate && typeof candidate === "object" && typeof candidate.ok === "boolean") { + return { parsed: candidate }; + } + } catch { + /* Ignore non-JSON line and try earlier line. */ + } + } + return { + parsed: null, + errorMessage: stderr.trim() || thrownMessage || "Invalid response from Desktop CLI manager.", + }; +} + +async function inspectInternal( + desktopAppPath: string, +): Promise<{ info: DshDesktopCliInfo; fingerprint?: string; paths?: DesktopCliPaths }> { + const resolved = await resolveDesktopCliPaths(desktopAppPath); + if (typeof resolved === "string") { + return { + info: { + desktopAppPath, + canInstall: false, + managed: false, + available: false, + reason: resolved, + }, + }; + } + + const { parsed, errorMessage } = await runCommandManager(resolved, ["inspect"]); + if (!parsed) { + return { + info: { + desktopAppPath, + canInstall: false, + managed: false, + available: false, + reason: errorMessage ?? "Failed to inspect DeepSeek Harness Desktop CLI.", + }, + }; + } + if (!parsed.ok) { + return { + info: { + desktopAppPath, + canInstall: false, + managed: false, + available: false, + reason: parsed.message || "Desktop CLI inspection returned an error.", + }, + }; + } + + const state = parsed.state; + if ( + !state || + typeof state.fingerprint !== "string" || + !FINGERPRINT_RE.test(state.fingerprint) || + typeof state.managed !== "boolean" || + typeof state.available !== "boolean" + ) { + return { + info: { + desktopAppPath, + canInstall: false, + managed: false, + available: false, + reason: "Desktop CLI inspection returned an unexpected response format.", + }, + }; + } + + const launcherPath = + typeof state.launcher === "string" && state.launcher.trim() + ? state.launcher + : resolved.launcherPath; + + return { + fingerprint: state.fingerprint, + paths: resolved, + info: { + desktopAppPath, + canInstall: true, + managed: state.managed, + available: state.available, + launcherPath, + ...(typeof state.activeCommand === "string" && state.activeCommand + ? { activeCommand: state.activeCommand } + : {}), + }, + }; +} + +export async function inspectDshDesktopCli(desktopAppPath: string): Promise { + return (await inspectInternal(desktopAppPath)).info; +} + +function prependWindowsPathDir(dir: string): void { + const pathKey = Object.keys(process.env).find((k) => k.toLowerCase() === "path") ?? "PATH"; + const entries = (process.env[pathKey] ?? "") + .split(delimiter) + .map((part) => part.replace(/^"|"$/g, "").trim()) + .filter(Boolean); + const lower = dir.toLowerCase(); + if (!entries.some((entry) => entry.toLowerCase() === lower)) { + process.env[pathKey] = [dir, ...entries].join(delimiter); + } +} + +export async function installDshDesktopCli( + desktopAppPath: string, +): Promise<{ installed: boolean; needsDesktopMenu?: boolean; message: string; launcherPath?: string }> { + const inspected = await inspectInternal(desktopAppPath); + if (!inspected.info.canInstall || !inspected.fingerprint || !inspected.paths) { + return { + installed: false, + message: inspected.info.reason ?? "DeepSeek Harness Desktop CLI helper is unavailable.", + }; + } + + const { parsed, errorMessage } = await runCommandManager(inspected.paths, [ + "install", + inspected.fingerprint, + ]); + if (!parsed) { + return { + installed: false, + message: errorMessage ?? "Failed to install DeepSeek Harness CLI.", + }; + } + + if (!parsed.ok) { + if (inspected.paths.isMac && (parsed.code === "EACCES" || parsed.code === "EPERM")) { + return { + installed: false, + needsDesktopMenu: true, + message: "Open DeepSeek Harness Desktop and choose Manage dsh Command… to authorize /usr/local/bin/dsh.", + }; + } + return { + installed: false, + message: parsed.message || "Failed to install DeepSeek Harness CLI.", + }; + } + + const launcherPath = + typeof parsed.state?.launcher === "string" && parsed.state.launcher.trim() + ? parsed.state.launcher + : inspected.info.launcherPath ?? inspected.paths.launcherPath; + + if (process.platform === "win32") { + await refreshWindowsUserPath(); + prependWindowsPathDir(dirname(launcherPath)); + } + + return { + installed: true, + message: "DeepSeek Harness CLI installed.", + launcherPath, + }; +} diff --git a/runtime/dsh-migration.ts b/runtime/dsh-migration.ts new file mode 100644 index 0000000..7be5248 --- /dev/null +++ b/runtime/dsh-migration.ts @@ -0,0 +1,713 @@ +import { execFile } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { join, relative } from "node:path"; +import { promisify } from "node:util"; +import type { + DshDesktopDiff, + DshDesktopProviderCandidate, + DshDryRunResult, + DshProviderFailure, + DshSkippedDesktopItem, + ModelOption, +} from "../src/shared"; +import { probeStandardCatalog } from "./agents/standard-acp"; +import { childEnv, exists, type Command } from "./commands"; +import { + inspectDshProfiles, + isTemporaryDryRunProfile, + normalizeDshProfile, + resolveDshHome, +} from "./dsh-profiles"; +import { + hasInlineSecret, + hasJsTag, + parseDshPatchYaml, + stringifyDshPatchYaml, +} from "./dsh-yaml"; + +const execFileAsync = promisify(execFile); +const STALE_DRYRUN_AGE_MS = 60 * 60 * 1000; +const SNAPSHOT_FILES = ["package.json", "cordis.patch.yml", "pnpm-lock.yaml"] as const; +const STAGING_COPY_FILES = [ + "package.json", + "cordis.patch.yml", + "pnpm-workspace.yaml", + "pnpm-lock.yaml", +] as const; + +export type StrictAcpProbe = (profile: string, command: Command) => Promise; + +interface DesktopPatchData { + piAiProviders: Map>; + pluginConfigRows: Map>; + diff: DshDesktopDiff; +} + +function isPlainObject(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function cloneJson(value: T): T { + return JSON.parse(JSON.stringify(value)) as T; +} + +function buildDshEnv(dshHome: string, command: Command, env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return { + ...childEnv(), + ...command.env, + ...(env !== process.env ? env : {}), + DSH_HOME: dshHome, + }; +} + +function withDshHomeCommand(command: Command, dshHome: string, env: NodeJS.ProcessEnv): Command { + return { + ...command, + env: { + ...command.env, + ...(env !== process.env && env.PATH ? { PATH: env.PATH } : {}), + DSH_HOME: dshHome, + }, + }; +} + +function extractErrorMessage(error: unknown): string { + if (error instanceof Error) { + const err = error as Error & { stderr?: string; stdout?: string }; + const detail = err.stderr?.trim() || err.stdout?.trim(); + return detail ? `${err.message}: ${detail}` : err.message; + } + return String(error); +} + +async function isDirectory(path: string): Promise { + try { + return (await stat(path)).isDirectory(); + } catch { + return false; + } +} + +async function readJsonSafe(path: string): Promise> { + try { + const parsed = JSON.parse(await readFile(path, "utf8")); + return isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } +} + +async function readPatchSafe(path: string): Promise<{ entries: any[]; hasJsExpression: boolean }> { + try { + return parseDshPatchYaml(await readFile(path, "utf8")); + } catch { + return { entries: [], hasJsExpression: false }; + } +} + +function extractPiAiProviders(entries: unknown[]): { + providers: Map>; + tainted: boolean; +} { + const providers = new Map>(); + let tainted = false; + for (const entry of entries) { + if (!isPlainObject(entry)) continue; + if (entry.id !== "llm-pi-ai" && entry.name !== "@deepseek-ai/dsh-llm-pi-ai") continue; + const config = entry.config; + if (!isPlainObject(config)) continue; + const rawProviders = config.providers; + if (!isPlainObject(rawProviders)) { + if (hasJsTag(config)) tainted = true; + continue; + } + for (const [providerId, providerConfig] of Object.entries(rawProviders)) { + if (isPlainObject(providerConfig)) { + providers.set(providerId, providerConfig); + } + } + } + return { providers, tainted }; +} + +function extractModelIds(providerConfig: Record): string[] { + if (!Array.isArray(providerConfig.models)) return []; + const ids: string[] = []; + for (const model of providerConfig.models) { + if (typeof model === "string" && model.trim()) ids.push(model.trim()); + else if (isPlainObject(model)) { + const id = typeof model.id === "string" ? model.id.trim() : typeof model.name === "string" ? model.name.trim() : ""; + if (id) ids.push(id); + } + } + return ids; +} + +function findMatchingPluginRow( + entries: unknown[], + pkgName: string, +): Record | undefined { + const shortName = pkgName.replace(/^@[^/]+\//, "").replace(/^dsh-/, ""); + for (const entry of entries) { + if (!isPlainObject(entry)) continue; + if (Array.isArray(entry.insert) && !entry.id && !entry.name) continue; + if (entry.name === pkgName || entry.id === shortName || entry.id === pkgName) { + return entry; + } + } + return undefined; +} + +function buildPluginSpec(pkgName: string, rawSpec: unknown): { + spec: string; + source: "registry" | "local-link"; + defaultSelected: boolean; + warning?: string; +} { + const trimmed = typeof rawSpec === "string" ? rawSpec.trim() : ""; + if (trimmed.startsWith("link:") || trimmed.startsWith("file:")) { + return { + spec: trimmed, + source: "local-link", + defaultSelected: false, + warning: "Local linked plugin may add non-LLM hooks or require Desktop services.", + }; + } + const spec = trimmed + ? /^(?:https?:|git\+|npm:|github:|workspace:)/i.test(trimmed) + ? trimmed + : `${pkgName}@${trimmed}` + : pkgName; + return { + spec, + source: "registry", + defaultSelected: true, + }; +} + +async function computeDesktopDiff( + targetProfile: string, + env: NodeJS.ProcessEnv, +): Promise { + const normalizedTarget = normalizeDshProfile(targetProfile); + const dshHome = resolveDshHome(env); + const desktopDir = join(dshHome, "profiles", "desktop"); + const targetDir = join(dshHome, "profiles", normalizedTarget); + + if (!(await isDirectory(desktopDir))) { + return { + piAiProviders: new Map(), + pluginConfigRows: new Map(), + diff: { + targetProfile: normalizedTarget, + desktopPresent: false, + providers: [], + skipped: [], + }, + }; + } + + const [desktopPatch, desktopPkg, targetPatch, targetPkg, homePatch] = await Promise.all([ + readPatchSafe(join(desktopDir, "cordis.patch.yml")), + readJsonSafe(join(desktopDir, "package.json")), + readPatchSafe(join(targetDir, "cordis.patch.yml")), + readJsonSafe(join(targetDir, "package.json")), + readPatchSafe(join(dshHome, "cordis.patch.yml")), + ]); + + const providers: DshDesktopProviderCandidate[] = []; + const skipped: DshSkippedDesktopItem[] = []; + const piAiProviders = new Map>(); + const pluginConfigRows = new Map>(); + + const desktopPiAi = extractPiAiProviders(desktopPatch.entries); + const existingModels = new Map>(); + for (const patch of [homePatch, targetPatch]) { + const extracted = extractPiAiProviders(patch.entries); + for (const [providerId, cfg] of extracted.providers) { + let set = existingModels.get(providerId); + if (!set) { + set = new Set(); + existingModels.set(providerId, set); + } + for (const modelId of extractModelIds(cfg)) set.add(modelId); + } + } + + if (desktopPiAi.tainted) { + skipped.push({ + name: "llm-pi-ai", + reason: "Desktop llm-pi-ai configuration contains !!js expression and was skipped.", + }); + } else { + for (const [providerId, cfg] of desktopPiAi.providers) { + if (hasJsTag(cfg)) { + skipped.push({ + name: providerId, + reason: "Contains !!js expression; skipped for safety.", + }); + continue; + } + if (hasInlineSecret(cfg)) { + skipped.push({ + name: providerId, + reason: "Contains inline credential or secret; use apiKeyEnv or .credentials.yaml.", + }); + continue; + } + const models = extractModelIds(cfg); + const existing = existingModels.get(providerId); + const missingModels = existing ? models.filter((m) => !existing.has(m)) : undefined; + if (existing && (!missingModels || missingModels.length === 0)) continue; + + piAiProviders.set(providerId, cfg); + const displayName = + typeof cfg.displayName === "string" && cfg.displayName.trim() + ? cfg.displayName.trim() + : providerId; + providers.push({ + id: `pi-ai:${providerId}`, + kind: "pi-ai", + name: displayName, + providerId, + models, + ...(missingModels ? { missingModels } : {}), + defaultSelected: true, + }); + } + } + + const targetPackages = new Set([ + ...(Array.isArray((targetPkg.dsh as { profile?: { bundles?: unknown[] } } | undefined)?.profile?.bundles) + ? ((targetPkg.dsh as { profile: { bundles: unknown[] } }).profile.bundles.filter( + (b): b is string => typeof b === "string", + )) + : []), + ...(isPlainObject(targetPkg.dependencies) ? Object.keys(targetPkg.dependencies) : []), + ]); + + const desktopBundles = Array.isArray( + (desktopPkg.dsh as { profile?: { bundles?: unknown[] } } | undefined)?.profile?.bundles, + ) + ? ((desktopPkg.dsh as { profile: { bundles: unknown[] } }).profile.bundles.filter( + (b): b is string => typeof b === "string", + )) + : []; + const desktopDeps = isPlainObject(desktopPkg.dependencies) ? desktopPkg.dependencies : {}; + const desktopPackages = [...new Set([...desktopBundles, ...Object.keys(desktopDeps)])]; + + for (const pkgName of desktopPackages) { + if (pkgName.startsWith("@deepseek-ai/") || targetPackages.has(pkgName)) continue; + + const pkgDir = join(desktopDir, "node_modules", ...pkgName.split("/")); + const pkgJson = await readJsonSafe(join(pkgDir, "package.json")); + const peers = isPlainObject(pkgJson.peerDependencies) ? pkgJson.peerDependencies : null; + if (!peers || !Object.prototype.hasOwnProperty.call(peers, "@deepseek-ai/dsh-llm")) { + continue; + } + + const exportsField = isPlainObject(pkgJson.exports) ? pkgJson.exports : null; + const dotExport = exportsField && isPlainObject(exportsField["."]) ? exportsField["."] : null; + const mainRel = + typeof pkgJson.main === "string" && pkgJson.main.trim() + ? pkgJson.main.trim() + : typeof dotExport?.default === "string" + ? dotExport.default + : typeof exportsField?.["."] === "string" + ? (exportsField["."] as string) + : ""; + if (!mainRel) continue; + + const mainPath = join(pkgDir, mainRel); + if (relative(pkgDir, mainPath).startsWith("..")) continue; + let mainSource = ""; + try { + mainSource = await readFile(mainPath, "utf8"); + } catch { + continue; + } + if (!mainSource.includes("registerAdapter(")) continue; + + const { spec, source, defaultSelected, warning } = buildPluginSpec(pkgName, desktopDeps[pkgName]); + const configRow = findMatchingPluginRow(desktopPatch.entries, pkgName); + let hasConfigPatch = false; + if (configRow) { + if (hasJsTag(configRow) || hasInlineSecret(configRow)) { + skipped.push({ + name: pkgName, + reason: "Desktop config row contains !!js or inline secrets and was skipped.", + }); + } else { + pluginConfigRows.set(pkgName, configRow); + hasConfigPatch = true; + } + } + + providers.push({ + id: `plugin:${pkgName}`, + kind: "plugin", + name: pkgName, + providerId: pkgName, + models: [], + source, + spec, + ...(hasConfigPatch ? { hasConfigPatch: true } : {}), + defaultSelected, + ...(warning ? { warning } : {}), + }); + } + + return { + piAiProviders, + pluginConfigRows, + diff: { + targetProfile: normalizedTarget, + desktopPresent: true, + providers, + skipped, + }, + }; +} + +export async function diffDshDesktopModels( + targetProfile: string, + env: NodeJS.ProcessEnv = process.env, +): Promise { + return (await computeDesktopDiff(targetProfile, env)).diff; +} + +function mergePatchEntries( + existingEntries: any[], + selectedIds: string[], + data: DesktopPatchData, +): any[] { + const entries = cloneJson(existingEntries); + const selectedPiAi = selectedIds + .filter((id) => id.startsWith("pi-ai:")) + .map((id) => id.slice("pi-ai:".length)); + + if (selectedPiAi.length > 0) { + let piAiEntry = entries.find( + (entry) => + isPlainObject(entry) && + (entry.id === "llm-pi-ai" || entry.name === "@deepseek-ai/dsh-llm-pi-ai"), + ); + if (!piAiEntry) { + piAiEntry = { + id: "llm-pi-ai", + name: "@deepseek-ai/dsh-llm-pi-ai", + config: { providers: {} }, + }; + entries.push(piAiEntry); + } + if (!isPlainObject(piAiEntry.config)) piAiEntry.config = {}; + if (!isPlainObject(piAiEntry.config.providers)) piAiEntry.config.providers = {}; + + for (const providerId of selectedPiAi) { + const desktopCfg = data.piAiProviders.get(providerId); + if (!desktopCfg) continue; + const existingCfg = piAiEntry.config.providers[providerId]; + if (!isPlainObject(existingCfg)) { + piAiEntry.config.providers[providerId] = cloneJson(desktopCfg); + } else if (Array.isArray(desktopCfg.models)) { + const currentModels = Array.isArray(existingCfg.models) ? existingCfg.models : []; + const existingIds = new Set(extractModelIds(existingCfg)); + for (const model of desktopCfg.models) { + const modelId = + typeof model === "string" + ? model + : isPlainObject(model) + ? (typeof model.id === "string" ? model.id : typeof model.name === "string" ? model.name : "") + : ""; + if (modelId && !existingIds.has(modelId)) { + currentModels.push(cloneJson(model)); + existingIds.add(modelId); + } + } + existingCfg.models = currentModels; + } + } + } + + for (const id of selectedIds) { + if (!id.startsWith("plugin:")) continue; + const pkgName = id.slice("plugin:".length); + const row = data.pluginConfigRows.get(pkgName); + if (!row) continue; + const alreadyExists = entries.some( + (entry) => + isPlainObject(entry) && + ((row.id !== undefined && entry.id === row.id) || + (row.name !== undefined && entry.name === row.name)), + ); + if (!alreadyExists) { + entries.push(cloneJson(row)); + } + } + + return entries; +} + +async function applySelectedToProfileDir( + command: Command, + profileName: string, + profileDir: string, + selectedIds: string[], + data: DesktopPatchData, + dshHome: string, + env: NodeJS.ProcessEnv, + onPluginStart?: (id: string, pkgName: string) => void, +): Promise { + const byId = new Map(data.diff.providers.map((p) => [p.id, p])); + for (const id of selectedIds) { + if (!id.startsWith("plugin:")) continue; + const candidate = byId.get(id); + if (!candidate) { + throw new Error(`Selected migration candidate "${id}" was not found in Desktop profile.`); + } + const spec = candidate.spec ?? candidate.providerId; + onPluginStart?.(id, candidate.name); + await execFileAsync( + command.command, + [...command.prefix, "plugin", "--profile", profileName, "add", spec], + { + shell: false, + windowsHide: true, + timeout: 60_000, + maxBuffer: 10 * 1024 * 1024, + encoding: "utf8", + env: buildDshEnv(dshHome, command, env), + }, + ); + } + + const patchPath = join(profileDir, "cordis.patch.yml"); + const currentPatch = await readPatchSafe(patchPath); + const merged = mergePatchEntries(currentPatch.entries, selectedIds, data); + await writeFile(patchPath, stringifyDshPatchYaml(merged), "utf8"); +} + +async function cleanupStaleDryRunDirs(profilesDir: string): Promise { + try { + const entries = await readdir(profilesDir, { withFileTypes: true }); + const now = Date.now(); + for (const entry of entries) { + if (!entry.isDirectory() || !isTemporaryDryRunProfile(entry.name)) continue; + const dir = join(profilesDir, entry.name); + try { + const info = await stat(dir); + if (now - info.mtimeMs > STALE_DRYRUN_AGE_MS) { + await rm(dir, { recursive: true, force: true }); + } + } catch { + /* Ignore transient cleanup failure. */ + } + } + } catch { + /* profilesDir may not exist yet. */ + } +} + +async function assertExistingAcpProfile( + profile: string, + env: NodeJS.ProcessEnv, +): Promise<{ dshHome: string; normalizedTarget: string; targetDir: string }> { + const normalizedTarget = normalizeDshProfile(profile); + const inspected = await inspectDshProfiles(normalizedTarget, env); + if (inspected.activeProfileIssue === "missing") { + throw new Error(`DeepSeek Harness profile "${normalizedTarget}" does not exist.`); + } + if (inspected.activeProfileIssue === "non-acp") { + throw new Error(`DeepSeek Harness profile "${normalizedTarget}" is not an ACP profile.`); + } + return { + dshHome: inspected.dshHome, + normalizedTarget, + targetDir: join(inspected.dshHome, "profiles", normalizedTarget), + }; +} + +export async function dryRunDshMigration( + command: Command, + targetProfile: string, + selectedIds: string[], + options?: { env?: NodeJS.ProcessEnv; probe?: StrictAcpProbe }, +): Promise { + const env = options?.env ?? process.env; + const { dshHome, normalizedTarget, targetDir } = await assertExistingAcpProfile(targetProfile, env); + const profilesDir = join(dshHome, "profiles"); + await cleanupStaleDryRunDirs(profilesDir); + + const probeCmd = withDshHomeCommand(command, dshHome, env); + const probe: StrictAcpProbe = + options?.probe ?? + ((profile, cmd) => probeStandardCatalog("dsh", cmd, profile, { strictStdout: true })); + + if (selectedIds.length === 0) { + const previewModels = await probe(normalizedTarget, probeCmd); + return { + ok: true, + targetProfile: normalizedTarget, + passedIds: [], + failed: [], + previewModels, + }; + } + + const data = await computeDesktopDiff(normalizedTarget, env); + const candidateMap = new Map(data.diff.providers.map((p) => [p.id, p])); + + const runStaging = async (ids: string[]): Promise => { + const stagingName = `memcode-dryrun-${randomBytes(4).toString("hex")}`; + const stagingDir = join(profilesDir, stagingName); + await mkdir(stagingDir, { recursive: true }); + try { + for (const file of STAGING_COPY_FILES) { + const src = join(targetDir, file); + if (await exists(src)) { + await copyFile(src, join(stagingDir, file)); + } + } + await applySelectedToProfileDir(command, stagingName, stagingDir, ids, data, dshHome, env); + return await probe(stagingName, probeCmd); + } finally { + await rm(stagingDir, { recursive: true, force: true }).catch(() => {}); + } + }; + + try { + const previewModels = await runStaging(selectedIds); + return { + ok: true, + targetProfile: normalizedTarget, + passedIds: [...selectedIds], + failed: [], + previewModels, + }; + } catch { + const passedIds: string[] = []; + const failed: DshProviderFailure[] = []; + for (const id of selectedIds) { + const candidate = candidateMap.get(id); + try { + await runStaging([id]); + passedIds.push(id); + } catch (error) { + failed.push({ + id, + name: candidate?.name ?? id, + reason: extractErrorMessage(error), + }); + } + } + return { + ok: false, + targetProfile: normalizedTarget, + passedIds, + failed, + previewModels: [], + }; + } +} + +export async function applyDshMigration( + command: Command, + targetProfile: string, + selectedIds: string[], + options?: { env?: NodeJS.ProcessEnv; probe?: StrictAcpProbe }, +): Promise<{ + ok: boolean; + appliedIds: string[]; + failed: DshProviderFailure[]; + models: ModelOption[]; +}> { + const env = options?.env ?? process.env; + const { dshHome, normalizedTarget, targetDir } = await assertExistingAcpProfile(targetProfile, env); + const probeCmd = withDshHomeCommand(command, dshHome, env); + const probe: StrictAcpProbe = + options?.probe ?? + ((profile, cmd) => probeStandardCatalog("dsh", cmd, profile, { strictStdout: true })); + + if (selectedIds.length === 0) { + const models = await probe(normalizedTarget, probeCmd); + return { ok: true, appliedIds: [], failed: [], models }; + } + + const data = await computeDesktopDiff(normalizedTarget, env); + const candidateMap = new Map(data.diff.providers.map((p) => [p.id, p])); + + const snapshots = new Map(); + for (const file of SNAPSHOT_FILES) { + const path = join(targetDir, file); + try { + snapshots.set(file, await readFile(path)); + } catch { + snapshots.set(file, null); + } + } + + const selectedPlugins = selectedIds + .filter((id) => id.startsWith("plugin:")) + .map((id) => id.slice("plugin:".length)); + const preExistingPlugins = new Set(); + for (const pkgName of selectedPlugins) { + if (await exists(join(targetDir, "node_modules", ...pkgName.split("/")))) { + preExistingPlugins.add(pkgName); + } + } + + let activeId = selectedIds[0] ?? "migration"; + let activeName = candidateMap.get(activeId)?.name ?? activeId; + try { + await applySelectedToProfileDir( + command, + normalizedTarget, + targetDir, + selectedIds, + data, + dshHome, + env, + (id, name) => { + activeId = id; + activeName = name; + }, + ); + const models = await probe(normalizedTarget, probeCmd); + return { + ok: true, + appliedIds: [...selectedIds], + failed: [], + models, + }; + } catch (error) { + for (const [file, content] of snapshots) { + const path = join(targetDir, file); + if (content === null) { + await rm(path, { force: true }).catch(() => {}); + } else { + await writeFile(path, content).catch(() => {}); + } + } + for (const pkgName of selectedPlugins) { + if (!preExistingPlugins.has(pkgName)) { + await rm(join(targetDir, "node_modules", ...pkgName.split("/")), { + recursive: true, + force: true, + }).catch(() => {}); + } + } + return { + ok: false, + appliedIds: [], + failed: [ + { + id: activeId, + name: activeName, + reason: extractErrorMessage(error), + }, + ], + models: [], + }; + } +} diff --git a/runtime/dsh-profiles.ts b/runtime/dsh-profiles.ts new file mode 100644 index 0000000..8b30ea1 --- /dev/null +++ b/runtime/dsh-profiles.ts @@ -0,0 +1,250 @@ +import { execFile } from "node:child_process"; +import { readdir, readFile, stat } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import type { DshProfileSummary } from "../src/shared"; +import { childEnv, exists, type Command } from "./commands"; +import { parseDshPatchYaml } from "./dsh-yaml"; + +const execFileAsync = promisify(execFile); + +export const defaultDshProfile = "acp"; + +const PROFILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; +const CONFLICTING_APP_BUNDLES = new Set([ + "@deepseek-ai/dsh-web-app", + "@deepseek-ai/dsh-sdk-app", + "@deepseek-ai/dsh-tui-app", + "@deepseek-ai/dsh-headless-app", +]); + +export function resolveDshHome(env: NodeJS.ProcessEnv = process.env): string { + return env.DSH_HOME?.trim() || join(homedir(), ".dsh"); +} + +export function normalizeDshProfile(value?: string): string { + const trimmed = value?.trim(); + if (!trimmed) return defaultDshProfile; + if (trimmed.toLowerCase() === "desktop") { + throw new Error('Profile name "desktop" is reserved for DeepSeek Harness Desktop and cannot be used as an ACP profile.'); + } + if (trimmed.toLowerCase() === "node_modules") { + throw new Error('Profile name "node_modules" is reserved and cannot be used as an ACP profile.'); + } + if (!PROFILE_NAME_RE.test(trimmed)) { + throw new Error( + `Invalid DeepSeek Harness profile name "${trimmed}". Use 1-64 characters matching [A-Za-z0-9._-], starting with a letter or digit.`, + ); + } + return trimmed; +} + +export function isTemporaryDryRunProfile(name: string): boolean { + return /^memcode-dryrun-[a-f0-9]+$/i.test(name); +} + +function patchInsertsAcp(entries: unknown[]): boolean { + for (const entry of entries) { + if (!entry || typeof entry !== "object") continue; + const insert = (entry as Record).insert; + if (!Array.isArray(insert)) continue; + for (const item of insert) { + if (item === "@deepseek-ai/dsh-acp") return true; + if (item && typeof item === "object" && (item as Record).name === "@deepseek-ai/dsh-acp") { + return true; + } + } + } + return false; +} + +async function isDirectory(path: string): Promise { + try { + return (await stat(path)).isDirectory(); + } catch { + return false; + } +} + +async function classifyProfileDir(profileDir: string, name: string): Promise { + let pkg: { dependencies?: Record; dsh?: { profile?: { bundles?: unknown[] } } } = {}; + try { + pkg = JSON.parse(await readFile(join(profileDir, "package.json"), "utf8")); + } catch { + /* Missing or unreadable package.json; treat as empty. */ + } + + let patchEntries: unknown[] = []; + try { + patchEntries = parseDshPatchYaml(await readFile(join(profileDir, "cordis.patch.yml"), "utf8")).entries; + } catch { + /* Missing or unreadable cordis.patch.yml; treat as empty. */ + } + + const bundles = Array.isArray(pkg.dsh?.profile?.bundles) + ? pkg.dsh.profile.bundles.filter((b): b is string => typeof b === "string") + : []; + const hasAcp = bundles.includes("@deepseek-ai/dsh-acp-app") || patchInsertsAcp(patchEntries); + const hasConflict = bundles.some((bundle) => CONFLICTING_APP_BUNDLES.has(bundle)); + const hasCustomConfig = + Object.keys(pkg.dependencies ?? {}).length > 0 || patchEntries.length > 0; + + return { + name, + kind: hasAcp && !hasConflict ? "acp" : "non-acp", + hasCustomConfig, + }; +} + +export interface DshProfilesInspection { + dshHome: string; + activeProfile: string; + configuredProfile?: string; + recommendedProfile?: string; + activeProfileIssue?: "missing" | "non-acp"; + acpProfiles: DshProfileSummary[]; + nonAcpProfiles: DshProfileSummary[]; + desktopProfilePresent: boolean; + needsProfileCreation: boolean; +} + +export async function inspectDshProfiles( + configuredProfile?: string, + env: NodeJS.ProcessEnv = process.env, +): Promise { + const dshHome = resolveDshHome(env); + const profilesDir = join(dshHome, "profiles"); + const desktopProfilePresent = await isDirectory(join(profilesDir, "desktop")); + + const acpProfiles: DshProfileSummary[] = []; + const nonAcpProfiles: DshProfileSummary[] = []; + + try { + const entries = await readdir(profilesDir, { withFileTypes: true }); + for (const entry of entries) { + const name = entry.name; + const lower = name.toLowerCase(); + if ( + lower === "desktop" || + lower === "node_modules" || + name.startsWith(".") || + isTemporaryDryRunProfile(name) + ) { + continue; + } + const fullPath = join(profilesDir, name); + if (!entry.isDirectory() && !(await isDirectory(fullPath))) continue; + const summary = await classifyProfileDir(fullPath, name); + if (summary.kind === "acp") acpProfiles.push(summary); + else nonAcpProfiles.push(summary); + } + } catch { + /* $DSH_HOME/profiles may not exist yet. */ + } + + acpProfiles.sort((a, b) => a.name.localeCompare(b.name)); + nonAcpProfiles.sort((a, b) => a.name.localeCompare(b.name)); + + const acpDefault = acpProfiles.find((p) => p.name === defaultDshProfile); + const customAcp = acpProfiles.find((p) => p.hasCustomConfig); + const recommendedProfile = + customAcp && (!acpDefault || !acpDefault.hasCustomConfig) + ? customAcp.name + : acpDefault?.name ?? acpProfiles[0]?.name; + + const trimmedConfigured = configuredProfile?.trim(); + if (trimmedConfigured) { + const normalized = normalizeDshProfile(trimmedConfigured); + const inAcp = acpProfiles.find((p) => p.name === normalized); + const inNonAcp = nonAcpProfiles.find((p) => p.name === normalized); + return { + dshHome, + activeProfile: normalized, + configuredProfile: normalized, + ...(recommendedProfile ? { recommendedProfile } : {}), + ...(!inAcp + ? { activeProfileIssue: inNonAcp ? ("non-acp" as const) : ("missing" as const) } + : {}), + acpProfiles, + nonAcpProfiles, + desktopProfilePresent, + needsProfileCreation: acpProfiles.length === 0, + }; + } + + if (customAcp && (!acpDefault || !acpDefault.hasCustomConfig)) { + return { + dshHome, + activeProfile: customAcp.name, + recommendedProfile: customAcp.name, + acpProfiles, + nonAcpProfiles, + desktopProfilePresent, + needsProfileCreation: false, + }; + } + + if (acpProfiles.length > 0) { + const active = acpDefault?.name ?? acpProfiles[0].name; + return { + dshHome, + activeProfile: active, + ...(recommendedProfile ? { recommendedProfile } : {}), + acpProfiles, + nonAcpProfiles, + desktopProfilePresent, + needsProfileCreation: false, + }; + } + + return { + dshHome, + activeProfile: defaultDshProfile, + acpProfiles, + nonAcpProfiles, + desktopProfilePresent, + needsProfileCreation: true, + }; +} + +export async function createDshAcpProfile( + command: Command, + name: string, + env: NodeJS.ProcessEnv = process.env, +): Promise { + const normalized = normalizeDshProfile(name); + const targetName = normalized.toLowerCase() === defaultDshProfile ? defaultDshProfile : normalized; + const dshHome = resolveDshHome(env); + const profileDir = join(dshHome, "profiles", targetName); + + if (await exists(profileDir)) { + throw new Error(`DeepSeek Harness profile "${targetName}" already exists.`); + } + + // dsh rejects --from-default-profile for shipped profile names like "acp". + const args = + targetName === defaultDshProfile + ? [...command.prefix, "--profile", defaultDshProfile, "--dump-config"] + : [...command.prefix, "--profile", targetName, "--from-default-profile", defaultDshProfile, "--dump-config"]; + + await execFileAsync(command.command, args, { + shell: false, + windowsHide: true, + timeout: 30_000, + maxBuffer: 10 * 1024 * 1024, + encoding: "utf8", + env: { + ...childEnv(), + ...command.env, + ...(env !== process.env ? env : {}), + DSH_HOME: dshHome, + }, + }); + + const inspected = await inspectDshProfiles(targetName, env); + if (!inspected.acpProfiles.some((p) => p.name === targetName)) { + throw new Error(`Created profile "${targetName}" did not produce a valid DeepSeek Harness ACP profile.`); + } + return targetName; +} diff --git a/runtime/dsh-yaml.ts b/runtime/dsh-yaml.ts new file mode 100644 index 0000000..c225e47 --- /dev/null +++ b/runtime/dsh-yaml.ts @@ -0,0 +1,595 @@ +const JS_EXPR = Symbol("dsh.jsExpression"); + +function markJsExpr(value: T): T { + if (value && typeof value === "object") { + Object.defineProperty(value, JS_EXPR, { value: true, enumerable: false, configurable: true }); + } + return value; +} + +export function hasJsTag(value: unknown): boolean { + if (!value || typeof value !== "object") return false; + if ((value as Record)[JS_EXPR] === true) return true; + if (Array.isArray(value)) return value.some((item) => hasJsTag(item)); + return Object.values(value).some((item) => hasJsTag(item)); +} + +export function hasInlineSecret(obj: unknown): boolean { + if (!obj || typeof obj !== "object") return false; + if (Array.isArray(obj)) return obj.some((item) => hasInlineSecret(item)); + for (const [key, value] of Object.entries(obj)) { + if ( + key !== "apiKeyEnv" && + /(?:api[_-]?key|secret|token|password)/i.test(key) && + typeof value === "string" && + value.trim().length > 0 + ) { + return true; + } + if (hasInlineSecret(value)) return true; + } + return false; +} + +function stripInlineComment(line: string): string { + let quote: "'" | '"' | null = null; + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (quote === "'") { + if (ch === "'") { + if (line[i + 1] === "'") i++; + else quote = null; + } + continue; + } + if (quote === '"') { + if (ch === "\\") { + i++; + continue; + } + if (ch === '"') quote = null; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + continue; + } + if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) { + return line.slice(0, i).replace(/\s+$/, ""); + } + } + return line.replace(/\s+$/, ""); +} + +function countIndent(line: string): number { + let i = 0; + while (i < line.length && line[i] === " ") i++; + return i; +} + +function findUnquotedColon(text: string): number { + let quote: "'" | '"' | null = null; + let depth = 0; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === "'") { + if (ch === "'") { + if (text[i + 1] === "'") i++; + else quote = null; + } + continue; + } + if (quote === '"') { + if (ch === "\\") { + i++; + continue; + } + if (ch === '"') quote = null; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + continue; + } + if (ch === "[" || ch === "{") depth++; + else if ((ch === "]" || ch === "}") && depth > 0) depth--; + else if (ch === ":" && depth === 0 && (i + 1 === text.length || /\s/.test(text[i + 1]))) { + return i; + } + } + return -1; +} + +function unquoteKey(raw: string): string { + const trimmed = raw.trim(); + if (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2) { + return trimmed.slice(1, -1).replace(/''/g, "'"); + } + if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) { + return unescapeDoubleQuoted(trimmed.slice(1, -1)); + } + return trimmed; +} + +function unescapeDoubleQuoted(raw: string): string { + return raw.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (_, seq: string) => { + if (seq === "n") return "\n"; + if (seq === "r") return "\r"; + if (seq === "t") return "\t"; + if (seq === "0") return "\0"; + if (seq === "\\") return "\\"; + if (seq === '"') return '"'; + if (seq === "/") return "/"; + if (seq.startsWith("u") || seq.startsWith("x")) { + return String.fromCharCode(Number.parseInt(seq.slice(1), 16)); + } + return seq; + }); +} + +function parseScalar(raw: string, ctx: { hasJsExpression: boolean }): { value: unknown; taggedJs: boolean } { + let trimmed = raw.trim(); + let taggedJs = false; + const jsMatch = /^!!js(?:\/[A-Za-z0-9_-]+)?(?:\s+([\s\S]*))?$/.exec(trimmed); + if (jsMatch) { + ctx.hasJsExpression = true; + taggedJs = true; + trimmed = (jsMatch[1] ?? "").trim(); + if (!trimmed) return { value: undefined, taggedJs: true }; + } + if (trimmed === "" || trimmed === "null" || trimmed === "~") return { value: null, taggedJs }; + if (trimmed === "true") return { value: true, taggedJs }; + if (trimmed === "false") return { value: false, taggedJs }; + if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(trimmed)) { + return { value: Number(trimmed), taggedJs }; + } + if (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2) { + return { value: trimmed.slice(1, -1).replace(/''/g, "'"), taggedJs }; + } + if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) { + return { value: unescapeDoubleQuoted(trimmed.slice(1, -1)), taggedJs }; + } + return { value: trimmed, taggedJs }; +} + +function splitFlowItems(inner: string): string[] { + const items: string[] = []; + let start = 0; + let quote: "'" | '"' | null = null; + let depth = 0; + for (let i = 0; i < inner.length; i++) { + const ch = inner[i]; + if (quote === "'") { + if (ch === "'") { + if (inner[i + 1] === "'") i++; + else quote = null; + } + continue; + } + if (quote === '"') { + if (ch === "\\") { + i++; + continue; + } + if (ch === '"') quote = null; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + continue; + } + if (ch === "[" || ch === "{") depth++; + else if ((ch === "]" || ch === "}") && depth > 0) depth--; + else if (ch === "," && depth === 0) { + items.push(inner.slice(start, i)); + start = i + 1; + } + } + const tail = inner.slice(start); + if (tail.trim()) items.push(tail); + return items; +} + +function parseFlow(text: string, ctx: { hasJsExpression: boolean }): { value: unknown; taggedJs: boolean } { + let trimmed = text.trim(); + let taggedJs = false; + const jsMatch = /^!!js(?:\/[A-Za-z0-9_-]+)?(?:\s+([\s\S]*))?$/.exec(trimmed); + if (jsMatch) { + ctx.hasJsExpression = true; + taggedJs = true; + trimmed = (jsMatch[1] ?? "").trim(); + } + if (trimmed.startsWith("[") && trimmed.endsWith("]")) { + const inner = trimmed.slice(1, -1).trim(); + if (!inner) { + const arr: unknown[] = []; + return { value: taggedJs ? markJsExpr(arr) : arr, taggedJs }; + } + let anyJs = taggedJs; + const arr = splitFlowItems(inner).map((item) => { + const res = parseFlow(item, ctx); + if (res.taggedJs) anyJs = true; + return res.value; + }); + return { value: anyJs ? markJsExpr(arr) : arr, taggedJs: anyJs }; + } + if (trimmed.startsWith("{") && trimmed.endsWith("}")) { + const inner = trimmed.slice(1, -1).trim(); + const obj: Record = {}; + if (!inner) return { value: taggedJs ? markJsExpr(obj) : obj, taggedJs }; + let anyJs = taggedJs; + for (const part of splitFlowItems(inner)) { + const colon = findUnquotedColon(part); + if (colon === -1) continue; + const key = unquoteKey(part.slice(0, colon)); + const res = parseFlow(part.slice(colon + 1), ctx); + if (res.taggedJs) anyJs = true; + obj[key] = res.value; + } + return { value: anyJs ? markJsExpr(obj) : obj, taggedJs: anyJs }; + } + return parseScalar(trimmed, ctx); +} + +function isFlowComplete(text: string): boolean { + let quote: "'" | '"' | null = null; + let depth = 0; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === "'") { + if (ch === "'") { + if (text[i + 1] === "'") i++; + else quote = null; + } + continue; + } + if (quote === '"') { + if (ch === "\\") { + i++; + continue; + } + if (ch === '"') quote = null; + continue; + } + if (ch === "'" || ch === '"') quote = ch; + else if (ch === "[" || ch === "{") depth++; + else if ((ch === "]" || ch === "}") && depth > 0) depth--; + } + return quote === null && depth === 0; +} + +class YamlParser { + readonly lines: string[]; + index = 0; + hasJsExpression = false; + + constructor(text: string) { + this.lines = text.replace(/\r\n?/g, "\n").split("\n"); + } + + private skipIgnorable(): void { + while (this.index < this.lines.length) { + const cleaned = stripInlineComment(this.lines[this.index]); + if (cleaned.trim() === "") this.index++; + else break; + } + } + + private peekContent(): { indent: number; text: string } | null { + this.skipIgnorable(); + if (this.index >= this.lines.length) return null; + const cleaned = stripInlineComment(this.lines[this.index]); + return { indent: countIndent(cleaned), text: cleaned.trimStart() }; + } + + private parseBlockScalar(header: string, parentIndent: number): string { + const style = header[0] as "|" | ">"; + const rest = header.slice(1).trim(); + const chomp = rest.includes("-") ? "-" : rest.includes("+") ? "+" : ""; + const indentDigit = /\d+/.exec(rest)?.[0]; + let contentIndent = indentDigit ? parentIndent + Number.parseInt(indentDigit, 10) : -1; + const rawLines: string[] = []; + + while (this.index < this.lines.length) { + const line = this.lines[this.index]; + const indent = countIndent(line); + if (line.trim() === "") { + rawLines.push(""); + this.index++; + continue; + } + if (contentIndent === -1) { + if (indent <= parentIndent) break; + contentIndent = indent; + } else if (indent < contentIndent) { + break; + } + rawLines.push(line.slice(contentIndent)); + this.index++; + } + + let trailingEmpty = 0; + while (trailingEmpty < rawLines.length && rawLines[rawLines.length - 1 - trailingEmpty] === "") { + trailingEmpty++; + } + const bodyLines = chomp === "+" ? rawLines : rawLines.slice(0, rawLines.length - trailingEmpty); + + let body: string; + if (style === "|") { + body = bodyLines.join("\n"); + } else { + const parts: string[] = []; + for (let i = 0; i < bodyLines.length; i++) { + const current = bodyLines[i]; + if (i === 0) { + parts.push(current); + continue; + } + const prev = bodyLines[i - 1]; + if (current === "") { + parts.push("\n"); + } else if (prev === "") { + parts.push(current); + } else { + parts.push(" " + current); + } + } + body = parts.join(""); + } + + if (chomp === "-" || bodyLines.length === 0) return body; + return body + "\n"; + } + + private collectFlow(firstPart: string): string { + let acc = firstPart; + while (!isFlowComplete(acc) && this.index < this.lines.length) { + const next = stripInlineComment(this.lines[this.index++]).trim(); + if (next) acc += " " + next; + } + return acc; + } + + private parseValue(rawVal: string, parentIndent: number): { value: unknown; taggedJs: boolean } { + const val = rawVal.trim(); + const jsOnly = /^!!js(?:\/[A-Za-z0-9_-]+)?$/.exec(val); + if (jsOnly) { + this.hasJsExpression = true; + const next = this.peekContent(); + if (next && next.indent > parentIndent) { + const parsed = this.parseBlock(next.indent); + return { value: markJsExpr(parsed.value ?? {}), taggedJs: true }; + } + return { value: undefined, taggedJs: true }; + } + const jsPrefixed = /^!!js(?:\/[A-Za-z0-9_-]+)?\s+([\s\S]+)$/.exec(val); + if (jsPrefixed) { + this.hasJsExpression = true; + const inner = jsPrefixed[1].trim(); + if (/^[|>][+-]?\d*$/.test(inner)) { + return { value: this.parseBlockScalar(inner, parentIndent), taggedJs: true }; + } + if (inner.startsWith("[") || inner.startsWith("{")) { + const res = parseFlow(this.collectFlow(inner), this); + return { value: markJsExpr(res.value), taggedJs: true }; + } + return { value: parseScalar(val, this).value, taggedJs: true }; + } + if (/^[|>][+-]?\d*$/.test(val)) { + return { value: this.parseBlockScalar(val, parentIndent), taggedJs: false }; + } + if (val === "") { + const next = this.peekContent(); + const isSeq = next && (next.text === "-" || next.text.startsWith("- ")); + if (next && (next.indent > parentIndent || (next.indent === parentIndent && isSeq))) { + return this.parseBlock(next.indent); + } + return { value: null, taggedJs: false }; + } + if (val.startsWith("[") || val.startsWith("{")) { + return parseFlow(this.collectFlow(val), this); + } + return parseScalar(val, this); + } + + private parseMapping(minIndent: number, seed?: { key: string; rawVal: string; lineIndent: number }): { value: Record; taggedJs: boolean } { + const obj: Record = {}; + let anyJs = false; + if (seed) { + const res = this.parseValue(seed.rawVal, seed.lineIndent); + if (res.taggedJs) anyJs = true; + obj[seed.key] = res.value; + } + + while (true) { + const next = this.peekContent(); + if (!next || next.indent < minIndent || next.indent !== minIndent) break; + if (next.text === "-" || next.text.startsWith("- ")) break; + const colon = findUnquotedColon(next.text); + if (colon === -1) break; + this.index++; + const key = unquoteKey(next.text.slice(0, colon)); + const rawVal = next.text.slice(colon + 1); + const res = this.parseValue(rawVal, next.indent); + if (res.taggedJs) anyJs = true; + obj[key] = res.value; + } + return { value: anyJs ? markJsExpr(obj) : obj, taggedJs: anyJs }; + } + + private parseSequence(seqIndent: number): { value: unknown[]; taggedJs: boolean } { + const arr: unknown[] = []; + let anyJs = false; + while (true) { + const next = this.peekContent(); + if (!next || next.indent !== seqIndent) break; + if (next.text !== "-" && !next.text.startsWith("- ")) break; + const lineIdx = this.index++; + const afterDash = next.text.slice(1).trimStart(); + if (!afterDash) { + const nested = this.peekContent(); + if (nested && nested.indent > seqIndent) { + const res = this.parseBlock(nested.indent); + if (res.taggedJs) anyJs = true; + arr.push(res.value); + } else { + arr.push(null); + } + continue; + } + + const dashCol = countIndent(this.lines[lineIdx]); + const itemIndent = dashCol + (next.text.length - afterDash.length); + const colon = findUnquotedColon(afterDash); + if (colon !== -1 && !afterDash.startsWith("{") && !afterDash.startsWith("[")) { + const key = unquoteKey(afterDash.slice(0, colon)); + const rawVal = afterDash.slice(colon + 1); + const res = this.parseMapping(itemIndent, { key, rawVal, lineIndent: itemIndent }); + if (res.taggedJs) anyJs = true; + arr.push(res.value); + } else if (afterDash === "-" || afterDash.startsWith("- ")) { + // Nested inline sequence `- - a` + this.lines[lineIdx] = " ".repeat(itemIndent) + afterDash; + this.index = lineIdx; + const res = this.parseSequence(itemIndent); + if (res.taggedJs) anyJs = true; + arr.push(res.value); + } else { + const res = this.parseValue(afterDash, itemIndent); + if (res.taggedJs) anyJs = true; + arr.push(res.value); + } + } + return { value: anyJs ? markJsExpr(arr) : arr, taggedJs: anyJs }; + } + + parseBlock(expectedIndent?: number): { value: unknown; taggedJs: boolean } { + const next = this.peekContent(); + if (!next) return { value: [], taggedJs: false }; + const indent = expectedIndent ?? next.indent; + if (next.text === "---") { + this.index++; + return this.parseBlock(); + } + if (next.text === "-" || next.text.startsWith("- ")) { + return this.parseSequence(indent); + } + if (next.text.startsWith("[") || next.text.startsWith("{")) { + this.index++; + return parseFlow(this.collectFlow(next.text), this); + } + if (findUnquotedColon(next.text) !== -1) { + return this.parseMapping(indent); + } + this.index++; + return parseScalar(next.text, this); + } +} + +export function parseDshPatchYaml(text: string): { entries: any[]; hasJsExpression: boolean } { + const parser = new YamlParser(text); + const parsed = parser.parseBlock(); + const entries = Array.isArray(parsed.value) ? parsed.value : []; + return { entries, hasJsExpression: parser.hasJsExpression }; +} + +function needsQuotes(text: string): boolean { + if (text === "") return true; + if (/^\s|\s$/.test(text)) return true; + if (text === "true" || text === "false" || text === "null" || text === "~") return true; + if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(text)) return true; + if (/^[-?:,\[\]{}#&*!|>'"%@`]/.test(text)) return true; + if (/:(?:\s|$)/.test(text) || /\s#/.test(text)) return true; + return false; +} + +function formatKey(key: string): string { + if (/^[A-Za-z0-9._-]+$/.test(key) && key !== "true" && key !== "false" && key !== "null") { + return key; + } + return formatString(key); +} + +function formatString(value: string): string { + if (/[\x00-\x1f\x7f]/.test(value)) { + return JSON.stringify(value); + } + if (!needsQuotes(value)) return value; + return `'${value.replace(/'/g, "''")}'`; +} + +function formatScalar(value: unknown): string { + if (value === null || value === undefined) return "null"; + if (typeof value === "boolean" || typeof value === "number") return String(value); + return formatString(String(value)); +} + +function isPlainObject(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function dumpValue(value: unknown, indent: number): string[] { + const pad = " ".repeat(indent); + if (Array.isArray(value)) { + if (value.length === 0) return [`${pad}[]`]; + const lines: string[] = []; + for (const item of value) { + if (isPlainObject(item)) { + const entries = Object.entries(item); + if (entries.length === 0) { + lines.push(`${pad}- {}`); + continue; + } + const [firstKey, firstVal] = entries[0]; + if ((isPlainObject(firstVal) && Object.keys(firstVal).length > 0) || (Array.isArray(firstVal) && firstVal.length > 0)) { + lines.push(`${pad}- ${formatKey(firstKey)}:`); + lines.push(...dumpValue(firstVal, indent + 4)); + } else { + lines.push(`${pad}- ${formatKey(firstKey)}: ${formatInlineEmptyOrScalar(firstVal)}`); + } + for (const [k, v] of entries.slice(1)) { + lines.push(...dumpEntry(k, v, indent + 2)); + } + } else if (Array.isArray(item)) { + if (item.length === 0) lines.push(`${pad}- []`); + else { + lines.push(`${pad}-`); + lines.push(...dumpValue(item, indent + 2)); + } + } else { + lines.push(`${pad}- ${formatScalar(item)}`); + } + } + return lines; + } + if (isPlainObject(value)) { + const entries = Object.entries(value); + if (entries.length === 0) return [`${pad}{}`]; + const lines: string[] = []; + for (const [k, v] of entries) { + lines.push(...dumpEntry(k, v, indent)); + } + return lines; + } + return [`${pad}${formatScalar(value)}`]; +} + +function formatInlineEmptyOrScalar(value: unknown): string { + if (Array.isArray(value)) return "[]"; + if (isPlainObject(value)) return "{}"; + return formatScalar(value); +} + +function dumpEntry(key: string, value: unknown, indent: number): string[] { + const pad = " ".repeat(indent); + const k = formatKey(key); + if ((isPlainObject(value) && Object.keys(value).length > 0) || (Array.isArray(value) && value.length > 0)) { + return [`${pad}${k}:`, ...dumpValue(value, indent + 2)]; + } + return [`${pad}${k}: ${formatInlineEmptyOrScalar(value)}`]; +} + +export function stringifyDshPatchYaml(entries: unknown[]): string { + if (!Array.isArray(entries) || entries.length === 0) return "[]\n"; + return dumpValue(entries, 0).join("\n") + "\n"; +} diff --git a/runtime/local.ts b/runtime/local.ts index 54d641c..681d5e7 100644 --- a/runtime/local.ts +++ b/runtime/local.ts @@ -100,7 +100,9 @@ export class LocalStore { return pending; } async runtime(): Promise { - const harnesses = await discoverHarnesses(); + const harnesses = await discoverHarnesses(false, undefined, { + dshProfile: this.state.settings.dshProfile, + }); return { appVersion, harnesses, diff --git a/runtime/mac-commands.ts b/runtime/mac-commands.ts index 72aef14..3625ccb 100644 --- a/runtime/mac-commands.ts +++ b/runtime/mac-commands.ts @@ -74,7 +74,9 @@ export async function findMacDesktopApp( ? ["Codex.app", "ChatGPT.app"] : name === "cursor" ? ["Cursor.app"] - : []; + : name === "dsh" + ? ["DeepSeek Harness.app"] + : []; for (const root of appRoots(options)) for (const app of names) { const path = join(root, app); diff --git a/runtime/review-agent.ts b/runtime/review-agent.ts index 1f1ef74..430c048 100644 --- a/runtime/review-agent.ts +++ b/runtime/review-agent.ts @@ -31,6 +31,7 @@ import { probeClaudeCatalog } from "./agents/claude"; import { selectClaudeModel } from "./agents/claude-models"; import { readonlyACPTransport, type StandardHarness } from "./agents/standard-acp"; import { selectStandardACPModel, standardModelMeasurement } from "./agents/acp-models"; +import { inspectDshProfiles } from "./dsh-profiles"; type Json = Record; export interface ReadonlyReviewQuestion { @@ -65,6 +66,7 @@ export interface ReviewAgentOptions { policy?: string; modelPinned?: boolean; localModel?: boolean; + dshProfile?: string; commandFor?: typeof findCommand; /** Test transport injection; product callers use the installed approved CLI. */ spawn?: typeof spawn; @@ -735,7 +737,11 @@ async function standardQuestion( harness: StandardHarness, command: Command, capsule: string, prompt: string, requested: string, input: ReadonlyQuestionHooks, options: ReviewAgentOptions, ): Promise { - const transport = await readonlyACPTransport(harness, capsule); + const transport = await readonlyACPTransport( + harness, + capsule, + harness === "dsh" ? options.dshProfile : undefined, + ); const rpc = new ReviewRpc(command, transport.args, capsule, options, true); const source = await readFile(join(capsule, "review-context.json"), "utf8"); let sessionId = "", answer = ""; @@ -1233,8 +1239,23 @@ export async function askInCapsule( : "Read review-context.json"; const prompt = question.prompt(readInstruction); try { - if (harness === "copilot" || harness === "dsh") - return await standardQuestion(harness, command, capsule, prompt, requested, input, { ...options, modelPinned: !!explicit }); + if (harness === "copilot" || harness === "dsh") { + const dshProfile = + harness === "dsh" + ? options.dshProfile ?? + ( + await inspectDshProfiles(settings?.dshProfile).catch( + () => undefined, + ) + )?.activeProfile ?? + settings?.dshProfile + : undefined; + return await standardQuestion(harness, command, capsule, prompt, requested, input, { + ...options, + modelPinned: !!explicit, + ...(dshProfile !== undefined ? { dshProfile } : {}), + }); + } return await { codex: codexQuestion, claude: claudeQuestion, diff --git a/runtime/worker-connections.ts b/runtime/worker-connections.ts index 96e97b0..203c82f 100644 --- a/runtime/worker-connections.ts +++ b/runtime/worker-connections.ts @@ -14,6 +14,7 @@ import { probeStandardCatalog, type StandardHarness, } from "./agents/standard-acp"; +import { inspectDshProfiles } from "./dsh-profiles"; import type { NativeHost } from "./host"; import { harnessNames, @@ -68,20 +69,53 @@ type WorkerReadiness = Pick< async function probeStandardConnection( harness: StandardHarness, command: Command, -): Promise { + dshProfile?: string, +): Promise<{ readiness: WorkerReadiness; note?: string }> { + let profile: string | undefined; + if (harness === "dsh") { + let info; + try { + info = await inspectDshProfiles(dshProfile); + } catch { + return { + readiness: { auth: "unknown", connectionIssue: "unavailable" }, + note: "The configured DeepSeek Harness profile name is invalid. Choose or create an ACP profile in DeepSeek Harness setup.", + }; + } + profile = info.activeProfile; + if (info.activeProfileIssue === "non-acp") { + return { + readiness: { auth: "unknown", connectionIssue: "unavailable" }, + note: `DeepSeek Harness profile "${profile}" is not an ACP profile. Choose or create an ACP profile in DeepSeek Harness setup.`, + }; + } + if (info.activeProfileIssue === "missing" && profile !== "acp") { + return { + readiness: { auth: "unknown", connectionIssue: "unavailable" }, + note: `DeepSeek Harness profile "${profile}" does not exist. Choose or create an ACP profile in DeepSeek Harness setup.`, + }; + } + } try { - const models = await probeStandardCatalog(harness, command); + const models = await probeStandardCatalog(harness, command, profile); // The CLI confirms provider access at the first model call. - if (models.length) return { auth: "provider-managed" }; + if (models.length) return { readiness: { auth: "provider-managed" } }; } catch (error) { if ( harness === "dsh" && + profile === "acp" && error instanceof Error && /profile ["']acp["'] does not exist/i.test(clean(error.message)) ) - return { auth: "unknown", connectionIssue: "unsupported-cli" }; + return { readiness: { auth: "unknown", connectionIssue: "unsupported-cli" } }; + if (harness === "dsh" && profile && profile !== "acp") { + return { + readiness: { auth: "unknown", connectionIssue: "unavailable" }, + note: `MemCode couldn’t read the model list from DeepSeek Harness profile "${profile}". Check the profile setup and providers, then try again.`, + }; + } } - return { auth: "unknown", connectionIssue: "unavailable" }; + return { readiness: { auth: "unknown", connectionIssue: "unavailable" } }; } function connectionIssueNote( @@ -232,11 +266,18 @@ export function registerConnections( loginCommand: loginCommands[harness], }; let auth: WorkerReadiness; + let customIssueNote: string | undefined; if (harness === "codex" && state().settings.localModel) auth = { auth: "local", accountLabel: "Configured local model" }; - else if (harness === "copilot" || harness === "dsh") - auth = await probeStandardConnection(harness, command); - else { + else if (harness === "copilot" || harness === "dsh") { + const probed = await probeStandardConnection( + harness, + command, + harness === "dsh" ? state().settings.dshProfile : undefined, + ); + auth = probed.readiness; + customIssueNote = probed.note; + } else { const args = harness === "codex" ? ["login", "status"] @@ -294,7 +335,7 @@ export function registerConnections( ...auth, approvedAt: approved ? receipt?.approvedAt : undefined, note: connectionIssue - ? connectionIssueNote(harness, connectionIssue) + ? (customIssueNote ?? connectionIssueNote(harness, connectionIssue)) : connected ? connectedNote(authStatus) : approved diff --git a/runtime/workers.ts b/runtime/workers.ts index 26cb089..b0d4c07 100644 --- a/runtime/workers.ts +++ b/runtime/workers.ts @@ -26,6 +26,7 @@ import type { Command } from "./local"; import { commandIdentity } from "./commands"; import type { MemtraceEngine } from "./memtrace"; import { discoverHarnesses } from "./catalog"; +import { inspectDshProfiles } from "./dsh-profiles"; import { assignedHarness, planRoute } from "./router"; import { readRoutingCalibration, readRoutingLanguage } from "./story-route"; import { assertWorkerConnected, connectedRuntimes } from "./worker-connections"; @@ -104,6 +105,7 @@ export function harnessArgs( briefPath = ".memcode/brief.md", contextConfig?: string, toolArgs: string[] = [], + dshProfile?: string, ): { args: string[]; stdin?: string } { if (id === "codex") return { @@ -156,7 +158,7 @@ export function harnessArgs( ], }; if (id === "copilot") return { args: ["--acp", "--stdio"] }; - if (id === "dsh") return { args: ["--profile", "acp"] }; + if (id === "dsh") return { args: ["--profile", dshProfile?.trim() || "acp"] }; throw new Error("Unsupported worker harness."); } @@ -237,7 +239,10 @@ export class WorkerManager { name: string, ) => Promise = findCommand, private readonly catalog: (only?: WorkItem["harness"]) => Promise = - (only) => discoverHarnesses(false, only), + (only) => + discoverHarnesses(false, only, { + dshProfile: this.state().settings.dshProfile, + }), private readonly browsers?: AgentBrowserManager, private readonly terminals?: TerminalManager, private readonly sessionFactory: typeof startHarnessSession = startHarnessSession, @@ -1114,6 +1119,14 @@ export class WorkerManager { .join("\n\n"); const briefPath = join(workerRoot, "brief.md").replaceAll("\\", "/"); await writeFile(join(workspace, briefPath), prompt, "utf8"); + const dshProfile = + task.harness === "dsh" + ? ( + await inspectDshProfiles(this.state().settings.dshProfile).catch( + () => undefined, + ) + )?.activeProfile ?? this.state().settings.dshProfile + : undefined; const invocation = harnessArgs( task.harness, workspace, @@ -1124,6 +1137,7 @@ export class WorkerManager { briefPath, contextConfig, toolProfile.args, + dshProfile, ); continuing(); closeArtifacts = watchArtifacts( @@ -1244,6 +1258,7 @@ export class WorkerManager { effort: task.route.effort, calibratedModel: task.route.selection?.calibratedModel, localModel: task.route.localModel, + ...(launchedHarness === "dsh" ? { dshProfile } : {}), permissionMode, prompt, briefPath, diff --git a/src/components/Dialogs.tsx b/src/components/Dialogs.tsx index f34d7ba..3e9dc37 100644 --- a/src/components/Dialogs.tsx +++ b/src/components/Dialogs.tsx @@ -676,6 +676,15 @@ export function SettingsDialog({ const models = runtime.harnesses.find((harness) => harness.id === draft.defaultHarness) ?.models ?? []; + const dshRuntime = runtime.harnesses.find((harness) => harness.id === "dsh"); + const dshProfiles = dshRuntime?.profiles?.length + ? dshRuntime.profiles + : [draft.dshProfile || dshRuntime?.activeProfile || "acp"]; + const selectedDshProfile = + draft.dshProfile || dshRuntime?.activeProfile || dshProfiles[0] || "acp"; + const dshProfileOptions = dshProfiles.includes(selectedDshProfile) + ? dshProfiles + : [selectedDshProfile, ...dshProfiles]; const previousSettings = useRef(settings); useEffect(() => { const previous = previousSettings.current; @@ -888,6 +897,29 @@ export function SettingsDialog({ )} Automatic stories use this override. Story assignments take precedence. + {(draft.defaultHarness === "dsh" || + (dshRuntime?.available && + (dshRuntime.profiles?.length ?? 0) > 0)) && ( + + )} )} diff --git a/src/components/DshSetupFlow.tsx b/src/components/DshSetupFlow.tsx index b1b62ba..40466e0 100644 --- a/src/components/DshSetupFlow.tsx +++ b/src/components/DshSetupFlow.tsx @@ -52,6 +52,12 @@ export function DshSetupFlow({ const [profileName, setProfileName] = useState("acp"); const [selectedIds, setSelectedIds] = useState([]); const [dryRunResult, setDryRunResult] = useState(null); + // Which step produced dryRunResult, and whether a failed import was rolled back. + const [failure, setFailure] = useState<{ phase: "dry-run" | "import"; restored: boolean }>({ + phase: "dry-run", + restored: true, + }); + const [diffError, setDiffError] = useState(""); const [migrationResult, setMigrationResult] = useState<{ appliedCount: number; modelCount: number; @@ -64,6 +70,7 @@ export function DshSetupFlow({ nextStatus.cliInstalled && !nextStatus.needsProfileCreation && !nextStatus.activeProfileIssue; + setDiffError(""); if (!profileReady || !nextStatus.desktopProfilePresent) { setDiff(null); setSelectedIds([]); @@ -79,8 +86,10 @@ export function DshSetupFlow({ .map((provider) => provider.id), ); } catch (err) { - setError((err as Error).message); + // A failed comparison says nothing about whether providers are in sync. + setDiffError((err as Error).message || "The comparison could not be completed."); setDiff(null); + setSelectedIds([]); } finally { setDiffLoading(false); } @@ -113,7 +122,9 @@ export function DshSetupFlow({ status.cliInstalled && !status.needsProfileCreation && !status.activeProfileIssue; - const hasPendingProviders = !!diff && diff.providers.length > 0; + const hasPendingProviders = + (!!diff && diff.providers.length > 0) || + (!!diffError && status?.desktopProfilePresent === true); const ready = !loading && !diffLoading && @@ -200,12 +211,14 @@ export function DshSetupFlow({ setBusyAction("migrate"); setError(""); setDryRunResult(null); + setFailure({ phase: "dry-run", restored: true }); try { const dryRun = await window.memcode.dryRunDshMigration({ targetProfile: status.activeProfile, selectedIds: ids, }); - if (!dryRun.ok || dryRun.failed.length > 0) { + // Import only what the combined dry-run verified, through its plan. + if (!dryRun.ok || dryRun.failed.length > 0 || !dryRun.planId) { const failedIds = new Set(dryRun.failed.map((item) => item.id)); setDryRunResult(dryRun); if (failedIds.size > 0) { @@ -213,14 +226,13 @@ export function DshSetupFlow({ } return; } - const applied = await window.memcode.applyDshMigration({ - targetProfile: status.activeProfile, - selectedIds: dryRun.passedIds.length > 0 ? dryRun.passedIds : ids, - }); + setBusyAction("import"); + const applied = await window.memcode.applyDshMigration({ planId: dryRun.planId }); onRuntime?.(applied.runtime); await onRefreshStatus(); if (!applied.ok || applied.failed.length > 0) { const failedIds = new Set(applied.failed.map((item) => item.id)); + setFailure({ phase: "import", restored: applied.restored !== false }); setDryRunResult({ ok: false, targetProfile: applied.targetProfile, @@ -617,12 +629,13 @@ export function DshSetupFlow({ )} - {busyAction === "migrate" && ( + {(busyAction === "migrate" || busyAction === "import") && (
- Testing selected providers in an isolated dry-run… Your - active profile is unchanged. + {busyAction === "migrate" + ? "Testing selected providers in an isolated dry-run… Your active profile is unchanged." + : `Importing the verified providers into “${diff.targetProfile}”…`}
)} @@ -636,8 +649,11 @@ export function DshSetupFlow({
- Dry-run failed — “{dryRunResult.targetProfile}” was not - modified + {failure.phase === "dry-run" + ? `Dry-run failed — “${dryRunResult.targetProfile}” was not modified` + : failure.restored + ? `Import failed — “${dryRunResult.targetProfile}” was restored to its previous state` + : `Import failed — “${dryRunResult.targetProfile}” may need manual recovery`} {dryRunResult.failed.length > 0 ? (
    @@ -681,7 +697,7 @@ export function DshSetupFlow({ disabled={selectedIds.length === 0 || !!busyAction} onClick={() => void runMigration(selectedIds)} > - {busyAction === "migrate" ? : null} + {busyAction === "migrate" || busyAction === "import" ? : null} Test & Import Selected )} @@ -689,6 +705,44 @@ export function DshSetupFlow({ )} + ) : diffError ? ( +
    + +
    + Desktop providers could not be compared +

    {diffError}

    + {skippedSync ? ( + + Skipped Desktop import. Using the current models in{" "} + {status.activeProfile}. + + ) : null} +
    + + {!skippedSync && ( + + )} +
    +
    +
    ) : (
    diff --git a/src/components/WorkerConnections.tsx b/src/components/WorkerConnections.tsx index 7271076..abcd020 100644 --- a/src/components/WorkerConnections.tsx +++ b/src/components/WorkerConnections.tsx @@ -136,15 +136,20 @@ export function WorkerConnections({ useEffect(() => { if (!selectedHarness) return; const frame = requestAnimationFrame(() => - document - .querySelector( + ( + document.querySelector( selectedHarness === "dsh" ? ".dsh-setup-flow button:not([disabled]), .dsh-setup-flow input:not([disabled]), .connection-approval input" : readyToApprove ? ".connection-approval input" : ".connection-sign-in button", + ) ?? + // While setup is still loading only a spinner renders; keep keyboard + // focus inside the modal on its always-present Close button. + document.querySelector( + 'button[aria-label="Close connection approval"]', ) - ?.focus(), + )?.focus(), ); return () => cancelAnimationFrame(frame); }, [selectedHarness, readyToApprove]); diff --git a/src/shared.ts b/src/shared.ts index a4a70e5..baa149c 100644 --- a/src/shared.ts +++ b/src/shared.ts @@ -134,6 +134,8 @@ export interface DshDryRunResult { failed: DshProviderFailure[]; previewModels: ModelOption[]; error?: string; + /** Present when the dry-run passed; import accepts only this verified plan. */ + planId?: string; } export interface DshApplyMigrationResult { ok: boolean; @@ -143,6 +145,8 @@ export interface DshApplyMigrationResult { models: ModelOption[]; runtime: RuntimeInfo; error?: string; + /** False when a failed import could not be fully rolled back. */ + restored?: boolean; } export interface RouteDecision { policyVersion: "memcode-envelope-v2" | "memcode-evidence-v3" | "memcode-evidence-v4"; @@ -664,10 +668,7 @@ export interface MemCodeAPI extends CodeReviewAPI { targetProfile?: string; selectedIds: string[]; }): Promise; - applyDshMigration(input: { - targetProfile?: string; - selectedIds: string[]; - }): Promise; + applyDshMigration(input: { planId: string }): Promise; installationStatus(): Promise<{ state: string; needsInstall: boolean; diff --git a/tests/dsh-migration.test.ts b/tests/dsh-migration.test.ts index 5b1db33..91a00b0 100644 --- a/tests/dsh-migration.test.ts +++ b/tests/dsh-migration.test.ts @@ -2,13 +2,15 @@ import test from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readdir, readFile, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { applyDshMigration, diffDshDesktopModels, dryRunDshMigration, + type DshMigrationPlan, } from "../runtime/dsh-migration"; import { + hasExplicitJsTag, hasInlineSecret, hasJsTag, parseDshPatchYaml, @@ -92,6 +94,91 @@ async function writePluginPkg( ); } +/** + * A dsh stand-in that behaves like the real CLI where migration depends on it: + * `plugin` forwards install/add to the profile, a profile's third-party bundles + * only load from its own node_modules, and catalog values are the JSON + * `[provider, model]` tuples dsh's ACP model control advertises. + */ +async function writeMockDsh(dshHome: string): Promise<{ command: string; prefix: string[] }> { + const script = join(dshHome, "mock-dsh.mjs"); + await writeFile( + script, + `import { createInterface } from "node:readline"; +import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +const argv = process.argv.slice(2); +const home = process.env.DSH_HOME; +const profile = argv[argv.indexOf("--profile") + 1]; +const pDir = join(home, "profiles", profile); +const readPkg = () => JSON.parse(readFileSync(join(pDir, "package.json"), "utf8")); +if (argv[0] === "plugin") { + const sub = argv[3]; + appendFileSync(join(home, "calls.log"), profile + " " + argv.slice(3).join(" ") + "\\n"); + if (sub === "install") { + for (const dep of Object.keys(readPkg().dependencies || {})) mkdirSync(join(pDir, "node_modules", dep), { recursive: true }); + process.exit(0); + } + const spec = argv[argv.length - 1]; + const pkgName = spec.split("@")[0]; + if (process.env.MOCK_FAIL_ADD === pkgName) { process.stderr.write("add rejected"); process.exit(1); } + const pkg = readPkg(); + pkg.dependencies = { ...(pkg.dependencies || {}), [pkgName]: "1.0.0" }; + writeFileSync(join(pDir, "package.json"), JSON.stringify(pkg, null, 2)); + writeFileSync(join(pDir, "pnpm-lock.yaml"), "lockfileVersion: '9.0'\\nupdated: true\\n"); + writeFileSync(join(pDir, "pnpm-workspace.yaml"), "changed: true\\n"); + for (const dep of Object.keys(pkg.dependencies)) mkdirSync(join(pDir, "node_modules", dep), { recursive: true }); + process.exit(0); +} +const deps = Object.keys(readPkg().dependencies || {}); +for (const dep of deps) if (!existsSync(join(pDir, "node_modules", dep))) { + process.stderr.write("Cannot find bundle " + dep); + process.exit(3); +} +if (deps.includes("dsh-bad-noise")) process.stdout.write("NOISY_STDOUT_BEFORE_ACP\\n"); +const tuples = [["deepseek-official", "deepseek-v4-flash"]]; +let provider = null; +const patch = join(pDir, "cordis.patch.yml"); +for (const line of existsSync(patch) ? readFileSync(patch, "utf8").split(/\\r?\\n/) : []) { + const key = /^ {6}([A-Za-z0-9_-]+):\\s*$/.exec(line); + if (key) { provider = key[1]; continue; } + const model = /^ {10}- id: (\\S+)/.exec(line); + if (model && provider && !provider.startsWith("ghost")) tuples.push([provider, model[1]]); + if (/^ {0,4}\\S/.test(line)) provider = null; +} +for (const dep of deps) if (dep !== "dsh-silent") tuples.push([dep + "-provider", "model"]); +const send = (x) => process.stdout.write(JSON.stringify(x) + "\\n"); +createInterface({ input: process.stdin }).on("close", () => process.exit(0)).on("line", (line) => { + const msg = JSON.parse(line); + if (msg.method === "initialize") return send({ jsonrpc: "2.0", id: msg.id, result: { agentCapabilities: {} } }); + if (msg.method === "session/close") return send({ jsonrpc: "2.0", id: msg.id, result: {} }); + if (msg.method === "session/new") { + const groups = [...new Set(tuples.map(([p]) => p))].map((group) => ({ + group, + options: tuples.filter(([p]) => p === group).map((tuple) => ({ value: JSON.stringify(tuple), name: tuple[1] })), + })); + return send({ + jsonrpc: "2.0", + id: msg.id, + result: { + sessionId: "s1", + configOptions: [{ id: "model", category: "model", currentValue: JSON.stringify(tuples[0]), options: groups }], + }, + }); + } +}); +`, + ); + return { command: process.execPath, prefix: [script] }; +} + +const tuple = (provider: string, model: string) => JSON.stringify([provider, model]); + +async function callsLog(dshHome: string): Promise { + const text = await readFile(join(dshHome, "calls.log"), "utf8").catch(() => ""); + return text.split("\n").filter(Boolean); +} + test("dsh-yaml parses subset YAML, preserves !!js comment safety, detects real !!js and inline secrets", () => { const yaml = `# header comment mentioning \`!!js\` safely - id: ui-theme @@ -154,25 +241,89 @@ test("dsh-yaml parses subset YAML, preserves !!js comment safety, detects real ! assert.throws(() => parseDshPatchYaml("- id: unclosed\n items: [1, 2\n")); }); -test("diffDshDesktopModels filters pi-ai providers, plugins, secrets, !!js, and link specs", async (t) => { - const { dshHome, env, desktopDir } = await setupMigrationFixture(t); +test("dsh-yaml keeps credentials out, including numeric, boolean and private-key fields", () => { + assert.equal(hasInlineSecret({ privateKey: "-----BEGIN KEY-----" }), true); + assert.equal(hasInlineSecret({ password: 123456 }), true); + assert.equal(hasInlineSecret({ "x-api-key": "abc" }), true); + assert.equal(hasInlineSecret({ key: "abc" }), true); + assert.equal(hasInlineSecret({ auth: "user:pass" }), true); + assert.equal(hasInlineSecret({ token: true }), true); + // Model limits and env-var indirections are not credentials. + assert.equal(hasInlineSecret({ maxTokens: 4096, tokenLimit: 8000, contextWindow: 128000 }), false); + assert.equal(hasInlineSecret({ apiKeyEnv: "KEY", tokenEnv: "TOKEN" }), false); + assert.equal(hasInlineSecret({ auth: false, password: null }), false); +}); - await writeFile( - join(dshHome, "cordis.patch.yml"), - stringifyDshPatchYaml([ - { - id: "llm-pi-ai", - config: { - providers: { - "home-only": { apiKeyEnv: "HOME_KEY", models: [{ id: "h1", name: "h1" }] }, - }, - }, - }, - ]), +test("dsh-yaml round-trips escapes, folded breaks and scalar types without changing them", () => { + const escaped = parseDshPatchYaml('- a: "x\\by\\fz\\u00e9\\U0001F600\\e\\/"\n'); + assert.equal(escaped.entries[0].a, "x\by\fz\u00e9\u{1F600}\x1b/"); + assert.throws(() => parseDshPatchYaml('- a: "bad \\q escape"\n'), /escape/); + assert.throws(() => parseDshPatchYaml("- a: \"unterminated\n")); + assert.throws(() => parseDshPatchYaml("- a: 'it's'\n")); + + const folded = parseDshPatchYaml("- note: >\n intro\n code\n outro\n"); + assert.equal(folded.entries[0].note, "intro\n code\noutro\n"); + const spec = parseDshPatchYaml( + "- s: >\n\n folded\n line\n\n next\n line\n * bullet\n\n * list\n * lines\n\n last\n line\n", ); + assert.equal(spec.entries[0].s, "\nfolded line\nnext line\n * bullet\n\n * list\n * lines\n\nlast line\n"); + + const typed = parseDshPatchYaml( + "- a: True\n b: NULL\n c: 0x10\n d: 0o17\n e: .inf\n f: -.Inf\n g: 1e3\n h: '+.5'\n i: \"True\"\n j: '0x10'\n k: 'NULL'\n l: +.5\n", + ); + const row = typed.entries[0]; + assert.equal(row.a, true); + assert.equal(row.b, null); + assert.equal(row.c, 16); + assert.equal(row.d, 15); + assert.equal(row.e, Infinity); + assert.equal(row.f, -Infinity); + assert.equal(row.g, 1000); + assert.equal(row.i, "True"); + assert.equal(row.j, "0x10"); + assert.equal(row.k, "NULL"); + assert.equal(row.l, "+.5"); + + const keys = parseDshPatchYaml("- 'True': quoted\n True: plain\n '123': q\n 0x1F: hex\n"); + assert.deepEqual(keys.entries[0], { True: "quoted", true: "plain", "123": "q", "31": "hex" }); + + const values = [ + { + strings: ["True", "NULL", "0x10", "1.50", ".inf", "yes", "2024", "", " padded ", "a: b", "#tag"], + control: "tab\there\bbell\x07del\x7f", + numbers: [Infinity, -Infinity, 0.5, 1e21], + nan: Number.NaN, + "True": 1, + "123": 2, + "1.50": 3, + }, + ]; + const text = stringifyDshPatchYaml(values); + assert.deepEqual(parseDshPatchYaml(text).entries, values); + + // Forms whose type cannot be reproduced exactly are refused, not guessed. + assert.throws(() => parseDshPatchYaml("- released: 2024-01-15\n"), /Unsupported YAML scalar/); + assert.throws(() => parseDshPatchYaml("- size: 1_000\n"), /Unsupported YAML scalar/); +}); + +test("dsh-yaml distinguishes an explicit !!js tag from one inherited from a descendant", () => { + const parsed = parseDshPatchYaml( + "- id: x\n config: !!js\n a: 1\n other:\n b: !!js/function () => 1\n flow: !!js [1, 2]\n", + ); + const row = parsed.entries[0]; + assert.equal(hasExplicitJsTag(row.config), true); + assert.equal(hasExplicitJsTag(row.other), false); + assert.equal(hasJsTag(row.other), true); + assert.equal(hasExplicitJsTag(row.flow), true); + assert.equal(hasExplicitJsTag(row), false); +}); + +test("diffDshDesktopModels filters pi-ai providers, plugins, secrets, !!js, and link specs", async (t) => { + const { dshHome, env, desktopDir } = await setupMigrationFixture(t); await writePluginPkg(desktopDir, "dsh-sample-provider", { hasLlmPeer: true, hasRegisterAdapter: true }); await writePluginPkg(desktopDir, "dsh-local-plugin", { hasLlmPeer: true, hasRegisterAdapter: true }); + await writePluginPkg(desktopDir, "dsh-relative-plugin", { hasLlmPeer: true, hasRegisterAdapter: true }); await writePluginPkg(desktopDir, "dsh-doublecheck", { hasLlmPeer: false, hasRegisterAdapter: false }); await writePluginPkg(desktopDir, "dsh-peer-no-adapter", { hasLlmPeer: true, hasRegisterAdapter: false }); await writePluginPkg(desktopDir, "@deepseek-ai/dsh-internal", { hasLlmPeer: true, hasRegisterAdapter: true }); @@ -187,6 +338,7 @@ test("diffDshDesktopModels filters pi-ai providers, plugins, secrets, !!js, and "@deepseek-ai/dsh-internal", "dsh-sample-provider", "dsh-local-plugin", + "dsh-relative-plugin", "dsh-doublecheck", "dsh-peer-no-adapter", ], @@ -195,6 +347,7 @@ test("diffDshDesktopModels filters pi-ai providers, plugins, secrets, !!js, and dependencies: { "dsh-sample-provider": "0.4.6", "dsh-local-plugin": "link:D:/fake/dsh-local-plugin", + "dsh-relative-plugin": "file:./plugins/dsh-relative-plugin", "dsh-doublecheck": "0.9.0", "dsh-peer-no-adapter": "1.0.0", }, @@ -252,31 +405,81 @@ test("diffDshDesktopModels filters pi-ai providers, plugins, secrets, !!js, and [ ["pi-ai:custom-provider", "pi-ai", undefined, true, undefined], ["pi-ai:partial", "pi-ai", undefined, true, undefined], + ["pi-ai:home-only", "pi-ai", undefined, true, undefined], ["plugin:dsh-sample-provider", "plugin", "registry", true, true], ["plugin:dsh-local-plugin", "plugin", "local-link", false, undefined], + ["plugin:dsh-relative-plugin", "plugin", "local-link", false, undefined], ], ); const partial = diff.providers.find((p) => p.id === "pi-ai:partial")!; assert.deepEqual(partial.missingModels, ["m2"]); const localLink = diff.providers.find((p) => p.id === "plugin:dsh-local-plugin")!; assert.match(localLink.warning ?? "", /Local linked plugin/); + assert.equal(localLink.spec, "link:D:/fake/dsh-local-plugin"); + // dsh runs plugin commands inside the target profile, so a relative spec is + // resolved against Desktop's profile rather than copied verbatim. + const relativeLink = diff.providers.find((p) => p.id === "plugin:dsh-relative-plugin")!; + assert.equal(relativeLink.spec, `file:${resolve(desktopDir, "./plugins/dsh-relative-plugin")}`); assert.deepEqual( diff.skipped.map((s) => s.name), ["inline-secret", "js-provider"], ); + + // A home llm-pi-ai row replaces every profile's providers, so imports into + // the profile would be hidden: they are refused, and its models count. + await writeFile( + join(dshHome, "cordis.patch.yml"), + stringifyDshPatchYaml([ + { + id: "llm-pi-ai", + config: { + providers: { + "home-only": { apiKeyEnv: "HOME_KEY", models: [{ id: "h1", name: "h1" }] }, + }, + }, + }, + ]), + ); + const masked = await diffDshDesktopModels("custom-acp", env); + assert.deepEqual( + masked.providers.filter((p) => p.kind === "pi-ai").map((p) => p.id), + [], + ); + assert.deepEqual( + masked.skipped.map((s) => s.name), + ["custom-provider", "partial", "inline-secret", "js-provider"], + ); + assert.match(masked.skipped[0].reason, /sets llm-pi-ai for every profile/); }); -test("dryRunDshMigration never mutates target profile, cleans staging dirs, and isolates broken providers", async (t) => { - const { dshHome, env, desktopDir, targetDir } = await setupMigrationFixture(t); +test("diffDshDesktopModels refuses providers under an explicitly tagged container but keeps safe siblings", async (t) => { + const { env, desktopDir } = await setupMigrationFixture(t); + await writeFile( + join(desktopDir, "cordis.patch.yml"), + "- id: llm-pi-ai\n config:\n providers: !!js\n tagged-child:\n apiKeyEnv: K\n models:\n - id: t1\n", + ); + const tagged = await diffDshDesktopModels("custom-acp", env); + assert.deepEqual(tagged.providers, []); + assert.deepEqual(tagged.skipped.map((s) => s.name), ["llm-pi-ai"]); - await writePluginPkg(desktopDir, "dsh-good", { hasLlmPeer: true, hasRegisterAdapter: true }); - await writePluginPkg(desktopDir, "dsh-bad-noise", { hasLlmPeer: true, hasRegisterAdapter: true }); + await writeFile( + join(desktopDir, "cordis.patch.yml"), + "- id: llm-pi-ai\n config:\n providers:\n safe:\n apiKeyEnv: K\n models:\n - id: s1\n hooked:\n headers: !!js\n x: 1\n models:\n - id: h1\n", + ); + const siblings = await diffDshDesktopModels("custom-acp", env); + assert.deepEqual(siblings.providers.map((p) => p.id), ["pi-ai:safe"]); + assert.deepEqual(siblings.skipped.map((s) => s.name), ["hooked"]); +}); + +async function writeCustomProviderDesktop(desktopDir: string, plugins: string[]): Promise { + for (const plugin of plugins) + await writePluginPkg(desktopDir, plugin, { hasLlmPeer: true, hasRegisterAdapter: true }); await writeFile( join(desktopDir, "package.json"), JSON.stringify({ - dsh: { profile: { bundles: ["dsh-good", "dsh-bad-noise"] } }, - dependencies: { "dsh-good": "1.0.0", "dsh-bad-noise": "1.0.0" }, + dsh: { profile: { bundles: plugins } }, + dependencies: Object.fromEntries(plugins.map((plugin) => [plugin, "1.0.0"])), }), ); await writeFile( @@ -287,94 +490,62 @@ test("dryRunDshMigration never mutates target profile, cleans staging dirs, and config: { providers: { "custom-provider": { displayName: "Custom Provider", apiKeyEnv: "CUSTOM_PROVIDER_API_KEY", models: [{ id: "r1", name: "r1" }] }, + "ghost-provider": { displayName: "Ghost", apiKeyEnv: "GHOST_KEY", models: [{ id: "g1", name: "g1" }] }, }, }, }, + ...(plugins.includes("dsh-good") ? [{ id: "good", name: "dsh-good", config: { enabled: true } }] : []), ]), ); +} - // Stale marked dryrun directory > 1h old should be cleaned; unmarked user directory must stay untouched +test("dryRunDshMigration never mutates target profile, cleans staging dirs, and isolates broken providers", async (t) => { + const { dshHome, env, desktopDir, targetDir } = await setupMigrationFixture(t); + await writeCustomProviderDesktop(desktopDir, ["dsh-good", "dsh-bad-noise", "dsh-silent"]); + + // Stale marked dryrun directory > 1h old should be cleaned; an unmarked or + // differently marked directory with the same name shape must stay untouched. const staleDir = join(dshHome, "profiles", "memcode-dryrun-deadbeef"); await mkdir(staleDir, { recursive: true }); await writeFile(join(staleDir, ".memcode-dryrun"), "memcode-dryrun\n"); const userDir = join(dshHome, "profiles", "memcode-dryrun-feedface"); await mkdir(userDir, { recursive: true }); await writeFile(join(userDir, "package.json"), "{}"); + const forgedDir = join(dshHome, "profiles", "memcode-dryrun-0badf00d"); + await mkdir(forgedDir, { recursive: true }); + await writeFile(join(forgedDir, ".memcode-dryrun"), "mine, not MemCode's\n"); const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000); - await utimes(staleDir, twoHoursAgo, twoHoursAgo); - await utimes(userDir, twoHoursAgo, twoHoursAgo); - - const mockCli = join(dshHome, "mock-dsh-acp.mjs"); - await writeFile( - mockCli, - `import { createInterface } from "node:readline"; -import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -const argv = process.argv.slice(2); -if (argv[0] === "plugin") { - const profile = argv[argv.indexOf("--profile") + 1]; - const spec = argv[argv.length - 1]; - const pkgName = spec.split("@")[0]; - const pDir = join(process.env.DSH_HOME, "profiles", profile); - const pkgPath = join(pDir, "package.json"); - const pkg = JSON.parse(readFileSync(pkgPath, "utf8")); - pkg.dependencies = { ...(pkg.dependencies || {}), [pkgName]: "1.0.0" }; - writeFileSync(pkgPath, JSON.stringify(pkg, null, 2)); - mkdirSync(join(pDir, "node_modules", pkgName), { recursive: true }); - process.exit(0); -} -const profile = argv[argv.indexOf("--profile") + 1]; -const pDir = join(process.env.DSH_HOME, "profiles", profile); -const pkg = JSON.parse(readFileSync(join(pDir, "package.json"), "utf8")); -if (pkg.dependencies?.["dsh-bad-noise"]) { - process.stdout.write("NOISY_STDOUT_BEFORE_ACP\\n"); -} -const send = (x) => process.stdout.write(JSON.stringify(x) + "\\n"); -createInterface({ input: process.stdin }).on("close", () => process.exit(0)).on("line", (line) => { - const msg = JSON.parse(line); - if (msg.method === "initialize") return send({ jsonrpc: "2.0", id: msg.id, result: { agentCapabilities: {} } }); - if (msg.method === "session/close") return send({ jsonrpc: "2.0", id: msg.id, result: {} }); - if (msg.method === "session/new") { - return send({ - jsonrpc: "2.0", - id: msg.id, - result: { - sessionId: "s1", - configOptions: [{ - id: "model", - category: "model", - currentValue: "r1", - options: [{ group: "Custom Provider", options: [{ value: "r1", name: "R1" }] }], - }], - }, - }); - } -}); -`, - ); + for (const dir of [staleDir, userDir, forgedDir]) await utimes(dir, twoHoursAgo, twoHoursAgo); + const cmd = await writeMockDsh(dshHome); const beforePkg = await readFile(join(targetDir, "package.json")); const beforePatch = await readFile(join(targetDir, "cordis.patch.yml")); const beforeLock = await readFile(join(targetDir, "pnpm-lock.yaml")); - const cmd = { command: process.execPath, prefix: [mockCli] }; const result = await dryRunDshMigration( cmd, "custom-acp", - ["pi-ai:custom-provider", "plugin:dsh-good", "plugin:dsh-bad-noise"], + ["pi-ai:custom-provider", "pi-ai:ghost-provider", "plugin:dsh-good", "plugin:dsh-bad-noise", "plugin:dsh-silent"], { env }, ); assert.equal(result.ok, false); + assert.equal(result.plan, undefined); assert.deepEqual(result.passedIds, ["pi-ai:custom-provider", "plugin:dsh-good"]); - assert.equal(result.failed.length, 1); - assert.equal(result.failed[0].id, "plugin:dsh-bad-noise"); - assert.match(result.failed[0].reason, /unreadable|JSON|NOISY_STDOUT/i); + assert.deepEqual( + result.failed.map((f) => f.id), + ["pi-ai:ghost-provider", "plugin:dsh-bad-noise", "plugin:dsh-silent"], + ); + // A provider that loads but lists none of its models is not verified. + assert.match(result.failed[0].reason, /did not list g1/); + assert.match(result.failed[1].reason, /unreadable|JSON|NOISY_STDOUT/i); + assert.match(result.failed[2].reason, /no new models/); assert.equal(await exists(staleDir), false); assert.equal(await exists(userDir), true); + assert.equal(await exists(forgedDir), true); const leftover = (await readdir(join(dshHome, "profiles"))).filter( - (n) => n.startsWith("memcode-dryrun-") && n !== "memcode-dryrun-feedface", + (n) => n.startsWith("memcode-dryrun-") && n !== "memcode-dryrun-feedface" && n !== "memcode-dryrun-0badf00d", ); assert.deepEqual(leftover, []); @@ -388,92 +559,108 @@ createInterface({ input: process.stdin }).on("close", () => process.exit(0)).on( assert.equal(okRun.ok, true); assert.deepEqual(okRun.passedIds, ["pi-ai:custom-provider", "plugin:dsh-good"]); assert.equal(okRun.failed.length, 0); - assert.equal(okRun.previewModels[0]?.id, "r1"); - assert.equal(okRun.previewModels[0]?.group, "Custom Provider"); + assert.ok(okRun.previewModels.some((m) => m.id === tuple("custom-provider", "r1") && m.group === "custom-provider")); + assert.deepEqual(okRun.plan?.expectedModelIds.sort(), [ + tuple("custom-provider", "r1"), + tuple("dsh-good-provider", "model"), + ].sort()); + + // A selection Desktop no longer offers is refused, never silently skipped. + const stale = await dryRunDshMigration(cmd, "custom-acp", ["pi-ai:custom-provider", "pi-ai:removed"], { env }); + assert.equal(stale.ok, false); + assert.deepEqual(stale.failed.map((f) => f.id), ["pi-ai:removed"]); + assert.match(stale.failed[0].reason, /No longer offered/); }); -test("applyDshMigration merges cleanly and rolls back exact snapshot on failure", async (t) => { +test("dryRunDshMigration stages the target's own dependency tree before probing", async (t) => { const { dshHome, env, desktopDir, targetDir } = await setupMigrationFixture(t); + await writeCustomProviderDesktop(desktopDir, []); + // A healthy customized profile whose third-party bundle loads from node_modules. + const pkg = JSON.parse(await readFile(join(targetDir, "package.json"), "utf8")); + pkg.dependencies = { "dsh-existing": "1.0.0" }; + await writeFile(join(targetDir, "package.json"), JSON.stringify(pkg)); + await mkdir(join(targetDir, "node_modules", "dsh-existing"), { recursive: true }); + + const cmd = await writeMockDsh(dshHome); + const result = await dryRunDshMigration(cmd, "custom-acp", ["pi-ai:custom-provider"], { env }); + assert.equal(result.ok, true, result.error ?? ""); + const installs = (await callsLog(dshHome)).filter((line) => / install --frozen-lockfile$/.test(line)); + assert.ok(installs.length >= 2, "baseline and candidate staging both install the target tree"); + assert.ok(installs.every((line) => line.startsWith("memcode-dryrun-")), "the target itself is never reinstalled"); +}); - await writePluginPkg(desktopDir, "dsh-good", { hasLlmPeer: true, hasRegisterAdapter: true }); - await writeFile( - join(desktopDir, "package.json"), - JSON.stringify({ - dsh: { profile: { bundles: ["dsh-good"] } }, - dependencies: { "dsh-good": "1.0.0" }, - }), - ); - await writeFile( - join(desktopDir, "cordis.patch.yml"), - stringifyDshPatchYaml([ - { - id: "llm-pi-ai", - config: { - providers: { - "custom-provider": { displayName: "Custom Provider", apiKeyEnv: "CUSTOM_PROVIDER_API_KEY", models: [{ id: "r1", name: "r1" }] }, - }, - }, - }, - { id: "good", name: "dsh-good", config: { enabled: true } }, - ]), - ); - - const mockCli = join(dshHome, "mock-apply.mjs"); - await writeFile( - mockCli, - `import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -const argv = process.argv.slice(2); -if (argv[0] === "plugin") { - const profile = argv[argv.indexOf("--profile") + 1]; - const spec = argv[argv.length - 1]; - const pkgName = spec.split("@")[0]; - const pDir = join(process.env.DSH_HOME, "profiles", profile); - const pkgPath = join(pDir, "package.json"); - const pkg = JSON.parse(readFileSync(pkgPath, "utf8")); - pkg.dependencies = { ...(pkg.dependencies || {}), [pkgName]: "1.0.0" }; - writeFileSync(pkgPath, JSON.stringify(pkg, null, 2)); - writeFileSync(join(pDir, "pnpm-lock.yaml"), "lockfileVersion: '9.0'\\nupdated: true\\n"); - mkdirSync(join(pDir, "node_modules", pkgName), { recursive: true }); -} -`, - ); - - const cmd = { command: process.execPath, prefix: [mockCli] }; - const beforePkg = await readFile(join(targetDir, "package.json")); - const beforePatch = await readFile(join(targetDir, "cordis.patch.yml")); - const beforeLock = await readFile(join(targetDir, "pnpm-lock.yaml")); - - const failedApply = await applyDshMigration( - cmd, - "custom-acp", - ["pi-ai:custom-provider", "plugin:dsh-good"], - { - env, - probe: async () => { - throw new Error("Simulated post-apply probe failure"); - }, +test("applyDshMigration applies only the verified plan and fully rolls back on failure", async (t) => { + const { dshHome, env, desktopDir, targetDir } = await setupMigrationFixture(t); + await writeCustomProviderDesktop(desktopDir, ["dsh-good"]); + await writeFile(join(targetDir, "pnpm-workspace.yaml"), "original: true\n"); + const cmd = await writeMockDsh(dshHome); + const ids = ["pi-ai:custom-provider", "plugin:dsh-good"]; + const snapshot = async () => ({ + pkg: await readFile(join(targetDir, "package.json")), + patch: await readFile(join(targetDir, "cordis.patch.yml")), + lock: await readFile(join(targetDir, "pnpm-lock.yaml")), + workspace: await readFile(join(targetDir, "pnpm-workspace.yaml")), + }); + const before = await snapshot(); + const planFor = async (): Promise => { + const dryRun = await dryRunDshMigration(cmd, "custom-acp", ids, { env }); + assert.equal(dryRun.ok, true, dryRun.error ?? ""); + return dryRun.plan!; + }; + + // Desktop changed after the dry-run: refuse before touching the profile. + const stalePlan = await planFor(); + const desktopPatch = join(desktopDir, "cordis.patch.yml"); + const desktopText = await readFile(desktopPatch, "utf8"); + await writeFile(desktopPatch, desktopText.replace("displayName: Custom Provider", "displayName: Changed")); + const refused = await applyDshMigration(cmd, stalePlan, { env }); + assert.equal(refused.ok, false); + assert.match(refused.error ?? "", /changed after the dry-run/); + assert.deepEqual(await snapshot(), before); + await writeFile(desktopPatch, desktopText); + + // A failed post-apply probe belongs to the profile, not the last plugin, and + // rollback restores every file and reinstalls the restored lockfile. + const plan = await planFor(); + await rm(join(dshHome, "calls.log"), { force: true }); + const failedApply = await applyDshMigration(cmd, plan, { + env, + probe: async () => { + throw new Error("Simulated post-apply probe failure"); }, - ); + }); assert.equal(failedApply.ok, false); + assert.equal(failedApply.restored, true); + assert.equal(failedApply.failed[0]?.id, "profile:custom-acp"); assert.match(failedApply.failed[0]?.reason ?? "", /Simulated post-apply probe failure/); - assert.deepEqual(await readFile(join(targetDir, "package.json")), beforePkg); - assert.deepEqual(await readFile(join(targetDir, "cordis.patch.yml")), beforePatch); - assert.deepEqual(await readFile(join(targetDir, "pnpm-lock.yaml")), beforeLock); + assert.deepEqual(await snapshot(), before); assert.equal(await exists(join(targetDir, "node_modules", "dsh-good")), false); + assert.deepEqual(await callsLog(dshHome), [ + "custom-acp add dsh-good@1.0.0", + "custom-acp install --frozen-lockfile", + ]); - const okApply = await applyDshMigration( - cmd, - "custom-acp", - ["pi-ai:custom-provider", "plugin:dsh-good"], - { - env, - probe: async () => [{ id: "r1", label: "R1", group: "Custom Provider", source: "acp" }], - }, - ); - assert.equal(okApply.ok, true); - assert.deepEqual(okApply.appliedIds, ["pi-ai:custom-provider", "plugin:dsh-good"]); - assert.equal(okApply.models.length, 1); + // The catalog must still show what the dry-run verified. + const missing = await applyDshMigration(cmd, plan, { + env, + probe: async () => [{ id: tuple("deepseek-official", "deepseek-v4-flash"), label: "v4", source: "acp" }], + }); + assert.equal(missing.ok, false); + assert.match(missing.error ?? "", /did not list 2 models the dry-run verified/); + assert.deepEqual(await snapshot(), before); + + // A rejected plugin install is attributed to that plugin. + const rejected = await applyDshMigration(cmd, plan, { + env: { ...env, MOCK_FAIL_ADD: "dsh-good" }, + }); + assert.equal(rejected.ok, false); + assert.equal(rejected.failed[0]?.id, "plugin:dsh-good"); + assert.deepEqual(await snapshot(), before); + + const okApply = await applyDshMigration(cmd, plan, { env }); + assert.equal(okApply.ok, true, okApply.error ?? ""); + assert.deepEqual(okApply.appliedIds, ids); + assert.ok(okApply.models.some((m) => m.id === tuple("custom-provider", "r1"))); const mergedPatch = parseDshPatchYaml(await readFile(join(targetDir, "cordis.patch.yml"), "utf8")); assert.equal(mergedPatch.entries.find((e) => e.id === "ui-theme")?.config?.fontSize, 14); @@ -481,6 +668,11 @@ if (argv[0] === "plugin") { assert.ok(mergedPatch.entries.find((e) => e.id === "llm-pi-ai")?.config?.providers?.["custom-provider"]); assert.equal(mergedPatch.entries.find((e) => e.id === "good")?.config?.enabled, true); assert.equal(await exists(join(targetDir, "node_modules", "dsh-good")), true); + + // The profile changed since that plan was verified, so it cannot run again. + const replay = await applyDshMigration(cmd, plan, { env }); + assert.equal(replay.ok, false); + assert.match(replay.error ?? "", /changed after the dry-run/); }); test("dryRunDshMigration fails fast on broken baseline, surfaces combination conflicts, and blocks !!js targets", async (t) => { @@ -504,7 +696,7 @@ test("dryRunDshMigration fails fast on broken baseline, surfaces combination con const calls: string[] = []; const noopCmd = { command: process.execPath, prefix: ["-e", "process.exit(0)"] }; - // 1. Broken baseline stops immediately without attributing blame to providers + // 1. A broken baseline stops before any provider is tested or blamed const brokenBase = await dryRunDshMigration( noopCmd, "custom-acp", @@ -520,10 +712,14 @@ test("dryRunDshMigration fails fast on broken baseline, surfaces combination con assert.equal(brokenBase.ok, false); assert.equal(brokenBase.failed.length, 1); assert.equal(brokenBase.failed[0].id, "profile:custom-acp"); - assert.equal(calls.length, 2); // combined attempt + single baseline check only + assert.equal(calls.length, 1); // 2. Combination conflict: each provider passes alone, combined fails -> ok:false with error let comboCall = 0; + const both = [ + { id: tuple("p1", "m1"), label: "m1", group: "p1", source: "acp" as const }, + { id: tuple("p2", "m2"), label: "m2", group: "p2", source: "acp" as const }, + ]; const combo = await dryRunDshMigration( noopCmd, "custom-acp", @@ -532,8 +728,9 @@ test("dryRunDshMigration fails fast on broken baseline, surfaces combination con env, probe: async () => { comboCall++; - if (comboCall === 1) throw new Error("p1+p2 incompatible"); - return [{ id: "m1", label: "M1", group: "G", source: "acp" }]; + if (comboCall === 1) return []; + if (comboCall === 2) throw new Error("p1+p2 incompatible"); + return both; }, }, ); @@ -541,19 +738,15 @@ test("dryRunDshMigration fails fast on broken baseline, surfaces combination con assert.deepEqual(combo.failed, []); assert.match(combo.error ?? "", /p1\+p2 incompatible/); - // 3. Target cordis.patch.yml containing !!js is refused rather than stripping tags + // 3. A target cordis.patch.yml containing !!js is never rewritten const taggedTarget = "- id: hook\n fn: !!js/function '() => 1'\n"; await writeFile(join(targetDir, "cordis.patch.yml"), taggedTarget); - const blockedApply = await applyDshMigration( - noopCmd, - "custom-acp", - ["pi-ai:p1"], - { - env, - probe: async () => [{ id: "m1", label: "M1", group: "G", source: "acp" }], - }, - ); - assert.equal(blockedApply.ok, false); - assert.match(blockedApply.error ?? "", /!!js expressions/); + const blocked = await dryRunDshMigration(noopCmd, "custom-acp", ["pi-ai:p1"], { + env, + probe: async () => both, + }); + assert.equal(blocked.ok, false); + assert.match(blocked.failed[0]?.reason ?? "", /!!js expressions/); assert.equal(await readFile(join(targetDir, "cordis.patch.yml"), "utf8"), taggedTarget); + void dshHome; }); diff --git a/tests/dsh-profiles.test.ts b/tests/dsh-profiles.test.ts index b8a2f95..5d8d795 100644 --- a/tests/dsh-profiles.test.ts +++ b/tests/dsh-profiles.test.ts @@ -117,9 +117,38 @@ test("inspectDshProfiles requests profile creation when no ACP profiles exist", const inspected = await inspectDshProfiles(undefined, { DSH_HOME: dshHome }); assert.equal(inspected.needsProfileCreation, true); assert.equal(inspected.activeProfile, "acp"); + assert.equal(inspected.activeProfileIssue, undefined); assert.equal(inspected.desktopProfilePresent, false); }); +test("inspectDshProfiles flags a non-ACP default directory and never selects unusable names", async (t) => { + const dshHome = await makeTempDshHome(t); + const profilesDir = join(dshHome, "profiles"); + const env = { DSH_HOME: dshHome }; + const acpBundles = JSON.stringify({ + dependencies: { "dsh-sample-provider": "0.4.6" }, + dsh: { profile: { bundles: ["@deepseek-ai/dsh-acp-app"] } }, + }); + // Customized ACP profiles whose names dsh cannot be given. + for (const name of ["acp copy", "_backup"]) { + await mkdir(join(profilesDir, name), { recursive: true }); + await writeFile(join(profilesDir, name, "package.json"), acpBundles); + } + // An existing "acp" directory that is a web profile, not ACP. + await mkdir(join(profilesDir, "acp"), { recursive: true }); + await writeFile( + join(profilesDir, "acp", "package.json"), + JSON.stringify({ dsh: { profile: { bundles: ["@deepseek-ai/dsh-web-app"] } } }), + ); + + const inspected = await inspectDshProfiles(undefined, env); + assert.deepEqual(inspected.acpProfiles, []); + assert.deepEqual(inspected.nonAcpProfiles.map((p) => p.name), ["acp"]); + assert.equal(inspected.activeProfile, "acp"); + assert.equal(inspected.activeProfileIssue, "non-acp"); + assert.equal(inspected.needsProfileCreation, true); +}); + test("createDshAcpProfile uses correct CLI flags for shipped acp vs custom profile names", async (t) => { const dshHome = await makeTempDshHome(t); const scriptPath = join(dshHome, "mock-dsh.mjs"); diff --git a/tests/dsh-setup-gate.test.ts b/tests/dsh-setup-gate.test.ts new file mode 100644 index 0000000..c8b30b9 --- /dev/null +++ b/tests/dsh-setup-gate.test.ts @@ -0,0 +1,46 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { DshSetupGate } from "../runtime/dsh-setup-gate"; + +test("DshSetupGate keeps setup, reviewers and other setup operations apart", async () => { + const gate = new DshSetupGate(); + + // A running reviewer keeps profile-changing setup out until it exits. + const release = gate.admit("review"); + await assert.rejects(gate.run("apply-migrate", async () => "x"), /review or plan in progress/); + // A dry-run only touches staging and may run beside a reviewer. + assert.equal(await gate.run("dry-run", async () => "staged", { mutates: false }), "staged"); + release(); + release(); // idempotent + + let finish!: () => void; + const running = gate.run("apply-migrate", () => new Promise((resolve) => (finish = () => resolve("applied")))); + assert.equal(gate.operation, "apply-migrate"); + assert.equal(gate.mutating, true); + assert.throws(() => gate.admit("review"), /Wait for DeepSeek Harness setup to finish/); + await assert.rejects(gate.run("select-profile", async () => 1), /already in progress/); + finish(); + assert.equal(await running, "applied"); + assert.equal(gate.operation, null); + + // A failing operation still releases the gate. + await assert.rejects(gate.run("install-cli", async () => { throw new Error("boom"); }), /boom/); + gate.admit("plan")(); +}); + +test("DshSetupGate.close waits for a running operation and refuses new ones", async () => { + const gate = new DshSetupGate(); + let finish!: () => void; + let settled = false; + const running = gate.run("apply-migrate", () => new Promise((resolve) => (finish = resolve))).then(() => { + settled = true; + }); + const closing = gate.close(); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(settled, false); + finish(); + await closing; + assert.equal(settled, true); + await running; + await assert.rejects(gate.run("select-profile", async () => 1), /shutting down/); +}); diff --git a/tests/review-agent.test.ts b/tests/review-agent.test.ts index 39b2294..5e4f12f 100644 --- a/tests/review-agent.test.ts +++ b/tests/review-agent.test.ts @@ -70,7 +70,11 @@ if(harness==='copilot'||harness==='dsh'){ setInterval(()=>{},1000); `; -async function fixture(harness: Harness, scenario = "safe") { +async function fixture( + harness: Harness, + scenario = "safe", + extra: Parameters[2] = {}, +) { const root = await mkdtemp(join(tmpdir(), "memcode-readonly-review-")); const script = join(root, "provider.mjs"), record = join(root, "record.json"), @@ -115,6 +119,7 @@ async function fixture(harness: Harness, scenario = "safe") { coverage: { complete: false, limitations: [] }, } as unknown as StoryReviewRun; const agent = createReadonlyReviewAgent(profile, () => state, { + ...extra, timeoutMs: 10000, commandFor: async () => ({ command: process.execPath, @@ -525,6 +530,35 @@ test("review cleanup terminates the exact Node launcher and its long-running gra } }); +test("dsh reviews hold setup admission for the whole process and start only when admitted", async () => { + const events: string[] = []; + let admit = true; + const f = await fixture("dsh", "safe", { + dshAdmission: () => { + if (!admit) throw new Error("Wait for DeepSeek Harness setup to finish before starting a DeepSeek Harness review."); + events.push("admitted"); + return () => events.push("released"); + }, + }); + try { + const answer = await f.agent.ask({ task: f.task, review: f.review, question: "Summarize the review." }); + assert.equal(answer.harness, "dsh"); + assert.deepEqual(events, ["admitted", "released"]); + assert.equal(((await f.record()) as { prompted: boolean }).prompted, true); + + admit = false; + await rm(join(f.root, "record.json"), { force: true }); + await assert.rejects( + f.agent.ask({ task: f.task, review: f.review, question: "Again." }), + /Wait for DeepSeek Harness setup to finish/, + ); + await assert.rejects(readFile(join(f.root, "record.json")), "no reviewer process started"); + assert.deepEqual(events, ["admitted", "released"]); + } finally { + await f.close(); + } +}); + test("dsh review agent resolves active custom ACP profile when settings.dshProfile is unset", async () => { const dshHome = await mkdtemp(join(tmpdir(), "memcode-review-dsh-home-")); const prevDshHome = process.env.DSH_HOME; diff --git a/tests/standard-acp.test.ts b/tests/standard-acp.test.ts index 946922f..b210405 100644 --- a/tests/standard-acp.test.ts +++ b/tests/standard-acp.test.ts @@ -207,6 +207,30 @@ createInterface({input:process.stdin}).on('close',()=>process.exit(0)).on('line' probeStandardCatalog("dsh", { command: process.execPath, prefix: [emptyScript] }, "acp", { strictStdout: true }), /empty model catalog/i, ); + + // A JSON log line is still stdout pollution, not an ACP message. + const loggingScript = join(cwd, "json-log-acp.mjs"); + await writeFile(loggingScript, ` +import { createInterface } from 'node:readline'; +process.stdout.write(JSON.stringify({ message: 'starting' }) + '\\n'); +const send = x => process.stdout.write(JSON.stringify(x)+'\\n'); +createInterface({input:process.stdin}).on('close',()=>process.exit(0)).on('line', line => { + const x = JSON.parse(line); + if (x.method === 'initialize') return send({jsonrpc:'2.0',id:x.id,result:{agentCapabilities:{}}}); + if (x.method === 'session/new') return send({jsonrpc:'2.0',id:x.id,result:{sessionId:'s1',configOptions:[{id:'model',category:'model',currentValue:'m1',options:[{value:'m1',name:'Model 1'}]}]}}); + if (x.method === 'session/close') return send({jsonrpc:'2.0',id:x.id,result:{}}); +}); +`); + const logging = { command: process.execPath, prefix: [loggingScript] }; + assert.equal((await probeStandardCatalog("dsh", logging, "acp"))[0]?.id, "m1"); + await assert.rejects( + probeStandardCatalog("dsh", logging, "acp", { strictStdout: true }), + /not an ACP message/i, + ); + + // An unusable profile name rejects, so a caller's .catch() always applies. + const invalid = probeStandardCatalog("dsh", cmd, "acp copy"); + await assert.rejects(invalid, /Invalid DeepSeek Harness profile/); } finally { await rm(cwd, { recursive: true, force: true }); }