feat: streamline agent integration and MCP routing

This commit is contained in:
N0zoM1z0
2026-07-20 17:11:06 +08:00
parent 0810486f63
commit 3e3d45856e
151 changed files with 2642 additions and 663 deletions
+12 -4
View File
@@ -17,7 +17,11 @@ export interface ClientRegistrationStatus {
const objectSchema = z.record(z.string(), z.unknown());
const registrationSchema = z
.object({ command: z.string().min(1), args: z.array(z.string()).default([]) })
.object({
command: z.string().min(1),
args: z.array(z.string()).default([]),
startup_timeout_sec: z.number().positive().optional(),
})
.passthrough();
/** Inspect supported client registrations without reading their environment. */
@@ -49,7 +53,7 @@ export const readClientRegistrationStatuses = async (
client.name,
client.configPath,
command,
registrationAligned(command, currentCommandPath)
registrationAligned(registration, client.name, currentCommandPath)
? "aligned"
: "stale",
),
@@ -71,14 +75,18 @@ export const readClientRegistrationStatuses = async (
};
const registrationAligned = (
command: readonly string[],
registration: z.output<typeof registrationSchema>,
client: string,
currentCommandPath: string,
): boolean => {
const command = [registration.command, ...registration.args];
if (client === "codex" && registration.startup_timeout_sec !== 30)
return false;
if (
command.length === 4 &&
command[0] === "npx" &&
command[1] === "-y" &&
command[2] === PRODUCT_IDENTITY.packageSpecifier &&
command[2] === PRODUCT_IDENTITY.registrationPackageSpecifier &&
command[3] === "mcp"
)
return true;
+3 -3
View File
@@ -45,7 +45,7 @@ export { canonicalSkillNeedsInstall, installCanonicalSkill };
const registrationCommand = (): readonly string[] =>
process.env.npm_command === "exec"
? ["npx", "-y", PRODUCT_IDENTITY.packageSpecifier, "mcp"]
? PRODUCT_IDENTITY.mcpCommand.split(" ")
: [resolve(process.argv[1] ?? PRODUCT_IDENTITY.cliBinary), "mcp"];
/** Result of one backup/write/readback transaction. */
@@ -188,7 +188,7 @@ export const runSetup = async (
plannedActions,
appliedActions,
clients,
doctor: await host.doctor(),
doctor: discovery.initialDoctor,
remediation:
"Review the setup plan, then rerun interactively or with --yes.",
};
@@ -273,7 +273,7 @@ const resolveSetupSelection = async (
selected.has(`configure_client:${client.name}`),
);
interactiveApproval = decision.approved;
approved = decision.approved || plannedActions.length === 0;
approved = decision.approved;
}
}
return {
+19 -3
View File
@@ -17,10 +17,12 @@ import type { SetupClient } from "./SupportedClients.js";
const defaultCommand = (): readonly string[] => [
"npx",
"-y",
PRODUCT_IDENTITY.packageSpecifier,
PRODUCT_IDENTITY.registrationPackageSpecifier,
"mcp",
];
const CODEX_STARTUP_TIMEOUT_SECONDS = 30;
/** Back up, atomically update, and semantically read back one JSON MCP configuration. */
export const configureJsonClient = async (
client: SetupClient,
@@ -47,6 +49,7 @@ export const configureJsonClient = async (
return { status: "failed", reason: "readback" };
}
const desired = clientConfigurationDesired(
client,
normalizeProviderEnvironment(environment),
command,
);
@@ -122,6 +125,7 @@ export const configureTomlClient = async (
return { status: "failed", reason: "readback" };
}
const desired = clientConfigurationDesired(
client,
normalizeProviderEnvironment(environment),
command,
);
@@ -172,7 +176,11 @@ export const clientConfigurationAligned = async (
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<boolean> => {
const desired = clientConfigurationDesired(providerEnvironment, command);
const desired = clientConfigurationDesired(
client,
providerEnvironment,
command,
);
try {
const original = await readFile(client.configPath, "utf8");
const document =
@@ -215,7 +223,11 @@ export const inspectClientConfiguration = async (
"The configuration file could not be read. Check its permissions before rerunning setup.",
};
}
const desired = clientConfigurationDesired(providerEnvironment, command);
const desired = clientConfigurationDesired(
client,
providerEnvironment,
command,
);
try {
const document =
client.format === "toml"
@@ -274,6 +286,7 @@ const restoreConfig = async (
};
const clientConfigurationDesired = (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
) => {
@@ -285,6 +298,9 @@ const clientConfigurationDesired = (
return {
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
args: command.slice(1),
...(client.name === "codex"
? { startup_timeout_sec: CODEX_STARTUP_TIMEOUT_SECONDS }
: {}),
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
};
};
+3 -7
View File
@@ -83,14 +83,9 @@ const setupPlan = (input: SetupPlanOptions): readonly SetupAction[] => [
id: "install_skill",
kind: "install_skill" as const,
label: "REA reverse-engineering skill",
target: join(
homedir(),
".agents/skills",
PRODUCT_IDENTITY.skillName,
"SKILL.md",
),
target: join(homedir(), ".agents/skills", PRODUCT_IDENTITY.skillName),
detail:
"Install or update the bundled REA reverse-engineering skill.",
"Install or update the bundled REA reverse-engineering skill and on-demand references.",
external: false,
operation: "install" as const,
},
@@ -178,6 +173,7 @@ export const discoverSetupActions = async (input: {
const linuxDistribution =
host.platform === "linux" ? await host.linuxDistribution() : undefined;
return {
initialDoctor,
installHopper,
installSkill,
detectedClients: clientPlans.map(({ client }) => client),
+67 -47
View File
@@ -4,8 +4,23 @@ import writeFileAtomic from "write-file-atomic";
import { PRODUCT_IDENTITY } from "../identity.js";
const skillDestination = (home: string, name: string): string =>
join(home, ".agents/skills", name, "SKILL.md");
const SKILL_FILES = [
"SKILL.md",
"references/native-and-artifacts.md",
"references/javascript-applications.md",
"references/runtime-observation.md",
"references/evidence-workflows.md",
"references/controlled-replay.md",
] as const;
interface CanonicalSkillFile {
readonly content: string;
readonly destination: string;
readonly original: string | undefined;
}
const skillRoot = (home: string): string =>
join(home, ".agents/skills", PRODUCT_IDENTITY.skillName);
const readOptionalText = async (path: string): Promise<string | undefined> => {
try {
@@ -19,70 +34,75 @@ const readOptionalText = async (path: string): Promise<string | undefined> => {
const canonicalSkillFiles = async (
home: string,
): Promise<{ readonly content: string; readonly destination: string }> => ({
destination: skillDestination(home, PRODUCT_IDENTITY.skillName),
content: await readFile(
new URL(
`../../skills/${PRODUCT_IDENTITY.skillName}/SKILL.md`,
import.meta.url,
),
"utf8",
),
});
): Promise<readonly CanonicalSkillFile[]> =>
Promise.all(
SKILL_FILES.map(async (relativePath) => {
const destination = join(skillRoot(home), relativePath);
return {
destination,
content: await readFile(
new URL(
`../../skills/${PRODUCT_IDENTITY.skillName}/${relativePath}`,
import.meta.url,
),
"utf8",
),
original: await readOptionalText(destination),
};
}),
);
/** Report whether setup would change the managed REA skill. */
/** Report whether setup would change any file in the managed REA skill bundle. */
export const canonicalSkillNeedsInstall = async (
home: string,
): Promise<boolean> => {
try {
const { content, destination } = await canonicalSkillFiles(home);
return (await readOptionalText(destination)) !== content;
return (await canonicalSkillFiles(home)).some(
({ content, original }) => original !== content,
);
} catch {
return true;
}
};
/** Transactionally install or upgrade the versioned canonical REA skill. */
const writeText = (path: string, content: string): Promise<void> =>
writeFileAtomic(path, content, { encoding: "utf8", mode: 0o600 });
const restoreSkillFiles = async (
changed: readonly CanonicalSkillFile[],
): Promise<void> => {
for (const { destination, original } of [...changed].reverse()) {
if (original === undefined) await rm(destination, { force: true });
else await writeText(destination, original);
}
};
/** Transactionally install or upgrade the canonical REA skill and references. */
export const installCanonicalSkill = async (
home: string,
): Promise<"installed" | "unchanged" | "failed"> => {
let destination = skillDestination(home, PRODUCT_IDENTITY.skillName);
let backup = `${destination}.rea.backup`;
let original: string | undefined;
let canonicalChanged = false;
let changed: readonly CanonicalSkillFile[] = [];
try {
const canonical = await canonicalSkillFiles(home);
destination = canonical.destination;
backup = `${destination}.rea.backup`;
const { content } = canonical;
original = await readOptionalText(destination);
if (original === content) return "unchanged";
await mkdir(dirname(destination), { recursive: true });
if (original !== undefined && original !== content)
await writeFileAtomic(backup, original, {
encoding: "utf8",
mode: 0o600,
});
canonicalChanged = original !== content;
if (canonicalChanged)
await writeFileAtomic(destination, content, {
encoding: "utf8",
mode: 0o600,
});
if ((await readFile(destination, "utf8")) !== content)
throw new Error("skill readback mismatch");
changed = canonical.filter(({ content, original }) => original !== content);
if (changed.length === 0) return "unchanged";
for (const { destination, original } of changed) {
await mkdir(dirname(destination), { recursive: true });
if (original !== undefined)
await writeText(`${destination}.rea.backup`, original);
}
for (const { destination, content } of changed)
await writeText(destination, content);
for (const { destination, content } of changed)
if ((await readFile(destination, "utf8")) !== content)
throw new Error(`skill readback mismatch: ${destination}`);
return "installed";
} catch {
try {
if (canonicalChanged && original === undefined)
await rm(destination, { force: true });
else if (canonicalChanged && original !== undefined)
await writeFileAtomic(destination, original, {
encoding: "utf8",
mode: 0o600,
});
await restoreSkillFiles(changed);
} catch {
// The canonical backup remains beside the skill for operator recovery.
// Per-file backups remain beside changed files for operator recovery.
}
return "failed";
}
+7 -1
View File
@@ -225,7 +225,13 @@ const isOwnedRegistration = (value: unknown): boolean => {
args[0] === "mcp") ||
(command === "npx" &&
(JSON.stringify(args) ===
JSON.stringify(["-y", PRODUCT_IDENTITY.packageSpecifier, "mcp"]) ||
JSON.stringify([
"-y",
PRODUCT_IDENTITY.registrationPackageSpecifier,
"mcp",
]) ||
JSON.stringify(args) ===
JSON.stringify(["-y", PRODUCT_IDENTITY.packageSpecifier, "mcp"]) ||
JSON.stringify(args) ===
JSON.stringify(["-y", PRODUCT_IDENTITY.packageName, "mcp"])))
);
+26 -1
View File
@@ -12,6 +12,9 @@ import { PRODUCT_IDENTITY } from "../identity.js";
const execFileAsync = promisify(execFile);
const registryResponseSchema = z.object({ version: z.string().min(1) });
const UPGRADE_COMMAND = "npm install --global rea-agents@latest";
const CLI_SCRIPT_PATH = fileURLToPath(
new URL("../../scripts/rea.mjs", import.meta.url),
);
/** Location of the global npm installation that owns the running CLI. */
export interface NpmInstallation {
@@ -36,6 +39,7 @@ export interface UpgradeHost {
installation: NpmInstallation,
output: UpgradeOutput,
): Promise<boolean>;
syncAgentIntegration(output: UpgradeOutput): Promise<boolean | undefined>;
}
/** Caller-visible outcome of checking and updating the REA CLI. */
@@ -53,6 +57,7 @@ export type UpgradeResult =
readonly versionCheck: "available" | "unavailable";
readonly installMethod: "npm";
readonly command: typeof UPGRADE_COMMAND;
readonly integrationSync: "setup_invoked" | "deferred" | "failed";
readonly clientRestartRequired: true;
readonly remediation: string;
}
@@ -111,6 +116,13 @@ export const runUpgrade = async (
remediation: `REA could not update through npm. Check npm registry access and global install permissions, then run: ${UPGRADE_COMMAND}`,
};
const integrationSyncResult = await host.syncAgentIntegration(output);
const integrationSync =
integrationSyncResult === undefined
? "deferred"
: integrationSyncResult
? "setup_invoked"
: "failed";
return {
status: "upgraded",
previousVersion: currentVersion,
@@ -118,9 +130,12 @@ export const runUpgrade = async (
versionCheck: "available",
installMethod: "npm",
command: UPGRADE_COMMAND,
integrationSync,
clientRestartRequired: true,
remediation:
"Rerun rea setup to refresh registrations and the skill, then restart clients that may retain an older MCP server.",
integrationSync === "setup_invoked"
? "The updated setup journey was opened to align registrations and the skill. Restart clients whose approved registration changed."
: "Run rea setup --all-detected to align registrations and the skill, then restart clients that may retain an older MCP server.",
};
};
@@ -156,6 +171,16 @@ export const systemUpgradeHost = (): UpgradeHost => ({
],
output,
),
syncAgentIntegration: (output) =>
output === "structured" ||
process.stdin.isTTY !== true ||
process.stderr.isTTY !== true
? Promise.resolve(undefined)
: runCommand(
process.execPath,
[CLI_SCRIPT_PATH, "setup", "--all-detected"],
"human",
),
});
const systemNpmInstallationHost: NpmInstallationHost = {