2026-09-08 10:59:13 +08:00
import {
parseClientConfiguration ,
serializeClientConfiguration ,
2026-10-06 21:58:20 -07:00
clientServerPath ,
legacyClientServerPath ,
withClientServers ,
type ClientConfigurationDocument ,
2026-09-08 10:59:13 +08:00
} from "./ClientConfigurationDocument.js" ;
2026-07-14 20:50:07 +00:00
import { copyFile , lstat , readFile , realpath , rm } from "node:fs/promises" ;
2026-07-12 23:42:20 +00:00
import { homedir } from "node:os" ;
2026-10-05 23:06:19 +08:00
import { join } from "node:path" ;
2026-07-12 23:42:20 +00:00
import writeFileAtomic from "write-file-atomic" ;
import { z } from "zod" ;
import { PRODUCT_IDENTITY } from "../identity.js" ;
2026-10-05 23:06:19 +08:00
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js" ;
2026-07-14 20:50:07 +00:00
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js" ;
2026-10-09 06:08:29 +08:00
import {
manualRegistrationRemediation ,
supportedClients ,
type SetupClient ,
} from "./SupportedClients.js" ;
2026-07-12 23:42:20 +00:00
2026-07-13 19:09:27 +00:00
interface ManagedPathStats {
2026-07-14 20:50:07 +00:00
readonly uid? : number ;
isFile ? () : boolean ;
2026-07-13 19:09:27 +00:00
isSymbolicLink () : boolean ;
}
/** Injectable filesystem operations used to prove uninstall failure recovery. */
export interface UninstallFileSystem {
readText ( path : string ) : Promise < string >;
copy ( source : string , destination : string ) : Promise < void >;
writeText ( path : string , contents : string ) : Promise < void >;
stat ( path : string ) : Promise < ManagedPathStats >;
2026-07-14 20:50:07 +00:00
realpath ? ( path : string ) : Promise < string >;
2026-07-13 19:09:27 +00:00
remove ( path : string ) : Promise < void >;
}
const systemFileSystem : UninstallFileSystem = {
readText : ( path ) => readFile ( path , "utf8" ),
copy : ( source , destination ) => copyFile ( source , destination ),
writeText : ( path , contents ) =>
writeFileAtomic ( path , contents , { encoding : "utf8" }),
stat : ( path ) => lstat ( path ),
2026-07-14 20:50:07 +00:00
realpath : ( path ) => realpath ( path ),
2026-07-13 19:09:27 +00:00
remove : ( path ) => rm ( path , { recursive : true }),
};
2026-07-12 23:42:20 +00:00
/** One explicitly classified uninstall action. */
export interface UninstallItem {
readonly name : string ;
readonly status : "removed" | "retained" | "skipped" | "failed" ;
readonly detail : string ;
}
/** Structured, idempotent result of removing REA-owned state. */
export interface UninstallResult {
readonly status : "complete" | "failed" ;
readonly items : readonly UninstallItem [];
}
2026-10-06 00:50:38 +08:00
/** Whether any requested REA-owned uninstall action failed. */
export const isUninstallFailure = ( result : UninstallResult ) : boolean => {
const status = result . status ;
switch ( status ) {
case "complete" :
return false ;
case "failed" :
return true ;
default : {
const exhaustive : never = status ;
throw new TypeError (
`Unhandled uninstall result status: ${ String ( exhaustive ) } ` ,
);
}
}
};
2026-07-12 23:42:20 +00:00
/** Filesystem boundary used by the contained uninstall workflow. */
export interface UninstallHost {
clients () : Promise < readonly SetupClient [] >;
2026-10-09 03:07:40 +00:00
/** Report a configuration that cannot be read safely, before any removal. */
inspectClient ( client : SetupClient ) : Promise < UninstallItem | undefined >;
2026-07-12 23:42:20 +00:00
removeClient ( client : SetupClient ) : Promise < UninstallItem >;
removeSkill () : Promise < UninstallItem >;
purgeData () : Promise < readonly UninstallItem [] >;
}
2026-10-09 03:07:40 +00:00
/**
* Remove only REA-owned registrations and managed files, optionally including
* local state. A client configuration that cannot be read safely stops the
2026-10-09 03:17:11 +00:00
* operation before anything is removed; one that fails during removal stops
* the remaining removals.
2026-10-09 03:07:40 +00:00
*/
2026-07-12 23:42:20 +00:00
export const runUninstall = async (
purgeData : boolean ,
host : UninstallHost = systemUninstallHost (),
) : Promise < UninstallResult > => {
2026-10-09 03:07:40 +00:00
const clients = await host . clients ();
const blocked : UninstallItem [] = [];
for ( const client of clients ) {
const blocking = await host . inspectClient ( client );
if ( blocking !== undefined ) blocked . push ( blocking );
}
const items : UninstallItem [] =
blocked . length > 0
? [
... blocked ,
item (
"uninstall" ,
"skipped" ,
"No REA registration, skill, or data was removed. Repair each failed configuration, then rerun uninstall." ,
),
]
: await removeAll ( clients , purgeData , host );
2026-07-12 23:42:20 +00:00
items . push ({
name : "analysis_engine" ,
status : "retained" ,
detail : "Hopper is not owned by REA uninstall." ,
});
return {
status : items.some (({ status }) => status === "failed" )
? "failed"
: "complete" ,
items ,
};
};
2026-10-09 03:17:11 +00:00
/**
* Each client is reread when it is edited, so a concurrent change is never
* overwritten. A client that fails then still stops the remaining removals.
*/
2026-10-09 03:07:40 +00:00
const removeAll = async (
clients : readonly SetupClient [],
purgeData : boolean ,
host : UninstallHost ,
) : Promise < UninstallItem [] > => {
const items : UninstallItem [] = [];
2026-10-09 03:17:11 +00:00
for ( const client of clients ) {
const removed = await host . removeClient ( client );
items . push ( removed );
if ( removed . status === "failed" )
return [
... items ,
item (
"uninstall" ,
"skipped" ,
"Uninstall stopped at this failure; the items above report what changed. Repair the failed configuration, then rerun uninstall." ,
),
];
}
2026-10-09 03:07:40 +00:00
items . push ( await host . removeSkill ());
if ( purgeData ) items . push (...( await host . purgeData ()));
return items ;
};
2026-07-12 23:42:20 +00:00
/** Create uninstall effects contained to detected client configs and REA-owned paths. */
2026-07-13 19:09:27 +00:00
export const systemUninstallHost = (
home = homedir (),
fileSystem : UninstallFileSystem = systemFileSystem ,
) : UninstallHost => ({
2026-07-12 23:42:20 +00:00
clients : () => Promise . resolve ( supportedClients ( home )),
2026-10-09 03:07:40 +00:00
inspectClient : async ( client ) => {
const read = await readClientConfiguration ( client , fileSystem );
return read . kind === "item" && read . item . status === "failed"
? read.item
: undefined ;
},
2026-07-13 19:09:27 +00:00
removeClient : ( client ) => removeClient ( client , fileSystem ),
2026-07-17 00:35:19 +00:00
removeSkill : () => removeManagedSkills ( home , fileSystem ),
2026-07-12 23:42:20 +00:00
purgeData : async () => [
2026-07-13 19:09:27 +00:00
await removeManagedPath ( join ( home , ".rea/cache" ), "cache" , fileSystem ),
await removeManagedPath ( join ( home , ".rea/state" ), "state" , fileSystem ),
2026-07-12 23:42:20 +00:00
],
});
2026-10-09 03:07:40 +00:00
type ClientConfigurationRead =
| { readonly kind : "item" ; readonly item : UninstallItem }
| {
readonly kind : "configuration" ;
readonly transactionPath : string ;
readonly original : string ;
readonly parsed : ClientConfigurationDocument ;
};
const readClientConfiguration = async (
2026-07-13 19:09:27 +00:00
client : SetupClient ,
fileSystem : UninstallFileSystem ,
2026-10-09 03:07:40 +00:00
) : Promise < ClientConfigurationRead > => {
2026-07-12 23:42:20 +00:00
if ( client . format === "unsupported" )
2026-10-09 03:07:40 +00:00
return itemRead (
item (
client . name ,
"skipped" ,
manualRegistrationRemediation ( client . name ) ??
"This client has no documented local MCP configuration boundary." ,
),
2026-07-12 23:42:20 +00:00
);
2026-07-14 20:50:07 +00:00
const resolved = await resolveUninstallConfigPath ( client , fileSystem );
2026-10-09 03:07:40 +00:00
if ( typeof resolved !== "string" ) return itemRead ( resolved );
2026-07-14 20:50:07 +00:00
const transactionPath = resolved ;
2026-07-12 23:42:20 +00:00
let original : string ;
try {
2026-07-14 20:50:07 +00:00
original = await fileSystem . readText ( transactionPath );
2026-07-12 23:42:20 +00:00
} catch ( cause : unknown ) {
2026-10-09 03:07:40 +00:00
return itemRead (
isMissing ( cause )
? item ( client . name , "skipped" , "Configuration does not exist." )
: item (
client . name ,
"failed" ,
"Configuration could not be read. Check file permissions, then rerun uninstall." ,
),
);
2026-07-12 23:42:20 +00:00
}
try {
2026-10-09 03:07:40 +00:00
const parsed = parseClientConfiguration ( original , client . format );
return { kind : "configuration" , transactionPath , original , parsed };
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
void cause ;
2026-10-09 03:07:40 +00:00
return itemRead (
item (
client . name ,
"failed" ,
`Configuration is not valid ${ client . format === "toml" || client . format === "grok" ? "TOML" : client . format === "opencode" ? "JSONC" : "JSON" } and was not changed. Repair it, then rerun uninstall.` ,
),
2026-07-12 23:42:20 +00:00
);
}
2026-10-09 03:07:40 +00:00
};
const itemRead = ( result : UninstallItem ) : ClientConfigurationRead => ({
kind : "item" ,
item : result ,
});
const removeClient = async (
client : SetupClient ,
fileSystem : UninstallFileSystem ,
) : Promise < UninstallItem > => {
const read = await readClientConfiguration ( client , fileSystem );
if ( read . kind === "item" ) return read . item ;
const { transactionPath , original , parsed } = read ;
2026-10-06 21:58:20 -07:00
const name = PRODUCT_IDENTITY . mcpServerKey ;
// 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 )
2026-07-12 23:42:20 +00:00
return item ( client . name , "skipped" , "REA registration is absent." );
2026-10-06 21:58:20 -07:00
const removeNative =
hasNative && isOwnedRegistration ( parsed . servers [ name ], client );
const removeLegacy =
legacyPath !== undefined &&
isOwnedRegistration ( parsed . legacyServers [ name ], client );
if ( ! removeNative && ! removeLegacy )
2026-07-12 23:42:20 +00:00
return item (
client . name ,
"retained" ,
"The rea-named registration is not REA-owned." ,
);
2026-10-06 21:58:20 -07:00
const remaining = { ... parsed . servers };
if ( removeNative ) delete remaining [ name ];
const document = withClientServers (
parsed ,
remaining ,
removeLegacy ? name : undefined ,
);
const editedPaths = [
...( removeNative ? [ clientServerPath ( parsed , name )] : []),
...( removeLegacy ? [ legacyPath ] : []),
];
2026-07-12 23:42:20 +00:00
const backupPath = ` ${ client . configPath } .rea.backup` ;
try {
2026-07-14 20:50:07 +00:00
await fileSystem . copy ( transactionPath , backupPath );
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
void cause ;
2026-07-12 23:42:20 +00:00
return item (
client . name ,
"failed" ,
2026-07-13 19:09:27 +00:00
"Configuration could not be backed up, so no change was made. Check file permissions, then rerun uninstall." ,
2026-07-12 23:42:20 +00:00
);
}
try {
2026-09-08 10:59:13 +08:00
await fileSystem . writeText (
transactionPath ,
2026-10-05 23:06:19 +08:00
serializeClientConfiguration (
document ,
client . format ,
original ,
2026-10-06 21:58:20 -07:00
editedPaths ,
2026-10-05 23:06:19 +08:00
),
2026-09-08 10:59:13 +08:00
);
const readback = parseClientConfiguration (
await fileSystem . readText ( transactionPath ),
client . format ,
2026-07-12 23:42:20 +00:00
);
2026-10-06 21:58:20 -07:00
if (
( removeNative && Object . hasOwn ( readback . servers , name )) ||
( removeLegacy && Object . hasOwn ( readback . legacyServers , name ))
)
2026-07-12 23:42:20 +00:00
throw new Error ( "registration readback mismatch" );
return item (
client . name ,
"removed" ,
`Removed registration from ${ client . configPath } .` ,
);
2026-10-06 05:58:46 +08:00
} catch ( cause : unknown ) {
// Update failure attempts a restore before reporting; cause is preserved below.
void cause ;
2026-07-13 19:09:27 +00:00
try {
2026-07-14 20:50:07 +00:00
await fileSystem . writeText ( transactionPath , original );
2026-10-06 05:58:46 +08:00
} catch ( restoreCause : unknown ) {
void restoreCause ;
2026-07-13 19:09:27 +00:00
return item (
client . name ,
"failed" ,
"Configuration could not be updated or restored. Restore its `.rea.backup` manually, then rerun uninstall." ,
);
}
2026-07-12 23:42:20 +00:00
return item (
client . name ,
"failed" ,
2026-07-13 19:09:27 +00:00
"Configuration could not be updated. The original was restored and its `.rea.backup` was retained. Repair the configuration or restore the backup, then rerun uninstall." ,
2026-07-12 23:42:20 +00:00
);
}
};
2026-07-14 20:50:07 +00:00
const resolveUninstallConfigPath = async (
client : SetupClient ,
fileSystem : UninstallFileSystem ,
) : Promise < string | UninstallItem > => {
const path = await resolveClientConfigTransactionPath (
client . configPath ,
fileSystem . realpath === undefined
? { lstat : fileSystem.stat }
: { lstat : fileSystem.stat , realpath : fileSystem.realpath },
);
return (
path ??
item (
client . name ,
"failed" ,
"Configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun uninstall." ,
)
);
};
2026-07-12 23:42:20 +00:00
/** Ownership rule for persistent MCP registrations created by REA setup. */
2026-10-05 23:06:19 +08:00
const isOwnedRegistration = ( value : unknown , client : SetupClient ) : boolean => {
if ( client . format === "opencode" ) {
const parsed = z
. object ({ type : z . literal ( "local" ), command : z.array ( z . string ()). min ( 1 ) })
. passthrough ()
. safeParse ( value );
if ( ! parsed . success ) return false ;
const command = parsed . data . command ;
return isOwnedClientRegistrationCommand ( command );
}
2026-07-12 23:42:20 +00:00
const parsed = registrationSchema . safeParse ( value );
if ( ! parsed . success ) return false ;
const { command , args } = parsed . data ;
2026-10-05 23:06:19 +08:00
return isOwnedClientRegistrationCommand ([ command , ... args ]);
2026-07-12 23:42:20 +00:00
};
const removeManagedPath = async (
path : string ,
name : string ,
2026-07-13 19:09:27 +00:00
fileSystem : UninstallFileSystem ,
2026-07-12 23:42:20 +00:00
) : Promise < UninstallItem > => {
try {
2026-07-13 19:09:27 +00:00
const stats = await fileSystem . stat ( path );
2026-07-12 23:42:20 +00:00
if ( stats . isSymbolicLink ())
2026-07-13 19:09:27 +00:00
return item (
name ,
"retained" ,
"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually." ,
);
await fileSystem . remove ( path );
2026-07-12 23:42:20 +00:00
return item ( name , "removed" , `Removed ${ path } .` );
} catch ( cause : unknown ) {
return isMissing ( cause )
? item ( name , "skipped" , ` ${ path } does not exist.` )
2026-07-13 19:09:27 +00:00
: item (
name ,
"failed" ,
"This item could not be removed. Check file permissions, then rerun uninstall." ,
);
2026-07-12 23:42:20 +00:00
}
};
2026-07-17 00:35:19 +00:00
const removeManagedSkills = async (
home : string ,
fileSystem : UninstallFileSystem ,
2026-07-17 01:28:42 +00:00
) : Promise < UninstallItem > =>
removeManagedPath (
join ( home , ".agents/skills" , PRODUCT_IDENTITY . skillName ),
"skill" ,
fileSystem ,
);
2026-07-17 00:35:19 +00:00
2026-07-12 23:42:20 +00:00
const item = (
name : string ,
status : UninstallItem [ "status" ],
detail : string ,
) : UninstallItem => ({ name , status , detail });
const registrationSchema = z
. object ({ command : z.string (), args : z.array ( z . string ()) })
. passthrough ();
const isMissing = ( cause : unknown ) : boolean =>
cause instanceof Error && "code" in cause && cause . code === "ENOENT" ;