2026-10-10 17:03:43 +08:00
import { readClientPolicyBlock } from "./GeminiClientSettings.js" ;
2026-10-12 22:51:40 +08:00
import {
readClientConfigurationFiles ,
readConfigurationText ,
} from "./ClientConfigurationFiles.js" ;
import { err , ok , type Result } from "../domain/result.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 ,
2026-10-12 22:51:40 +08:00
parseZcodeFallbackConfiguration ,
2026-09-08 10:59:13 +08:00
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-13 14:51:55 +08:00
import { createHash } from "node:crypto" ;
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-13 11:04:22 -03:00
import { packageReadTargetChanged } from "./MsixPackageStorage.js" ;
2026-10-11 06:30:31 +08:00
import {
2026-10-13 14:51:55 +08:00
readRegularFile ,
2026-10-11 06:30:31 +08:00
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-10-13 11:04:22 -03:00
import {
registrationWriteBlocker ,
type SetupClient ,
} from "./SupportedClients.js" ;
2026-07-18 04:11:29 +00:00
2026-10-13 14:51:55 +08:00
export class ClientConfigurationCleanupRollbackFailure extends RegularFileCleanupFailure < string > {
constructor (
failure : RegularFileCleanupFailure < string >,
readonly configurationFailure : Extract <
ClientConfigurationResult ,
{ readonly status : "failed" ; readonly reason : "rollback" }
> ,
) {
super (
failure . path ,
failure . owner ,
failure . outcome ,
new AggregateError (
[ failure . cleanupCause , new Error ( configurationFailure . failure . detail )],
`Configuration readback cleanup and rollback failed: ${ configurationFailure . failure . path } ` ,
),
);
}
}
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-12 11:58:49 +08:00
const existing = files . value . at ( - 1 );
const editabilityError =
existing ? . dialect === "dsh"
? dshDocument ( existing . document ). editabilityError
: undefined ;
if ( editabilityError !== undefined )
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-12 22:51:40 +08:00
const fallback = await readZcodeFallbackServers ( client , parsed );
if ( ! fallback . ok ) {
throwCleanupFailure ( fallback . error );
return { status : "failed" , reason : "readback" };
}
const desired = clientConfigurationDesired ( client , environment , command , {
... parsed ,
servers : { ... fallback . value , ... parsed . servers },
});
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 ,
2026-10-12 22:51:40 +08:00
fallbackServers : fallback.value ,
2026-10-11 06:30:31 +08:00
});
};
interface ClientConfigurationUpdate {
readonly client : SetupClient ;
readonly transactionPath : string ;
readonly format : NonNullable < SetupClient [ "format" ] >;
readonly original : string | undefined ;
readonly parsed : ClientConfigurationDocument ;
readonly desired : unknown ;
2026-10-12 22:51:40 +08:00
readonly fallbackServers : Readonly < Record < string , unknown >>;
2026-10-11 06:30:31 +08:00
}
const persistClientConfiguration = async ({
client ,
transactionPath ,
format ,
original ,
parsed ,
desired ,
2026-10-12 22:51:40 +08:00
fallbackServers ,
2026-10-11 06:30:31 +08:00
} : ClientConfigurationUpdate ) : Promise < ClientConfigurationResult > => {
2026-10-13 11:04:22 -03:00
// The plan chose this file; an MSIX package may have switched to its
// private copy since, for example when it quit.
if (
client . msixPackage !== undefined &&
( await packageReadTargetChanged ( client . msixPackage , client . configPath ))
)
return { status : "failed" , reason : "target_changed" };
2026-09-08 10:59:13 +08:00
const backupPath =
original === undefined ? undefined : ` ${ client . configPath } .rea.backup` ;
2026-10-13 14:51:55 +08:00
let recoveryBackupPath : string | undefined ;
if ( backupPath !== undefined && original !== undefined ) {
const selection = await selectCurrentRecoveryBackup ( backupPath , original );
if ( ! selection . ok ) return { status : "failed" , reason : "backup" };
if (
! ( await preserveConfigBackup ( transactionPath , selection . value . backupPath ))
)
return { status : "failed" , reason : "backup" };
const verified = await selectCurrentRecoveryBackup ( backupPath , original );
if (
! verified . ok ||
verified . value . backupPath !== selection . value . backupPath ||
! verified . value . present
)
return { status : "failed" , reason : "backup" };
recoveryBackupPath = verified . value . backupPath ;
}
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 ,
2026-10-12 22:51:40 +08:00
{
... fallbackServers ,
... parsed . servers ,
[ PRODUCT_IDENTITY . mcpServerKey ] : desired ,
},
2026-10-06 21:58:20 -07:00
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 , [
2026-10-12 22:51:40 +08:00
... Object . keys ( fallbackServers )
. filter (( name ) => name !== PRODUCT_IDENTITY . mcpServerKey )
. map (( name ) => clientServerPath ( parsed , name )),
2026-10-06 21:58:20 -07:00
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-12 22:51:40 +08:00
if (
! registrationCurrent ( readback , desired ) ||
Object . entries ( fallbackServers ). some (
([ name , entry ]) =>
name !== PRODUCT_IDENTITY . mcpServerKey &&
! clientConfigurationValuesEqual ( readback . servers [ name ], entry ),
)
) {
2026-10-13 14:51:55 +08:00
return rollbackOrReadbackFailure (
transactionPath ,
original ,
recoveryBackupPath ,
);
2026-07-18 04:11:29 +00:00
}
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
2026-10-13 14:51:55 +08:00
if ( cause instanceof RegularFileCleanupFailure ) {
const rollback = await restoreConfig ( transactionPath , original );
if ( ! rollback . ok )
throw new ClientConfigurationCleanupRollbackFailure ( cause , {
status : "failed" ,
reason : "rollback" ,
...( recoveryBackupPath === undefined
? {}
: { backupPath : recoveryBackupPath }),
failure : rollback.error ,
});
throw cause ;
}
2026-10-06 05:58:46 +08:00
// Readback failure restores the transaction before reporting.
void cause ;
2026-10-13 14:51:55 +08:00
return rollbackOrReadbackFailure (
transactionPath ,
original ,
recoveryBackupPath ,
);
2026-07-18 04:11:29 +00:00
}
return {
status : "configured" ,
2026-10-13 14:51:55 +08:00
...( recoveryBackupPath === undefined
? {}
: { backupPath : recoveryBackupPath }),
2026-07-18 04:11:29 +00:00
};
};
/** 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 [],
2026-10-13 11:04:22 -03:00
) : Promise < ClientConfigurationInspection > => {
const inspection = await inspectClientDocument (
client ,
providerEnvironment ,
command ,
);
if ( inspection . status !== "create" && inspection . status !== "update" )
return inspection ;
// A change the running client would overwrite is not a persisted registration.
const blocker = registrationWriteBlocker ( client , "setup" );
return blocker === undefined
? inspection
: { status : "invalid" , remediation : blocker };
};
const inspectClientDocument = async (
client : SetupClient ,
providerEnvironment : SetupProviderEnvironment ,
command : readonly string [],
2026-07-18 05:18:05 +00:00
) : 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-12 11:58:49 +08:00
const existing = files . value . at ( - 1 );
const editabilityError =
existing ? . dialect === "dsh"
? dshDocument ( existing . document ). editabilityError
: undefined ;
if ( editabilityError !== undefined )
return {
status : "invalid" ,
remediation : editabilityError.message ,
};
2026-10-10 17:03:43 +08:00
const policy = await readClientPolicyBlock (
client ,
undefined ,
2026-10-12 11:58:49 +08:00
clientConfigurationDesired ( client , providerEnvironment , command , existing ),
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-10-12 22:51:40 +08:00
if ( isMissing ( cause )) {
const fallback = await readZcodeFallbackServers ( client );
if ( ! fallback . ok ) {
throwCleanupFailure ( fallback . error );
return { status : "invalid" , remediation : fallback.error.detail };
}
return { status : "create" };
}
2026-07-18 05:18:05 +00:00
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-12 22:51:40 +08:00
const fallback = await readZcodeFallbackServers ( client , parsed );
if ( ! fallback . ok ) {
throwCleanupFailure ( fallback . error );
return { status : "invalid" , remediation : fallback.error.detail };
}
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." ,
};
}
2026-10-13 14:51:55 +08:00
const backupSelection = await selectCurrentRecoveryBackup (
` ${ client . configPath } .rea.backup` ,
original ,
);
if ( ! backupSelection . ok )
return {
status : "invalid" ,
remediation : backupSelection.error.detail ,
};
2026-07-18 05:18:05 +00:00
return {
status : "update" ,
2026-10-13 14:51:55 +08:00
backupPath : backupSelection.value.backupPath ,
2026-07-18 05:18:05 +00:00
};
};
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-10-12 22:51:40 +08:00
/** Admit the fallback only when the first native ZCode server would suppress it. */
const readZcodeFallbackServers = async (
client : SetupClient ,
parsed? : ClientConfigurationDocument ,
) : Promise <
Result < Readonly < Record < string , unknown >>, ClientConfigurationFileError >
> => {
if (
client . format !== "zcode" ||
( parsed !== undefined && Object . keys ( parsed . servers ). length > 0 )
)
return ok ({});
const path = client . zcodeFallbackPath ;
const detail = `The ZCode fallback configuration ${ path ?? "path" } is unresolved, malformed or unreadable. Repair it before rerunning setup: the first native server would suppress that fallback.` ;
if ( path === undefined )
return err ({ kind : "unreadable" , path : client.configPath , detail });
const transactionPath = await resolveClientConfigTransactionPath ( path );
if ( transactionPath === undefined )
return err ({ kind : "unreadable" , path , detail });
const source = await readConfigurationText ( transactionPath );
if ( ! source . ok )
return err ({ ... source . error , detail : ` ${ detail } ${ source . error . detail } ` });
if ( source . value === undefined ) return ok ({});
try {
const parsed = parseZcodeFallbackConfiguration ( source . value );
const environment = clientRegistrationEnvironment ( parsed );
if ( ! environment . ok )
return err ({
kind : "malformed" ,
path ,
detail : ` ${ detail } ${ environment . error . settings . map (({ setting , constraint } ) => ` $ { setting } : $ { constraint } `).join("; ")}` ,
});
return ok ( parsed . servers );
} catch ( cause : unknown ) {
return err ({
kind : "malformed" ,
path ,
detail : ` ${ detail } ${ cause instanceof Error ? cause.message : String ( cause ) } ` ,
});
}
};
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" ;
}
};
2026-10-13 14:51:55 +08:00
interface RecoveryBackupSelection {
readonly backupPath : string ;
readonly present : boolean ;
}
interface RecoveryBackupSelectionFailure {
readonly kind : "unreadable" | "occupied" ;
readonly path : string ;
readonly detail : string ;
}
const selectCurrentRecoveryBackup = async (
firstBackupPath : string ,
original : string ,
) : Promise < Result < RecoveryBackupSelection , RecoveryBackupSelectionFailure >> => {
const expected = Buffer . from ( original , "utf8" );
let firstBackup : Buffer | undefined ;
try {
firstBackup = await readRegularFile ( firstBackupPath , {
symlinks : "reject" ,
});
} catch ( cause : unknown ) {
if ( cause instanceof RegularFileCleanupFailure ) throw cause ;
if ( ! isMissing ( cause ))
return err ({
kind : "unreadable" ,
path : firstBackupPath ,
detail : `The recovery backup could not be checked: ${ errorDetail ( cause ) } ` ,
});
}
if ( firstBackup === undefined )
return ok ({ backupPath : firstBackupPath , present : false });
if ( firstBackup . equals ( expected ))
return ok ({ backupPath : firstBackupPath , present : true });
const digest = createHash ( "sha256" ). update ( original , "utf8" ). digest ( "hex" );
const recoveryPath = ` ${ firstBackupPath } . ${ digest } .recovery` ;
let recovery : Buffer | undefined ;
try {
recovery = await readRegularFile ( recoveryPath , { symlinks : "reject" });
} catch ( cause : unknown ) {
if ( cause instanceof RegularFileCleanupFailure ) throw cause ;
if ( ! isMissing ( cause ))
return err ({
kind : "unreadable" ,
path : recoveryPath ,
detail : `The recovery backup could not be checked: ${ errorDetail ( cause ) } ` ,
});
}
if ( recovery !== undefined && ! recovery . equals ( expected ))
return err ({
kind : "occupied" ,
path : recoveryPath ,
detail : `The recovery path already contains different data: ${ recoveryPath } ` ,
});
return ok ({ backupPath : recoveryPath , present : recovery !== undefined });
};
2026-07-18 04:11:29 +00:00
const restoreConfig = async (
path : string ,
original : string | undefined ,
2026-10-13 14:51:55 +08:00
) : Promise <
Result <
void ,
{ readonly kind : "restore" ; readonly path : string ; readonly detail : string }
>
> => {
2026-07-18 04:11:29 +00:00
try {
if ( original === undefined ) await rm ( path , { force : true });
else await writeFile ( path , original , { encoding : "utf8" , mode : 0o600 });
2026-10-13 14:51:55 +08:00
return ok ( undefined );
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
2026-10-13 14:51:55 +08:00
return err ({ kind : "restore" , path , detail : errorDetail ( cause ) });
2026-07-18 04:11:29 +00:00
}
};
2026-10-13 14:51:55 +08:00
const rollbackOrReadbackFailure = async (
targetPath : string ,
original : string | undefined ,
backupPath : string | undefined ,
) : Promise < ClientConfigurationResult > => {
const rollback = await restoreConfig ( targetPath , original );
return rollback . ok
? { status : "failed" , reason : "readback" }
: {
status : "failed" ,
reason : "rollback" ,
...( backupPath === undefined ? {} : { backupPath }),
failure : rollback.error ,
};
};
const errorDetail = ( cause : unknown ) : string =>
cause instanceof Error ? cause.message : String ( cause );
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-10-13 23:36:54 +08:00
const previous = parsed ? . servers [ PRODUCT_IDENTITY . mcpServerKey ];
if (
client . name === "kimi" &&
typeof previous === "object" &&
previous !== null &&
"enabledTools" in previous
)
registration . enabledTools = previous . enabledTools ;
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-10-13 23:36:54 +08:00
...( client . name === "kimi"
? {
startupTimeoutMs : MCP_STARTUP_POLICY.kimiStartupTimeoutMs ,
toolTimeoutMs : MCP_STARTUP_POLICY.kimiToolTimeoutMs ,
}
: {}),
2026-07-18 04:11:29 +00:00
};
};