feat(setup): register DeepSeek Harness through setup, doctor and uninstall (#1929)

* feat(setup): register DeepSeek Harness through setup, doctor and uninstall

DeepSeek Harness registers MCP clients through a Cordis YAML patch
sequence in the home patch rather than a server table, so setup could
not configure it and users had to append the documented entry by hand.

Add a dsh client: the home patch $DSH_HOME/cordis.patch.yml
(~/.dsh/cordis.patch.yml when unset) is parsed as a patch list, the REA
entry owns the stable rea-mcp id, and setup appends or replaces exactly
that entry while preserving unrelated patches and comments in place.
Doctor reports the registration through the same entry, and uninstall
removes it, dropping insert operations it emptied. Skill destinations
follow ~/.agents/skills ($DSH_AGENTS_HOME/skills when configured), the
home the rest of the client machinery already uses.

Fixes #1839

* fix(setup): carry environment and identity validation into DSH registrations

Address review: the DSH entry discarded discovered provider overrides;
config.env is now emitted and retained like the other dialects. An entry
carrying the rea-mcp id under a wrong or missing package name, or
duplicated entries, reads back as absent so setup rewrites exactly one
canonical entry instead of reporting unchanged. Doctor now requires
serverName rea and stdio transport before calling a DSH registration
aligned, and the Harness skill identifier in the docs matches the
installed reverse-engineer-anything skill.

* fix(setup): apply Cordis patch order and collapse DSH registrations

Address review: a later direct { id, config } operation replaces the
row's config under the native patch DSL, so the registration view now
applies patches in order instead of only reading insert operations;
doctor reports the effective command rather than the inserted one.
Setup rewrites exactly one canonical entry: duplicate id-matching rows
collapse to the first, direct patches to the entry are dropped from the
document and from the edited YAML, and uninstall removes them with the
entry. The client-location test fixture now clears DSH_HOME and
DSH_AGENTS_HOME so a developer environment cannot point the suite at
real Harness homes.

* fix(setup): repair direct-only registrations and preserve Cordis entry state

Serialize now edits the first insertion carrying rea-mcp in place, so a
grouped entry keeps its scope, neighbors, and comments instead of moving
to a fresh root-level insertion, and later carrying insertions and direct
patches collapse away. Entry-level disabled state projects into the
registration the doctor and setup compare, so a disabled row reads as
stale and the repair re-enables it. A direct-only registration no longer
suppresses the canonical insert append, and an update retains the
registration environment. Duplicate entries collapse across operations,
not only within one.

* fix(setup): preserve Harness row state through identity and refresh repairs

A wrong-package row still reads back as a server record carrying its
environment and caller fields, projected with a package marker the
alignment path treats as stale, instead of vanishing and dropping
config.env from the repair. A direct Cordis patch without a preceding
insertion configures nothing, so a direct-only registration reads as
absent even when its config matches and the repair appends the insert.
Caller-owned config fields beyond the REA-owned keys, such as the cwd
the native verifier sets, survive a refresh instead of being silently
dropped.

* fix(setup): preserve Cordis tags and collapse aligned Harness rows

A refresh rebuilt Harness config from parsed values, so a caller !!js
expression was written back as a literal. Owned keys are now overlaid on
the winning config node and other nodes stay in place. Two already-aligned
rea-mcp insertions read as stale, so setup collapses them to one row, and
the bundled skill lists dsh with the other clients.

* fix(setup): drop the unused DSH configuration type

Knip reports DshConfigurationFormat as an unused export. The format union
does not depend on that alias.

* fix(setup): keep Harness env tags and comment-only patches

A refresh replaced the whole env map, so a caller !!js value was written
back as a literal. Environment entries now stay in place unless the value
changed. A comment-only cordis.patch.yml parses as an empty patch list and
keeps those comments when the registration is appended. Docs describe
plain rea uninstall, which scans supported clients and has no --client flag.

* fix(setup): own Harness rows by entry id and expression state

Uninstall removes a rea-mcp row even when the launcher is stale or the
patch never established a server record. A non-boolean disabled value,
including a Cordis expression, reads as stale. Expression text on a known
environment setting is not validated as a literal path, so a refresh can
keep the tag.

* fix(setup): collapse aliased Harness insertions

An anchored insert followed by an alias parses as two rea-mcp rows, but
the YAML edit kept the alias, so readback stayed duplicated and setup
restored the file. Aliases that resolve to the owned entry are now
dropped, including an alias of the entry inside one insert. Aliases of
other patches stay.

* fix(setup): resolve aliased Harness lists and config maps

An insert value that aliases another entry list still loaded a second
rea-mcp row after the operation-level alias collapse. That alias is now
dropped once the anchored list is rewritten. A config: *cfg map is
resolved and cloned before the refresh, so a caller !!js field on the
aliased map is not rewritten as a plain literal.

* fix(setup): follow Harness aliases for ids, lists, and env tags

An insert alias whose anchor is not another insert is copied so
unrelated rows stay while the owned row is rewritten. An aliased
entry id is resolved before ownership checks, and an environment alias
of an unchanged !!js scalar is left in place.

* fix(setup): keep aliased Harness env maps through uninstall

An env alias is cloned before a refresh so tagged values are not rebuilt
as literals, and expression-key scans follow aliases before path checks.
Insert aliases that carry REA are recorded before uninstall empties their
anchor, so the later alias is dropped instead of dangling.

* fix(setup): follow root Harness aliases and mark dsh as main-only

Winning-config walks resolve a root alias before patch order, so a replayed direct config's !!js env is not validated as a literal path. Root aliases that own rea-mcp are recorded before uninstall empties their anchor. An insert whose only owned member is an external alias is cloned so Cordis tags survive. Docs state dsh is not in npm 6.4.0.

* fix(setup): keep rows behind inert Harness aliases

A root alias whose anchor is not a loaded operation is copied and only the owned row is edited, so unrelated rows stay active. Entry id aliases become a scalar before their anchor patch is dropped. Root-alias ownership follows insert-list aliases, so a replay is removed instead of dangling after uninstall.

* refactor(setup): centralize Cordis source ownership

* fix(javascript): share Electron mutation proof with wrapped calls

* test(mcp): align graph and catalog checks with current contracts

* fix(setup): separate Cordis ownership from editability

* docs: clarify ownership and interpretation boundaries

* fix(setup): preserve Cordis applicability and caller metadata

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
BaaRai
2026-10-12 11:06:26 +08:00
committed by GitHub
co-authored by Cursor Agent morluto
parent 04089d5bec
commit d9d2a17381
16 changed files with 3065 additions and 52 deletions
@@ -5,6 +5,13 @@ import {
stringify as stringifyYaml,
} from "yaml";
import { isDeepStrictEqual } from "node:util";
import {
parseDshCordisDocument,
serializeDshDocument,
editDshDocument,
dshClientRegistrationEntry,
} from "./DshCordisPatch.js";
import {
applyEdits,
findNodeAtLocation,
@@ -131,6 +138,8 @@ export const parseClientConfiguration = (
): ClientConfigurationDocument => {
if (format === undefined || format === "unsupported")
throw new TypeError("client does not have a supported MCP config format");
// DeepSeek Harness stores a Cordis patch list, not a server table.
if (format === "dsh") return parseDshCordisDocument(text);
const document = parseDocument(text, format);
const serversKey = clientConfigurationServersKey(format);
const value = document[serversKey];
@@ -184,6 +193,14 @@ export const withClientServers = (
servers: Record<string, unknown>,
removeLegacy?: string,
): Record<string, unknown> => {
// The Harness patch list upserts or removes by entry id, not by table.
if (parsed.dialect === "dsh")
return Object.hasOwn(servers, PRODUCT_IDENTITY.mcpServerKey)
? editDshDocument(
parsed,
objectSchema.parse(servers[PRODUCT_IDENTITY.mcpServerKey]),
)
: editDshDocument(parsed);
const [key = "", nested] = parsed.serversPath;
if (nested === undefined) return { ...parsed.document, [key]: servers };
const outer = { ...objectSchema.parse(parsed.document[key]) };
@@ -1280,6 +1297,7 @@ export const serializeClientConfiguration = (
return serializeGrokConfiguration(document, originalText);
if (format === "hermes")
return serializeHermesConfiguration(document, originalText);
if (format === "dsh") return serializeDshDocument(document);
// An empty original holds no comments or settings to preserve. Writing a
// fresh document also keeps a lone BOM from shifting past the closing brace.
if (
@@ -1398,6 +1416,8 @@ export const clientRegistrationEntry = (
args,
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
};
case "dsh":
return dshClientRegistrationEntry(command, environment);
case "hermes":
// Hermes reads stdio servers from `mcp_servers.<name>` and connects them
// unless `enabled` is false, so the entry states it explicitly.
@@ -9,12 +9,15 @@ import {
} from "./ClientConfigurationDocument.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { dshDocument } from "./DshCordisPatch.js";
/** Read explicit REA overrides without dropping peers when one value is invalid. */
export const clientRegistrationEnvironment = (
parsed: ClientConfigurationDocument | undefined,
overrides: Readonly<Record<string, string>> = {},
): Result<Readonly<Record<string, string>>, ConfigurationError> => {
if (parsed?.dialect === "dsh")
return dshDocument(parsed.document).environment(overrides);
const key =
parsed?.dialect === "opencode" || parsed?.dialect === "opencode_v2"
? "environment"
@@ -26,6 +26,7 @@ import {
} from "./SupportedClients.js";
import type { SetupClient } from "./SupportedClients.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { dshDocument } from "./DshCordisPatch.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
interface ClientRegistrationStatusBase {
@@ -66,6 +67,7 @@ const registrationSchema = z
startup_timeout_sec: z.number().positive().optional(),
type: z.string().optional(),
transport: z.string().optional(),
serverName: z.string().optional(),
tools: z.array(z.string()).optional(),
disabled: z.boolean().optional(),
enabled: z.boolean().optional(),
@@ -178,6 +180,7 @@ export const readClientRegistrationStatuses = async (
parsed,
PRODUCT_IDENTITY.mcpServerKey,
) &&
(parsed.dialect !== "dsh" || dshDocument(parsed.document).ready) &&
policyBlock === undefined
? "aligned"
: "stale",
@@ -221,6 +224,13 @@ const registrationAligned = (
)
return false;
if (client.format === "vscode" && registration.type !== "stdio") return false;
// A Harness registration only connects as the rea stdio server; another
// server name or transport leaves the session without REA tools.
if (
client.format === "dsh" &&
(registration.serverName !== "rea" || registration.transport !== "stdio")
)
return false;
// OMP and Pi infer stdio for a command entry without an explicit type.
if (
(client.format === "omp" || client.format === "pi") &&
@@ -264,6 +274,11 @@ const parseRegistration = (
value: unknown,
client: SetupClient,
): z.output<typeof registrationSchema> => {
if (client.format === "dsh")
return registrationSchema
.pick({ command: true, args: true, serverName: true, transport: true })
.strip()
.parse(value);
if (client.format === "opencode") {
const entry = z
.object({
+375
View File
@@ -0,0 +1,375 @@
import { isMap, isSeq, type Node, type YAMLMap } from "yaml";
import { parseEnvironment } from "../config/environment.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ClientConfigurationDocument } from "./ClientConfigurationDocument.js";
import { CordisExpression, DshCordisYaml } from "./DshCordisYaml.js";
export const DSH_ENTRY_ID = "rea-mcp";
export const DSH_CLIENT_PACKAGE = "@deepseek-ai/dsh-mcp-client";
const LAUNCHER_KEYS = new Set(["serverName", "transport", "command", "args"]);
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
!(value instanceof CordisExpression);
interface PatchOperation {
readonly source: unknown;
readonly map: YAMLMap<unknown, unknown>;
readonly ownedRows: readonly number[];
readonly direct: boolean;
}
/** One interpretation of identity, ordered patch applicability and source nodes. */
export class DshCordisDocument {
readonly #yaml: DshCordisYaml;
readonly #operations: readonly PatchOperation[];
readonly #fields = new Map<string, unknown>();
#entryNode: YAMLMap<unknown, unknown> | undefined;
readonly #insertions: number;
#unknownSelector = false;
readonly config: Record<string, unknown> | undefined;
constructor(text: string) {
this.#yaml = new DshCordisYaml(text);
const root = this.#yaml.document.contents;
if (!isSeq(root))
throw new ConfigurationError("Cordis patches must be a list");
const operations: PatchOperation[] = [];
let insertions = 0;
for (const source of root.items) {
const map = this.#map(source);
if (map === undefined) continue;
const inserted = this.#yaml.resolve(this.#yaml.field(map, "insert"));
const targetId = this.#id(map);
const ownedRows = isSeq(inserted)
? inserted.items.flatMap((entry, index) =>
this.#id(entry) === DSH_ENTRY_ID ? [index] : [],
)
: [];
const direct = !isSeq(inserted) && targetId === DSH_ENTRY_ID;
if (ownedRows.length > 0 && targetId)
throw new ConfigurationError(
"Cannot establish the target group for a Cordis REA insertion from the home patch alone",
);
operations.push({ source, map, ownedRows, direct });
if (isSeq(inserted)) {
for (const index of ownedRows) {
const entry = this.#map(inserted.items[index]);
if (entry === undefined) continue;
insertions += 1;
this.#entryNode = entry;
this.#fields.clear();
this.#unknownSelector = false;
this.#readFields(entry);
}
} else if (direct) {
if (insertions === 0) continue;
// Cordis uses name as a selector, not a rename operation.
const selector = this.#yaml.value(this.#yaml.field(map, "name"));
if (
selector instanceof CordisExpression ||
(selector && this.#field("name") instanceof CordisExpression)
) {
this.#unknownSelector = true;
continue;
}
if (selector && selector !== this.#field("name")) continue;
this.#readFields(map, new Set(["id", "name"]));
}
}
this.#operations = operations;
this.#insertions = insertions;
const config = this.#field("config");
// Ownership survives malformed config so uninstall can remove the source row.
this.config = insertions === 0 ? undefined : isRecord(config) ? config : {};
}
#map(node: unknown): YAMLMap<unknown, unknown> | undefined {
const map = this.#yaml.resolve(node);
return isMap(map) ? map : undefined;
}
#id(node: unknown): unknown {
const id = this.#yaml.value(this.#yaml.field(this.#map(node), "id"));
if (id instanceof CordisExpression)
throw new ConfigurationError(
"Expression-backed Cordis IDs have unknown ownership; use literal IDs before changing registrations",
);
return id;
}
#field(key: string): unknown {
return this.#yaml.value(this.#fields.get(key));
}
#readFields(
map: YAMLMap<unknown, unknown>,
omitted: ReadonlySet<string> = new Set(),
): void {
for (const pair of map.items) {
const key = this.#yaml.value(pair.key);
if (typeof key === "string" && !omitted.has(key))
this.#fields.set(key, pair.value);
}
}
get carriesEntry(): boolean {
return this.#operations.some((op) => op.direct || op.ownedRows.length > 0);
}
get ready(): boolean {
const disabled = this.#field("disabled");
return (
this.#insertions === 1 &&
!this.#unknownSelector &&
this.#field("name") === DSH_CLIENT_PACKAGE &&
(disabled === undefined || disabled === false)
);
}
/** Validate literals without treating expression source as an environment value. */
environment(
overrides: Readonly<Record<string, string>> = {},
): Result<Readonly<Record<string, string>>, ConfigurationError> {
if (this.#unknownSelector)
return err(
new ConfigurationError(
"Expression-backed Cordis name selectors have unknown applicability; use literal selectors before setup",
{
settings: [
{
setting: "name",
constraint: "Use literal selectors before setup",
},
],
},
),
);
const config = this.#field("config");
if (config instanceof CordisExpression)
return err(
new ConfigurationError(
"Expression-backed Cordis config cannot be safely edited",
{
settings: [
{
setting: "config",
constraint:
"Use a literal mapping to preserve caller fields during setup",
},
],
},
),
);
if (config !== undefined && !isRecord(config))
return err(
new ConfigurationError("Cordis REA config must be a mapping", {
settings: [
{
setting: "config",
constraint: "Use a literal mapping before setup",
},
],
}),
);
const raw = this.config?.env;
if (raw !== undefined && !isRecord(raw))
return err(
new ConfigurationError("Cordis server environment must be a mapping"),
);
const literals: Record<string, string> = {};
for (const [key, value] of Object.entries(raw ?? {})) {
if (value instanceof CordisExpression) continue;
if (typeof value !== "string")
return err(
new ConfigurationError("Invalid Cordis server environment", {
settings: [
{
setting: `env.${key}`,
constraint:
"Environment values must be strings or Cordis expressions",
},
],
}),
);
literals[key] = value;
}
const environment = { ...literals, ...overrides };
const validated = parseEnvironment(environment);
return validated.ok ? ok(environment) : validated;
}
desired(
command: readonly string[],
overrides: Readonly<Record<string, string>>,
): Result<Record<string, unknown>, ConfigurationError> {
const environment = this.environment(overrides);
if (!environment.ok) return environment;
const env = {
...(isRecord(this.config?.env) ? this.config.env : {}),
...overrides,
};
const desired = { ...this.config, ...dshClientRegistrationEntry(command) };
delete desired.env;
if (Object.keys(env).length > 0) desired.env = env;
return ok(desired);
}
/** Plan every replacement from source snapshots before changing an output tree. */
serialize(desired?: Record<string, unknown>): string {
const root = this.#yaml.document.contents;
if (!isSeq(root))
throw new ConfigurationError("Cordis patches must be a list");
const replacements = new Map<unknown, unknown>();
const invalidated = new Set(
this.#operations.flatMap((op) =>
op.direct || op.ownedRows.length > 0
? this.#yaml.anchors(op.source)
: [],
),
);
let carried = false;
for (const op of this.#operations) {
if (op.direct) {
replacements.set(op.source, undefined);
continue;
}
if (op.ownedRows.length === 0) continue;
const copy = this.#yaml.detach(op.map, invalidated);
if (!isMap(copy))
throw new ConfigurationError("Cordis operation is not a mapping");
const inserted = this.#yaml.detach(
this.#yaml.resolve(this.#yaml.field(op.map, "insert")),
invalidated,
);
if (!isSeq(inserted))
throw new ConfigurationError("Cordis insertion is not a list");
copy.set("insert", inserted);
const owned = new Set(op.ownedRows);
inserted.items = inserted.items.flatMap((entry, index) => {
if (!owned.has(index)) return [entry];
if (carried || desired === undefined) return [];
carried = true;
return [this.#entry(desired, invalidated)] as typeof inserted.items;
});
replacements.set(
op.source,
inserted.items.length === 0 ? undefined : copy,
);
}
const output = this.#yaml.document.clone();
const outputRoot = output.contents;
if (!isSeq(outputRoot))
throw new ConfigurationError("Cordis patches must be a list");
outputRoot.items = root.items.flatMap((source) => {
const copy = replacements.has(source)
? replacements.get(source)
: this.#yaml.copy(source, invalidated);
return copy === undefined ? [] : [copy];
}) as typeof outputRoot.items;
if (!carried && desired !== undefined)
outputRoot.items.push(
output.createNode({
insert: [
{ id: DSH_ENTRY_ID, name: DSH_CLIENT_PACKAGE, config: desired },
],
}) as never,
);
return output.toString({ lineWidth: 0 });
}
#entry(
desired: Record<string, unknown>,
invalidated: ReadonlySet<Node>,
): YAMLMap<unknown, unknown> {
const entry = this.#yaml.detach(this.#entryNode, invalidated);
if (!isMap(entry))
throw new ConfigurationError("Cordis entry is not a mapping");
this.#yaml.setValue(entry, "id", DSH_ENTRY_ID);
this.#yaml.setValue(entry, "name", DSH_CLIENT_PACKAGE);
entry.delete("disabled");
for (const [key, value] of this.#fields) {
if (["id", "name", "config", "disabled"].includes(key)) continue;
entry.set(key, this.#yaml.detach(value, invalidated));
}
const sourceConfig = this.#map(this.#fields.get("config"));
const config =
sourceConfig === undefined
? this.#yaml.document.createNode({})
: this.#yaml.detach(sourceConfig, invalidated);
if (!isMap(config))
throw new ConfigurationError(
"Cordis registration config is not a mapping",
);
// Caller nodes keep their tags and spelling; only literal launcher values change.
for (const key of LAUNCHER_KEYS)
this.#yaml.setValue(config, key, desired[key]);
const env = this.#map(this.#yaml.field(sourceConfig, "env"));
const desiredEnv = desired.env;
if (isRecord(desiredEnv)) {
const nextEnv =
env === undefined
? this.#yaml.document.createNode({})
: this.#yaml.detach(env, invalidated);
if (!isMap(nextEnv))
throw new ConfigurationError("Cordis environment is not a mapping");
for (const [key, value] of Object.entries(desiredEnv)) {
this.#yaml.setValue(nextEnv, key, value);
}
config.set("env", nextEnv);
} else config.delete("env");
entry.set("config", config);
return entry;
}
}
class DshCordisEdit {
constructor(
readonly source: DshCordisDocument,
readonly desired?: Record<string, unknown>,
) {}
}
export const dshDocument = (
document: Record<string, unknown>,
): DshCordisDocument => {
if (!(document.cordis instanceof DshCordisDocument))
throw new ConfigurationError("Missing Cordis document owner");
return document.cordis;
};
export const parseDshCordisDocument = (
text: string,
): ClientConfigurationDocument => {
const source = new DshCordisDocument(text);
return {
document: { cordis: source },
servers: source.config === undefined ? {} : { rea: source.config },
serversPath: [],
dialect: "dsh",
legacyServers: {},
};
};
export const editDshDocument = (
parsed: ClientConfigurationDocument,
desired?: Record<string, unknown>,
): Record<string, unknown> => ({
cordis: new DshCordisEdit(dshDocument(parsed.document), desired),
});
export const serializeDshDocument = (
document: Record<string, unknown>,
): string => {
if (!(document.cordis instanceof DshCordisEdit))
throw new ConfigurationError("Missing Cordis edit plan");
return document.cordis.source.serialize(document.cordis.desired);
};
export const dshClientRegistrationEntry = (
command: readonly string[],
environment: Readonly<Record<string, string>> = {},
): Record<string, unknown> => {
const [executable = "rea", ...args] = command;
return {
serverName: "rea",
transport: "stdio",
command: executable,
args,
...(Object.keys(environment).length === 0
? {}
: { env: { ...environment } }),
};
};
+175
View File
@@ -0,0 +1,175 @@
import { isDeepStrictEqual } from "node:util";
import {
isAlias,
isMap,
isNode,
isScalar,
isSeq,
parseDocument,
visit,
type Document,
type Node,
type YAMLMap,
} from "yaml";
import { ConfigurationError } from "../domain/configurationErrors.js";
/** Expression source is never a literal value and is never evaluated by REA. */
export class CordisExpression {
readonly kind = "cordis-expression";
constructor(readonly source: string) {}
}
/** Immutable source graph; all alias resolution happens against this document. */
export class DshCordisYaml {
readonly document: Document;
readonly #values = new Map<Node, unknown>();
readonly #visiting = new Set<Node>();
constructor(text: string) {
this.document = parseDocument(text, {
customTags: [
{ tag: "tag:yaml.org,2002:js", resolve: (source: string) => source },
],
logLevel: "silent",
});
if (this.document.errors.length > 0 || this.document.warnings.length > 0)
throw new ConfigurationError("Invalid or unsupported Cordis YAML", {
cause: this.document.errors[0] ?? this.document.warnings[0],
});
if (this.document.contents === null)
this.document.contents = this.document.createNode([]);
if (!isSeq(this.document.contents))
throw new ConfigurationError(
"Cordis patches must be a YAML operation list",
);
this.value(this.document.contents);
try {
// Retain YAML's native alias-expansion admission before copying edits.
// This value is discarded; source nodes own every Cordis interpretation.
this.document.toJS();
} catch (cause) {
throw new ConfigurationError("Unsafe Cordis YAML alias expansion", {
cause,
});
}
}
resolve(node: unknown): unknown {
if (!isAlias(node)) return node;
const resolved = node.resolve(this.document);
if (resolved === undefined)
throw new ConfigurationError("Cordis YAML contains an unresolved alias");
return resolved;
}
value(node: unknown): unknown {
const resolved = this.resolve(node);
if (!isNode(resolved)) return resolved;
if (this.#values.has(resolved)) return this.#values.get(resolved);
if (this.#visiting.has(resolved))
throw new ConfigurationError(
"Cyclic Cordis YAML cannot be safely edited",
);
this.#visiting.add(resolved);
let value: unknown;
if (isScalar(resolved))
value =
resolved.tag === "tag:yaml.org,2002:js"
? new CordisExpression(String(resolved.value))
: resolved.value;
else if (isSeq(resolved))
value = resolved.items.map((item) => this.value(item));
else if (isMap(resolved)) {
const entries: [string, unknown][] = [];
for (const pair of resolved.items) {
entries.push([this.#key(pair.key), this.value(pair.value)]);
}
value = Object.fromEntries(entries);
}
this.#visiting.delete(resolved);
this.#values.set(resolved, value);
return value;
}
#key(node: unknown): string {
const key = this.value(node);
if (typeof key === "object" && key !== null)
throw new ConfigurationError(
"Cordis YAML mapping keys must be literal scalars",
);
// Match YAML's JS object projection while retaining the original key node.
return key === null ? "" : String(key);
}
field(map: YAMLMap | undefined, key: string): unknown {
return map?.items.findLast((pair) => this.#key(pair.key) === key)?.value;
}
/** Preserve unchanged nodes and carry their comments when replacing values. */
setValue(map: YAMLMap, key: string, value: unknown): void {
const original = this.field(map, key);
if (isDeepStrictEqual(this.value(original), value)) return;
const replacement = this.document.createNode(value);
if (isNode(original) && isNode(replacement)) {
if (original.comment !== undefined)
replacement.comment = original.comment;
if (original.commentBefore !== undefined)
replacement.commentBefore = original.commentBefore;
}
map.set(key, replacement);
}
/** Copy from the source before edits; materialized nodes own no anchors. */
copy(node: unknown, invalidated?: ReadonlySet<Node>): unknown {
if (isAlias(node)) {
const target = this.resolve(node);
return invalidated === undefined ||
(isNode(target) && invalidated.has(target))
? this.copy(target)
: node.clone();
}
if (!isNode(node)) return node;
const copied = node.clone();
if (
(invalidated === undefined || invalidated.has(node)) &&
(isScalar(copied) || isMap(copied) || isSeq(copied))
)
delete copied.anchor;
if (isSeq(node) && isSeq(copied))
copied.items = node.items.map((item) =>
this.copy(item, invalidated),
) as typeof copied.items;
if (isMap(node) && isMap(copied))
copied.items.forEach((pair, index) => {
pair.key = this.copy(node.items[index]!.key, invalidated);
pair.value = this.copy(node.items[index]!.value, invalidated);
});
return copied;
}
/** Replacing an anchor must not change untouched consumers of its old value. */
detach(node: unknown, invalidated: ReadonlySet<Node>): unknown {
const copied = this.copy(node, invalidated);
if (isNode(copied))
visit(copied, {
Pair: (_key, pair) => {
if (isAlias(pair.key)) pair.key = this.copy(this.resolve(pair.key));
},
Value: (_key, value) => {
delete value.anchor;
},
});
return copied;
}
anchors(node: unknown): readonly Node[] {
if (!isNode(node)) return [];
const anchors: Node[] = [];
visit(node, {
Value: (_key, value) => {
if (value.anchor) anchors.push(value);
},
});
return anchors;
}
}
+18 -2
View File
@@ -12,6 +12,7 @@ import {
withClientServers,
type ClientConfigurationDocument,
} from "./ClientConfigurationDocument.js";
import { dshDocument, DshCordisDocument } from "./DshCordisPatch.js";
import { constants as fsConstants } from "node:fs";
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
@@ -89,7 +90,10 @@ const configureClientDocument = async (
let parsed: ClientConfigurationDocument;
try {
parsed = parseClientConfiguration(
original ?? (format === "toml" || format === "grok" ? "" : "{}"),
original ??
(format === "toml" || format === "grok" || format === "dsh"
? ""
: "{}"),
format,
);
const policy = await readClientPolicyBlock(
@@ -396,6 +400,7 @@ const registrationCurrent = (
parsed: ClientConfigurationDocument,
desired: unknown,
): boolean =>
(parsed.dialect !== "dsh" || dshDocument(parsed.document).ready) &&
clientConfigurationValuesEqual(
parsed.servers[PRODUCT_IDENTITY.mcpServerKey],
desired,
@@ -410,6 +415,17 @@ const clientConfigurationDesired = (
parsed?: ClientConfigurationDocument,
) => {
const format = parsed?.dialect ?? client.format ?? "json";
const launcher =
command.length === 0 ? [PRODUCT_IDENTITY.cliBinary, "mcp"] : command;
if (format === "dsh") {
const desired = (
parsed === undefined
? new DshCordisDocument("")
: dshDocument(parsed.document)
).desired(launcher, providerEnvironment);
if (!desired.ok) throw desired.error;
return desired.value;
}
// Preserve explicitly configured server settings, never the ambient process
// environment. Newly discovered provider paths win only for their own keys.
const environment = clientRegistrationEnvironment(
@@ -419,7 +435,7 @@ const clientConfigurationDesired = (
if (!environment.ok) throw environment.error;
const registration = clientRegistrationEntry(
format,
command.length === 0 ? [PRODUCT_IDENTITY.cliBinary, "mcp"] : command,
launcher,
environment.value,
);
return {
+18
View File
@@ -38,6 +38,7 @@ export interface SetupClient {
| "omp"
| "pi"
| "hermes"
| "dsh"
| "unsupported";
}
@@ -129,6 +130,12 @@ const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => {
const grokDirectory = ({ home, env }: ClientPathContext): string =>
env.GROK_HOME || join(home, ".grok");
const dshHomeDirectory = ({ home, env }: ClientPathContext): string =>
env.DSH_HOME ?? join(home, ".dsh");
const dshPatchDirectory = (context: ClientPathContext): string =>
join(dshHomeDirectory(context), "cordis.patch.yml");
const hermesDirectory = ({ home, platform, env }: ClientPathContext): string =>
resolveHermesClientHome(home, platform, env);
@@ -492,6 +499,17 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
markerPath: hermesDirectory,
format: "hermes",
},
{
name: "dsh",
displayName: "DeepSeek Harness",
// The home Cordis patch applies to every profile; the skill directory is
// shared agent storage Harness discovers.
skillPath: ({ home, env }: ClientPathContext) =>
join(env.DSH_AGENTS_HOME ?? join(home, ".agents"), "skills"),
configPath: dshPatchDirectory,
markerPath: dshHomeDirectory,
format: "dsh",
},
{
name: "grok_bot",
displayName: "Grok Bot",
+10 -2
View File
@@ -22,6 +22,7 @@ import {
skillDestinations,
} from "./SetupSkill.js";
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
import { dshDocument } from "./DshCordisPatch.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import { readRegularFileText } from "./RegularFileRead.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
@@ -305,10 +306,15 @@ const removeClient = async (
// Beside a native OpenCode V2 table, OpenCode also loads a V1 `mcp.rea`.
const legacyPath = legacyClientServerPath(parsed, name);
const hasNative = Object.hasOwn(parsed.servers, name);
if (!hasNative && legacyPath === undefined)
// Harness ownership is the stable entry id. A stale or malformed launcher
// still belongs to that id, and so does a direct patch that projects no row.
const carriesDshEntry =
parsed.dialect === "dsh" && dshDocument(parsed.document).carriesEntry;
if (!hasNative && legacyPath === undefined && !carriesDshEntry)
return item(client.name, "skipped", "REA registration is absent.");
const removeNative =
hasNative && isOwnedRegistration(parsed.servers[name], client);
carriesDshEntry ||
(hasNative && isOwnedRegistration(parsed.servers[name], client));
const removeLegacy =
legacyPath !== undefined &&
isOwnedRegistration(parsed.legacyServers[name], client);
@@ -356,6 +362,8 @@ const removeClient = async (
);
if (
(removeNative && Object.hasOwn(readback.servers, name)) ||
(readback.dialect === "dsh" &&
dshDocument(readback.document).carriesEntry) ||
(removeLegacy && Object.hasOwn(readback.legacyServers, name))
)
throw new Error("registration readback mismatch");