fix(setup): honor active client configuration and skill roots (#1504)
* refactor(setup): resolve skill destinations per client * fix(setup): honor active client configuration and skill roots * fix(setup): validate effective client scopes and Gemini trust * fix(setup): treat empty OpenCode overrides as unset An empty OPENCODE_CONFIG_DIR now stays on the XDG directory, and doctor and setup inspect global OpenCode files when a custom directory is absent. Uninstall reports one status per client so a missing earlier layer does not hide a removed registration. --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
@@ -1413,3 +1413,45 @@ export const clientRegistrationEntry = (
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/** Parse one Gemini policy at its source boundary before consolidating scopes. */
|
||||
export const parseGeminiMcpPolicy = (parsed: ClientConfigurationDocument) =>
|
||||
z
|
||||
.object({
|
||||
allowed: z.array(z.string()).optional(),
|
||||
excluded: z.array(z.string()).optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.parse(parsed.document.mcp ?? {});
|
||||
|
||||
/** Gemini consolidates excludes by union and allowlists by normalized intersection. */
|
||||
export const geminiServerPolicyBlock = (
|
||||
policies: readonly ReturnType<typeof parseGeminiMcpPolicy>[],
|
||||
serverKey: string,
|
||||
): string | undefined => {
|
||||
if (policies.some(({ excluded }) => excluded?.includes(serverKey)))
|
||||
return `Gemini mcp.excluded blocks ${serverKey}. Review the selected settings policies before rerunning setup.`;
|
||||
const allowlists = policies.flatMap(({ allowed }) =>
|
||||
allowed === undefined ? [] : [allowed],
|
||||
);
|
||||
const allowed = allowlists.reduce<string[] | undefined>(
|
||||
(previous, current) => {
|
||||
if (previous === undefined) return current;
|
||||
const normalized = new Set(
|
||||
current.map((name) => name.toLowerCase().trim()),
|
||||
);
|
||||
return previous.filter((name) =>
|
||||
normalized.has(name.toLowerCase().trim()),
|
||||
);
|
||||
},
|
||||
undefined,
|
||||
);
|
||||
// Gemini's manager applies the consolidated allowlist only when nonempty.
|
||||
if (
|
||||
allowed !== undefined &&
|
||||
allowed.length > 0 &&
|
||||
!allowed.includes(serverKey)
|
||||
)
|
||||
return `Gemini mcp.allowed does not include ${serverKey}. Review the selected settings policies before rerunning setup.`;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import {
|
||||
effectiveClientServer,
|
||||
parseClientConfiguration,
|
||||
type ClientConfigurationDocument,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
/** A named source failure that setup can explain without losing the bad path. */
|
||||
export interface ClientConfigurationFileError {
|
||||
readonly kind: "unreadable" | "malformed";
|
||||
readonly path: string;
|
||||
readonly detail: string;
|
||||
}
|
||||
|
||||
/** Preserve named read failures and distinguish a missing source from an empty file. */
|
||||
export const readConfigurationText = async (
|
||||
path: string,
|
||||
): Promise<Result<string | undefined, ClientConfigurationFileError>> => {
|
||||
try {
|
||||
return ok(await readFile(path, "utf8"));
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return ok(undefined);
|
||||
return err({
|
||||
kind: "unreadable",
|
||||
path,
|
||||
detail: `Configuration ${path} could not be read: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/** Read and parse one configuration at its source boundary. */
|
||||
export const readConfigurationFile = async (
|
||||
path: string,
|
||||
format: SetupClient["format"],
|
||||
): Promise<
|
||||
Result<ClientConfigurationDocument | undefined, ClientConfigurationFileError>
|
||||
> => {
|
||||
const source = await readConfigurationText(path);
|
||||
if (!source.ok) return source;
|
||||
const content = source.value;
|
||||
if (content === undefined) return ok(undefined);
|
||||
try {
|
||||
return ok(parseClientConfiguration(content, format));
|
||||
} catch (cause: unknown) {
|
||||
return err({
|
||||
kind: "malformed",
|
||||
path,
|
||||
detail: `Configuration ${path} is malformed: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/** Read every applicable user file; malformed lower-priority files also stop setup. */
|
||||
export const readClientConfigurationFiles = async (
|
||||
client: SetupClient,
|
||||
): Promise<
|
||||
Result<readonly ClientConfigurationDocument[], ClientConfigurationFileError>
|
||||
> => {
|
||||
const documents: ClientConfigurationDocument[] = [];
|
||||
for (const path of client.configPaths ?? [client.configPath]) {
|
||||
const document = await readConfigurationFile(path, client.format);
|
||||
if (!document.ok) return document;
|
||||
if (document.value !== undefined) documents.push(document.value);
|
||||
}
|
||||
return ok(documents);
|
||||
};
|
||||
|
||||
/** OpenCode merges server objects in file order, replacing arrays and scalar values. */
|
||||
const mergeConfigurationValue = (previous: unknown, next: unknown): unknown => {
|
||||
if (!isObject(previous) || !isObject(next)) return next;
|
||||
return Object.fromEntries(
|
||||
[...new Set([...Object.keys(previous), ...Object.keys(next)])].map(
|
||||
(key) => [
|
||||
key,
|
||||
Object.hasOwn(next, key)
|
||||
? mergeConfigurationValue(previous[key], next[key])
|
||||
: previous[key],
|
||||
],
|
||||
),
|
||||
);
|
||||
};
|
||||
const isObject = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
/** Project a client's effective user registration without modifying its source files. */
|
||||
export const effectiveClientConfiguration = (
|
||||
documents: readonly ClientConfigurationDocument[],
|
||||
): ClientConfigurationDocument | undefined => {
|
||||
const last = documents.at(-1);
|
||||
if (last === undefined) return undefined;
|
||||
if (documents.length === 1) return last;
|
||||
const servers: Record<string, unknown> = {};
|
||||
for (const document of documents) {
|
||||
const names = new Set([
|
||||
...Object.keys(document.legacyServers),
|
||||
...Object.keys(document.servers),
|
||||
]);
|
||||
for (const name of names)
|
||||
servers[name] = mergeConfigurationValue(
|
||||
servers[name],
|
||||
effectiveClientServer(document, name),
|
||||
);
|
||||
}
|
||||
return { ...last, servers, legacyServers: {} };
|
||||
};
|
||||
@@ -1,10 +1,14 @@
|
||||
import { readClientPolicyBlock } from "./GeminiClientSettings.js";
|
||||
import {
|
||||
effectiveClientConfiguration,
|
||||
readClientConfigurationFiles,
|
||||
} from "./ClientConfigurationFiles.js";
|
||||
import {
|
||||
clientServerForcedEnabled,
|
||||
clientServerListedDisabled,
|
||||
effectiveClientServer,
|
||||
parseClientConfiguration,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { access, readFile } from "node:fs/promises";
|
||||
import { access } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
@@ -16,6 +20,7 @@ import {
|
||||
npxRegistrationCommand,
|
||||
} from "./ClientRegistrationIdentity.js";
|
||||
import {
|
||||
clientEvidencePaths,
|
||||
manualRegistrationRemediation,
|
||||
supportedClients,
|
||||
} from "./SupportedClients.js";
|
||||
@@ -90,11 +95,7 @@ export const readClientRegistrationStatuses = async (
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
!(await exists(client.markerPath)) &&
|
||||
!(await exists(client.configPath))
|
||||
)
|
||||
continue;
|
||||
if (!(await clientEvidencePresent(client))) continue;
|
||||
const manualRemediation = manualRegistrationRemediation(client.name);
|
||||
if (client.format === "unsupported") {
|
||||
if (manualRemediation !== undefined)
|
||||
@@ -108,8 +109,36 @@ export const readClientRegistrationStatuses = async (
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const content = await readFile(client.configPath, "utf8");
|
||||
const parsed = parseClientConfiguration(content, client.format);
|
||||
const files = await readClientConfigurationFiles(client);
|
||||
if (!files.ok) {
|
||||
statuses.push({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
state: "invalid",
|
||||
remediation: files.error.detail,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const parsed = effectiveClientConfiguration(files.value);
|
||||
if (parsed === undefined) {
|
||||
statuses.push(
|
||||
unavailableStatus(client.name, client.configPath, "missing"),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const policy = await readClientPolicyBlock(client, parsed);
|
||||
if (!policy.ok) {
|
||||
statuses.push({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
state: "invalid",
|
||||
remediation: policy.error.detail,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const policyBlock = policy.value;
|
||||
const raw = effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey);
|
||||
if (raw === undefined) {
|
||||
statuses.push(
|
||||
@@ -134,9 +163,14 @@ export const readClientRegistrationStatuses = async (
|
||||
options.platform ?? process.platform,
|
||||
clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey),
|
||||
) &&
|
||||
!clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey)
|
||||
!clientServerListedDisabled(
|
||||
parsed,
|
||||
PRODUCT_IDENTITY.mcpServerKey,
|
||||
) &&
|
||||
policyBlock === undefined
|
||||
? "aligned"
|
||||
: "stale",
|
||||
policyBlock,
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
@@ -163,7 +197,7 @@ const registrationAligned = (
|
||||
): boolean => {
|
||||
const command = [registration.command, ...registration.args];
|
||||
if (
|
||||
registration.disabled === true ||
|
||||
(client.format !== "grok" && registration.disabled === true) ||
|
||||
(registration.enabled === false && !forcedEnabled)
|
||||
)
|
||||
return false;
|
||||
@@ -256,10 +290,17 @@ const configuredStatus = (
|
||||
configPath: string,
|
||||
command: RegistrationCommand,
|
||||
state: "aligned" | "stale",
|
||||
policyRemediation?: string,
|
||||
): ClientRegistrationStatus =>
|
||||
state === "aligned"
|
||||
? { client, config_path: configPath, command, state, remediation: null }
|
||||
: { client, config_path: configPath, command, state, remediation };
|
||||
: {
|
||||
client,
|
||||
config_path: configPath,
|
||||
command,
|
||||
state,
|
||||
remediation: policyRemediation ?? remediation,
|
||||
};
|
||||
|
||||
const unavailableStatus = (
|
||||
client: string,
|
||||
@@ -273,6 +314,12 @@ const unavailableStatus = (
|
||||
remediation,
|
||||
});
|
||||
|
||||
const clientEvidencePresent = async (client: SetupClient): Promise<boolean> => {
|
||||
for (const path of clientEvidencePaths(client))
|
||||
if (await exists(path)) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const exists = async (path: string | undefined): Promise<boolean> => {
|
||||
if (path === undefined) return false;
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { stripComments } from "jsonc-parser";
|
||||
import { z } from "zod";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import {
|
||||
clientConfigurationValuesEqual,
|
||||
clientRegistrationEntry,
|
||||
geminiServerPolicyBlock,
|
||||
parseGeminiMcpPolicy,
|
||||
type ClientConfigurationDocument,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import {
|
||||
readConfigurationFile,
|
||||
readConfigurationText,
|
||||
type ClientConfigurationFileError,
|
||||
} from "./ClientConfigurationFiles.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
type SettingsSource = { path: string; document: ClientConfigurationDocument };
|
||||
const folderTrustSchema = z
|
||||
.object({
|
||||
security: z
|
||||
.object({
|
||||
folderTrust: z
|
||||
.object({ enabled: z.boolean().optional() })
|
||||
.passthrough()
|
||||
.optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.optional(),
|
||||
})
|
||||
.passthrough();
|
||||
const trustRulesSchema = z.record(
|
||||
z.string(),
|
||||
z.enum(["TRUST_FOLDER", "TRUST_PARENT", "DO_NOT_TRUST"]),
|
||||
);
|
||||
const sourceFailure = (
|
||||
path: string,
|
||||
cause: unknown,
|
||||
): ClientConfigurationFileError => ({
|
||||
kind: "malformed",
|
||||
path,
|
||||
detail: `Gemini settings in ${path} are malformed: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
});
|
||||
|
||||
// Gemini resolves symlinks when possible and compares macOS/Windows paths without case.
|
||||
const normalizedPath = async (
|
||||
path: string,
|
||||
platform: NodeJS.Platform,
|
||||
): Promise<string> => {
|
||||
const physical = await realpath(path).catch(() => path);
|
||||
const absolute = resolve(physical).replaceAll("\\", "/");
|
||||
return platform === "win32" || platform === "darwin"
|
||||
? absolute.toLowerCase()
|
||||
: absolute;
|
||||
};
|
||||
|
||||
const workspaceTrusted = async (
|
||||
settings: NonNullable<SetupClient["geminiSettings"]>,
|
||||
sources: readonly SettingsSource[],
|
||||
): Promise<Result<boolean, ClientConfigurationFileError>> => {
|
||||
let enabled = true;
|
||||
for (const { path, document } of sources) {
|
||||
const parsed = folderTrustSchema.safeParse(document.document);
|
||||
if (!parsed.success) return err(sourceFailure(path, parsed.error));
|
||||
enabled = parsed.data.security?.folderTrust?.enabled ?? enabled;
|
||||
}
|
||||
if (settings.trustOverride !== undefined) return ok(settings.trustOverride);
|
||||
if (!enabled) return ok(true);
|
||||
const text = await readConfigurationText(settings.trustedFoldersPath);
|
||||
if (!text.ok) return text;
|
||||
if (text.value === undefined) return ok(false);
|
||||
let rules: z.output<typeof trustRulesSchema>;
|
||||
try {
|
||||
// Gemini strips comments, but rejects trailing commas, BOMs and invalid trust levels.
|
||||
rules = trustRulesSchema.parse(JSON.parse(stripComments(text.value)));
|
||||
} catch (cause: unknown) {
|
||||
return err(sourceFailure(settings.trustedFoldersPath, cause));
|
||||
}
|
||||
const workspace = await normalizedPath(
|
||||
settings.workspaceDirectory,
|
||||
settings.platform,
|
||||
);
|
||||
let longest = -1;
|
||||
let trusted = false;
|
||||
for (const [path, level] of Object.entries(rules)) {
|
||||
const effective = await normalizedPath(
|
||||
level === "TRUST_PARENT" ? dirname(path) : path,
|
||||
settings.platform,
|
||||
);
|
||||
if (
|
||||
(workspace === effective ||
|
||||
workspace.startsWith(
|
||||
effective.endsWith("/") ? effective : `${effective}/`,
|
||||
)) &&
|
||||
path.length > longest
|
||||
) {
|
||||
longest = path.length;
|
||||
trusted = level !== "DO_NOT_TRUST";
|
||||
}
|
||||
}
|
||||
return ok(trusted);
|
||||
};
|
||||
|
||||
/** Check effective Gemini scopes while preserving their authority and source identity. */
|
||||
export const readClientPolicyBlock = async (
|
||||
client: SetupClient,
|
||||
userDocument?: ClientConfigurationDocument,
|
||||
desiredRegistration?: unknown,
|
||||
): Promise<Result<string | undefined, ClientConfigurationFileError>> => {
|
||||
if (client.name !== "gemini_cli" || client.geminiSettings === undefined)
|
||||
return ok(undefined);
|
||||
const settings = client.geminiSettings;
|
||||
const sources: SettingsSource[] = [];
|
||||
const higher: SettingsSource[] = [];
|
||||
for (const path of [
|
||||
settings.defaultsPath,
|
||||
client.configPath,
|
||||
settings.systemPath,
|
||||
]) {
|
||||
const parsed =
|
||||
path === client.configPath && userDocument !== undefined
|
||||
? ok(userDocument)
|
||||
: await readConfigurationFile(path, "json");
|
||||
if (!parsed.ok) return parsed;
|
||||
if (parsed.value !== undefined)
|
||||
sources.push({ path, document: parsed.value });
|
||||
}
|
||||
const workspace = await normalizedPath(
|
||||
settings.workspaceDirectory,
|
||||
settings.platform,
|
||||
);
|
||||
const home = await normalizedPath(
|
||||
dirname(dirname(client.configPath)),
|
||||
settings.platform,
|
||||
);
|
||||
if (workspace !== home) {
|
||||
const path = resolve(
|
||||
settings.workspaceDirectory,
|
||||
".gemini",
|
||||
"settings.json",
|
||||
);
|
||||
const document = await readConfigurationFile(path, "json");
|
||||
if (!document.ok) return document;
|
||||
if (document.value !== undefined) {
|
||||
const trusted = await workspaceTrusted(settings, sources);
|
||||
if (!trusted.ok) return trusted;
|
||||
if (trusted.value) {
|
||||
const source = { path, document: document.value };
|
||||
const systemIndex = sources.findIndex(
|
||||
(item) => item.path === settings.systemPath,
|
||||
);
|
||||
sources.splice(
|
||||
systemIndex < 0 ? sources.length : systemIndex,
|
||||
0,
|
||||
source,
|
||||
);
|
||||
higher.push(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
const system = sources.find(({ path }) => path === settings.systemPath);
|
||||
if (system !== undefined) higher.push(system);
|
||||
const policies: ReturnType<typeof parseGeminiMcpPolicy>[] = [];
|
||||
for (const { path, document } of sources) {
|
||||
try {
|
||||
policies.push(parseGeminiMcpPolicy(document));
|
||||
} catch (cause: unknown) {
|
||||
return err(sourceFailure(path, cause));
|
||||
}
|
||||
}
|
||||
const policy = geminiServerPolicyBlock(
|
||||
policies,
|
||||
PRODUCT_IDENTITY.mcpServerKey,
|
||||
);
|
||||
if (policy !== undefined)
|
||||
return ok(
|
||||
`${policy} Settings sources: ${sources.map(({ path }) => path).join(", ")}.`,
|
||||
);
|
||||
// mcpServers uses shallow merge: the entire same-name definition is replaced.
|
||||
const override = higher.findLast(({ document }) =>
|
||||
Object.hasOwn(document.servers, PRODUCT_IDENTITY.mcpServerKey),
|
||||
);
|
||||
const desired =
|
||||
desiredRegistration ??
|
||||
userDocument?.servers[PRODUCT_IDENTITY.mcpServerKey] ??
|
||||
clientRegistrationEntry("json", npxRegistrationCommand(), {});
|
||||
if (
|
||||
override !== undefined &&
|
||||
!clientConfigurationValuesEqual(
|
||||
override.document.servers[PRODUCT_IDENTITY.mcpServerKey],
|
||||
desired,
|
||||
)
|
||||
)
|
||||
return ok(
|
||||
`Gemini mcpServers.${PRODUCT_IDENTITY.mcpServerKey} in ${override.path} overrides the user registration. Review that settings file before rerunning setup; REA does not modify system or workspace settings.`,
|
||||
);
|
||||
return ok(undefined);
|
||||
};
|
||||
@@ -1,3 +1,5 @@
|
||||
import { readClientPolicyBlock } from "./GeminiClientSettings.js";
|
||||
import { readClientConfigurationFiles } from "./ClientConfigurationFiles.js";
|
||||
import {
|
||||
clientRegistrationEntry,
|
||||
clientConfigurationValuesEqual,
|
||||
@@ -46,6 +48,15 @@ const configureClientDocument = async (
|
||||
command: readonly string[],
|
||||
format: NonNullable<SetupClient["format"]>,
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
const files = await readClientConfigurationFiles(client);
|
||||
if (!files.ok) return { status: "failed", reason: "readback" };
|
||||
const policy = await readClientPolicyBlock(
|
||||
client,
|
||||
undefined,
|
||||
clientConfigurationDesired(client, environment, command, client.format),
|
||||
);
|
||||
if (!policy.ok || policy.value !== undefined)
|
||||
return { status: "failed", reason: "readback" };
|
||||
const transactionPath = await resolveClientConfigTransactionPath(
|
||||
client.configPath,
|
||||
);
|
||||
@@ -63,6 +74,13 @@ const configureClientDocument = async (
|
||||
original ?? (format === "toml" || format === "grok" ? "" : "{}"),
|
||||
format,
|
||||
);
|
||||
const policy = await readClientPolicyBlock(
|
||||
client,
|
||||
parsed,
|
||||
clientConfigurationDesired(client, environment, command, parsed.dialect),
|
||||
);
|
||||
if (!policy.ok || policy.value !== undefined)
|
||||
return { status: "failed", reason: "readback" };
|
||||
} catch (cause: unknown) {
|
||||
// Malformed existing configuration fails the readback gate.
|
||||
void cause;
|
||||
@@ -158,9 +176,12 @@ export const clientConfigurationAligned = async (
|
||||
): Promise<boolean> => {
|
||||
if (client.configPathError !== undefined) return false;
|
||||
try {
|
||||
const files = await readClientConfigurationFiles(client);
|
||||
if (!files.ok) return false;
|
||||
const original = await readFile(client.configPath, "utf8");
|
||||
const parsed = parseClientConfiguration(original, client.format);
|
||||
return registrationCurrent(
|
||||
const policy = await readClientPolicyBlock(
|
||||
client,
|
||||
parsed,
|
||||
clientConfigurationDesired(
|
||||
client,
|
||||
@@ -169,6 +190,19 @@ export const clientConfigurationAligned = async (
|
||||
parsed.dialect,
|
||||
),
|
||||
);
|
||||
return (
|
||||
policy.ok &&
|
||||
policy.value === undefined &&
|
||||
registrationCurrent(
|
||||
parsed,
|
||||
clientConfigurationDesired(
|
||||
client,
|
||||
providerEnvironment,
|
||||
command,
|
||||
parsed.dialect,
|
||||
),
|
||||
)
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
// Unreadable configuration is treated as not aligned so setup repairs it.
|
||||
void cause;
|
||||
@@ -185,6 +219,22 @@ export const inspectClientConfiguration = async (
|
||||
if (client.configPathError !== undefined)
|
||||
return { status: "invalid", remediation: client.configPathError };
|
||||
if (client.format === "unsupported") return { status: "already_current" };
|
||||
const files = await readClientConfigurationFiles(client);
|
||||
if (!files.ok) return { status: "invalid", remediation: files.error.detail };
|
||||
const policy = await readClientPolicyBlock(
|
||||
client,
|
||||
undefined,
|
||||
clientConfigurationDesired(
|
||||
client,
|
||||
providerEnvironment,
|
||||
command,
|
||||
client.format,
|
||||
),
|
||||
);
|
||||
if (!policy.ok)
|
||||
return { status: "invalid", remediation: policy.error.detail };
|
||||
if (policy.value !== undefined)
|
||||
return { status: "invalid", remediation: policy.value };
|
||||
const transactionPath = await resolveClientConfigTransactionPath(
|
||||
client.configPath,
|
||||
);
|
||||
@@ -207,6 +257,20 @@ export const inspectClientConfiguration = async (
|
||||
}
|
||||
try {
|
||||
const parsed = parseClientConfiguration(original, client.format);
|
||||
const policy = await readClientPolicyBlock(
|
||||
client,
|
||||
parsed,
|
||||
clientConfigurationDesired(
|
||||
client,
|
||||
providerEnvironment,
|
||||
command,
|
||||
parsed.dialect,
|
||||
),
|
||||
);
|
||||
if (!policy.ok)
|
||||
return { status: "invalid", remediation: policy.error.detail };
|
||||
if (policy.value !== undefined)
|
||||
return { status: "invalid", remediation: policy.value };
|
||||
const desired = clientConfigurationDesired(
|
||||
client,
|
||||
providerEnvironment,
|
||||
|
||||
@@ -14,7 +14,11 @@ import {
|
||||
systemLinuxHopperInstallHost,
|
||||
} from "./LinuxHopper.js";
|
||||
import { installMacHopper, systemMacHopperInstallHost } from "./MacHopper.js";
|
||||
import { supportedClients, type SetupClient } from "./SupportedClients.js";
|
||||
import {
|
||||
clientEvidencePaths,
|
||||
supportedClients,
|
||||
type SetupClient,
|
||||
} from "./SupportedClients.js";
|
||||
import {
|
||||
skillDestinations,
|
||||
canonicalSkillNeedsInstall,
|
||||
@@ -168,17 +172,19 @@ export const detectClients = async (
|
||||
const detected: SetupClient[] = [];
|
||||
for (const candidate of supportedClients(home, platform, environment)) {
|
||||
if (candidate.configPathError !== undefined) continue;
|
||||
const [hasConfig, hasMarker] = await Promise.all([
|
||||
exists(candidate.configPath),
|
||||
candidate.markerPath === undefined ? false : exists(candidate.markerPath),
|
||||
]);
|
||||
if (hasConfig || hasMarker) detected.push(candidate);
|
||||
if (await clientEvidencePresent(candidate)) detected.push(candidate);
|
||||
}
|
||||
return detected;
|
||||
};
|
||||
|
||||
const major = (version: string): number =>
|
||||
Number.parseInt(version.split(".")[0] ?? "0", 10);
|
||||
const clientEvidencePresent = async (client: SetupClient): Promise<boolean> => {
|
||||
for (const path of clientEvidencePaths(client))
|
||||
if (await exists(path)) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const exists = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
await access(path);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isAbsolute, join, resolve, win32 } from "node:path";
|
||||
import { dirname, isAbsolute, join, resolve, win32 } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { lstatSync } from "node:fs";
|
||||
|
||||
@@ -7,6 +7,17 @@ export interface SetupClient {
|
||||
readonly name: string;
|
||||
readonly displayName?: string;
|
||||
readonly configPath: string;
|
||||
/** User configuration files in increasing precedence, including the write target. */
|
||||
readonly configPaths?: readonly string[];
|
||||
/** Read-only Gemini scopes and trust inputs; never setup write targets. */
|
||||
readonly geminiSettings?: {
|
||||
readonly systemPath: string;
|
||||
readonly defaultsPath: string;
|
||||
readonly workspaceDirectory: string;
|
||||
readonly trustedFoldersPath: string;
|
||||
readonly trustOverride?: boolean;
|
||||
readonly platform: NodeJS.Platform;
|
||||
};
|
||||
/** Unresolved path evidence only; consumers must not perform I/O on it. */
|
||||
readonly configPathError?: string;
|
||||
readonly markerPath?: string;
|
||||
@@ -39,6 +50,10 @@ interface ClientDefinition {
|
||||
readonly markerPath: ClientPath;
|
||||
readonly format: NonNullable<SetupClient["format"]>;
|
||||
readonly skillPath?: ClientPath;
|
||||
readonly configPaths?: (context: ClientPathContext) => readonly string[];
|
||||
readonly geminiSettings?: (
|
||||
context: ClientPathContext,
|
||||
) => NonNullable<SetupClient["geminiSettings"]>;
|
||||
}
|
||||
|
||||
const vscodeUserDirectory = ({
|
||||
@@ -76,7 +91,7 @@ const claudeCodeMarkerDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.CLAUDE_CONFIG_DIR ?? join(home, ".claude");
|
||||
|
||||
const codexDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.CODEX_HOME ?? join(home, ".codex");
|
||||
env.CODEX_HOME || join(home, ".codex");
|
||||
|
||||
/** Match Qwen Code's home override, including tilde and cwd-relative paths. */
|
||||
const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => {
|
||||
@@ -98,7 +113,7 @@ const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => {
|
||||
};
|
||||
|
||||
const grokDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.GROK_HOME ?? join(home, ".grok");
|
||||
env.GROK_HOME || join(home, ".grok");
|
||||
|
||||
/**
|
||||
* Hermes Agent home. `HERMES_HOME` wins; otherwise the platform default mirrors
|
||||
@@ -188,17 +203,14 @@ const ompProfile = ({ env }: ClientPathContext): string | undefined => {
|
||||
/**
|
||||
* The OMP agent directory whose `mcp.json` holds user-scope MCP servers. OMP
|
||||
* joins PI_CONFIG_DIR to the home directory, and a named profile ignores
|
||||
* PI_CODING_AGENT_DIR. OMP resolves a relative agent directory against each
|
||||
* process's working directory, so only an absolute override names one file.
|
||||
* PI_CODING_AGENT_DIR. Relative overrides use the setup process working directory.
|
||||
*/
|
||||
const ompAgentDirectory = (context: ClientPathContext): string => {
|
||||
const root = join(context.home, context.env.PI_CONFIG_DIR || ".omp");
|
||||
const profile = ompProfile(context);
|
||||
if (profile !== undefined) return join(root, "profiles", profile, "agent");
|
||||
const override = context.env.PI_CODING_AGENT_DIR;
|
||||
return override !== undefined && override !== "" && isAbsolute(override)
|
||||
? override
|
||||
: join(root, "agent");
|
||||
return override ? resolve(override) : join(root, "agent");
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -242,21 +254,66 @@ const copilotDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
const commandCodeDirectory = ({ home }: ClientPathContext): string =>
|
||||
join(home, ".commandcode");
|
||||
|
||||
const opencodeDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "opencode");
|
||||
/**
|
||||
* OpenCode appends `OPENCODE_CONFIG_DIR` only when the value is non-empty.
|
||||
* An empty variable is the same as unset and leaves the XDG directory in place.
|
||||
*/
|
||||
const openCodeOverrideDirectory = (
|
||||
env: ClientPathContext["env"],
|
||||
): string | undefined => {
|
||||
const directory = env.OPENCODE_CONFIG_DIR;
|
||||
return directory === undefined || directory === "" ? undefined : directory;
|
||||
};
|
||||
|
||||
const opencodeDirectory = (context: ClientPathContext): string =>
|
||||
openCodeOverrideDirectory(context.env) ??
|
||||
join(
|
||||
context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
|
||||
"opencode",
|
||||
);
|
||||
|
||||
/** OpenCode loads global JSON before JSONC, then explicit file and directory overrides. */
|
||||
const openCodeConfigurationPaths = (
|
||||
context: ClientPathContext,
|
||||
): readonly string[] => {
|
||||
const directory = join(
|
||||
context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
|
||||
"opencode",
|
||||
);
|
||||
const overrideDirectory = openCodeOverrideDirectory(context.env);
|
||||
const paths = [
|
||||
join(directory, "config.json"),
|
||||
join(directory, "opencode.json"),
|
||||
join(directory, "opencode.jsonc"),
|
||||
...(context.env.OPENCODE_CONFIG ? [context.env.OPENCODE_CONFIG] : []),
|
||||
...(overrideDirectory !== undefined
|
||||
? [
|
||||
join(overrideDirectory, "opencode.json"),
|
||||
join(overrideDirectory, "opencode.jsonc"),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
const resolved = paths.map((path) => resolve(path));
|
||||
return resolved.filter((path, index) => resolved.lastIndexOf(path) === index);
|
||||
};
|
||||
|
||||
const existingOpenCodeConfigPath = (context: ClientPathContext): string => {
|
||||
if (context.env.OPENCODE_CONFIG !== undefined)
|
||||
return context.env.OPENCODE_CONFIG;
|
||||
const directory = opencodeDirectory(context);
|
||||
const candidates = [
|
||||
"opencode.json",
|
||||
"opencode.jsonc",
|
||||
".opencode.json",
|
||||
".opencode.jsonc",
|
||||
].map((filename) => join(directory, filename));
|
||||
// The selected directory is loaded after an explicit file by OpenCode V1.
|
||||
const overrideDirectory = openCodeOverrideDirectory(context.env);
|
||||
const candidates =
|
||||
overrideDirectory !== undefined
|
||||
? [
|
||||
join(overrideDirectory, "opencode.json"),
|
||||
join(overrideDirectory, "opencode.jsonc"),
|
||||
].map((path) => resolve(path))
|
||||
: context.env.OPENCODE_CONFIG
|
||||
? [resolve(context.env.OPENCODE_CONFIG)]
|
||||
: [
|
||||
join(opencodeDirectory(context), "opencode.json"),
|
||||
join(opencodeDirectory(context), "opencode.jsonc"),
|
||||
].map((path) => resolve(path));
|
||||
return (
|
||||
candidates.find((path) => {
|
||||
[...candidates].reverse().find((path) => {
|
||||
try {
|
||||
lstatSync(path);
|
||||
return true;
|
||||
@@ -268,15 +325,52 @@ const existingOpenCodeConfigPath = (context: ClientPathContext): string => {
|
||||
);
|
||||
}
|
||||
}) ??
|
||||
candidates[0] ??
|
||||
join(directory, "opencode.json")
|
||||
resolve(
|
||||
overrideDirectory !== undefined
|
||||
? join(overrideDirectory, "opencode.json")
|
||||
: context.env.OPENCODE_CONFIG ||
|
||||
join(opencodeDirectory(context), "opencode.json"),
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const geminiSettings = ({
|
||||
home,
|
||||
platform,
|
||||
env,
|
||||
}: ClientPathContext): NonNullable<SetupClient["geminiSettings"]> => {
|
||||
const system =
|
||||
env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ||
|
||||
(platform === "darwin"
|
||||
? "/Library/Application Support/GeminiCli/settings.json"
|
||||
: platform === "win32"
|
||||
? "C:\\ProgramData\\gemini-cli\\settings.json"
|
||||
: "/etc/gemini-cli/settings.json");
|
||||
const trustOverride =
|
||||
env.GEMINI_RESTRICTED_MODE === "true" ||
|
||||
env.GEMINI_CLI_TRUST_WORKSPACE === "false"
|
||||
? false
|
||||
: env.GEMINI_CLI_TRUST_WORKSPACE === "true"
|
||||
? true
|
||||
: undefined;
|
||||
return {
|
||||
systemPath: system,
|
||||
defaultsPath:
|
||||
env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ||
|
||||
join(dirname(system), "system-defaults.json"),
|
||||
workspaceDirectory: process.cwd(),
|
||||
trustedFoldersPath:
|
||||
env.GEMINI_CLI_TRUSTED_FOLDERS_PATH ||
|
||||
join(env.GEMINI_CLI_HOME || home, ".gemini", "trustedFolders.json"),
|
||||
...(trustOverride === undefined ? {} : { trustOverride }),
|
||||
platform,
|
||||
};
|
||||
};
|
||||
|
||||
const devinDirectory = ({ home, platform, env }: ClientPathContext): string =>
|
||||
platform === "win32"
|
||||
? join(env.APPDATA ?? join(home, "AppData", "Roaming"), "devin")
|
||||
: join(home, ".config", "devin");
|
||||
: join(env.XDG_CONFIG_HOME || join(home, ".config"), "devin");
|
||||
|
||||
/** Stable product metadata used to derive setup discovery and documentation. */
|
||||
export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
@@ -316,8 +410,13 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
{
|
||||
name: "gemini_cli",
|
||||
displayName: "Gemini CLI",
|
||||
configPath: [".gemini", "settings.json"],
|
||||
markerPath: [".gemini"],
|
||||
geminiSettings,
|
||||
configPath: ({ home, env }: ClientPathContext) =>
|
||||
join(env.GEMINI_CLI_HOME || home, ".gemini", "settings.json"),
|
||||
markerPath: ({ home, env }: ClientPathContext) =>
|
||||
join(env.GEMINI_CLI_HOME || home, ".gemini"),
|
||||
skillPath: ({ home, env }: ClientPathContext) =>
|
||||
join(env.GEMINI_CLI_HOME || home, ".agents", "skills"),
|
||||
format: "json",
|
||||
},
|
||||
{
|
||||
@@ -339,12 +438,14 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
name: "opencode",
|
||||
displayName: "OpenCode",
|
||||
configPath: existingOpenCodeConfigPath,
|
||||
configPaths: openCodeConfigurationPaths,
|
||||
markerPath: opencodeDirectory,
|
||||
format: "opencode",
|
||||
},
|
||||
{
|
||||
name: "antigravity",
|
||||
displayName: "Antigravity",
|
||||
skillPath: [".gemini", "config", "skills"],
|
||||
configPath: [".gemini", "config", "mcp_config.json"],
|
||||
markerPath: [".gemini", "config"],
|
||||
format: "json",
|
||||
@@ -427,6 +528,23 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
},
|
||||
] as const satisfies readonly ClientDefinition[];
|
||||
|
||||
/**
|
||||
* Paths whose presence means doctor and setup should inspect the client.
|
||||
* Layered sources count: OpenCode still loads its XDG files when a custom
|
||||
* directory override does not exist.
|
||||
*/
|
||||
export const clientEvidencePaths = (
|
||||
client: Pick<SetupClient, "configPath" | "configPaths" | "markerPath">,
|
||||
): readonly string[] => [
|
||||
...new Set(
|
||||
[
|
||||
client.configPath,
|
||||
...(client.configPaths ?? []),
|
||||
client.markerPath,
|
||||
].filter((path): path is string => path !== undefined && path.length > 0),
|
||||
),
|
||||
];
|
||||
|
||||
const resolvePath = (path: ClientPath, context: ClientPathContext): string =>
|
||||
typeof path === "function" ? path(context) : join(context.home, ...path);
|
||||
|
||||
@@ -437,12 +555,24 @@ export const supportedClients = (
|
||||
env: ClientPathContext["env"] = process.env,
|
||||
): readonly SetupClient[] => {
|
||||
const context = { home, platform, env };
|
||||
return SUPPORTED_CLIENT_DEFINITIONS.map((definition) => {
|
||||
const definitions: readonly ClientDefinition[] = SUPPORTED_CLIENT_DEFINITIONS;
|
||||
return definitions.map((definition) => {
|
||||
try {
|
||||
const configPath = resolvePath(definition.configPath, context);
|
||||
return {
|
||||
name: definition.name,
|
||||
displayName: definition.displayName,
|
||||
configPath: resolvePath(definition.configPath, context),
|
||||
configPath,
|
||||
...(definition.geminiSettings === undefined
|
||||
? {}
|
||||
: { geminiSettings: definition.geminiSettings(context) }),
|
||||
...(definition.configPaths === undefined
|
||||
? {}
|
||||
: {
|
||||
configPaths: [
|
||||
...new Set([...definition.configPaths(context), configPath]),
|
||||
],
|
||||
}),
|
||||
markerPath: resolvePath(definition.markerPath, context),
|
||||
format: definition.format,
|
||||
};
|
||||
|
||||
@@ -124,11 +124,12 @@ export const runUninstall = async (
|
||||
status: "retained",
|
||||
detail: "Hopper is not owned by REA uninstall.",
|
||||
});
|
||||
const reported = collapseUninstallItems(items);
|
||||
return {
|
||||
status: items.some(({ status }) => status === "failed")
|
||||
status: reported.some(({ status }) => status === "failed")
|
||||
? "failed"
|
||||
: "complete",
|
||||
items,
|
||||
items: reported,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -171,7 +172,16 @@ export const systemUninstallHost = (
|
||||
selectedHome ?? homeDirectoryFromEnvironment(environment, platform);
|
||||
return {
|
||||
clients: () =>
|
||||
Promise.resolve(supportedClients(home, platform, environment)),
|
||||
Promise.resolve(
|
||||
supportedClients(home, platform, environment).flatMap((client) =>
|
||||
client.configPaths === undefined
|
||||
? [client]
|
||||
: client.configPaths.map((configPath) => ({
|
||||
...client,
|
||||
configPath,
|
||||
})),
|
||||
),
|
||||
),
|
||||
inspectClient: async (client) => {
|
||||
const read = await readClientConfiguration(client, fileSystem);
|
||||
return read.kind === "item" && read.item.status === "failed"
|
||||
@@ -452,6 +462,68 @@ const item = (
|
||||
status: UninstallItem["status"],
|
||||
detail: string,
|
||||
): UninstallItem => ({ name, status, detail });
|
||||
|
||||
/**
|
||||
* Layered clients are removed file by file, but callers look up one status by
|
||||
* client name. A missing earlier file must not hide a later removal.
|
||||
*/
|
||||
const collapseUninstallItems = (
|
||||
items: readonly UninstallItem[],
|
||||
): UninstallItem[] => {
|
||||
const collapsed: UninstallItem[] = [];
|
||||
for (const next of items) {
|
||||
const index = collapsed.findIndex(({ name }) => name === next.name);
|
||||
const current = collapsed[index];
|
||||
if (current === undefined) {
|
||||
collapsed.push(next);
|
||||
continue;
|
||||
}
|
||||
collapsed[index] = mergeUninstallItems(current, next);
|
||||
}
|
||||
return collapsed;
|
||||
};
|
||||
|
||||
const mergeUninstallItems = (
|
||||
current: UninstallItem,
|
||||
next: UninstallItem,
|
||||
): UninstallItem => {
|
||||
const status = preferredUninstallStatus(current.status, next.status);
|
||||
const details = [current, next]
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.status === status ||
|
||||
(status === "removed" && entry.status === "retained"),
|
||||
)
|
||||
.map(({ detail }) => detail);
|
||||
return item(current.name, status, [...new Set(details)].join(" "));
|
||||
};
|
||||
|
||||
const preferredUninstallStatus = (
|
||||
current: UninstallItem["status"],
|
||||
next: UninstallItem["status"],
|
||||
): UninstallItem["status"] =>
|
||||
uninstallStatusPriority(next) > uninstallStatusPriority(current)
|
||||
? next
|
||||
: current;
|
||||
|
||||
const uninstallStatusPriority = (status: UninstallItem["status"]): number => {
|
||||
switch (status) {
|
||||
case "failed":
|
||||
return 3;
|
||||
case "removed":
|
||||
return 2;
|
||||
case "retained":
|
||||
return 1;
|
||||
case "skipped":
|
||||
return 0;
|
||||
default: {
|
||||
const exhaustive: never = status;
|
||||
throw new TypeError(
|
||||
`Unhandled uninstall item status: ${String(exhaustive)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
const registrationSchema = z
|
||||
.object({ command: z.string(), args: z.array(z.string()) })
|
||||
.passthrough();
|
||||
|
||||
Reference in New Issue
Block a user