diff --git a/docs/account-and-workers.md b/docs/account-and-workers.md index 69e872c..a849340 100644 --- a/docs/account-and-workers.md +++ b/docs/account-and-workers.md @@ -134,3 +134,41 @@ are omitted and Memtrace sign-in opens only the official claim host. Actual installed status checks on the Windows development machine confirmed the Codex, Claude Code and Cursor CLIs had existing provider authentication, without granting production consent. + +### DeepSeek Harness setup and ACP profiles + +When DeepSeek Harness (`dsh`) is not on `PATH` and DeepSeek Harness Desktop is +installed, **Workers** detects the Desktop app and runs its bundled +`command-manager.js` helper with the Desktop app’s bundled Node runtime and a +verified inspect fingerprint. On Windows, MemCode refreshes the user `PATH` +in-process after installation; on macOS, if `/usr/local/bin/dsh` returns +`EACCES` or `EPERM`, MemCode directs the user to **Manage dsh Command…** in +DeepSeek Harness Desktop without invoking `osascript`. + +MemCode scans `$DSH_HOME/profiles/*` for ACP profiles (`@deepseek-ai/dsh-acp-app` +or `@deepseek-ai/dsh-acp`), excluding conflicting web/Desktop bundles, +`node_modules`, and temporary `memcode-dryrun-*` directories. When +`settings.dshProfile` is unset, MemCode automatically selects a customized ACP +profile if present; when no ACP profile exists (or only non-ACP profiles are +found), setup guides the user through creating one before connecting. + +Desktop-to-ACP provider sync compares Desktop `llm-pi-ai` entries in +`cordis.patch.yml` and `@deepseek-ai/dsh-llm` `registerAdapter` plugins against +the active ACP profile. Inline credentials and unsafe YAML tags are skipped, +and `link:`/`file:` local plugins stay unchecked by default; a relative local +path is resolved against the Desktop profile. When `$DSH_HOME/cordis.patch.yml` +sets `llm-pi-ai`, it replaces every profile's providers, so custom providers are +not offered for import into a profile and the list says why. + +Selected providers are tested first in an isolated `memcode-dryrun-*` staging +profile that gets its own copy of the target's dependency tree. The unchanged +profile is checked first; then each provider must actually contribute models to +the strict ACP catalog. Failing providers are isolated with a **Retry without +broken providers** action before the target profile is modified. **Import** +applies only the plan that dry-run verified and refuses if Desktop, the home +patch or the target changed in between. A failed import restores the profile +files, reinstalls the restored lockfile and reports whether rollback completed. +DeepSeek Harness reviews, plans and workers do not start while setup changes the +profile, and setup waits for running dsh reviews; quitting MemCode waits for an +import to finish. ACP model catalogs preserve provider group headings and full +`["provider", "model"]` identifiers in Worker Assignment. 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..18077df 100644 --- a/runtime/agents/cursor.ts +++ b/runtime/agents/cursor.ts @@ -192,17 +192,44 @@ 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, probeOptions?.strictStdout === true); + 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.`); + if (models.length === 0) throw Error(`${transport.name} returned an empty model catalog.`); + } } finally { clearTimeout(timer); } return models; } finally { @@ -210,7 +237,20 @@ export async function probeStandardACPCatalog(transport: ACPTransport, command: } } -function runCursorSession(options: AgentSessionOptions, inspect?: (session: Json) => void, transport?: ACPTransport): AgentSession { +/** A JSON-RPC 2.0 request, notification or response, as ACP sends them. */ +function isJsonRpcMessage(message: Json): boolean { + if (message.jsonrpc !== "2.0") return false; + if (typeof message.method === "string") return true; + return hasId(message) && ("result" in message || "error" in message); +} + +function runCursorSession( + options: AgentSessionOptions, + inspect?: (session: Json) => void, + transport?: ACPTransport, + /** Treat any stdout line that is not a JSON-RPC message as an error. */ + strictStdout = false, +): AgentSession { const brand = transport?.name ?? "Cursor"; // Current ACP ignores --auto-review even though interactive Cursor supports it. // Never silently run an allowlist/bypass session labelled as Smart auto. @@ -646,7 +686,18 @@ function runCursorSession(options: AgentSessionOptions, inspect?: (session: Json const lines = createInterface({ input: child.stdout! }); lines.on("line", (line) => { try { - incoming(record(JSON.parse(line))); + const message = record(JSON.parse(line)); + // JSON log lines such as {"message":"starting"} are ignored by incoming(); + // a strict probe must still see that stdout is not a clean ACP stream. + if (strictStdout && !isJsonRpcMessage(message)) { + emit({ + type: "error", + message: `${brand} wrote a JSON line that is not an ACP message to stdout.`, + fatal: false, + }); + return; + } + incoming(message); } catch { emit({ type: "error", diff --git a/runtime/agents/standard-acp.ts b/runtime/agents/standard-acp.ts index 70a2762..79a5e22 100644 --- a/runtime/agents/standard-acp.ts +++ b/runtime/agents/standard-acp.ts @@ -1,14 +1,33 @@ 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> & { + allowStaging?: boolean; + }, +): 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, { + allowStaging: options?.allowStaging, + }), + ], + }; } export function startStandardSession(id: StandardHarness, options: AgentSessionOptions) { if (options.localModel) throw Error("The local-model override currently supports Codex with Ollama."); @@ -18,12 +37,30 @@ 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); +// Async, so an invalid profile name rejects instead of throwing before a +// caller's .catch() is attached. +export async function probeStandardCatalog( + id: StandardHarness, + command: Command, + dshProfile?: string, + options?: { strictStdout?: boolean; allowStaging?: boolean }, +) { + return probeStandardACPCatalog( + standardTransport( + id, + id === "dsh" ? { dshProfile, allowStaging: options?.allowStaging } : 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 +76,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..2223095 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, refreshWindowsUserPath } from "./commands"; import { observePersistence } from "./persistence"; import { MemtraceEngine } from "./memtrace"; import { ensureProjectRepository } from "./project-repository"; @@ -26,7 +27,21 @@ 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, + type DshMigrationPlan, +} from "./dsh-migration"; +import { DshSetupGate } from "./dsh-setup-gate"; import { planDefinedStory, readRoutingCalibration, readRoutingLanguage } from "./story-route"; import { qualificationRequestFingerprint } from "./qualification"; import { registerPlanning } from "./planning"; @@ -149,6 +164,10 @@ export async function createRuntime( let betaNeedsAnalysis = false; let betaReady = false; let requireFreshWorkerContext = false; + // Setup changes, dsh workers and dsh reviewers never overlap. + const dshGate = new DshSetupGate(); + // Only the most recent successful dry-run can be applied, and only once. + let dshPlan: { id: string; plan: DshMigrationPlan } | null = null; const qaProfile = process.env.MEMCODE_NATIVE_TEST_PROFILE === "1" || !!process.env.NODE_TEST_CONTEXT; @@ -249,10 +268,15 @@ export async function createRuntime( release: (taskId, projectId) => team?.release(taskId, projectId) ?? Promise.resolve(), }, - () => { + (harness) => { appUpdateGate.assertMayStart(); beta?.assertMayStart(); if (!beta?.usesBeta()) connections.account.assertMayStart(); + if (harness === "dsh" && dshGate.operation) { + throw new Error( + "Wait for DeepSeek Harness setup to finish before starting a DeepSeek Harness worker.", + ); + } }, (project) => betaReady && @@ -773,7 +797,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 +844,247 @@ export async function createRuntime( host.call("installation_show_applications", {}), ); register("connection:refresh-catalog", z.undefined(), async () => { - await discoverHarnesses(true); + if (process.platform === "win32" && !(await findCommand("dsh"))) { + await refreshWindowsUserPath(); + } + await discoverHarnesses(true, undefined, { + dshProfile: store.state.settings.dshProfile, + }); return store.runtime(); }); + const resolveDshCommand = async () => { + let command = await findCommand("dsh"); + if (!command && process.platform === "win32") { + await refreshWindowsUserPath(); + command = await findCommand("dsh"); + } + return command; + }; + const dshSetupStatus = async (): Promise => { + const [command, desktopAppPath, profiles] = await Promise.all([ + resolveDshCommand(), + 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 withDshSetupLock = async ( + operation: string, + fn: () => Promise, + options: { readOnly?: boolean } = {}, + ): Promise => { + if (!options.readOnly) assertNoActiveDshWorker(); + try { + return await dshGate.run(operation, fn, { mutates: !options.readOnly }); + } finally { + dispatchQueued?.(); + } + }; + /** + * A model chosen from one profile's catalog may not exist in another. After + * a profile or its providers change, drop dsh overrides the new catalog does + * not offer, so later dsh tasks cannot fail model selection. + */ + const revalidateDshOverrides = async () => { + const runtime = await store.runtime(); + const offered = new Set( + runtime.harnesses.find((item) => item.id === "dsh")?.models.map((model) => model.id) ?? [], + ); + // An unavailable catalog cannot prove an override wrong; keep them. + if (offered.size === 0) return runtime; + let dropped = false; + const settings = store.state.settings; + if (settings.defaultHarness === "dsh" && !settings.localModel && settings.model && !offered.has(settings.model)) { + settings.model = ""; + dropped = true; + } + for (const item of store.state.tasks) + if ( + !item.example && + item.harness === "dsh" && + item.stage !== "done" && + item.modelOverride && + !offered.has(item.modelOverride) + ) { + item.modelOverride = null; + dropped = true; + } + if (dropped) await changed(); + return runtime; + }; + 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(), () => + withDshSetupLock("install-cli", async () => { + 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(), + ]); + const discoverable = !installed.installed || status.cliInstalled; + return { + installed: installed.installed && status.cliInstalled, + ...(installed.needsDesktopMenu !== undefined + ? { needsDesktopMenu: installed.needsDesktopMenu } + : {}), + message: discoverable + ? installed.message + : "DeepSeek Harness Desktop registered the CLI, but MemCode could not discover the launcher yet. Restart MemCode or verify dsh is on PATH.", + status, + runtime, + }; + }), + ); + register( + "dsh:create-profile", + z.object({ name: nonempty.max(64) }).strict(), + ({ name }) => + withDshSetupLock("create-profile", async () => { + const normalized = normalizeDshProfile(name); + const command = await resolveDshCommand(); + 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; + dshPlan = null; + await changed(); + invalidateHarnessCache("dsh"); + const [status, runtime] = await Promise.all([ + dshSetupStatus(), + revalidateDshOverrides(), + ]); + return { profile, status, runtime }; + }), + ); + register( + "dsh:select-profile", + z.object({ name: nonempty.max(64) }).strict(), + ({ name }) => + withDshSetupLock("select-profile", async () => { + 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; + dshPlan = null; + await changed(); + invalidateHarnessCache("dsh"); + const [status, runtime] = await Promise.all([ + dshSetupStatus(), + revalidateDshOverrides(), + ]); + 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(), + ({ targetProfile, selectedIds }) => + withDshSetupLock( + "dry-run-migrate", + async () => { + const command = await resolveDshCommand(); + if (!command) + throw new Error( + "Install the DeepSeek Harness CLI before testing Desktop model migration.", + ); + const profile = await resolveDshTargetProfile(targetProfile); + dshPlan = null; + const { plan, ...result } = await dryRunDshMigration(command, profile, selectedIds, { + probe: (p, cmd) => + probeStandardCatalog("dsh", cmd, p, { + strictStdout: true, + allowStaging: true, + }), + }); + if (!plan) return result; + dshPlan = { id: randomUUID(), plan }; + return { ...result, planId: dshPlan.id }; + }, + // Staging never touches the target profile or running workers. + { readOnly: true }, + ), + ); + register( + "dsh:apply-migrate", + z.object({ planId: z.string().min(1).max(100) }).strict(), + ({ planId }) => + withDshSetupLock("apply-migrate", async () => { + // Apply runs exactly what a dry-run verified, at most once. + const verified = dshPlan && dshPlan.id === planId ? dshPlan.plan : null; + dshPlan = null; + if (!verified) + throw new Error( + "Test the selected providers again before importing them.", + ); + const command = await resolveDshCommand(); + if (!command) + throw new Error( + "Install the DeepSeek Harness CLI before importing Desktop models.", + ); + const applied = await applyDshMigration(command, verified, { + probe: (p, cmd) => + probeStandardCatalog("dsh", cmd, p, { strictStdout: true }), + }); + invalidateHarnessCache("dsh"); + const runtime = await revalidateDshOverrides(); + return { + ok: applied.ok, + targetProfile: verified.targetProfile, + appliedIds: applied.appliedIds, + failed: applied.failed, + models: applied.models, + ...(applied.error ? { error: applied.error } : {}), + ...(applied.restored !== undefined ? { restored: applied.restored } : {}), + runtime, + }; + }), + ); register("connection:guide", z.object({ harness }).strict(), ({ harness }) => host.call("open_worker_setup", { harness }), ); @@ -1043,6 +1305,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), @@ -1108,15 +1371,31 @@ export async function createRuntime( throw new Error( "Stop active workers before changing runtime settings.", ); + if (dshGate.operation) + throw new Error( + "Another DeepSeek Harness setup operation is already in progress. Wait for it to finish.", + ); // Saving speech, retrieval or worker preferences must not permanently // close the shared engine. Only its executable changes the connection; // 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; + const dshProfileChanged = dshProfile !== store.state.settings.dshProfile; + if (dshProfileChanged) { + invalidateHarnessCache("dsh"); + dshPlan = null; + } // 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, @@ -1124,7 +1403,7 @@ export async function createRuntime( handoffAttribution: state().settings.handoffAttribution, }; await changed(); - return store.runtime(); + return dshProfileChanged ? revalidateDshOverrides() : store.runtime(); }, ); register("artifact:thumbnail", identifier, async (id) => { @@ -1228,7 +1507,12 @@ export async function createRuntime( ); registerGoalPlanner( register, - new GoalPlanner({ dataDir: store.dir, state, relatedFiles }), + new GoalPlanner({ + dataDir: store.dir, + state, + relatedFiles, + reviewOptions: { dshAdmission: () => dshGate.admit("plan") }, + }), ); registerGoalUpdates( register, @@ -1287,7 +1571,9 @@ export async function createRuntime( team?.identity(item.projectId) ?? connections.account.current.principal, reviewProject: (item, parent) => epicAnalysisProject(parent, item), engineVersion: (item) => engine.versionFor(item.id) ?? "Not reported", - reviewer: createReadonlyReviewAgent(store.dir, state), + reviewer: createReadonlyReviewAgent(store.dir, state, { + dshAdmission: () => dshGate.admit("review"), + }), implementationCount: () => workers.implementationCount(), implementationStarting: (taskId) => workers.implementationStarting(taskId), capacityChanged: () => workers.dispatchQueued(), @@ -1747,6 +2033,9 @@ export async function createRuntime( async close() { if (closed) return; closed = true; + // A DeepSeek Harness import holds its only rollback snapshots in memory: + // let it verify or restore the profile before the process exits. + await dshGate.close(); const betaClosing = beta?.close(); clearInterval(artifactMaintenance); await reconcilingArtifacts?.catch((error) => diff --git a/runtime/catalog.ts b/runtime/catalog.ts index 4c418f9..03a873c 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, defaultDshProfile } 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,19 @@ async function discoverOne(id: Harness, refresh: boolean): Promise []); + if (command && id === "copilot") + models = await probeStandardCatalog(id, command).catch(() => []); + if (command && id === "dsh") { + const canProbeDsh = + !dshInfo?.activeProfileIssue || + (dshInfo.activeProfileIssue === "missing" && + dshInfo.activeProfile === defaultDshProfile); + if (canProbeDsh) { + models = await probeStandardCatalog(id, command, dshInfo?.activeProfile).catch( + () => [], + ); + } + } return { id, name: harnessNames[id], @@ -47,6 +74,12 @@ async function discoverOne(id: Harness, refresh: boolean): Promise profile.name), + activeProfile: dshInfo.activeProfile, + } + : {}), models, ...(allModelsDenied ? { allModelsDenied } : {}), note: command @@ -58,14 +91,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..930e1dd 100644 --- a/runtime/commands.ts +++ b/runtime/commands.ts @@ -1,6 +1,15 @@ -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, + normalize, + resolve, + sep, +} from "node:path"; import { homedir } from "node:os"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; @@ -29,11 +38,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 { @@ -95,6 +174,89 @@ 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; + +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 + * `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]); + return dshInstallCommand(command, script); +} + async function cursorRuntime(): Promise { const root = join(homedir(), "AppData", "Local", "cursor-agent", "versions"); try { @@ -197,6 +359,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 { @@ -227,19 +391,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 === ".cmd") { + 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/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..fb2a095 --- /dev/null +++ b/runtime/dsh-migration.ts @@ -0,0 +1,1161 @@ +import { execFile } from "node:child_process"; +import { createHash, randomBytes } from "node:crypto"; +import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { isAbsolute, join, relative, resolve } 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, type Command } from "./commands"; +import { + inspectDshProfiles, + isTemporaryDryRunProfile, + normalizeDshProfile, + resolveDshHome, +} from "./dsh-profiles"; +import { + hasExplicitJsTag, + hasInlineSecret, + hasJsTag, + parseDshPatchYaml, + stringifyDshPatchYaml, +} from "./dsh-yaml"; + +const execFileAsync = promisify(execFile); +const STALE_DRYRUN_AGE_MS = 60 * 60 * 1000; +const DRYRUN_MARKER = ".memcode-dryrun"; +const DRYRUN_MARKER_TEXT = "memcode-dryrun\n"; +/** Every file `dsh plugin add` or a patch import can change, restored on rollback. */ +const PROFILE_FILES = [ + "package.json", + "cordis.patch.yml", + "pnpm-workspace.yaml", + "pnpm-lock.yaml", +] as const; +type ProfileFile = (typeof PROFILE_FILES)[number]; +type ProfileSnapshot = Map; + +export type StrictAcpProbe = (profile: string, command: Command) => Promise; + +/** + * What a successful dry-run verified. Apply accepts only this plan and refuses + * to mutate the profile when Desktop, the home patch, or the target changed. + */ +export interface DshMigrationPlan { + fingerprint: string; + targetProfile: string; + selectedIds: string[]; + /** Catalog entries the dry-run saw appear; apply must show every one. */ + expectedModelIds: string[]; +} + +interface DesktopPatchData { + piAiProviders: Map>; + pluginConfigRows: Map>; + homePatch: Buffer | null; + 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 readOptional(path: string): Promise { + try { + return await readFile(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } +} + +async function readJsonSafe(path: string): Promise> { + try { + const parsed = JSON.parse(await readFile(path, "utf8")); + return isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } +} + +async function readPatchStrict(path: string): Promise<{ entries: any[]; hasJsExpression: boolean }> { + const text = await readOptional(path); + return text === null ? { entries: [], hasJsExpression: false } : parseDshPatchYaml(text.toString("utf8")); +} + +async function readPatchSafe(path: string): Promise<{ entries: any[]; hasJsExpression: boolean }> { + try { + return await readPatchStrict(path); + } catch { + return { entries: [], hasJsExpression: false }; + } +} + +/** Snapshot every profile file; an unreadable existing file aborts instead of reading as absent. */ +async function readProfileSnapshot(profileDir: string): Promise { + const snapshot: ProfileSnapshot = new Map(); + for (const file of PROFILE_FILES) { + try { + snapshot.set(file, await readOptional(join(profileDir, file))); + } catch (error) { + throw new Error(`Cannot read existing profile file "${file}": ${extractErrorMessage(error)}`); + } + } + return snapshot; +} + +function isPiAiRow(entry: unknown): entry is Record { + return ( + isPlainObject(entry) && + (entry.id === "llm-pi-ai" || entry.name === "@deepseek-ai/dsh-llm-pi-ai") + ); +} + +/** + * The llm-pi-ai providers one patch layer sets. A row that sets `config` + * replaces the whole configuration of earlier layers and rows, so only the + * last such row counts. Providers under an explicitly `!!js`-tagged entry, + * config or providers container are never offered, but an untagged sibling of + * a tagged provider still is. + */ +function extractPiAiProviders(entries: unknown[]): { + providers: Map>; + tainted: boolean; + configured: boolean; +} { + let providers = new Map>(); + let tainted = false; + let configured = false; + for (const entry of entries) { + if (!isPiAiRow(entry)) continue; + if (hasExplicitJsTag(entry)) { + configured = true; + providers = new Map(); + tainted = true; + continue; + } + if (!Object.prototype.hasOwnProperty.call(entry, "config")) continue; + configured = true; + providers = new Map(); + tainted = false; + const config = entry.config; + if (!isPlainObject(config) || hasExplicitJsTag(config)) { + tainted = hasJsTag(entry); + continue; + } + const rawProviders = config.providers; + if (!isPlainObject(rawProviders) || hasExplicitJsTag(rawProviders)) { + tainted = hasJsTag(config); + continue; + } + for (const [providerId, providerConfig] of Object.entries(rawProviders)) { + if (isPlainObject(providerConfig)) providers.set(providerId, providerConfig); + } + } + return { providers, tainted, configured }; +} + +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, desktopDir: string): { + spec: string; + source: "registry" | "local-link"; + defaultSelected: boolean; + warning?: string; +} { + const trimmed = typeof rawSpec === "string" ? rawSpec.trim() : ""; + const local = /^(link|file):([\s\S]*)$/.exec(trimmed); + if (local) { + // dsh runs plugin commands inside the selected profile directory, so a + // relative path must be resolved against Desktop's profile, not copied. + const path = local[2]; + const absolute = isAbsolute(path) || /^[A-Za-z]:[\\/]/.test(path) || /^\\\\/.test(path); + return { + spec: `${local[1]}:${absolute ? path : resolve(desktopDir, path)}`, + 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); + const homePatchPath = join(dshHome, "cordis.patch.yml"); + let homePatchBytes: Buffer | null = null; + let homePatchUnreadable = false; + try { + homePatchBytes = await readOptional(homePatchPath); + } catch { + homePatchUnreadable = true; + } + + if (!(await isDirectory(desktopDir))) { + return { + piAiProviders: new Map(), + pluginConfigRows: new Map(), + homePatch: homePatchBytes, + diff: { + targetProfile: normalizedTarget, + desktopPresent: false, + providers: [], + skipped: [], + }, + }; + } + + let desktopPatch: { entries: any[]; hasJsExpression: boolean } = { entries: [], hasJsExpression: false }; + let desktopPatchUnsupported = false; + try { + desktopPatch = await readPatchStrict(join(desktopDir, "cordis.patch.yml")); + } catch { + desktopPatchUnsupported = true; + } + let homePatch: { entries: any[]; hasJsExpression: boolean } = { entries: [], hasJsExpression: false }; + let homePatchUnsupported = homePatchUnreadable; + try { + homePatch = homePatchBytes === null ? homePatch : parseDshPatchYaml(homePatchBytes.toString("utf8")); + } catch { + homePatchUnsupported = true; + } + const [desktopPkg, targetPatch, targetPkg] = await Promise.all([ + readJsonSafe(join(desktopDir, "package.json")), + readPatchSafe(join(targetDir, "cordis.patch.yml")), + readJsonSafe(join(targetDir, "package.json")), + ]); + + const providers: DshDesktopProviderCandidate[] = []; + const skipped: DshSkippedDesktopItem[] = []; + if (desktopPatchUnsupported) { + skipped.push({ + name: "cordis.patch.yml", + reason: "Desktop cordis.patch.yml uses unsupported YAML syntax and was skipped.", + }); + } + const piAiProviders = new Map>(); + const pluginConfigRows = new Map>(); + + const desktopPiAi = extractPiAiProviders(desktopPatch.entries); + // dsh composes the profile patch first and the home patch last; a home row + // that sets llm-pi-ai's config replaces the profile's provider list. + const homePiAi = extractPiAiProviders(homePatch.entries); + const effective = homePiAi.configured ? homePiAi : extractPiAiProviders(targetPatch.entries); + const existingModels = new Map>(); + for (const [providerId, cfg] of effective.providers) { + existingModels.set(providerId, new Set(extractModelIds(cfg))); + } + const maskedReason = homePatchUnsupported + ? `${homePatchPath} could not be read or uses unsupported YAML, so MemCode cannot tell whether it replaces this profile's providers.` + : homePiAi.configured + ? `${homePatchPath} sets llm-pi-ai for every profile and would hide this import. Add the provider there instead.` + : undefined; + + 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; + if (maskedReason) { + skipped.push({ name: providerId, reason: maskedReason }); + 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], + desktopDir, + ); + 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, + homePatch: homePatchBytes, + 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; +} + +/** Every selected id must still be offered; stale or unknown ids are refused, never skipped. */ +function staleSelections(selectedIds: string[], data: DesktopPatchData): DshProviderFailure[] { + const offered = new Set(data.diff.providers.map((p) => p.id)); + return selectedIds + .filter((id) => !offered.has(id)) + .map((id) => ({ + id, + name: id.replace(/^(?:pi-ai|plugin):/, ""), + reason: "No longer offered by DeepSeek Harness Desktop. Reload the provider list and test again.", + })); +} + +function hashBytes(bytes: Buffer | null): string | null { + return bytes === null ? null : createHash("sha256").update(bytes).digest("hex"); +} + +/** Binds a plan to the exact Desktop sources, home patch and target files it tested. */ +function migrationFingerprint( + targetProfile: string, + selectedIds: string[], + data: DesktopPatchData, + snapshot: ProfileSnapshot, +): string { + const byId = new Map(data.diff.providers.map((p) => [p.id, p])); + const sources = [...selectedIds].sort().map((id) => { + const candidate = byId.get(id); + const providerId = candidate?.providerId ?? id; + return { + id, + spec: candidate?.spec ?? null, + models: candidate?.missingModels ?? candidate?.models ?? null, + config: data.piAiProviders.get(providerId) ?? data.pluginConfigRows.get(providerId) ?? null, + }; + }); + return createHash("sha256") + .update( + JSON.stringify({ + targetProfile, + sources, + home: hashBytes(data.homePatch), + files: PROFILE_FILES.map((file) => [file, hashBytes(snapshot.get(file) ?? null)]), + }), + ) + .digest("hex"); +} + +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].reverse().find( + (entry) => isPiAiRow(entry) && Object.prototype.hasOwnProperty.call(entry, "config"), + ) ?? entries.find((entry) => isPiAiRow(entry)); + 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 runDshPlugin( + command: Command, + profileName: string, + args: string[], + dshHome: string, + env: NodeJS.ProcessEnv, + timeout = 120_000, +): Promise { + await execFileAsync( + command.command, + [...command.prefix, "plugin", "--profile", profileName, ...args], + { + shell: false, + windowsHide: true, + timeout, + maxBuffer: 10 * 1024 * 1024, + encoding: "utf8", + env: buildDshEnv(dshHome, command, env), + }, + ); +} + +/** Reinstall a profile's dependency tree from its manifest and lockfile, as `dsh plugin` repairs it. */ +function installArgs(hasLockfile: boolean): string[] { + return ["install", hasLockfile ? "--frozen-lockfile" : "--config.lockfile=false"]; +} + +function hasDependencies(pkg: Buffer | null | undefined): boolean { + if (!pkg) return false; + try { + const parsed = JSON.parse(pkg.toString("utf8")); + return isPlainObject(parsed?.dependencies) && Object.keys(parsed.dependencies).length > 0; + } catch { + return false; + } +} + +async function applySelectedToProfileDir( + command: Command, + profileName: string, + profileDir: string, + selectedIds: string[], + data: DesktopPatchData, + dshHome: string, + env: NodeJS.ProcessEnv, + progress?: { pluginStart?: (id: string, pkgName: string) => void; pluginsDone?: () => void }, +): Promise { + const patchPath = join(profileDir, "cordis.patch.yml"); + const currentPatch = await readPatchStrict(patchPath); + if (currentPatch.hasJsExpression) { + throw new Error( + "Target profile cordis.patch.yml contains !!js expressions and cannot be modified safely.", + ); + } + + 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.`); + } + progress?.pluginStart?.(id, candidate.name); + await runDshPlugin(command, profileName, ["add", candidate.spec ?? candidate.providerId], dshHome, env); + } + progress?.pluginsDone?.(); + + 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 { + // Only a directory MemCode created and marked is ever removed. + const marker = await readFile(join(dir, DRYRUN_MARKER), "utf8").catch(() => null); + if (marker !== DRYRUN_MARKER_TEXT) continue; + 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), + }; +} + +/** The provider a dsh catalog entry belongs to: ACP values are JSON `[provider, model]`. */ +function catalogEntry(model: ModelOption): { provider?: string; model: string } { + try { + const parsed = JSON.parse(model.id); + if (Array.isArray(parsed) && parsed.length === 2 && parsed.every((part) => typeof part === "string")) + return { provider: parsed[0], model: parsed[1] }; + } catch { + /* Not a dsh provider tuple. */ + } + return { provider: model.group, model: model.id }; +} + +function sameProvider(provider: string | undefined, providerId: string): boolean { + return ( + provider === providerId || + !!provider?.endsWith(`:${providerId}`) || + !!provider?.endsWith(`/${providerId}`) + ); +} + +/** + * Check that each selected provider really contributes to the catalog: a + * pi-ai provider must list every model it was imported for, and a plugin must + * add at least one model from a provider the baseline did not have. + */ +function unmetExpectations( + ids: string[], + data: DesktopPatchData, + baseline: ModelOption[], + after: ModelOption[], +): DshProviderFailure[] { + const byId = new Map(data.diff.providers.map((p) => [p.id, p])); + const entries = after.map((model) => ({ id: model.id, ...catalogEntry(model) })); + const baselineIds = new Set(baseline.map((model) => model.id)); + const baselineProviders = new Set(baseline.map((model) => catalogEntry(model).provider)); + const piAiProviders = ids + .filter((id) => id.startsWith("pi-ai:")) + .map((id) => byId.get(id)?.providerId ?? id.slice("pi-ai:".length)); + const failures: DshProviderFailure[] = []; + for (const id of ids) { + const candidate = byId.get(id); + if (!candidate) continue; + if (candidate.kind === "pi-ai") { + const expected = candidate.missingModels ?? candidate.models; + const listed = (modelId?: string) => + entries.some((entry) => { + if (modelId !== undefined && entry.model !== modelId) return false; + // An entry without provider identity can only vouch for a named model. + if (entry.provider === undefined) return modelId !== undefined; + return sameProvider(entry.provider, candidate.providerId) || entry.provider === candidate.name; + }); + const missing = expected.length ? expected.filter((modelId) => !listed(modelId)) : listed() ? [] : ["any model"]; + if (missing.length) + failures.push({ + id, + name: candidate.name, + reason: `DeepSeek Harness did not list ${missing.join(", ")} for this provider after the import. Check its configuration and API key environment variable in Desktop.`, + }); + } + } + const plugins = ids.filter((id) => byId.get(id)?.kind === "plugin"); + if (plugins.length) { + const added = new Set( + entries + .filter( + (entry) => + !baselineIds.has(entry.id) && + !baselineProviders.has(entry.provider) && + !piAiProviders.some((providerId) => sameProvider(entry.provider, providerId)), + ) + .map((entry) => entry.provider ?? entry.id), + ); + if (added.size < plugins.length) + for (const id of plugins) + failures.push({ + id, + name: byId.get(id)?.name ?? id, + reason: + plugins.length === 1 + ? "The plugin installed, but DeepSeek Harness listed no new models from it. Configure its provider in Desktop first." + : `The selected plugins added models from ${added.size} new provider${added.size === 1 ? "" : "s"}, not ${plugins.length}.`, + }); + } + return failures; +} + +function defaultProbe(options?: { probe?: StrictAcpProbe }): StrictAcpProbe { + return ( + options?.probe ?? + ((profile, cmd) => + probeStandardCatalog("dsh", cmd, profile, { strictStdout: true, allowStaging: true })) + ); +} + +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 = defaultProbe(options); + const ids = [...new Set(selectedIds)]; + + if (ids.length === 0) { + const previewModels = await probe(normalizedTarget, probeCmd); + return { + ok: true, + targetProfile: normalizedTarget, + passedIds: [], + failed: [], + previewModels, + }; + } + + const profileFailure = (reason: string): DshDryRunResult => ({ + ok: false, + targetProfile: normalizedTarget, + passedIds: [], + failed: [{ id: `profile:${normalizedTarget}`, name: normalizedTarget, reason }], + previewModels: [], + error: reason, + }); + + // The fingerprint and every staging copy come from the same bytes. + let snapshot: ProfileSnapshot; + try { + snapshot = await readProfileSnapshot(targetDir); + } catch (error) { + return profileFailure(extractErrorMessage(error)); + } + const data = await computeDesktopDiff(normalizedTarget, env); + const stale = staleSelections(ids, data); + if (stale.length) { + return { + ok: false, + targetProfile: normalizedTarget, + passedIds: [], + failed: stale, + previewModels: [], + error: "Some selected providers are no longer offered by DeepSeek Harness Desktop.", + }; + } + const candidateMap = new Map(data.diff.providers.map((p) => [p.id, p])); + const targetHasDependencies = hasDependencies(snapshot.get("package.json")); + + const runStaging = async (stagedIds: string[]): Promise => { + const stagingName = `memcode-dryrun-${randomBytes(4).toString("hex")}`; + const stagingDir = join(profilesDir, stagingName); + await mkdir(stagingDir, { recursive: true }); + await writeFile(join(stagingDir, DRYRUN_MARKER), DRYRUN_MARKER_TEXT, "utf8"); + try { + for (const [file, content] of snapshot) { + if (content !== null) await writeFile(join(stagingDir, file), content); + } + // A profile's third-party bundles load from its own node_modules. Build + // an independent tree in staging; `plugin add` installs it as well. + if (targetHasDependencies && !stagedIds.some((id) => id.startsWith("plugin:"))) { + await runDshPlugin( + command, + stagingName, + installArgs(snapshot.get("pnpm-lock.yaml") != null), + dshHome, + env, + ); + } + if (stagedIds.length > 0) { + await applySelectedToProfileDir(command, stagingName, stagingDir, stagedIds, data, dshHome, env); + } + return await probe(stagingName, probeCmd); + } finally { + await rm(stagingDir, { recursive: true, force: true }).catch(() => {}); + } + }; + + // An already broken profile is a profile failure, never blamed on providers. + let baseline: ModelOption[]; + try { + baseline = await runStaging([]); + } catch (baselineError) { + return profileFailure( + `Existing ACP profile failed validation before applying Desktop providers: ${extractErrorMessage(baselineError)}`, + ); + } + + const attempt = async (stagedIds: string[]): Promise<{ models: ModelOption[]; failures: DshProviderFailure[] }> => { + const models = await runStaging(stagedIds); + return { models, failures: unmetExpectations(stagedIds, data, baseline, models) }; + }; + + let combinedError: string; + try { + const combined = await attempt(ids); + if (combined.failures.length === 0) { + const baselineIds = new Set(baseline.map((model) => model.id)); + return { + ok: true, + targetProfile: normalizedTarget, + passedIds: ids, + failed: [], + previewModels: combined.models, + plan: { + fingerprint: migrationFingerprint(normalizedTarget, ids, data, snapshot), + targetProfile: normalizedTarget, + selectedIds: ids, + expectedModelIds: combined.models + .map((model) => model.id) + .filter((id) => !baselineIds.has(id)), + }, + }; + } + combinedError = combined.failures.map((failure) => `${failure.name}: ${failure.reason}`).join(" "); + } catch (error) { + combinedError = extractErrorMessage(error); + } + + const passedIds: string[] = []; + const failed: DshProviderFailure[] = []; + for (const id of ids) { + const candidate = candidateMap.get(id); + try { + const single = await attempt([id]); + if (single.failures.length) failed.push(...single.failures); + else passedIds.push(id); + } catch (error) { + failed.push({ + id, + name: candidate?.name ?? id, + reason: extractErrorMessage(error), + }); + } + } + const combinationError = + failed.length === 0 + ? `Selected providers passed individually but failed when combined: ${combinedError}` + : undefined; + return { + ok: false, + targetProfile: normalizedTarget, + passedIds, + failed, + previewModels: [], + ...(combinationError ? { error: combinationError } : {}), + }; +} + +export interface DshApplyResult { + ok: boolean; + appliedIds: string[]; + failed: DshProviderFailure[]; + models: ModelOption[]; + error?: string; + /** False when rollback could not restore the profile; it may need manual recovery. */ + restored?: boolean; +} + +export async function applyDshMigration( + command: Command, + plan: DshMigrationPlan, + options?: { env?: NodeJS.ProcessEnv; probe?: StrictAcpProbe }, +): Promise { + const env = options?.env ?? process.env; + const { dshHome, normalizedTarget, targetDir } = await assertExistingAcpProfile(plan.targetProfile, env); + const probeCmd = withDshHomeCommand(command, dshHome, env); + const probe = defaultProbe(options); + const selectedIds = plan.selectedIds; + const profileId = `profile:${normalizedTarget}`; + const refuse = (reason: string): DshApplyResult => ({ + ok: false, + appliedIds: [], + failed: [{ id: profileId, name: normalizedTarget, reason }], + models: [], + error: reason, + restored: true, + }); + + if (normalizedTarget !== plan.targetProfile || selectedIds.length === 0) + return refuse("Test the selected providers before importing them."); + + let snapshots: ProfileSnapshot; + try { + snapshots = await readProfileSnapshot(targetDir); + } catch (error) { + return refuse(`${extractErrorMessage(error)}. The profile was not modified.`); + } + const data = await computeDesktopDiff(normalizedTarget, env); + if ( + staleSelections(selectedIds, data).length > 0 || + migrationFingerprint(normalizedTarget, selectedIds, data, snapshots) !== plan.fingerprint + ) + return refuse( + "DeepSeek Harness Desktop or this profile changed after the dry-run. Test the selected providers again before importing them.", + ); + const candidateMap = new Map(data.diff.providers.map((p) => [p.id, p])); + + 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 isDirectory(join(targetDir, "node_modules", ...pkgName.split("/")))) { + preExistingPlugins.add(pkgName); + } + } + + // A failure is the profile's until a specific plugin is being installed. + let activeId = profileId; + let activeName = normalizedTarget; + let dependenciesTouched = false; + try { + await applySelectedToProfileDir( + command, + normalizedTarget, + targetDir, + selectedIds, + data, + dshHome, + env, + { + pluginStart: (id, name) => { + activeId = id; + activeName = candidateMap.get(id)?.name ?? name; + dependenciesTouched = true; + }, + pluginsDone: () => { + activeId = profileId; + activeName = normalizedTarget; + }, + }, + ); + const models = await probe(normalizedTarget, probeCmd); + const listed = new Set(models.map((model) => model.id)); + const missing = plan.expectedModelIds.filter((id) => !listed.has(id)); + if (missing.length > 0) + throw new Error( + `After the import DeepSeek Harness did not list ${missing.length} model${missing.length === 1 ? "" : "s"} the dry-run verified: ${missing.join(", ")}.`, + ); + return { + ok: true, + appliedIds: [...selectedIds], + failed: [], + models, + }; + } catch (error) { + const rollbackErrors: string[] = []; + for (const [file, content] of snapshots) { + const path = join(targetDir, file); + try { + if (content === null) { + await rm(path, { force: true }); + } else { + await writeFile(path, content); + } + } catch (rbError) { + rollbackErrors.push(`${file}: ${extractErrorMessage(rbError)}`); + } + } + if (dependenciesTouched) { + for (const pkgName of selectedPlugins) { + if (!preExistingPlugins.has(pkgName)) { + try { + await rm(join(targetDir, "node_modules", ...pkgName.split("/")), { + recursive: true, + force: true, + }); + } catch (rbError) { + rollbackErrors.push(`node_modules/${pkgName}: ${extractErrorMessage(rbError)}`); + } + } + } + // `plugin add` can also change existing and transitive dependencies. + // Reinstall the restored lockfile, as dsh itself does after a rejected add. + if (rollbackErrors.length === 0) { + try { + await runDshPlugin( + command, + normalizedTarget, + installArgs(snapshots.get("pnpm-lock.yaml") != null), + dshHome, + env, + 300_000, + ); + } catch (rbError) { + rollbackErrors.push( + `node_modules could not be reinstalled (${extractErrorMessage(rbError)}); run "dsh plugin --profile ${normalizedTarget} install"`, + ); + } + } + } + const reason = extractErrorMessage(error); + if (rollbackErrors.length > 0) { + const recoveryDir = join( + dshHome, + "memcode-recovery", + `${normalizedTarget}-${Date.now()}-${randomBytes(3).toString("hex")}`, + ); + let recoveryNote = ""; + try { + await mkdir(recoveryDir, { recursive: true }); + for (const [file, content] of snapshots) { + if (content !== null) { + await writeFile(join(recoveryDir, file), content); + } + } + recoveryNote = ` Recovery snapshots saved to ${recoveryDir}.`; + } catch (backupError) { + recoveryNote = ` Could not write recovery snapshots (${extractErrorMessage(backupError)}).`; + } + const fullError = `Migration failed (${reason}) and rollback could not restore all files (${rollbackErrors.join("; ")}).${recoveryNote}`; + return { + ok: false, + appliedIds: [], + failed: [{ id: activeId, name: activeName, reason: fullError }], + models: [], + error: fullError, + restored: false, + }; + } + return { + ok: false, + appliedIds: [], + failed: [ + { + id: activeId, + name: activeName, + reason, + }, + ], + models: [], + error: reason, + restored: true, + }; + } +} diff --git a/runtime/dsh-profiles.ts b/runtime/dsh-profiles.ts new file mode 100644 index 0000000..cb3e2ce --- /dev/null +++ b/runtime/dsh-profiles.ts @@ -0,0 +1,262 @@ +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, + options?: { allowStaging?: boolean }, +): 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 (!options?.allowStaging && isTemporaryDryRunProfile(trimmed)) { + throw new Error(`Profile name "${trimmed}" is reserved for MemCode temporary dry-run staging.`); + } + 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); +} + +/** A directory name MemCode can pass to `dsh --profile` as a user profile. */ +function isSelectableProfileName(name: string): boolean { + try { + return normalizeDshProfile(name) === name; + } catch { + return false; + } +} + +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; + // Desktop, node_modules, staging and names dsh cannot be given (such as + // "acp copy" or "_backup") are never offered or selected automatically. + if (!isSelectableProfileName(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, + }; + } + + // An existing "acp" directory that is not ACP must not be launched as one. + const defaultIsNonAcp = nonAcpProfiles.some((p) => p.name === defaultDshProfile); + return { + dshHome, + activeProfile: defaultDshProfile, + ...(defaultIsNonAcp ? { activeProfileIssue: "non-acp" as const } : {}), + 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-setup-gate.ts b/runtime/dsh-setup-gate.ts new file mode 100644 index 0000000..3773dd9 --- /dev/null +++ b/runtime/dsh-setup-gate.ts @@ -0,0 +1,73 @@ +/** + * Coordinates DeepSeek Harness setup changes with the separate dsh processes + * that read the profile. Setup does not start while a dsh reviewer or planner + * runs, and none of them starts while setup may be rewriting the profile. + * Shutdown waits for a running setup so its verification or rollback finishes. + */ +export class DshSetupGate { + private current: { operation: string; mutates: boolean; done: Promise } | null = null; + private readers = 0; + private closed = false; + + /** The setup operation in progress, if any. */ + get operation(): string | null { + return this.current?.operation ?? null; + } + + /** Whether the running operation may rewrite the profile or the CLI. */ + get mutating(): boolean { + return this.current?.mutates === true; + } + + /** + * Admit one dsh process that reads the profile. Call the returned function + * once the process has exited. + */ + admit(activity = "review"): () => void { + if (this.mutating) + throw new Error( + `Wait for DeepSeek Harness setup to finish before starting a DeepSeek Harness ${activity}.`, + ); + this.readers++; + let released = false; + return () => { + if (released) return; + released = true; + this.readers--; + }; + } + + /** + * Run one setup operation. Operations never overlap; one that `mutates` + * also waits for no dsh reader and keeps new readers out until it settles. + */ + async run( + operation: string, + fn: () => Promise, + { mutates = true }: { mutates?: boolean } = {}, + ): Promise { + if (this.closed) throw new Error("MemCode is shutting down. Try again after it restarts."); + if (this.current) + throw new Error( + "Another DeepSeek Harness setup operation is already in progress. Wait for it to finish.", + ); + if (mutates && this.readers > 0) + throw new Error( + "Wait for the DeepSeek Harness review or plan in progress to finish before changing its setup.", + ); + let settle!: () => void; + this.current = { operation, mutates, done: new Promise((resolve) => (settle = resolve)) }; + try { + return await fn(); + } finally { + this.current = null; + settle(); + } + } + + /** Refuse new setup operations and wait for a running one to finish. */ + async close(): Promise { + this.closed = true; + while (this.current) await this.current.done; + } +} diff --git a/runtime/dsh-yaml.ts b/runtime/dsh-yaml.ts new file mode 100644 index 0000000..d652159 --- /dev/null +++ b/runtime/dsh-yaml.ts @@ -0,0 +1,842 @@ +/** Set on a value that is itself tagged `!!js`, or that contains one that is. */ +const JS_EXPR = Symbol("dsh.jsExpression"); +/** Set only on a collection that carries an explicit `!!js` tag of its own. */ +const JS_EXPLICIT = Symbol("dsh.jsExplicitTag"); + +function markJsExpr(value: T): T { + if (value && typeof value === "object") { + Object.defineProperty(value, JS_EXPR, { value: true, enumerable: false, configurable: true }); + } + return value; +} + +function markExplicitJs(value: T): T { + if (value && typeof value === "object") { + markJsExpr(value); + Object.defineProperty(value, JS_EXPLICIT, { 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)); +} + +/** + * Whether this collection itself was written with an explicit `!!js` tag. + * Unlike {@link hasJsTag}, a marker propagated from a tagged descendant does + * not count, so safe siblings of a tagged value stay distinguishable. + */ +export function hasExplicitJsTag(value: unknown): boolean { + return ( + !!value && + typeof value === "object" && + (value as Record)[JS_EXPLICIT] === true + ); +} + +const SECRET_VALUE_RE = /^(?:Bearer|Basic)\s+\S+/i; +const SECRET_HEAD_WORDS = new Set([ + "secret", + "password", + "passwd", + "passphrase", + "pwd", + "token", + "authorization", + "auth", + "cookie", + "cookies", + "credential", + "credentials", + "apikey", + "privatekey", +]); +const SECRET_KEY_QUALIFIERS = new Set([ + "api", + "private", + "access", + "secret", + "signing", + "session", + "encryption", + "client", + "license", + "subscription", +]); + +function keyWords(key: string): string[] { + return key + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter(Boolean); +} + +/** + * A key whose value is itself a credential. The head noun decides, so + * `accessToken` and `privateKey` count while `maxTokens`, `tokenLimit` and the + * `apiKeyEnv` indirection (the name of an environment variable) do not. + */ +function isCredentialKey(key: string): boolean { + const words = keyWords(key); + const head = words.at(-1); + if (!head || head === "env") return false; + if (SECRET_HEAD_WORDS.has(head)) return true; + return head === "key" && (words.length === 1 || SECRET_KEY_QUALIFIERS.has(words[words.length - 2])); +} + +function hasNonEmptyCredentialValue(value: unknown): boolean { + if (typeof value === "string") return value.trim().length > 0; + if (typeof value === "number" || typeof value === "bigint") return true; + if (typeof value === "boolean") return value; + if (Array.isArray(value)) return value.some((item) => hasNonEmptyCredentialValue(item)); + if (value && typeof value === "object") { + return Object.values(value).some((item) => hasNonEmptyCredentialValue(item)); + } + return false; +} + +export function hasInlineSecret(obj: unknown): boolean { + if (typeof obj === "string") return SECRET_VALUE_RE.test(obj.trim()); + 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 (isCredentialKey(key) && hasNonEmptyCredentialValue(value)) 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, allowTightQuotedColon = false): number { + let quote: "'" | '"' | null = null; + let depth = 0; + let justClosedQuote = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (quote === "'") { + if (ch === "'") { + if (text[i + 1] === "'") i++; + else { + quote = null; + justClosedQuote = depth === 0; + } + } + continue; + } + if (quote === '"') { + if (ch === "\\") { + i++; + continue; + } + if (ch === '"') { + quote = null; + justClosedQuote = depth === 0; + } + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + justClosedQuote = false; + continue; + } + if (ch === "[" || ch === "{") { + depth++; + justClosedQuote = false; + } else if ((ch === "]" || ch === "}") && depth > 0) { + depth--; + justClosedQuote = false; + } else if ( + ch === ":" && + depth === 0 && + (i + 1 === text.length || /\s/.test(text[i + 1]) || (allowTightQuotedColon && justClosedQuote)) + ) { + return i; + } else if (!/\s/.test(ch)) { + justClosedQuote = false; + } + } + return -1; +} + +/** + * A quoted scalar, or `undefined` when the text is not one. Text that opens a + * quote without being exactly one quoted scalar is rejected rather than read as + * a plain string that dsh would parse differently. + */ +function quotedScalar(trimmed: string): string | undefined { + const quote = trimmed[0]; + if (quote !== "'" && quote !== '"') return undefined; + const inner = trimmed.slice(1, -1); + if (trimmed.length >= 2 && trimmed.endsWith(quote)) { + if (quote === "'" && !/'/.test(inner.replace(/''/g, ""))) return inner.replace(/''/g, "'"); + if (quote === '"' && !/"/.test(inner.replace(/\\[\s\S]/g, ""))) return unescapeDoubleQuoted(inner); + } + throw new Error("Unsupported multi-line or malformed quoted YAML scalar in cordis.patch.yml."); +} + +const ESCAPES: Readonly> = { + "0": "\0", + a: "\x07", + b: "\b", + t: "\t", + "\t": "\t", + n: "\n", + v: "\v", + f: "\f", + r: "\r", + e: "\x1b", + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + N: "\x85", + _: "\xa0", + L: "\u2028", + P: "\u2029", +}; + +function unescapeDoubleQuoted(raw: string): string { + return raw.replace(/\\(x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|[\s\S])/g, (_, seq: string) => { + if (seq.length === 1) { + if (Object.prototype.hasOwnProperty.call(ESCAPES, seq)) return ESCAPES[seq]; + throw new Error(`Unsupported YAML escape "\\${seq}" in cordis.patch.yml.`); + } + const code = Number.parseInt(seq.slice(1), 16); + if (code > 0x10ffff) throw new Error("Invalid YAML unicode escape in cordis.patch.yml."); + return String.fromCodePoint(code); + }); +} + +/** + * Resolve a plain (unquoted) scalar the way dsh's YAML 1.2 core schema does, + * so a value keeps its type when MemCode rewrites the patch. Plain forms whose + * type MemCode cannot reproduce exactly are refused instead of guessed. + */ +function resolvePlain(text: string): unknown { + if (text === "" || /^(?:~|null|Null|NULL)$/.test(text)) return null; + if (/^(?:true|True|TRUE)$/.test(text)) return true; + if (/^(?:false|False|FALSE)$/.test(text)) return false; + if (/^[-+]?[0-9]+$/.test(text)) return Number(text); + const radix = /^([-+]?)0(x[0-9a-fA-F]+|o[0-7]+|b[01]+)$/.exec(text); + if (radix) { + const value = Number.parseInt(radix[2].slice(1), { x: 16, o: 8, b: 2 }[radix[2][0] as "x" | "o" | "b"]); + return radix[1] === "-" ? -value : value; + } + if (/^[-+]?[0-9]+(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/.test(text) || /^\.[0-9]+(?:[eE][-+]?[0-9]+)?$/.test(text)) { + return Number(text); + } + if (/^[-+]?\.(?:inf|Inf|INF)$/.test(text)) return text.startsWith("-") ? -Infinity : Infinity; + if (/^\.(?:nan|NaN|NAN)$/.test(text)) return Number.NaN; + // Underscore digit separators and timestamps load as numbers or dates in + // dsh, with edge rules MemCode does not reproduce. + if ( + (text.includes("_") && + (/^[-+]?[0-9][0-9_]*(?:\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?$/.test(text) || + /^\.[0-9_]+(?:[eE][-+]?[0-9]+)?$/.test(text) || + /^[-+]?0[xob][0-9a-fA-F_]+$/.test(text))) || + /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}(?:$|[Tt ])/.test(text) + ) { + throw new Error(`Unsupported YAML scalar "${text}" in cordis.patch.yml.`); + } + return text; +} + +function unquoteKey(raw: string): string { + const trimmed = raw.trim(); + const quoted = quotedScalar(trimmed); + if (quoted !== undefined) return quoted; + // dsh resolves a plain key's type first and then uses its string form. + const resolved = resolvePlain(trimmed); + return resolved === null ? "null" : String(resolved); +} + +function assertSupportedYamlToken(trimmed: string): void { + if (/^&[^\s,\]}]+/.test(trimmed) || /^\*[^\s,\]}]+/.test(trimmed)) { + throw new Error("YAML anchors and aliases are not supported in cordis.patch.yml."); + } + if (/^![^!]|^!!(?!js(?:\/[A-Za-z0-9_-]+)?(?:\s|$))/i.test(trimmed)) { + throw new Error("Unsupported YAML tag in cordis.patch.yml."); + } +} + +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 }; + } + assertSupportedYamlToken(trimmed); + const quoted = quotedScalar(trimmed); + if (quoted !== undefined) return { value: quoted, taggedJs }; + return { value: resolvePlain(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(); + } + const mark = (value: T, anyJs: boolean): T => + taggedJs ? markExplicitJs(value) : anyJs ? markJsExpr(value) : value; + if (trimmed.startsWith("[") && trimmed.endsWith("]")) { + const inner = trimmed.slice(1, -1).trim(); + if (!inner) { + const arr: unknown[] = []; + return { value: mark(arr, false), 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: mark(arr, anyJs), taggedJs: anyJs }; + } + if (trimmed.startsWith("{") && trimmed.endsWith("}")) { + const inner = trimmed.slice(1, -1).trim(); + const obj: Record = {}; + if (!inner) return { value: mark(obj, false), taggedJs }; + let anyJs = taggedJs; + for (const part of splitFlowItems(inner)) { + const colon = findUnquotedColon(part, true); + if (colon === -1) { + throw new Error("Unsupported or malformed YAML flow mapping entry in cordis.patch.yml."); + } + const key = unquoteKey(part.slice(0, colon)); + if (key === "<<") { + throw new Error("YAML merge keys are not supported in cordis.patch.yml."); + } + const res = parseFlow(part.slice(colon + 1), ctx); + if (res.taggedJs) anyJs = true; + obj[key] = res.value; + } + return { value: mark(obj, anyJs), taggedJs: anyJs }; + } + const scalar = parseScalar(trimmed, ctx); + return { value: scalar.value, taggedJs: taggedJs || scalar.taggedJs }; +} + +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 contentLines = rawLines.slice(0, rawLines.length - trailingEmpty); + + let body: string; + if (style === "|") { + body = contentLines.join("\n"); + } else { + // Folding joins two adjacent normal lines with a space. A line that is + // more indented keeps its surrounding line breaks, and each empty line + // between two normal lines stands for one line break. + let previous: "normal" | "more" | null = null; + let empty = 0; + body = ""; + for (const line of contentLines) { + if (line === "") { + empty++; + continue; + } + const kind = /^[ \t]/.test(line) ? "more" : "normal"; + if (previous === null) body += "\n".repeat(empty); + else if (previous === "normal" && kind === "normal") body += empty ? "\n".repeat(empty) : " "; + else body += "\n".repeat(empty + 1); + body += line; + previous = kind; + empty = 0; + } + } + + if (contentLines.length === 0) return chomp === "+" ? "\n".repeat(trailingEmpty) : ""; + if (chomp === "-") return body; + return body + "\n" + (chomp === "+" ? "\n".repeat(trailingEmpty) : ""); + } + + 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; + } + if (!isFlowComplete(acc)) { + throw new Error("Incomplete YAML flow collection in cordis.patch.yml."); + } + return acc; + } + + private parseValue(rawVal: string, parentIndent: number): { value: unknown; taggedJs: boolean } { + const val = rawVal.trim(); + assertSupportedYamlToken(val); + 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: markExplicitJs(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: markExplicitJs(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) { + if (seed.key === "<<") { + throw new Error("YAML merge keys are not supported in cordis.patch.yml."); + } + 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)); + if (key === "<<") { + throw new Error("YAML merge keys are not supported in cordis.patch.yml."); + } + 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 }; + } + + parseTopLevel(): { value: unknown; taggedJs: boolean } { + let next = this.peekContent(); + if (!next) return { value: [], taggedJs: false }; + if (next.text === "---") { + this.index++; + next = this.peekContent(); + if (!next) return { value: [], taggedJs: false }; + } + if (next.text === "...") { + this.index++; + if (this.peekContent() !== null) { + throw new Error("Multiple YAML documents are not supported in cordis.patch.yml."); + } + return { value: [], taggedJs: false }; + } + const parsed = this.parseBlock(); + const trailing = this.peekContent(); + if (trailing?.text === "...") { + this.index++; + if (this.peekContent() !== null) { + throw new Error("Incomplete or unsupported YAML in cordis.patch.yml."); + } + } else if (trailing !== null) { + throw new Error("Incomplete or unsupported YAML in cordis.patch.yml."); + } + if (!Array.isArray(parsed.value)) { + throw new Error("Expected a top-level YAML list in cordis.patch.yml."); + } + return parsed; + } + + 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.parseTopLevel(); + return { entries: parsed.value as any[], hasJsExpression: parser.hasJsExpression }; +} + +/** Whether a plain (unquoted) spelling would load back as this exact string. */ +function plainKeepsString(text: string): boolean { + // YAML 1.1 booleans are strings under dsh's core schema; quote them anyway + // so no older reader turns them into booleans. + if (/^(?:y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF|<<|=)$/.test(text)) return false; + try { + return resolvePlain(text) === text; + } catch { + return false; + } +} + +function needsQuotes(text: string): boolean { + if (text === "") return true; + if (/^\s|\s$/.test(text)) return true; + if (!plainKeepsString(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) && !needsQuotes(key)) return key; + return formatString(key); +} + +const DOUBLE_QUOTED_ESCAPES: Readonly> = { + "\\": "\\\\", + '"': '\\"', + "\0": "\\0", + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\v": "\\v", + "\f": "\\f", + "\r": "\\r", +}; + +function formatString(value: string): string { + // Control and other non-printable characters are only safe escaped. + if (/[\x00-\x1f\x7f-\x9f\u2028\u2029\ufeff]/.test(value)) { + return `"${value.replace( + /[\x00-\x1f\x7f-\x9f"\\\u2028\u2029\ufeff]/g, + (ch) => DOUBLE_QUOTED_ESCAPES[ch] ?? `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`, + )}"`; + } + 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") return String(value); + if (typeof value === "number") { + if (Number.isNaN(value)) return ".nan"; + if (value === Infinity) return ".inf"; + if (value === -Infinity) return "-.inf"; + if (Object.is(value, -0)) return "-0.0"; + 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/goal-planner.ts b/runtime/goal-planner.ts index 9f7e800..8101a9a 100644 --- a/runtime/goal-planner.ts +++ b/runtime/goal-planner.ts @@ -5,6 +5,7 @@ import type { Command } from "./commands"; import { approvedHarnessCommand, askInCapsule, + type ReviewAgentOptions, } from "./review-agent"; type Register = ( @@ -24,6 +25,7 @@ export interface GoalPlannerDependencies { relatedFiles: (projectId: string, request: string) => Promise; resolveCommand?: (harness: Harness) => Promise; ask?: typeof askInCapsule; + reviewOptions?: Pick; } const maximumTasks = 5; @@ -125,7 +127,7 @@ export class GoalPlanner { `${readInstruction} for the planning context, then answer with the goal plan as JSON only.`, hooks: {}, }, - { policy: planningPolicy }, + { ...this.deps.reviewOptions, policy: planningPolicy }, ); return { ...readGoalPlan(answer.text, input.request), 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..13d5d2e 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,12 @@ export interface ReviewAgentOptions { policy?: string; modelPinned?: boolean; localModel?: boolean; + dshProfile?: string; + /** + * Admits a dsh reader process while no setup operation rewrites its + * profile; returns the release to call once the process has exited. + */ + dshAdmission?: () => () => void; commandFor?: typeof findCommand; /** Test transport injection; product callers use the installed approved CLI. */ spawn?: typeof spawn; @@ -735,7 +742,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 +1244,30 @@ 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") { + // A dsh reader must not start while setup may be rewriting its profile, + // and setup must not start while it reads; admission covers both. + const release = harness === "dsh" ? options.dshAdmission?.() : undefined; + try { + 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 } : {}), + }); + } finally { + release?.(); + } + } 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..da6d1f6 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,12 +239,15 @@ 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, private readonly teamClaims?: TeamWorkerClaims, - private readonly assertAccountSession?: () => void, + private readonly assertAccountSession?: (harness?: WorkItem["harness"]) => void, private readonly mayDispatch: (project?: Project) => boolean = () => true, private readonly telemetry?: WorkerTelemetry, private readonly retrievalAssistant?: () => Promise, @@ -562,7 +567,7 @@ export class WorkerManager { let permissionMode = effectivePermissionMode(task, permissionSettings); // Keep this synchronous with the Preparing transition: account changes // reject active workers, and queued passes use this same entry point. - this.assertAccountSession?.(); + this.assertAccountSession?.(task.harness); // A personal record and an invitation-created record may reuse the same // checkout. Only one project identity may drive its branch at a time. const checkoutKey = (value: string) => @@ -588,7 +593,7 @@ export class WorkerManager { try { await this.reviewStarting(task); continuing(); - this.assertAccountSession?.(); + this.assertAccountSession?.(task.harness); if (task.assignment !== "auto") assertWorkerConnected(this.state(), task.harness); if (isActive(task) || this.children.has(task.id)) @@ -1114,6 +1119,17 @@ export class WorkerManager { .join("\n\n"); const briefPath = join(workerRoot, "brief.md").replaceAll("\\", "/"); await writeFile(join(workspace, briefPath), prompt, "utf8"); + if (task.harness === "dsh") { + this.assertAccountSession?.("dsh"); + } + 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 +1140,7 @@ export class WorkerManager { briefPath, contextConfig, toolProfile.args, + dshProfile, ); continuing(); closeArtifacts = watchArtifacts( @@ -1244,6 +1261,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..947246c 100644 --- a/src/components/Dialogs.tsx +++ b/src/components/Dialogs.tsx @@ -673,9 +673,24 @@ export function SettingsDialog({ }) { const [draft, setDraft] = useState(settings); const [section, setSection] = useState(initialSection); + 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"; + // The loaded dsh catalog belongs to the saved profile. Until a different + // draft profile is saved, offer no models that profile may not have. + const dshProfilePending = + !!dshRuntime?.activeProfile && selectedDshProfile !== dshRuntime.activeProfile; const models = - runtime.harnesses.find((harness) => harness.id === draft.defaultHarness) - ?.models ?? []; + draft.defaultHarness === "dsh" && dshProfilePending + ? [] + : runtime.harnesses.find((harness) => harness.id === draft.defaultHarness) + ?.models ?? []; + const dshProfileOptions = dshProfiles.includes(selectedDshProfile) + ? dshProfiles + : [selectedDshProfile, ...dshProfiles]; const previousSettings = useRef(settings); useEffect(() => { const previous = previousSettings.current; @@ -888,6 +903,40 @@ export function SettingsDialog({ )} Automatic stories use this override. Story assignments take precedence. + {(draft.defaultHarness === "dsh" || + (dshRuntime?.available && + (dshRuntime.profiles?.length ?? 0) > 0)) && ( + + )}