2026-09-08 10:59:13 +08:00
import {
parseClientConfiguration ,
serializeClientConfiguration ,
2026-10-05 23:06:19 +08:00
type ClientServersKey ,
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-07-14 01:12:05 +00:00
import { 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 [] >;
removeClient ( client : SetupClient ) : Promise < UninstallItem >;
removeSkill () : Promise < UninstallItem >;
purgeData () : Promise < readonly UninstallItem [] >;
}
/** Remove only REA-owned registrations and managed files, optionally including local state. */
export const runUninstall = async (
purgeData : boolean ,
host : UninstallHost = systemUninstallHost (),
) : Promise < UninstallResult > => {
const items : UninstallItem [] = [];
for ( const client of await host . clients ())
items . push ( await host . removeClient ( client ));
items . push ( await host . removeSkill ());
if ( purgeData ) items . push (...( await host . purgeData ()));
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 ,
};
};
/** 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-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-07-13 19:09:27 +00:00
const removeClient = async (
client : SetupClient ,
fileSystem : UninstallFileSystem ,
) : Promise < UninstallItem > => {
2026-07-12 23:42:20 +00:00
if ( client . format === "unsupported" )
return item (
client . name ,
"skipped" ,
"This client has no documented local MCP configuration boundary." ,
);
2026-07-14 20:50:07 +00:00
const resolved = await resolveUninstallConfigPath ( client , fileSystem );
if ( typeof resolved !== "string" ) return resolved ;
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 ) {
return isMissing ( cause )
? item ( client . name , "skipped" , "Configuration does not exist." )
2026-07-13 19:09:27 +00:00
: item (
client . name ,
"failed" ,
"Configuration could not be read. Check file permissions, then rerun uninstall." ,
);
2026-07-12 23:42:20 +00:00
}
let document : Record < string , unknown >;
2026-10-05 23:06:19 +08:00
let key : ClientServersKey ;
2026-07-12 23:42:20 +00:00
let servers : Record < string , unknown >;
try {
2026-09-08 10:59:13 +08:00
({
document ,
servers ,
serversKey : key ,
} = parseClientConfiguration ( original , client . format ));
2026-07-12 23:42:20 +00:00
} catch {
return item (
client . name ,
"failed" ,
2026-10-05 23:06:19 +08:00
`Configuration is not valid ${ client . format === "toml" ? "TOML" : client . format === "opencode" ? "JSONC" : "JSON" } and was not changed. Repair it, then rerun uninstall.` ,
2026-07-12 23:42:20 +00:00
);
}
const registration = servers [ PRODUCT_IDENTITY . mcpServerKey ];
if ( registration === undefined )
return item ( client . name , "skipped" , "REA registration is absent." );
2026-10-05 23:06:19 +08:00
if ( ! isOwnedRegistration ( registration , client ))
2026-07-12 23:42:20 +00:00
return item (
client . name ,
"retained" ,
"The rea-named registration is not REA-owned." ,
);
const remaining = { ... servers };
delete remaining [ PRODUCT_IDENTITY . mcpServerKey ];
document [ key ] = remaining ;
const backupPath = ` ${ client . configPath } .rea.backup` ;
try {
2026-07-14 20:50:07 +00:00
await fileSystem . copy ( transactionPath , backupPath );
2026-07-12 23:42:20 +00:00
} catch {
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 ,
PRODUCT_IDENTITY . mcpServerKey ,
),
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-09-08 10:59:13 +08:00
if ( PRODUCT_IDENTITY . mcpServerKey in readback . servers )
2026-07-12 23:42:20 +00:00
throw new Error ( "registration readback mismatch" );
return item (
client . name ,
"removed" ,
`Removed registration from ${ client . configPath } .` ,
);
} catch {
2026-07-13 19:09:27 +00:00
try {
2026-07-14 20:50:07 +00:00
await fileSystem . writeText ( transactionPath , original );
2026-07-13 19:09:27 +00:00
} catch {
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" ;