2026-07-18 05:18:05 +00:00
import { join } from "node:path" ;
2026-10-05 23:06:19 +08:00
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js" ;
2026-07-18 05:18:05 +00:00
import {
linuxHopperInstallDisclosure ,
type LinuxPackageFamily ,
} from "./LinuxHopper.js" ;
2026-10-10 01:03:25 -07:00
import type { SkillDestination } from "./SetupSkill.js" ;
2026-07-18 05:18:05 +00:00
import { macHopperInstallDisclosure } from "./MacHopper.js" ;
2026-07-16 00:02:49 +08:00
import type {
2026-10-13 11:04:22 -03:00
ClientConfigurationInspection ,
2026-07-16 00:02:49 +08:00
SetupAction ,
2026-10-05 23:06:19 +08:00
SetupClientState ,
2026-07-18 05:18:05 +00:00
SetupHost ,
2026-07-16 00:02:49 +08:00
SetupProviderEnvironment ,
2026-10-06 05:00:32 +08:00
} from "./SetupTypes.js" ;
2026-10-13 11:04:22 -03:00
import {
appDataRedirection ,
registrationPersistenceDetail ,
type SetupClient ,
} from "./SupportedClients.js" ;
import { redirectedWriteBlocker } from "./MsixPackageStorage.js" ;
2026-10-07 19:52:43 +08:00
import type { DoctorReport } from "./Doctor.js" ;
2026-10-11 10:10:01 -07:00
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js" ;
2026-07-13 21:08:33 +00:00
2026-10-05 23:06:19 +08:00
/** Read-only setup facts shared by client selection and preflight. */
export interface SetupDiscovery {
readonly initialDoctor : Awaited < ReturnType < SetupHost [ "doctor" ] >>;
readonly installHopper : boolean ;
readonly clients : readonly SetupClient [];
readonly detectedClientIds : readonly string [];
readonly defaultClientIds : readonly string [];
readonly clientStates : readonly SetupClientState [];
readonly linuxPackageFamily? : LinuxPackageFamily ;
}
/** Discover supported clients and current registrations without mutation. */
export const discoverSetupState = async ( input : {
readonly host : SetupHost ;
readonly providerEnvironment : SetupProviderEnvironment ;
readonly forceHopperInstall : boolean ;
readonly proposeHopper : boolean ;
2026-10-09 20:02:52 +08:00
readonly initialDoctor : DoctorReport ;
2026-10-05 23:06:19 +08:00
}) : Promise < SetupDiscovery > => {
2026-10-09 20:02:52 +08:00
const { initialDoctor } = input ;
2026-10-05 23:06:19 +08:00
const linuxHopperRepairNeeded = initialDoctor . checks . some (
({ name , ok , detail }) =>
! ok &&
( name === "hopper-demo-runtime" ||
( name === "hopper-version" && detail === "/opt/hopper/bin/Hopper" )),
);
const linuxDistribution =
input . host . platform === "linux"
? await input . host . linuxDistribution ()
: undefined ;
const hopperInstallSupported =
( input . host . platform === "darwin" &&
majorVersion (( await input . host . macosVersion ()) ?? "0" ) >= 12 ) ||
2026-10-13 17:33:54 +02:00
( input . host . platform === "linux" &&
linuxDistribution ? . hopperSetupSupported === true );
2026-10-05 23:06:19 +08:00
const installHopper =
input . forceHopperInstall ||
( hopperInstallSupported &&
input . proposeHopper &&
( Object . keys ( input . providerEnvironment ). length === 0 ||
linuxHopperRepairNeeded ));
2026-10-10 01:59:12 +08:00
const [ clients , detectedClients ] = await Promise . all ([
2026-10-09 20:02:52 +08:00
input . host . supportedClients (),
2026-10-05 23:06:19 +08:00
input . host . detectedClients (),
]);
const detectedIds = new Set ( detectedClients . map (({ name }) => name ));
const registrations = initialDoctor . identity ? . registrations ?? [];
const registrationByClient = new Map (
registrations . map (( registration ) => [ registration . client , registration ]),
);
const clientStates = clients . map (( client ) : SetupClientState => {
const registration = registrationByClient . get ( client . name );
const ownedRegistration =
( registration ? . state === "aligned" || registration ? . state === "stale" ) &&
isOwnedClientRegistrationCommand ( registration . command );
const configured = ownedRegistration ;
const status : SetupClientState [ "status" ] =
registration ? . state === "invalid"
? "invalid"
: ownedRegistration && registration . state === "aligned"
? "configured"
: ownedRegistration && registration . state === "stale"
? "needs_configuration"
: detectedIds . has ( client . name )
? "needs_configuration"
: "missing" ;
return {
client ,
detected : detectedIds.has ( client . name ),
configured ,
status ,
};
});
const defaultClientIds = registrations
. filter (
( registration ) =>
( registration . state === "aligned" || registration . state === "stale" ) &&
isOwnedClientRegistrationCommand ( registration . command ),
)
. map (({ client }) => client );
return {
initialDoctor ,
installHopper ,
clients ,
detectedClientIds : [... detectedIds ],
defaultClientIds ,
clientStates ,
...( linuxDistribution ? . packageFamily === undefined
? {}
: { linuxPackageFamily : linuxDistribution.packageFamily }),
};
};
/** Preflight exactly the selected clients and produce their concrete actions. */
export const planSetupActions = async ( input : {
readonly discovery : SetupDiscovery ;
readonly host : SetupHost ;
readonly providerEnvironment : SetupProviderEnvironment ;
readonly command : readonly string [];
readonly clientIds : readonly string [];
2026-10-10 01:59:12 +08:00
readonly skillClientIds : readonly string [];
2026-10-05 23:06:19 +08:00
readonly installSkill : boolean ;
}) : Promise < {
readonly plannedActions : readonly SetupAction [];
readonly selectedClients : readonly SetupClient [];
readonly clientsToConfigure : readonly SetupClient [];
readonly blocker? : string ;
} > => {
const byId = new Map (
input . discovery . clients . map (( client ) => [ client . name , client ]),
);
const unknownClient = input . clientIds . find (( id ) => ! byId . has ( id ));
if ( unknownClient !== undefined ) {
return {
plannedActions : [],
selectedClients : [],
clientsToConfigure : [],
blocker : `Unsupported setup client: ${ unknownClient } .` ,
};
}
const selectedClients = input . clientIds . flatMap (( id ) => {
const client = byId . get ( id );
return client === undefined ? [] : [ client ];
});
const inspections = await Promise . all (
selectedClients . map ( async ( client ) => ({
client ,
2026-10-09 20:02:52 +08:00
inspection : await input . host . inspectClientConfiguration (
client ,
input . providerEnvironment ,
input . command ,
),
2026-10-05 23:06:19 +08:00
})),
);
const invalid = inspections . find (
({ inspection }) => inspection . status === "invalid" ,
);
if ( invalid ? . inspection . status === "invalid" ) {
return {
plannedActions : [],
selectedClients ,
clientsToConfigure : [],
blocker : ` ${ invalid . client . displayName ?? invalid . client . name } : ${ invalid . inspection . remediation } ` ,
};
}
2026-10-13 11:04:22 -03:00
const clientPlans = plannedClientWrites (
inspections ,
input . discovery . installHopper ,
);
const plannedActions = setupPlan ({
platform : input.host.platform ,
homeDirectory : input.host.homeDirectory ,
installHopper : input.discovery.installHopper ,
installSkill : input.installSkill ,
skillClientIds : input.skillClientIds ,
skillDestinations : input.host.skillDestinations ( input . skillClientIds ),
clients : clientPlans ,
providerEnvironment : input.providerEnvironment ,
...( input . discovery . linuxPackageFamily === undefined
? {}
: { linuxPackageFamily : input.discovery.linuxPackageFamily }),
command : input.command ,
});
const blocker =
( clientPlans . length > 0
? input.host.registrationCommandBlocker
: undefined ) ??
redirectedWriteBlocker (
appDataRedirection ( input . discovery . clients ),
plannedActions
. filter (({ kind }) => kind !== "install_hopper" )
. map (({ target }) => target ),
"setup" ,
);
return {
plannedActions ,
selectedClients ,
clientsToConfigure : selectedClients.filter (( client ) =>
clientPlans . some (({ client : planned }) => planned . name === client . name ),
),
...( blocker === undefined ? {} : { blocker }),
};
};
/** Selected clients whose registration setup writes, with the disclosed operation. */
const plannedClientWrites = (
inspections : readonly {
readonly client : SetupClient ;
readonly inspection : ClientConfigurationInspection ;
}[],
installHopper : boolean ,
) =>
inspections . flatMap (({ client , inspection }) =>
2026-10-09 06:08:29 +08:00
client . format !== "unsupported" &&
( inspection . status === "create" ||
inspection . status === "update" ||
2026-10-13 11:04:22 -03:00
( installHopper && inspection . status === "already_current" ))
2026-10-05 23:06:19 +08:00
? [
{
client ,
operation :
inspection.status === "already_current"
? ( "update" as const )
: inspection . status ,
...( inspection . status !== "already_current" &&
inspection . backupPath !== undefined
? { backupPath : inspection.backupPath }
: {}),
},
]
: [],
);
2026-07-18 05:18:05 +00:00
2026-10-05 23:06:19 +08:00
/** Describe every selected setup mutation before user approval. */
const setupPlan = ( input : {
2026-07-18 05:18:05 +00:00
readonly platform : NodeJS.Platform ;
2026-10-09 20:02:52 +08:00
readonly homeDirectory : string ;
2026-07-18 11:59:16 +08:00
readonly installHopper : boolean ;
readonly installSkill : boolean ;
2026-10-10 01:59:12 +08:00
readonly skillClientIds : readonly string [];
2026-10-10 01:03:25 -07:00
readonly skillDestinations : readonly SkillDestination [];
2026-10-05 23:06:19 +08:00
readonly clients : readonly {
readonly client : SetupClient ;
readonly operation : "create" | "update" ;
readonly backupPath? : string ;
}[];
2026-07-18 11:59:16 +08:00
readonly providerEnvironment : SetupProviderEnvironment ;
2026-07-18 05:18:05 +00:00
readonly linuxPackageFamily? : LinuxPackageFamily ;
2026-10-05 23:06:19 +08:00
readonly command : readonly string [];
}) : readonly SetupAction [] => [
2026-07-18 05:18:05 +00:00
...( input . installHopper
2026-07-13 21:08:33 +00:00
? [
{
2026-07-18 11:59:16 +08:00
id : "install_hopper" ,
2026-07-13 21:08:33 +00:00
kind : "install_hopper" as const ,
2026-07-18 11:59:16 +08:00
label : "Hopper deep-analysis provider" ,
2026-07-13 21:08:33 +00:00
target :
2026-07-18 11:59:16 +08:00
input.platform === "darwin"
2026-10-09 20:02:52 +08:00
? join (
input . homeDirectory ,
"Applications/Hopper Disassembler.app" ,
)
2026-07-13 21:08:33 +00:00
: "system package manager" ,
detail :
2026-07-18 11:59:16 +08:00
input.platform === "linux"
2026-07-13 21:08:33 +00:00
? "Download, verify, and install Hopper plus its Xvfb demo-session dependencies. For the supported demo build, REA uses a private display and selects Hopper's offered demo mode for each analysis session."
: "Download the official Hopper package, verify it, and install it. Hopper may show its demo or license prompt when first opened." ,
external : true ,
2026-07-18 11:59:16 +08:00
operation : "install" as const ,
...( input . platform === "linux"
? input . linuxPackageFamily === undefined
? {}
: linuxDisclosure ( input . linuxPackageFamily )
: {
networkOrigins : macHopperInstallDisclosure.networkOrigins ,
commands : macHopperInstallDisclosure.commands ,
}),
2026-07-13 21:08:33 +00:00
},
]
: []),
2026-07-18 05:18:05 +00:00
... input . clients
. filter (({ client }) => client . format !== "unsupported" )
2026-10-06 01:59:19 +08:00
. map (({ client , operation , backupPath }) : SetupAction => ({
id : `configure_client: ${ client . name } ` ,
kind : "configure_client" ,
label : client.displayName ?? client . name ,
target : client.configPath ,
detail : clientConfigurationDetail (
2026-10-13 11:04:22 -03:00
client ,
2026-10-06 01:59:19 +08:00
input . command ,
input . providerEnvironment ,
input . installHopper ,
),
external : false ,
operation ,
...( backupPath === undefined ? {} : { backupPath }),
})),
2026-07-18 05:18:05 +00:00
...( input . installSkill
2026-10-10 01:03:25 -07:00
? input . skillDestinations . map (({ client , path }) : SetupAction => ({
id : client === "shared" ? "install_skill" : `install_skill: ${ client } ` ,
2026-10-10 01:59:12 +08:00
kind : "install_skill" ,
label :
client === "claude_code"
? "REA skill for Claude Code"
: "REA reverse-engineering skill" ,
target : path ,
detail :
client === "claude_code"
? "Install or update the REA skill in Claude Code's personal skill directory."
: "Install or update the bundled REA reverse-engineering skill and on-demand references." ,
external : false ,
operation : "install" ,
}))
2026-07-14 20:14:58 +00:00
: []),
2026-07-13 21:08:33 +00:00
];
2026-07-16 00:02:49 +08:00
2026-07-18 11:59:16 +08:00
const linuxDisclosure = ( family : LinuxPackageFamily ) => {
const disclosure = linuxHopperInstallDisclosure (
family ,
process . getuid ? .() === 0 ,
);
return {
networkOrigins : [ disclosure . downloadUrl ],
commands : disclosure.commands ,
integrity : ` ${ String ( disclosure . expectedBytes ) } bytes · SHA-1 ${ disclosure . expectedSha1 } ` ,
};
};
2026-10-05 23:06:19 +08:00
const majorVersion = ( version : string ) : number =>
Number . parseInt ( version . split ( "." )[ 0 ] ?? "0" , 10 );
2026-07-16 00:02:49 +08:00
const clientConfigurationDetail = (
2026-10-13 11:04:22 -03:00
client : SetupClient ,
2026-10-05 23:06:19 +08:00
command : readonly string [],
2026-07-16 00:02:49 +08:00
environment : SetupProviderEnvironment ,
2026-10-05 23:06:19 +08:00
installHopper : boolean ,
2026-07-16 00:02:49 +08:00
) : string => {
const entries = Object . entries ( environment )
2026-10-11 10:10:01 -07:00
. sort (([ left ], [ right ]) => compareUnicodeCodePoints ( left , right ))
2026-07-16 00:02:49 +08:00
. map (([ name , value ]) => ` ${ name } = ${ value } ` );
2026-10-05 23:06:19 +08:00
const environmentDetail =
entries . length === 0
2026-10-10 23:23:02 +01:00
? " No additional provider environment variables. Existing server environment overrides are retained."
: ` Detected provider environment: ${ entries . join ( ", " ) } . Existing server environment overrides are retained; detected values replace matching keys.` ;
2026-10-05 23:06:19 +08:00
const hopperDetail = installHopper
? environment . HOPPER_LAUNCHER_PATH === undefined
? " If this plan installs Hopper, REA will add HOPPER_LAUNCHER_PATH using the launcher path reported by that installation."
: " The HOPPER_LAUNCHER_PATH value shown above is the current fallback; if this plan installs Hopper, REA will replace it with the launcher path reported by that installation."
: "" ;
2026-10-13 11:04:22 -03:00
const persistence = registrationPersistenceDetail ( client );
return `Add the REA MCP registration for ${ client . displayName ?? client . name } ; preserve unrelated configuration. The backup path reflects the configuration inspected for this plan; if that file changes before execution, setup will select a recovery path for its current contents. Command: ${ command . map (( part ) => JSON . stringify ( part )). join ( " " ) } . ${ environmentDetail }${ hopperDetail }${ persistence === undefined ? "" : ` ${ persistence } ` } ` ;
2026-07-16 00:02:49 +08:00
};