Skip to content
Merged
38 changes: 38 additions & 0 deletions docs/account-and-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
40 changes: 34 additions & 6 deletions runtime/agents/acp-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,49 @@ type Json = Record<string, any>;
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<string>();
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,
}];
});
}

Expand Down
65 changes: 58 additions & 7 deletions runtime/agents/cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,25 +192,65 @@ export function startStandardACPSession(transport: ACPTransport, options: AgentS
return runCursorSession(options, undefined, transport);
}

export async function probeStandardACPCatalog(transport: ACPTransport, command: Command): Promise<ModelOption[]> {
export async function probeStandardACPCatalog(
transport: ACPTransport,
command: Command,
probeOptions?: { strictStdout?: boolean },
): Promise<ModelOption[]> {
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 {
await rm(cwd, { recursive: true, force: true });
}
}

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.
Expand Down Expand Up @@ -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",
Expand Down
55 changes: 48 additions & 7 deletions runtime/agents/standard-acp.ts
Original file line number Diff line number Diff line change
@@ -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<AgentSessionOptions, "effort" | "permissionMode">): ACPTransport {
export function standardTransport(
id: StandardHarness,
options?: Partial<Pick<AgentSessionOptions, "effort" | "permissionMode" | "dshProfile">> & {
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.");
Expand All @@ -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<ACPTransport> {
export async function readonlyACPTransport(
id: StandardHarness,
capsule: string,
dshProfile?: string,
): Promise<ACPTransport> {
if (id === "copilot") return {
id, name: "GitHub Copilot", args: ["--acp", "--stdio", "--available-tools=view", "--disable-builtin-mcps", "--no-custom-instructions", "--no-auto-update"],
};
Expand All @@ -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],
};
}
1 change: 1 addition & 0 deletions runtime/agents/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading