2026-10-10 17:03:43 +08:00
import { readClientPolicyBlock } from "./GeminiClientSettings.js" ;
import { readClientConfigurationFiles } from "./ClientConfigurationFiles.js" ;
2026-09-08 10:59:13 +08:00
import {
2026-10-05 23:06:19 +08:00
clientRegistrationEntry ,
2026-09-30 00:41:05 +08:00
clientConfigurationValuesEqual ,
2026-10-09 08:51:12 -07:00
clientServerListedDisabled ,
2026-10-06 21:58:20 -07:00
clientServerPath ,
legacyClientServerPath ,
2026-10-09 08:51:12 -07:00
OMP_DISABLED_SERVERS_KEY ,
2026-09-08 10:59:13 +08:00
parseClientConfiguration ,
serializeClientConfiguration ,
2026-10-06 21:58:20 -07:00
withClientServers ,
2026-09-08 10:59:13 +08:00
type ClientConfigurationDocument ,
} from "./ClientConfigurationDocument.js" ;
2026-10-12 05:06:26 +02:00
import { dshDocument , DshCordisDocument } from "./DshCordisPatch.js" ;
2026-07-18 04:11:29 +00:00
import { constants as fsConstants } from "node:fs" ;
2026-10-11 00:27:36 +08:00
import { copyFile , mkdir , rm , writeFile } from "node:fs/promises" ;
2026-07-18 04:11:29 +00:00
import { dirname } from "node:path" ;
import writeFileAtomic from "write-file-atomic" ;
2026-10-10 23:23:02 +01:00
import { clientRegistrationEnvironment } from "./ClientRegistrationEnvironment.js" ;
2026-07-18 04:11:29 +00:00
import { PRODUCT_IDENTITY } from "../identity.js" ;
2026-10-08 22:11:54 +08:00
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js" ;
2026-07-26 15:02:58 +00:00
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js" ;
2026-07-18 04:11:29 +00:00
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js" ;
2026-10-11 06:30:31 +08:00
import {
readRegularFileText ,
RegularFileCleanupFailure ,
} from "./RegularFileRead.js" ;
import type { ClientConfigurationFileError } from "./ClientConfigurationFiles.js" ;
2026-07-18 04:11:29 +00:00
import type {
2026-07-18 05:18:05 +00:00
ClientConfigurationInspection ,
2026-07-18 04:11:29 +00:00
ClientConfigurationResult ,
SetupProviderEnvironment ,
2026-10-06 05:00:32 +08:00
} from "./SetupTypes.js" ;
2026-07-18 04:11:29 +00:00
import type { SetupClient } from "./SupportedClients.js" ;
2026-10-09 00:20:50 +08:00
/** Configure one supported client's native stdio MCP registration shape. */
export const configureClientConfiguration = (
client : SetupClient ,
environment : SetupProviderEnvironment = {},
2026-10-09 23:17:17 +08:00
command : readonly string [] = npxRegistrationCommand (),
2026-10-09 00:20:50 +08:00
) : Promise < ClientConfigurationResult > => {
2026-10-10 01:10:39 -07:00
if ( client . configPathError !== undefined )
return Promise . resolve ({ status : "failed" , reason : "path" });
2026-10-11 06:30:31 +08:00
return configureClientDocument ( client , environment , command );
2026-10-09 00:20:50 +08:00
};
2026-09-08 10:59:13 +08:00
const configureClientDocument = async (
client : SetupClient ,
environment : SetupProviderEnvironment ,
command : readonly string [],
2026-07-18 04:11:29 +00:00
) : Promise < ClientConfigurationResult > => {
2026-10-11 06:30:31 +08:00
const format = client . format ;
if ( format === undefined || format === "unsupported" )
return { status : "failed" , reason : "readback" };
2026-10-10 17:03:43 +08:00
const files = await readClientConfigurationFiles ( client );
2026-10-11 06:30:31 +08:00
if ( ! files . ok ) {
throwCleanupFailure ( files . error );
return { status : "failed" , reason : "readback" };
}
2026-10-10 17:03:43 +08:00
const policy = await readClientPolicyBlock (
client ,
undefined ,
2026-10-10 23:23:02 +01:00
clientConfigurationDesired (
client ,
environment ,
command ,
files . value . at ( - 1 ),
),
2026-10-10 17:03:43 +08:00
);
2026-10-11 06:30:31 +08:00
if ( ! policy . ok ) {
throwCleanupFailure ( policy . error );
return { status : "failed" , reason : "readback" };
}
if ( policy . value !== undefined )
2026-10-10 17:03:43 +08:00
return { status : "failed" , reason : "readback" };
2026-07-18 04:11:29 +00:00
const transactionPath = await resolveClientConfigTransactionPath (
client . configPath ,
);
if ( transactionPath === undefined )
return { status : "failed" , reason : "path" };
let original : string | undefined ;
try {
2026-10-11 00:27:36 +08:00
original = await readRegularFileText ( transactionPath );
2026-07-18 04:11:29 +00:00
} catch ( cause : unknown ) {
2026-10-11 06:30:31 +08:00
if ( cause instanceof RegularFileCleanupFailure ) throw cause ;
2026-07-18 04:11:29 +00:00
if ( ! isMissing ( cause )) return { status : "failed" , reason : "readback" };
}
2026-09-08 10:59:13 +08:00
let parsed : ClientConfigurationDocument ;
2026-07-18 04:11:29 +00:00
try {
2026-09-08 10:59:13 +08:00
parsed = parseClientConfiguration (
2026-10-12 05:06:26 +02:00
original ??
( format === "toml" || format === "grok" || format === "dsh"
? ""
: "{}" ),
2026-09-08 10:59:13 +08:00
format ,
);
2026-10-10 17:03:43 +08:00
const policy = await readClientPolicyBlock (
client ,
parsed ,
2026-10-10 23:23:02 +01:00
clientConfigurationDesired ( client , environment , command , parsed ),
2026-10-10 17:03:43 +08:00
);
2026-10-11 06:30:31 +08:00
if ( ! policy . ok ) {
throwCleanupFailure ( policy . error );
return { status : "failed" , reason : "readback" };
}
if ( policy . value !== undefined )
2026-10-10 17:03:43 +08:00
return { status : "failed" , reason : "readback" };
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
2026-10-11 06:30:31 +08:00
if ( cause instanceof RegularFileCleanupFailure ) throw cause ;
2026-10-06 05:58:46 +08:00
// Malformed existing configuration fails the readback gate.
void cause ;
2026-07-18 04:11:29 +00:00
return { status : "failed" , reason : "readback" };
}
2026-10-05 23:06:19 +08:00
const desired = clientConfigurationDesired (
client ,
environment ,
command ,
2026-10-10 23:23:02 +01:00
parsed ,
2026-10-05 23:06:19 +08:00
);
2026-10-06 21:58:20 -07:00
if ( registrationCurrent ( parsed , desired )) return { status : "unchanged" };
2026-10-11 06:30:31 +08:00
return persistClientConfiguration ({
client ,
transactionPath ,
format ,
original ,
parsed ,
desired ,
});
};
interface ClientConfigurationUpdate {
readonly client : SetupClient ;
readonly transactionPath : string ;
readonly format : NonNullable < SetupClient [ "format" ] >;
readonly original : string | undefined ;
readonly parsed : ClientConfigurationDocument ;
readonly desired : unknown ;
}
const persistClientConfiguration = async ({
client ,
transactionPath ,
format ,
original ,
parsed ,
desired ,
} : ClientConfigurationUpdate ) : Promise < ClientConfigurationResult > => {
2026-09-08 10:59:13 +08:00
const backupPath =
original === undefined ? undefined : ` ${ client . configPath } .rea.backup` ;
if (
backupPath !== undefined &&
! ( await preserveConfigBackup ( transactionPath , backupPath ))
)
return { status : "failed" , reason : "backup" };
2026-10-06 21:58:20 -07:00
// A native OpenCode V2 entry replaces REA's legacy V1 entry, which would
// otherwise conflict with it.
const legacyPath = legacyClientServerPath (
parsed ,
PRODUCT_IDENTITY . mcpServerKey ,
);
2026-10-09 08:51:12 -07:00
const registered = withClientServers (
2026-10-06 21:58:20 -07:00
parsed ,
{ ... parsed . servers , [ PRODUCT_IDENTITY . mcpServerKey ] : desired },
PRODUCT_IDENTITY . mcpServerKey ,
);
2026-10-09 08:51:12 -07:00
// OMP's denylist would hide the registration; keep every other listed name.
const ompDisabled =
parsed . dialect === "omp"
? parsed . document [ OMP_DISABLED_SERVERS_KEY ]
: undefined ;
const enableOmp =
Array . isArray ( ompDisabled ) &&
ompDisabled . includes ( PRODUCT_IDENTITY . mcpServerKey );
const document =
enableOmp && Array . isArray ( ompDisabled )
? {
... registered ,
[ OMP_DISABLED_SERVERS_KEY ] : ompDisabled . filter (
( name : unknown ) => name !== PRODUCT_IDENTITY . mcpServerKey ,
),
}
: registered ;
2026-07-18 04:11:29 +00:00
try {
await mkdir ( dirname ( client . configPath ), { recursive : true });
await writeFileAtomic (
transactionPath ,
2026-10-06 21:58:20 -07:00
serializeClientConfiguration ( document , format , original , [
clientServerPath ( parsed , PRODUCT_IDENTITY . mcpServerKey ),
...( legacyPath === undefined ? [] : [ legacyPath ]),
2026-10-09 08:51:12 -07:00
...( enableOmp ? [[ OMP_DISABLED_SERVERS_KEY ]] : []),
2026-10-06 21:58:20 -07:00
]),
2026-07-18 04:11:29 +00:00
{
encoding : "utf8" ,
mode : 0o600 ,
},
);
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
// Write failure is reported by the status reason.
void cause ;
2026-07-18 04:11:29 +00:00
return { status : "failed" , reason : "write" };
}
try {
2026-09-08 10:59:13 +08:00
const readback = parseClientConfiguration (
2026-10-11 00:27:36 +08:00
await readRegularFileText ( transactionPath ),
2026-09-08 10:59:13 +08:00
format ,
);
2026-10-06 21:58:20 -07:00
if ( ! registrationCurrent ( readback , desired )) {
2026-07-18 04:11:29 +00:00
await restoreConfig ( transactionPath , original );
return { status : "failed" , reason : "readback" };
}
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
2026-10-11 06:30:31 +08:00
if ( cause instanceof RegularFileCleanupFailure ) throw cause ;
2026-10-06 05:58:46 +08:00
// Readback failure restores the transaction before reporting.
void cause ;
2026-07-18 04:11:29 +00:00
await restoreConfig ( transactionPath , original );
return { status : "failed" , reason : "readback" };
}
return {
status : "configured" ,
...( backupPath === undefined ? {} : { backupPath }),
};
};
/** Determine whether an existing client configuration matches the desired registration. */
export const clientConfigurationAligned = async (
client : SetupClient ,
providerEnvironment : SetupProviderEnvironment ,
command : readonly string [],
) : Promise < boolean > => {
2026-10-10 01:10:39 -07:00
if ( client . configPathError !== undefined ) return false ;
2026-07-18 04:11:29 +00:00
try {
2026-10-10 17:03:43 +08:00
const files = await readClientConfigurationFiles ( client );
2026-10-11 06:30:31 +08:00
if ( ! files . ok ) {
throwCleanupFailure ( files . error );
return false ;
}
2026-10-11 00:27:36 +08:00
const original = await readRegularFileText ( client . configPath );
2026-10-06 21:58:20 -07:00
const parsed = parseClientConfiguration ( original , client . format );
2026-10-10 17:03:43 +08:00
const policy = await readClientPolicyBlock (
client ,
2026-10-06 21:58:20 -07:00
parsed ,
2026-10-10 23:23:02 +01:00
clientConfigurationDesired ( client , providerEnvironment , command , parsed ),
2026-09-30 00:41:05 +08:00
);
2026-10-11 06:30:31 +08:00
if ( ! policy . ok ) {
throwCleanupFailure ( policy . error );
return false ;
}
2026-10-10 17:03:43 +08:00
return (
policy . value === undefined &&
registrationCurrent (
parsed ,
clientConfigurationDesired (
client ,
providerEnvironment ,
command ,
2026-10-10 23:23:02 +01:00
parsed ,
2026-10-10 17:03:43 +08:00
),
)
);
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
2026-10-11 06:30:31 +08:00
if ( cause instanceof RegularFileCleanupFailure ) throw cause ;
2026-10-06 05:58:46 +08:00
// Unreadable configuration is treated as not aligned so setup repairs it.
void cause ;
2026-07-18 04:11:29 +00:00
return false ;
}
};
2026-07-18 05:18:05 +00:00
/** Preflight one client configuration before setup presents any mutations. */
export const inspectClientConfiguration = async (
client : SetupClient ,
providerEnvironment : SetupProviderEnvironment ,
command : readonly string [],
) : Promise < ClientConfigurationInspection > => {
2026-10-10 01:10:39 -07:00
if ( client . configPathError !== undefined )
return { status : "invalid" , remediation : client.configPathError };
2026-07-18 05:18:05 +00:00
if ( client . format === "unsupported" ) return { status : "already_current" };
2026-10-10 17:03:43 +08:00
const files = await readClientConfigurationFiles ( client );
2026-10-11 06:30:31 +08:00
if ( ! files . ok ) {
throwCleanupFailure ( files . error );
return {
status : "invalid" ,
remediation : files.error.detail ,
};
}
2026-10-10 17:03:43 +08:00
const policy = await readClientPolicyBlock (
client ,
undefined ,
clientConfigurationDesired (
client ,
providerEnvironment ,
command ,
2026-10-10 23:23:02 +01:00
files . value . at ( - 1 ),
2026-10-10 17:03:43 +08:00
),
);
2026-10-11 06:30:31 +08:00
if ( ! policy . ok ) {
throwCleanupFailure ( policy . error );
return {
status : "invalid" ,
remediation : policy.error.detail ,
};
}
2026-10-10 17:03:43 +08:00
if ( policy . value !== undefined )
return { status : "invalid" , remediation : policy.value };
2026-07-18 05:18:05 +00:00
const transactionPath = await resolveClientConfigTransactionPath (
client . configPath ,
);
if ( transactionPath === undefined )
return {
status : "invalid" ,
remediation :
"The configuration path is unsafe or unresolved. Check ownership and symbolic links before rerunning setup." ,
};
let original : string ;
try {
2026-10-11 00:27:36 +08:00
original = await readRegularFileText ( transactionPath );
2026-07-18 05:18:05 +00:00
} catch ( cause : unknown ) {
2026-10-11 06:30:31 +08:00
if ( cause instanceof RegularFileCleanupFailure ) throw cause ;
2026-07-18 05:18:05 +00:00
if ( isMissing ( cause )) return { status : "create" };
return {
status : "invalid" ,
2026-10-11 06:30:31 +08:00
remediation : `The configuration file could not be read. Check its permissions before rerunning setup. ${ cause instanceof Error ? cause.message : String ( cause ) } ` ,
2026-07-18 05:18:05 +00:00
};
}
try {
2026-10-06 21:58:20 -07:00
const parsed = parseClientConfiguration ( original , client . format );
2026-10-10 17:03:43 +08:00
const policy = await readClientPolicyBlock (
client ,
parsed ,
2026-10-10 23:23:02 +01:00
clientConfigurationDesired ( client , providerEnvironment , command , parsed ),
2026-10-10 17:03:43 +08:00
);
2026-10-11 06:30:31 +08:00
if ( ! policy . ok ) {
throwCleanupFailure ( policy . error );
return {
status : "invalid" ,
remediation : policy.error.detail ,
};
}
2026-10-10 17:03:43 +08:00
if ( policy . value !== undefined )
return { status : "invalid" , remediation : policy.value };
2026-10-06 21:58:20 -07:00
const desired = clientConfigurationDesired (
client ,
providerEnvironment ,
command ,
2026-10-10 23:23:02 +01:00
parsed ,
2026-10-06 21:58:20 -07:00
);
if ( registrationCurrent ( parsed , desired ))
2026-07-18 05:18:05 +00:00
return { status : "already_current" };
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
2026-10-11 06:30:31 +08:00
if ( cause instanceof RegularFileCleanupFailure ) throw cause ;
2026-10-06 05:58:46 +08:00
// Malformed configuration is reported with the invalid remediation.
void cause ;
2026-07-18 05:18:05 +00:00
return {
status : "invalid" ,
remediation :
"The existing configuration is malformed. Repair it before setup applies any other changes." ,
};
}
return {
status : "update" ,
backupPath : ` ${ client . configPath } .rea.backup` ,
};
};
2026-07-18 04:11:29 +00:00
const isMissing = ( cause : unknown ) : boolean =>
cause instanceof Error && "code" in cause && cause . code === "ENOENT" ;
2026-10-11 06:30:31 +08:00
const throwCleanupFailure = ( error : ClientConfigurationFileError ) : void => {
if ( error . cleanupFailure !== undefined ) throw error . cleanupFailure ;
};
2026-07-18 04:11:29 +00:00
const preserveConfigBackup = async (
source : string ,
destination : string ,
) : Promise < boolean > => {
try {
await copyFile ( source , destination , fsConstants . COPYFILE_EXCL );
return true ;
} catch ( cause : unknown ) {
return cause instanceof Error && "code" in cause && cause . code === "EEXIST" ;
}
};
const restoreConfig = async (
path : string ,
original : string | undefined ,
) : Promise < void > => {
try {
if ( original === undefined ) await rm ( path , { force : true });
else await writeFile ( path , original , { encoding : "utf8" , mode : 0o600 });
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
2026-07-18 04:11:29 +00:00
// The backup remains available for the remediation reported by setup.
2026-10-06 05:58:46 +08:00
void cause ;
2026-07-18 04:11:29 +00:00
}
};
2026-10-09 08:51:12 -07:00
/** Whether REA's entry matches, no legacy entry remains, and no client disable list suppresses it. */
2026-10-06 21:58:20 -07:00
const registrationCurrent = (
parsed : ClientConfigurationDocument ,
desired : unknown ,
) : boolean =>
2026-10-12 05:06:26 +02:00
( parsed . dialect !== "dsh" || dshDocument ( parsed . document ). ready ) &&
2026-10-06 21:58:20 -07:00
clientConfigurationValuesEqual (
parsed . servers [ PRODUCT_IDENTITY . mcpServerKey ],
desired ,
2026-10-09 06:08:29 +08:00
) &&
! Object . hasOwn ( parsed . legacyServers , PRODUCT_IDENTITY . mcpServerKey ) &&
2026-10-09 08:51:12 -07:00
! clientServerListedDisabled ( parsed , PRODUCT_IDENTITY . mcpServerKey );
2026-10-06 21:58:20 -07:00
2026-07-18 04:11:29 +00:00
const clientConfigurationDesired = (
2026-07-20 17:11:06 +08:00
client : SetupClient ,
2026-07-18 04:11:29 +00:00
providerEnvironment : SetupProviderEnvironment ,
command : readonly string [],
2026-10-10 23:23:02 +01:00
parsed? : ClientConfigurationDocument ,
2026-07-18 04:11:29 +00:00
) => {
2026-10-10 23:23:02 +01:00
const format = parsed ? . dialect ?? client . format ?? "json" ;
2026-10-12 05:06:26 +02:00
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 ;
}
2026-10-10 23:23:02 +01:00
// Preserve explicitly configured server settings, never the ambient process
// environment. Newly discovered provider paths win only for their own keys.
const environment = clientRegistrationEnvironment (
parsed ,
providerEnvironment ,
2026-07-18 04:11:29 +00:00
);
2026-10-10 23:23:02 +01:00
if ( ! environment . ok ) throw environment . error ;
2026-10-05 23:06:19 +08:00
const registration = clientRegistrationEntry (
2026-10-10 23:23:02 +01:00
format ,
2026-10-12 05:06:26 +02:00
launcher ,
2026-10-10 23:23:02 +01:00
environment . value ,
2026-10-05 23:06:19 +08:00
);
2026-07-18 04:11:29 +00:00
return {
2026-10-05 23:06:19 +08:00
... registration ,
2026-10-09 06:08:29 +08:00
...( client . name === "codex" || client . name === "grok_build"
2026-07-26 15:02:58 +00:00
? {
startup_timeout_sec : MCP_STARTUP_POLICY.codexStartupTimeoutSeconds ,
}
2026-07-20 17:11:06 +08:00
: {}),
2026-07-18 04:11:29 +00:00
};
};