feat: streamline agent integration and MCP routing
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 }),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
@@ -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"])))
|
||||
);
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -53,7 +53,9 @@ export const registerSetupCommands = (
|
||||
skill: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("Install or skip the bundled REA skill"),
|
||||
.describe(
|
||||
"Override the bundled skill included with agent integrations",
|
||||
),
|
||||
dryRun: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
@@ -129,8 +131,10 @@ const runSetupCommand = async (input: {
|
||||
const hasExplicitScope = setupHasExplicitScope(options);
|
||||
if (options.yes && !hasExplicitScope)
|
||||
process.stderr.write(
|
||||
"! Implicit `rea setup --yes` scope is deprecated; use `--all-detected --skill` to retain it.\n",
|
||||
"! Implicit `rea setup --yes` scope is deprecated; use `--all-detected` to retain it.\n",
|
||||
);
|
||||
const agentIntegrationSelected =
|
||||
options.allDetected || options.client.length > 0;
|
||||
const result = await runSetup(
|
||||
{
|
||||
approved: options.yes && !options.dryRun,
|
||||
@@ -140,7 +144,11 @@ const runSetupCommand = async (input: {
|
||||
...(!hasExplicitScope || options.allDetected
|
||||
? {}
|
||||
: { clientIds: options.client }),
|
||||
...(!hasExplicitScope ? {} : { installSkill: options.skill ?? false }),
|
||||
...(!hasExplicitScope
|
||||
? {}
|
||||
: {
|
||||
installSkill: options.skill ?? agentIntegrationSelected,
|
||||
}),
|
||||
...(interactive ? { onProgress: renderSetupProgress } : {}),
|
||||
},
|
||||
systemSetupHost(createSystemDoctorHost()),
|
||||
|
||||
+37
-16
@@ -28,7 +28,7 @@ const promptStreams = {
|
||||
withGuide: true,
|
||||
} as const;
|
||||
|
||||
const agentAccessCapabilityId = "agent_access";
|
||||
const agentIntegrationCapabilityId = "agent_integration";
|
||||
|
||||
interface SetupCapability {
|
||||
readonly id: string;
|
||||
@@ -138,37 +138,58 @@ const selectSetupActions = async (
|
||||
: await selectCapabilities(capabilities);
|
||||
if (selectedCapabilities === undefined) return undefined;
|
||||
const selectedCapabilityIds = new Set(selectedCapabilities);
|
||||
const bundledSkillAction = componentActions.find(
|
||||
({ kind }) => kind === "install_skill",
|
||||
);
|
||||
const selectedActionIds = componentActions
|
||||
.filter(({ id }) => selectedCapabilityIds.has(id))
|
||||
.filter(
|
||||
({ id }) =>
|
||||
id !== bundledSkillAction?.id && selectedCapabilityIds.has(id),
|
||||
)
|
||||
.map(({ id }) => id);
|
||||
if (!selectedCapabilityIds.has(agentAccessCapabilityId))
|
||||
if (!selectedCapabilityIds.has(agentIntegrationCapabilityId))
|
||||
return selectedActionIds;
|
||||
if (clientActions.length === 0)
|
||||
return [
|
||||
...(bundledSkillAction === undefined ? [] : [bundledSkillAction.id]),
|
||||
...selectedActionIds,
|
||||
];
|
||||
const selectedClients = accessible
|
||||
? await selectClientsAccessibly(clientActions)
|
||||
: await selectClients(clientActions);
|
||||
return selectedClients === undefined
|
||||
? undefined
|
||||
: [...selectedClients, ...selectedActionIds];
|
||||
if (selectedClients === undefined) return undefined;
|
||||
if (selectedClients.length === 0) return selectedActionIds;
|
||||
return [
|
||||
...selectedClients,
|
||||
...(bundledSkillAction === undefined ? [] : [bundledSkillAction.id]),
|
||||
...selectedActionIds,
|
||||
];
|
||||
};
|
||||
|
||||
const setupCapabilities = (
|
||||
clientActions: readonly SetupAction[],
|
||||
componentActions: readonly SetupAction[],
|
||||
): readonly SetupCapability[] => [
|
||||
...(clientActions.length === 0
|
||||
...(clientActions.length === 0 &&
|
||||
!componentActions.some(({ kind }) => kind === "install_skill")
|
||||
? []
|
||||
: [
|
||||
{
|
||||
id: agentAccessCapabilityId,
|
||||
label: "Coding-agent access (MCP)",
|
||||
hint: `${String(clientActions.length)} detected ${clientActions.length === 1 ? "agent" : "agents"}`,
|
||||
id: agentIntegrationCapabilityId,
|
||||
label: "Agent integration (MCP + guided workflow)",
|
||||
hint:
|
||||
clientActions.length === 0
|
||||
? "MCP registrations are aligned; installs the matching bundled skill"
|
||||
: `${String(clientActions.length)} detected ${clientActions.length === 1 ? "agent" : "agents"}; installs the bundled skill when needed`,
|
||||
},
|
||||
]),
|
||||
...componentActions.map((action) => ({
|
||||
id: action.id,
|
||||
label: `${action.label} (${actionModality(action)})`,
|
||||
hint: `${action.operation} · ${action.target}`,
|
||||
})),
|
||||
...componentActions
|
||||
.filter(({ kind }) => kind !== "install_skill")
|
||||
.map((action) => ({
|
||||
id: action.id,
|
||||
label: `${action.label} (${actionModality(action)})`,
|
||||
hint: `${action.operation} · ${action.target}`,
|
||||
})),
|
||||
];
|
||||
|
||||
const selectCapabilities = async (
|
||||
@@ -297,7 +318,7 @@ const renderReadyCapabilities = (
|
||||
const firstClient = readyClients[0];
|
||||
if (firstClient !== undefined)
|
||||
writeLine(
|
||||
`│ Try in ${firstClient}: "Use REA to explain how a feature works in /path/to/app."`,
|
||||
`│ Try in ${firstClient}: "Explain how a feature works in /path/to/app and show the evidence."`,
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { evidenceResultOf } from "./toolOutputSchemas.js";
|
||||
@@ -11,6 +13,8 @@ import {
|
||||
analyzeJavaScriptApplicationInputSchema,
|
||||
javascriptApplicationAnalysisResultSchema,
|
||||
} from "../domain/javascriptApplicationAnalysis.js";
|
||||
import { JAVASCRIPT_APPLICATION_NODE_KINDS } from "../domain/javascriptApplicationGraphSchemas.js";
|
||||
import { applicationCoverageSchema } from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import {
|
||||
javascriptRuntimeReconciliationResultSchema,
|
||||
reconcileJavaScriptRuntimeInputSchema,
|
||||
@@ -19,8 +23,62 @@ import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "./javascriptRuntimeRe
|
||||
|
||||
const listOutputSchema = evidenceResultOf(electronTargetListSchema);
|
||||
const inspectionOutputSchema = evidenceResultOf(electronPageInspectionSchema);
|
||||
/** MCP-only response selection; analysis identity does not depend on projection. */
|
||||
export const analyzeJavaScriptApplicationToolInputSchema =
|
||||
analyzeJavaScriptApplicationInputSchema.extend({
|
||||
detail: z
|
||||
.enum(["summary", "full"])
|
||||
.default("summary")
|
||||
.describe(
|
||||
"summary returns bounded findings and paged graph resource URIs; full returns the complete graph only when explicitly required",
|
||||
),
|
||||
});
|
||||
|
||||
/** Bounded default projection for agent-facing JavaScript application analysis. */
|
||||
export const javascriptApplicationAnalysisSummarySchema =
|
||||
javascriptApplicationAnalysisResultSchema.omit({ graph: true }).extend({
|
||||
unknowns: z.array(z.string().min(1).max(4_096)).max(1_000),
|
||||
graph: z.strictObject({
|
||||
graph_id: z.string().regex(/^jag_[a-f0-9]{64}$/u),
|
||||
node_count: z.number().int().min(0),
|
||||
edge_count: z.number().int().min(0),
|
||||
roots: z.strictObject({
|
||||
items: z.array(z.string().regex(/^jag_node_[a-f0-9]{64}$/u)),
|
||||
total: z.number().int().min(0),
|
||||
truncated: z.boolean(),
|
||||
}),
|
||||
node_kinds: z.array(
|
||||
z.strictObject({
|
||||
kind: z.enum(JAVASCRIPT_APPLICATION_NODE_KINDS),
|
||||
count: z.number().int().min(1),
|
||||
}),
|
||||
),
|
||||
top_findings: z.array(
|
||||
z.strictObject({
|
||||
node_id: z.string().regex(/^jag_node_[a-f0-9]{64}$/u),
|
||||
kind: z.enum(JAVASCRIPT_APPLICATION_NODE_KINDS),
|
||||
label: z.string().nullable(),
|
||||
authority: z.string(),
|
||||
state: z.string(),
|
||||
confidence: z.string(),
|
||||
location: z.json(),
|
||||
}),
|
||||
),
|
||||
coverage: applicationCoverageSchema,
|
||||
limitations: z.array(z.string()),
|
||||
pages: z.strictObject({
|
||||
nodes: z.string().startsWith("rea://evidence/"),
|
||||
edges: z.string().startsWith("rea://evidence/"),
|
||||
page_limit: z.number().int().min(1).max(500),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
const applicationOutputSchema = evidenceResultOf(
|
||||
javascriptApplicationAnalysisResultSchema,
|
||||
z.union([
|
||||
javascriptApplicationAnalysisSummarySchema,
|
||||
javascriptApplicationAnalysisResultSchema,
|
||||
]),
|
||||
);
|
||||
const reconciliationOutputSchema = evidenceResultOf(
|
||||
javascriptRuntimeReconciliationResultSchema,
|
||||
@@ -88,9 +146,9 @@ export const ELECTRON_TOOL_CONTRACTS = [
|
||||
name: "analyze_javascript_application",
|
||||
...toolContractMetadata("analyze_javascript_application"),
|
||||
description:
|
||||
"Statically reconstruct one approved local ASAR or extracted JavaScript application as Evidence v2 and JavaScript Application Graph v1. Maps BrowserWindow preferences, preload and contextBridge APIs, literal and dynamic IPC, handler locations, sender-validation observations, utility processes, and requested native addon bindings without executing JavaScript; source-map contents require separate approval.",
|
||||
"Statically reconstruct one approved local ASAR or extracted JavaScript application without executing it. The default summary returns architecture/security counts, top evidence-backed findings, unknowns, and paged graph resource URIs; request detail=full only when the complete graph must be returned immediately. Identical inputs are deterministic, so do not repeat the call or reread full Evidence without a specific missing detail.",
|
||||
kind: "electron-provider",
|
||||
inputSchema: analyzeJavaScriptApplicationInputSchema,
|
||||
inputSchema: analyzeJavaScriptApplicationToolInputSchema,
|
||||
outputSchema: applicationOutputSchema,
|
||||
examples: [
|
||||
{
|
||||
@@ -100,6 +158,7 @@ export const ELECTRON_TOOL_CONTRACTS = [
|
||||
format: "auto",
|
||||
approved: true,
|
||||
source_map_read_approved: false,
|
||||
detail: "summary",
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -6,6 +6,13 @@ import { toolContractMetadata } from "./toolEffects.js";
|
||||
|
||||
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
|
||||
export const managedArtifactInputSchema = z.object({
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
"Managed PE/CLI path to open before inspection; omit only when a managed target is already active",
|
||||
),
|
||||
reference_offset: z.number().int().min(0).default(0),
|
||||
reference_limit: z.number().int().min(1).max(500).default(100),
|
||||
resource_offset: z.number().int().min(0).default(0),
|
||||
@@ -122,14 +129,14 @@ export const MANAGED_TOOL_CONTRACTS = [
|
||||
name: "inspect_managed_artifact",
|
||||
...toolContractMetadata("inspect_managed_artifact"),
|
||||
description:
|
||||
"Classify the active PE/CLI artifact and inventory exact assembly/module identity, target framework evidence, references, resources, and custom attributes without loading or executing target code. Returns bounded pages and explicit partial or malformed coverage.",
|
||||
"Open and classify an explicit managed PE/CLI path, or inspect the active managed target, then inventory exact assembly/module identity, target framework evidence, references, resources, and custom attributes without loading or executing target code. Returns bounded pages and explicit partial or malformed coverage.",
|
||||
kind: "managed-provider",
|
||||
inputSchema: managedArtifactInputSchema,
|
||||
outputSchema,
|
||||
examples: [
|
||||
{
|
||||
title: "Example inspect managed artifact request",
|
||||
input: {},
|
||||
input: { path: "/tmp/Example.dll" },
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Caller observations and projection controls for binary_session. */
|
||||
export const binarySessionInputSchema = z.object({
|
||||
detail: z
|
||||
.enum(["summary", "capabilities", "full"])
|
||||
.default("summary")
|
||||
.describe(
|
||||
"summary returns routing state; capabilities returns one filtered tool-availability page; full returns complete diagnostics only when required",
|
||||
),
|
||||
capability_family: z
|
||||
.enum([
|
||||
"official-proxy",
|
||||
"enhanced",
|
||||
"native-provider",
|
||||
"artifact-provider",
|
||||
"managed-provider",
|
||||
"browser-provider",
|
||||
"electron-provider",
|
||||
"application",
|
||||
"session",
|
||||
])
|
||||
.optional()
|
||||
.describe("Optional tool family for detail=capabilities"),
|
||||
cursor: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.default(0)
|
||||
.describe("Zero-based capability cursor for detail=capabilities"),
|
||||
limit: z.number().int().min(1).max(100).default(25),
|
||||
expected_package_version: z.string().min(1).optional(),
|
||||
expected_catalog_digest: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
.optional(),
|
||||
expected_server_path: z.string().min(1).optional(),
|
||||
});
|
||||
@@ -34,6 +34,9 @@ import {
|
||||
} from "./sessionLifecycleInputs.js";
|
||||
import type { ToolContract, ToolExample } from "./toolContractTypes.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { binarySessionInputSchema } from "./sessionStatusContract.js";
|
||||
|
||||
export { binarySessionInputSchema } from "./sessionStatusContract.js";
|
||||
|
||||
export type { ToolContract, ToolExample } from "./toolContractTypes.js";
|
||||
|
||||
@@ -366,16 +369,6 @@ export const ENHANCED_TOOL_CONTRACTS = [
|
||||
),
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
/** Caller observations used to compare a live server with expected identity. */
|
||||
export const binarySessionInputSchema = z.object({
|
||||
expected_package_version: z.string().min(1).optional(),
|
||||
expected_catalog_digest: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
.optional(),
|
||||
expected_server_path: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/** Session-owned Evidence bundle export options. */
|
||||
export const exportEvidenceBundleInputSchema = z.strictObject({
|
||||
path: z.string().min(1).optional(),
|
||||
@@ -426,7 +419,7 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
),
|
||||
session(
|
||||
"binary_session",
|
||||
"Report deterministic deep-provider candidates, host availability, target support, the immutable active binding/profile, capability descriptors, and whether a target is open. Candidate discovery never starts an analysis process; use rejection codes and local diagnostics before choosing provider_id.",
|
||||
"Report compact target, provider, and alignment state without starting analysis. The default summary is the routing check agents should use; detail=capabilities returns one family-filtered availability page, while detail=full is reserved for complete provider diagnostics.",
|
||||
binarySessionInputSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -52,6 +52,8 @@ import {
|
||||
searchPageOutput,
|
||||
segmentOutput,
|
||||
sessionProvider,
|
||||
providerIdentity,
|
||||
toolAvailability,
|
||||
symbolDiscoveryOutput,
|
||||
targetFormatSchema,
|
||||
targetKindSchema,
|
||||
@@ -275,15 +277,57 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
),
|
||||
binary_session: lifecycleResultOf(
|
||||
z.union([
|
||||
sessionProvider.extend({ open: z.literal(false) }),
|
||||
sessionProvider.extend({
|
||||
open: z.literal(true),
|
||||
path: z.string(),
|
||||
format: targetFormatSchema,
|
||||
kind: targetKindSchema,
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
|
||||
z.object({
|
||||
view: z.literal("summary"),
|
||||
open: z.boolean(),
|
||||
provider: providerIdentity,
|
||||
active_provider: providerIdentity.nullable(),
|
||||
target: z
|
||||
.object({
|
||||
path: z.string(),
|
||||
format: targetFormatSchema,
|
||||
kind: targetKindSchema,
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
|
||||
})
|
||||
.nullable(),
|
||||
alignment: z.object({
|
||||
state: z.enum(["aligned", "mcp_server_restart_required", "unknown"]),
|
||||
reasons: z.array(z.string()),
|
||||
remediation: z.string().nullable(),
|
||||
}),
|
||||
recommended_actions: z.array(z.string()),
|
||||
}),
|
||||
z.object({
|
||||
view: z.literal("capabilities"),
|
||||
open: z.boolean(),
|
||||
provider: providerIdentity,
|
||||
active_provider: providerIdentity.nullable(),
|
||||
capability_family: z.string().nullable(),
|
||||
capabilities: z.object({
|
||||
items: z.array(toolAvailability),
|
||||
cursor: z.number().int().min(0),
|
||||
limit: z.number().int().min(1),
|
||||
total: z.number().int().min(0),
|
||||
next_cursor: z.number().int().min(0).nullable(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
}),
|
||||
z.union([
|
||||
sessionProvider.extend({
|
||||
view: z.literal("full"),
|
||||
open: z.literal(false),
|
||||
}),
|
||||
sessionProvider.extend({
|
||||
view: z.literal("full"),
|
||||
open: z.literal(true),
|
||||
path: z.string(),
|
||||
format: targetFormatSchema,
|
||||
kind: targetKindSchema,
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
|
||||
}),
|
||||
]),
|
||||
]),
|
||||
),
|
||||
export_evidence_bundle: lifecycleResultOf(
|
||||
|
||||
@@ -85,7 +85,7 @@ const providerCapability = z.object({
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
|
||||
const providerIdentity = z.object({
|
||||
export const providerIdentity = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
version: z.string().nullable(),
|
||||
@@ -139,6 +139,38 @@ const providerTargetSupport = z.discriminatedUnion("status", [
|
||||
}),
|
||||
]);
|
||||
|
||||
export const toolAvailability = z.object({
|
||||
name: z.string(),
|
||||
surface: z.string(),
|
||||
available: z.boolean(),
|
||||
reason: z.enum([
|
||||
"available",
|
||||
"target_required",
|
||||
"provider_missing",
|
||||
"provider_unavailable",
|
||||
"target_unsupported",
|
||||
"unsupported_host",
|
||||
"policy_disabled",
|
||||
]),
|
||||
remediation: z.string().nullable(),
|
||||
effects: z.strictObject({
|
||||
mutatesTarget: z.boolean(),
|
||||
mutatesSession: z.boolean(),
|
||||
writesFilesystem: z.boolean(),
|
||||
launchesProcess: z.boolean(),
|
||||
accessesNetwork: z.boolean(),
|
||||
changesUiState: z.boolean(),
|
||||
mayDiscardData: z.boolean(),
|
||||
idempotent: z.boolean(),
|
||||
}),
|
||||
annotations: z.object({
|
||||
read_only: z.boolean(),
|
||||
destructive: z.boolean(),
|
||||
idempotent: z.boolean(),
|
||||
open_world: z.boolean(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const sessionProvider = z.object({
|
||||
provider: providerIdentity,
|
||||
providers: z.array(providerIdentity),
|
||||
@@ -163,39 +195,7 @@ export const sessionProvider = z.object({
|
||||
capabilities: z.array(providerCapability),
|
||||
}),
|
||||
),
|
||||
tool_availability: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
surface: z.string(),
|
||||
available: z.boolean(),
|
||||
reason: z.enum([
|
||||
"available",
|
||||
"target_required",
|
||||
"provider_missing",
|
||||
"provider_unavailable",
|
||||
"target_unsupported",
|
||||
"unsupported_host",
|
||||
"policy_disabled",
|
||||
]),
|
||||
remediation: z.string().nullable(),
|
||||
effects: z.strictObject({
|
||||
mutatesTarget: z.boolean(),
|
||||
mutatesSession: z.boolean(),
|
||||
writesFilesystem: z.boolean(),
|
||||
launchesProcess: z.boolean(),
|
||||
accessesNetwork: z.boolean(),
|
||||
changesUiState: z.boolean(),
|
||||
mayDiscardData: z.boolean(),
|
||||
idempotent: z.boolean(),
|
||||
}),
|
||||
annotations: z.object({
|
||||
read_only: z.boolean(),
|
||||
destructive: z.boolean(),
|
||||
idempotent: z.boolean(),
|
||||
open_world: z.boolean(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
tool_availability: z.array(toolAvailability),
|
||||
client_features: z.object({
|
||||
elicitation_form: z.boolean(),
|
||||
elicitation_url: z.boolean(),
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
/** One REA MCP invocation observed in a Codex JSONL transcript. */
|
||||
interface CodexMcpCall {
|
||||
readonly id: string | null;
|
||||
readonly server: string | null;
|
||||
readonly tool: string;
|
||||
readonly arguments: unknown;
|
||||
readonly evidenceIds: readonly string[];
|
||||
readonly error: boolean;
|
||||
}
|
||||
|
||||
/** Release-evaluation metrics derived from an actual Codex JSONL transcript. */
|
||||
export interface CodexAgentMetrics {
|
||||
readonly naturalUse: boolean;
|
||||
readonly correctFirstTool: boolean;
|
||||
readonly firstTool: string | null;
|
||||
readonly reaCalls: readonly CodexMcpCall[];
|
||||
readonly repeatedCallCount: number;
|
||||
readonly inputTokens: number;
|
||||
readonly cachedInputTokens: number;
|
||||
readonly outputTokens: number;
|
||||
readonly finalMessage: string;
|
||||
readonly evidenceIds: readonly string[];
|
||||
readonly finalCitesEvidence: boolean;
|
||||
readonly contentCriteriaMet: boolean;
|
||||
readonly completionQuality: boolean;
|
||||
readonly authorityHonesty: boolean;
|
||||
}
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const record = (value: unknown): Record<string, unknown> | undefined =>
|
||||
isRecord(value) ? value : undefined;
|
||||
|
||||
const textValue = (value: unknown): string | undefined =>
|
||||
typeof value === "string" && value.length > 0 ? value : undefined;
|
||||
|
||||
const numberValue = (value: unknown): number =>
|
||||
typeof value === "number" && Number.isFinite(value) ? value : 0;
|
||||
|
||||
const canonicalValue = (value: unknown): unknown => {
|
||||
if (Array.isArray(value)) return value.map(canonicalValue);
|
||||
const object = record(value);
|
||||
if (object === undefined) return value;
|
||||
return Object.fromEntries(
|
||||
Object.entries(object)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, child]) => [key, canonicalValue(child)]),
|
||||
);
|
||||
};
|
||||
|
||||
const evidenceIdsFrom = (value: unknown): readonly string[] => {
|
||||
const encoded = JSON.stringify(value);
|
||||
if (encoded === undefined) return [];
|
||||
return [...new Set(encoded.match(/ev_[a-f0-9]{64}/gu) ?? [])];
|
||||
};
|
||||
|
||||
const toolResultFailed = (item: Record<string, unknown>): boolean => {
|
||||
if (
|
||||
item.status === "failed" ||
|
||||
(item.error !== undefined && item.error !== null)
|
||||
)
|
||||
return true;
|
||||
const result = record(item.result ?? item.output);
|
||||
const structured = record(
|
||||
result?.structured_content ?? result?.structuredContent,
|
||||
);
|
||||
return result?.isError === true || structured?.error !== undefined;
|
||||
};
|
||||
|
||||
const callFromItem = (value: unknown): CodexMcpCall | undefined => {
|
||||
const item = record(value);
|
||||
if (item?.type !== "mcp_tool_call") return undefined;
|
||||
const tool = textValue(item.tool) ?? textValue(item.name);
|
||||
if (tool === undefined) return undefined;
|
||||
return {
|
||||
id: textValue(item.id) ?? null,
|
||||
server: textValue(item.server) ?? textValue(item.server_name) ?? null,
|
||||
tool,
|
||||
arguments: item.arguments ?? item.input ?? {},
|
||||
evidenceIds: evidenceIdsFrom(item.result ?? item.output),
|
||||
error: toolResultFailed(item),
|
||||
};
|
||||
};
|
||||
|
||||
const agentTextFromItem = (value: unknown): string | undefined => {
|
||||
const item = record(value);
|
||||
if (item?.type !== "agent_message") return undefined;
|
||||
const direct = textValue(item.text) ?? textValue(item.message);
|
||||
if (direct !== undefined) return direct;
|
||||
if (!Array.isArray(item.content)) return undefined;
|
||||
const parts = item.content.flatMap((part) => {
|
||||
const object = record(part);
|
||||
const text = object === undefined ? undefined : textValue(object.text);
|
||||
return text === undefined ? [] : [text];
|
||||
});
|
||||
return parts.length === 0 ? undefined : parts.join("\n");
|
||||
};
|
||||
|
||||
interface EvaluationState {
|
||||
readonly calls: CodexMcpCall[];
|
||||
readonly seenCallIds: Set<string>;
|
||||
readonly finalMessages: string[];
|
||||
inputTokens: number;
|
||||
cachedInputTokens: number;
|
||||
outputTokens: number;
|
||||
}
|
||||
|
||||
const consumeEvent = (state: EvaluationState, value: unknown): void => {
|
||||
const event = record(value);
|
||||
if (event === undefined) return;
|
||||
const completedItem =
|
||||
event.type === "item.completed" ? event.item : undefined;
|
||||
const call =
|
||||
callFromItem(completedItem) ??
|
||||
(event.type === "mcp_tool_call" ? callFromItem(event) : undefined);
|
||||
if (call !== undefined) {
|
||||
const identity =
|
||||
call.id ??
|
||||
`${call.server ?? ""}:${call.tool}:${JSON.stringify(canonicalValue(call.arguments))}`;
|
||||
if (!state.seenCallIds.has(identity)) {
|
||||
state.seenCallIds.add(identity);
|
||||
state.calls.push(call);
|
||||
}
|
||||
}
|
||||
const message = agentTextFromItem(completedItem);
|
||||
if (message !== undefined) state.finalMessages.push(message);
|
||||
if (event.type !== "turn.completed") return;
|
||||
const usage = record(event.usage);
|
||||
state.inputTokens = Math.max(
|
||||
state.inputTokens,
|
||||
numberValue(usage?.input_tokens),
|
||||
);
|
||||
state.cachedInputTokens = Math.max(
|
||||
state.cachedInputTokens,
|
||||
numberValue(usage?.cached_input_tokens),
|
||||
);
|
||||
state.outputTokens = Math.max(
|
||||
state.outputTokens,
|
||||
numberValue(usage?.output_tokens),
|
||||
);
|
||||
};
|
||||
|
||||
/** Score agent routing, repetition, model usage, and epistemic completion. */
|
||||
export const evaluateCodexEvents = (
|
||||
events: readonly unknown[],
|
||||
expectedFirstTool: string,
|
||||
options: {
|
||||
readonly requireEvidence?: boolean;
|
||||
readonly requiredAnswerTermGroups?: readonly (readonly string[])[];
|
||||
} = {},
|
||||
): CodexAgentMetrics => {
|
||||
const state: EvaluationState = {
|
||||
calls: [],
|
||||
seenCallIds: new Set(),
|
||||
finalMessages: [],
|
||||
inputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 0,
|
||||
};
|
||||
for (const event of events) consumeEvent(state, event);
|
||||
|
||||
const reaCalls = state.calls.filter(
|
||||
({ server }) => server === null || server.toLowerCase() === "rea",
|
||||
);
|
||||
const signatures = new Map<string, number>();
|
||||
for (const call of reaCalls) {
|
||||
const signature = `${call.tool}:${JSON.stringify(canonicalValue(call.arguments))}`;
|
||||
signatures.set(signature, (signatures.get(signature) ?? 0) + 1);
|
||||
}
|
||||
const repeatedCallCount = [...signatures.values()].reduce(
|
||||
(total, count) => total + Math.max(0, count - 1),
|
||||
0,
|
||||
);
|
||||
const finalMessage = state.finalMessages.at(-1) ?? "";
|
||||
const evidenceIds = [
|
||||
...new Set(reaCalls.flatMap(({ evidenceIds: ids }) => ids)),
|
||||
];
|
||||
const finalCitesEvidence = evidenceIds.some((evidenceId) =>
|
||||
finalMessage.includes(evidenceId),
|
||||
);
|
||||
const normalizedFinalMessage = finalMessage.toLocaleLowerCase("en-US");
|
||||
const contentCriteriaMet = (options.requiredAnswerTermGroups ?? []).every(
|
||||
(terms) =>
|
||||
terms.some((term) =>
|
||||
normalizedFinalMessage.includes(term.toLocaleLowerCase("en-US")),
|
||||
),
|
||||
);
|
||||
const authorityHonesty =
|
||||
/\b(evidence|observed|inferred|unknown|unavailable|limitation|authority|not configured|could not|requires approval)\b/iu.test(
|
||||
finalMessage,
|
||||
);
|
||||
return {
|
||||
naturalUse: reaCalls.length > 0,
|
||||
correctFirstTool: reaCalls[0]?.tool === expectedFirstTool,
|
||||
firstTool: reaCalls[0]?.tool ?? null,
|
||||
reaCalls,
|
||||
repeatedCallCount,
|
||||
inputTokens: state.inputTokens,
|
||||
cachedInputTokens: state.cachedInputTokens,
|
||||
outputTokens: state.outputTokens,
|
||||
finalMessage,
|
||||
evidenceIds,
|
||||
finalCitesEvidence,
|
||||
contentCriteriaMet,
|
||||
completionQuality:
|
||||
finalMessage.trim().length >= 80 &&
|
||||
authorityHonesty &&
|
||||
contentCriteriaMet &&
|
||||
(options.requireEvidence !== true || finalCitesEvidence),
|
||||
authorityHonesty,
|
||||
};
|
||||
};
|
||||
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
|
||||
serverSdkVersion: "2.0.0-beta.4",
|
||||
clientSdkVersion: "2.0.0-beta.4",
|
||||
coreSdkVersion: "2.0.0-beta.4",
|
||||
skillVersion: "22",
|
||||
skillVersion: "23",
|
||||
} as const;
|
||||
|
||||
+2
-1
@@ -7,9 +7,10 @@ export const PRODUCT_IDENTITY = {
|
||||
displayName: "REA",
|
||||
packageName: PACKAGE_METADATA.name,
|
||||
packageSpecifier: `${PACKAGE_METADATA.name}@latest`,
|
||||
registrationPackageSpecifier: `${PACKAGE_METADATA.name}@${PACKAGE_METADATA.version}`,
|
||||
packageVersion: PACKAGE_METADATA.version,
|
||||
cliBinary: "rea",
|
||||
mcpCommand: `npx -y ${PACKAGE_METADATA.name}@latest mcp`,
|
||||
mcpCommand: `npx -y ${PACKAGE_METADATA.name}@${PACKAGE_METADATA.version} mcp`,
|
||||
mcpServerKey: "rea",
|
||||
skillName: "reverse-engineer-anything",
|
||||
skillVersion: PACKAGE_METADATA.skillVersion,
|
||||
|
||||
@@ -29,6 +29,12 @@ import { registerBrowserTools } from "./registerBrowserTools.js";
|
||||
import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
|
||||
import { registerElectronTools } from "./registerElectronTools.js";
|
||||
import { registerApplicationTools } from "./registerApplicationTools.js";
|
||||
|
||||
const TARGET_FREE_INSTRUCTIONS =
|
||||
"REA analyzes shipped artifacts and approved runtime evidence; use repository tools for source. Route: ASAR/JavaScript -> analyze_javascript_application; archive/package -> inventory_artifact; managed PE/CLI -> inspect_managed_artifact; browser/Electron runtime -> list_browser_targets/list_electron_targets; native binary/database -> open_binary, then binary_overview. Start with summaries and cite Evidence IDs. Never repeat identical analysis or read full Evidence unless a missing detail requires it.";
|
||||
|
||||
const ACTIVE_TARGET_INSTRUCTIONS =
|
||||
"REA analyzes the active reverse-engineering target. Start native analysis with binary_overview, then narrow with analyze_function, literal search, callers, callees, and xrefs. Prefer summary views, never repeat an identical call, and read full Evidence only when the task requires it.";
|
||||
import type {
|
||||
JavaScriptReplayHost,
|
||||
JavaScriptReplayPolicy,
|
||||
@@ -102,8 +108,8 @@ export const createServer = (
|
||||
requestState: { verify: processCaptureStateCodec.verify },
|
||||
instructions:
|
||||
session === undefined
|
||||
? "Reverse-engineering tools for an active analysis target. Start with binary_overview."
|
||||
: "Reverse-engineering tools for configured analysis providers. Open a target with open_binary, then start with binary_overview.",
|
||||
? ACTIVE_TARGET_INSTRUCTIONS
|
||||
: TARGET_FREE_INSTRUCTIONS,
|
||||
},
|
||||
);
|
||||
server.server.onclose = () => {
|
||||
@@ -276,6 +282,7 @@ const registerBinaryAnalysisTools = ({
|
||||
logger,
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
session,
|
||||
});
|
||||
if (session !== undefined)
|
||||
registerManagedWorkflowTools(server, {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../domain/javascriptApplicationAnalysis.js";
|
||||
import { compareCodePoints } from "../domain/javascriptApplicationGraph.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { javascriptApplicationAnalysisSummarySchema } from "../contracts/electronToolContracts.js";
|
||||
|
||||
const DEFAULT_GRAPH_PAGE_LIMIT = 100;
|
||||
const ROOT_SAMPLE_LIMIT = 10;
|
||||
const TOP_FINDING_LIMIT = 20;
|
||||
|
||||
const FINDING_PRIORITY: Readonly<Record<string, number>> = {
|
||||
"browser-window": 0,
|
||||
"electron-preload": 1,
|
||||
"context-bridge-api": 2,
|
||||
"ipc-channel": 3,
|
||||
"ipc-handler": 4,
|
||||
"electron-utility": 5,
|
||||
endpoint: 6,
|
||||
storage: 7,
|
||||
worker: 8,
|
||||
"service-worker": 9,
|
||||
"native-addon": 10,
|
||||
"native-export": 11,
|
||||
"source-map": 12,
|
||||
};
|
||||
|
||||
/** Project complete JavaScript application Evidence into a bounded agent result. */
|
||||
export const summarizeJavaScriptApplicationEvidence = (
|
||||
evidence: Evidence,
|
||||
): JsonValue => {
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
const nodeKinds = new Map<string, number>();
|
||||
for (const node of result.graph.nodes)
|
||||
nodeKinds.set(node.kind, (nodeKinds.get(node.kind) ?? 0) + 1);
|
||||
const rootItems = result.graph.root_node_ids.slice(0, ROOT_SAMPLE_LIMIT);
|
||||
const pageRoot = `rea://evidence/${evidence.evidence_id}/application-graph`;
|
||||
const topFindings = [...result.graph.nodes]
|
||||
.sort(
|
||||
(left, right) =>
|
||||
(FINDING_PRIORITY[left.kind] ?? Number.MAX_SAFE_INTEGER) -
|
||||
(FINDING_PRIORITY[right.kind] ?? Number.MAX_SAFE_INTEGER) ||
|
||||
compareCodePoints(left.node_id, right.node_id),
|
||||
)
|
||||
.slice(0, TOP_FINDING_LIMIT)
|
||||
.map((node) => {
|
||||
const observation = node.observations[0];
|
||||
if (observation === undefined)
|
||||
throw new TypeError("Application graph node has no observation");
|
||||
return {
|
||||
node_id: node.node_id,
|
||||
kind: node.kind,
|
||||
label: observation.label,
|
||||
authority: observation.evidence.authority,
|
||||
state: observation.evidence.state,
|
||||
confidence: observation.evidence.confidence,
|
||||
location: observation.evidence.location,
|
||||
};
|
||||
});
|
||||
const { graph: _graph, ...summary } = result;
|
||||
const unknowns = new Set([
|
||||
...result.limitations,
|
||||
...result.graph.limitations,
|
||||
]);
|
||||
if (result.statistics.parse_failures > 0)
|
||||
unknowns.add(
|
||||
`${String(result.statistics.parse_failures)} JavaScript file(s) could not be parsed.`,
|
||||
);
|
||||
if (result.statistics.truncated_scopes > 0)
|
||||
unknowns.add(
|
||||
`${String(result.statistics.truncated_scopes)} analysis scope(s) were truncated.`,
|
||||
);
|
||||
if (result.graph.coverage.status !== "complete")
|
||||
unknowns.add(
|
||||
`Application graph coverage is ${result.graph.coverage.status}; omitted facts remain unknown.`,
|
||||
);
|
||||
return javascriptApplicationAnalysisSummarySchema.parse({
|
||||
...summary,
|
||||
unknowns: [...unknowns],
|
||||
graph: {
|
||||
graph_id: result.graph.graph_id,
|
||||
node_count: result.graph.nodes.length,
|
||||
edge_count: result.graph.edges.length,
|
||||
roots: {
|
||||
items: rootItems,
|
||||
total: result.graph.root_node_ids.length,
|
||||
truncated: rootItems.length < result.graph.root_node_ids.length,
|
||||
},
|
||||
node_kinds: [...nodeKinds]
|
||||
.sort(([left], [right]) => compareCodePoints(left, right))
|
||||
.map(([kind, count]) => ({ kind, count })),
|
||||
top_findings: topFindings,
|
||||
coverage: result.graph.coverage,
|
||||
limitations: result.graph.limitations,
|
||||
pages: {
|
||||
nodes: `${pageRoot}/nodes/offset/0/limit/${String(DEFAULT_GRAPH_PAGE_LIMIT)}`,
|
||||
edges: `${pageRoot}/edges/offset/0/limit/${String(DEFAULT_GRAPH_PAGE_LIMIT)}`,
|
||||
page_limit: DEFAULT_GRAPH_PAGE_LIMIT,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -10,12 +10,14 @@ import {
|
||||
listElectronTargets,
|
||||
} from "../application/ElectronObservationService.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "../contracts/electronToolContracts.js";
|
||||
import {
|
||||
analyzeJavaScriptApplicationToolInputSchema,
|
||||
ELECTRON_TOOL_CONTRACTS,
|
||||
} from "../contracts/electronToolContracts.js";
|
||||
import {
|
||||
inspectElectronPageInputSchema,
|
||||
listElectronTargetsInputSchema,
|
||||
} from "../domain/electronObservation.js";
|
||||
import { analyzeJavaScriptApplicationInputSchema } from "../domain/javascriptApplicationAnalysis.js";
|
||||
import { reconcileJavaScriptRuntimeInputSchema } from "../domain/javascriptRuntimeReconciliationSchemas.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
@@ -28,6 +30,8 @@ import type { Evidence } from "../domain/evidence.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { summarizeJavaScriptApplicationEvidence } from "./javascriptApplicationResult.js";
|
||||
|
||||
interface ElectronToolRegistration {
|
||||
readonly logger: Logger;
|
||||
@@ -48,6 +52,13 @@ interface ElectronToolSpec<Schema extends z.ZodType> {
|
||||
parsed: z.output<Schema>,
|
||||
context: ElectronToolContext,
|
||||
) => Promise<Result<Evidence, AnalysisError>>;
|
||||
readonly projectEvidence?: (
|
||||
evidence: Evidence,
|
||||
parsed: z.output<Schema>,
|
||||
) => {
|
||||
readonly structured: JsonValue;
|
||||
readonly text?: JsonValue;
|
||||
};
|
||||
}
|
||||
|
||||
/** Register Electron tools even when provider or permission policy is absent. */
|
||||
@@ -87,13 +98,19 @@ export const registerElectronTools = (
|
||||
});
|
||||
registerElectronTool(server, options, {
|
||||
contract: analyzeContract,
|
||||
schema: analyzeJavaScriptApplicationInputSchema,
|
||||
schema: analyzeJavaScriptApplicationToolInputSchema,
|
||||
execute: (parsed, { signal, progress }) =>
|
||||
analyzeJavaScriptApplicationValidated(
|
||||
options.permissionAuthority,
|
||||
parsed,
|
||||
{ signal, progress },
|
||||
),
|
||||
projectEvidence: (evidence, parsed) => {
|
||||
const summary = summarizeJavaScriptApplicationEvidence(evidence);
|
||||
return parsed.detail === "full"
|
||||
? { structured: evidence.normalized_result, text: summary }
|
||||
: { structured: summary };
|
||||
},
|
||||
});
|
||||
registerElectronTool(server, options, {
|
||||
contract: reconcileContract,
|
||||
@@ -128,7 +145,12 @@ const registerElectronTool = <Schema extends z.ZodType>(
|
||||
}),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, spec.contract);
|
||||
return evidenceResult(options, spec.contract, result.value);
|
||||
return evidenceResult(
|
||||
options,
|
||||
spec.contract,
|
||||
result.value,
|
||||
spec.projectEvidence?.(result.value, parsedInput.value),
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -137,11 +159,22 @@ const evidenceResult = (
|
||||
options: ElectronToolRegistration,
|
||||
contract: ToolContract,
|
||||
evidence: Evidence,
|
||||
projection:
|
||||
| { readonly structured: JsonValue; readonly text?: JsonValue }
|
||||
| undefined,
|
||||
) => {
|
||||
const recorded = options.recordEvidence?.(evidence);
|
||||
return recorded !== undefined && !recorded.ok
|
||||
? toCallToolResult(recorded, contract)
|
||||
: toCallToolResult({ ok: true, value: evidence }, contract, {
|
||||
evidenceResourcesAvailable: recorded !== undefined,
|
||||
...(projection === undefined
|
||||
? {}
|
||||
: {
|
||||
evidenceResultProjection: projection.structured,
|
||||
...(projection.text === undefined
|
||||
? {}
|
||||
: { evidenceTextProjection: projection.text }),
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ import canonicalize from "canonicalize";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySessionPort.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { registerJavaScriptApplicationGraphResource } from "./registerJavaScriptApplicationGraphResource.js";
|
||||
|
||||
const evidenceUri = (evidenceId: string): string =>
|
||||
`rea://evidence/${evidenceId}`;
|
||||
@@ -26,6 +27,7 @@ export const registerEvidenceResources = (
|
||||
registerArtifactPageResource(server, session);
|
||||
registerFunctionDossierResource(server, session);
|
||||
registerEvidenceSectionResource(server, session);
|
||||
registerJavaScriptApplicationGraphResource(server, session);
|
||||
registerResidualUnknownResource(server, session);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import {
|
||||
ResourceNotFoundError,
|
||||
ResourceTemplate,
|
||||
type McpServer,
|
||||
} from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySessionPort.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../domain/javascriptApplicationAnalysis.js";
|
||||
|
||||
/** Register deterministic pages over one authenticated JavaScript graph. */
|
||||
export const registerJavaScriptApplicationGraphResource = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
): void => {
|
||||
server.registerResource(
|
||||
"javascript-application-graph-page",
|
||||
new ResourceTemplate(
|
||||
"rea://evidence/{evidenceId}/application-graph/{collection}/offset/{offset}/limit/{limit}",
|
||||
{
|
||||
list: undefined,
|
||||
complete: {
|
||||
evidenceId: (prefix) =>
|
||||
session
|
||||
.exportEvidenceBundle()
|
||||
.records.map(({ evidence_id }) => evidence_id)
|
||||
.filter((evidenceId) => evidenceId.startsWith(prefix)),
|
||||
collection: (prefix) =>
|
||||
["nodes", "edges"].filter((name) => name.startsWith(prefix)),
|
||||
},
|
||||
},
|
||||
),
|
||||
{
|
||||
title: "JavaScript application graph page",
|
||||
description:
|
||||
"One deterministic bounded node or edge page from authenticated JavaScript application Evidence.",
|
||||
mimeType: "application/json",
|
||||
},
|
||||
(uri, variables) => {
|
||||
const evidenceId = stringVariable(variables.evidenceId, uri.href);
|
||||
const collection = stringVariable(variables.collection, uri.href);
|
||||
if (collection !== "nodes" && collection !== "edges")
|
||||
throw new ResourceNotFoundError(uri.href);
|
||||
const offset = pageInteger(variables.offset, uri.href, 0, 100_000);
|
||||
const limit = pageInteger(variables.limit, uri.href, 1, 500);
|
||||
const evidence = session.evidenceById(evidenceId);
|
||||
if (
|
||||
evidence === undefined ||
|
||||
evidence.operation !== "analyze_javascript_application"
|
||||
)
|
||||
throw new ResourceNotFoundError(uri.href);
|
||||
const analysis = javascriptApplicationAnalysisResultSchema.safeParse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
if (!analysis.success) throw new ResourceNotFoundError(uri.href);
|
||||
const values = analysis.data.graph[collection];
|
||||
const items = values.slice(offset, offset + limit);
|
||||
const nextOffset = offset + items.length;
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.href,
|
||||
mimeType: "application/json" as const,
|
||||
text: JSON.stringify(
|
||||
{
|
||||
evidence_id: evidence.evidence_id,
|
||||
graph_id: analysis.data.graph.graph_id,
|
||||
collection,
|
||||
items,
|
||||
offset,
|
||||
limit,
|
||||
total: values.length,
|
||||
next_offset: nextOffset < values.length ? nextOffset : null,
|
||||
has_more: nextOffset < values.length,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const stringVariable = (value: unknown, uri: string): string => {
|
||||
if (typeof value !== "string") throw new ResourceNotFoundError(uri);
|
||||
return value;
|
||||
};
|
||||
|
||||
const pageInteger = (
|
||||
value: unknown,
|
||||
uri: string,
|
||||
minimum: number,
|
||||
maximum: number,
|
||||
): number => {
|
||||
const text = stringVariable(value, uri);
|
||||
if (!/^\d+$/u.test(text)) throw new ResourceNotFoundError(uri);
|
||||
const parsed = Number(text);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < minimum || parsed > maximum)
|
||||
throw new ResourceNotFoundError(uri);
|
||||
return parsed;
|
||||
};
|
||||
@@ -5,6 +5,7 @@ import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "../contracts/managedToolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import { registerEvidenceTools } from "./registerEvidenceTools.js";
|
||||
|
||||
/** Register execution-free managed PE/CLI inspection. */
|
||||
@@ -15,7 +16,32 @@ export const registerManagedTools = (
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly session: BinarySessionPort | undefined;
|
||||
},
|
||||
): void => {
|
||||
registerEvidenceTools(server, analysis, MANAGED_TOOL_CONTRACTS, options);
|
||||
const targetAwareAnalysis: AnalysisOperationPort = {
|
||||
execute: async (operation, parameters, executionOptions) => {
|
||||
const path =
|
||||
operation === "inspect_managed_artifact" &&
|
||||
typeof parameters.path === "string"
|
||||
? parameters.path
|
||||
: undefined;
|
||||
if (path !== undefined && options.session !== undefined) {
|
||||
const opened = await options.session.open(
|
||||
path,
|
||||
executionOptions?.signal === undefined
|
||||
? undefined
|
||||
: { signal: executionOptions.signal },
|
||||
);
|
||||
if (!opened.ok) return err(opened.error);
|
||||
}
|
||||
return analysis.execute(operation, parameters, executionOptions);
|
||||
},
|
||||
};
|
||||
registerEvidenceTools(
|
||||
server,
|
||||
targetAwareAnalysis,
|
||||
MANAGED_TOOL_CONTRACTS,
|
||||
options,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import {
|
||||
@@ -12,6 +13,9 @@ import { buildCapabilityInventory } from "../application/CapabilityInventory.js"
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { safeParseToolInput } from "./toolInputValidation.js";
|
||||
|
||||
type BinarySessionInput = z.output<typeof binarySessionInputSchema>;
|
||||
type ToolAvailability = ReturnType<typeof buildCapabilityInventory>[number];
|
||||
|
||||
/** Inputs required to register the binary session status tool. */
|
||||
export interface SessionStatusToolOptions {
|
||||
readonly server: McpServer;
|
||||
@@ -47,16 +51,40 @@ export const registerSessionStatusTool = (
|
||||
const client = server.server.getClientVersion();
|
||||
const clientCapabilities = server.server.getClientCapabilities();
|
||||
const status = session.status();
|
||||
const statusObject = jsonObjectSchema.parse(status);
|
||||
const toolAvailability = buildCapabilityInventory(
|
||||
status,
|
||||
availabilityPolicy(),
|
||||
);
|
||||
const serverIdentity = createServerIdentity({
|
||||
startedAt,
|
||||
expected: {
|
||||
...(parsed.expected_package_version === undefined
|
||||
? {}
|
||||
: { package_version: parsed.expected_package_version }),
|
||||
...(parsed.expected_catalog_digest === undefined
|
||||
? {}
|
||||
: { catalog_digest: parsed.expected_catalog_digest }),
|
||||
...(parsed.expected_server_path === undefined
|
||||
? {}
|
||||
: { server_path: parsed.expected_server_path }),
|
||||
},
|
||||
...(client === undefined ? {} : { client }),
|
||||
...(server.server.getNegotiatedProtocolVersion() === undefined
|
||||
? {}
|
||||
: {
|
||||
protocolVersion: server.server.getNegotiatedProtocolVersion(),
|
||||
}),
|
||||
});
|
||||
return toCallToolResult(
|
||||
{
|
||||
ok: true,
|
||||
value: {
|
||||
...jsonObjectSchema.parse(status),
|
||||
tool_availability: buildCapabilityInventory(
|
||||
status,
|
||||
availabilityPolicy(),
|
||||
),
|
||||
client_features: {
|
||||
value: projectSessionStatus({
|
||||
input: parsed,
|
||||
status: statusObject,
|
||||
toolAvailability,
|
||||
serverIdentity,
|
||||
clientFeatures: {
|
||||
elicitation_form:
|
||||
clientCapabilities?.elicitation?.form !== undefined,
|
||||
elicitation_url:
|
||||
@@ -64,31 +92,104 @@ export const registerSessionStatusTool = (
|
||||
roots: clientCapabilities?.roots !== undefined,
|
||||
sampling: clientCapabilities?.sampling !== undefined,
|
||||
},
|
||||
server_identity: createServerIdentity({
|
||||
startedAt,
|
||||
expected: {
|
||||
...(parsed.expected_package_version === undefined
|
||||
? {}
|
||||
: { package_version: parsed.expected_package_version }),
|
||||
...(parsed.expected_catalog_digest === undefined
|
||||
? {}
|
||||
: { catalog_digest: parsed.expected_catalog_digest }),
|
||||
...(parsed.expected_server_path === undefined
|
||||
? {}
|
||||
: { server_path: parsed.expected_server_path }),
|
||||
},
|
||||
...(client === undefined ? {} : { client }),
|
||||
...(server.server.getNegotiatedProtocolVersion() === undefined
|
||||
? {}
|
||||
: {
|
||||
protocolVersion:
|
||||
server.server.getNegotiatedProtocolVersion(),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
}),
|
||||
},
|
||||
contract,
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const projectSessionStatus = (options: {
|
||||
readonly input: BinarySessionInput;
|
||||
readonly status: Readonly<
|
||||
Record<string, import("../domain/jsonValue.js").JsonValue>
|
||||
>;
|
||||
readonly toolAvailability: readonly ToolAvailability[];
|
||||
readonly serverIdentity: ReturnType<typeof createServerIdentity>;
|
||||
readonly clientFeatures: Readonly<Record<string, boolean>>;
|
||||
}) => {
|
||||
if (options.input.detail === "full")
|
||||
return jsonObjectSchema.parse({
|
||||
view: "full",
|
||||
...options.status,
|
||||
tool_availability: options.toolAvailability,
|
||||
client_features: options.clientFeatures,
|
||||
server_identity: options.serverIdentity,
|
||||
});
|
||||
const open = options.status.open === true;
|
||||
const activeProvider = activeProviderFrom(options.status);
|
||||
if (options.input.detail === "capabilities") {
|
||||
const filtered =
|
||||
options.input.capability_family === undefined
|
||||
? options.toolAvailability
|
||||
: options.toolAvailability.filter(
|
||||
({ surface }) => surface === options.input.capability_family,
|
||||
);
|
||||
const items = filtered.slice(
|
||||
options.input.cursor,
|
||||
options.input.cursor + options.input.limit,
|
||||
);
|
||||
const nextCursor = options.input.cursor + items.length;
|
||||
return jsonObjectSchema.parse({
|
||||
view: "capabilities",
|
||||
open,
|
||||
provider: options.status.provider,
|
||||
active_provider: activeProvider,
|
||||
capability_family: options.input.capability_family ?? null,
|
||||
capabilities: {
|
||||
items,
|
||||
cursor: options.input.cursor,
|
||||
limit: options.input.limit,
|
||||
total: filtered.length,
|
||||
next_cursor: nextCursor < filtered.length ? nextCursor : null,
|
||||
has_more: nextCursor < filtered.length,
|
||||
},
|
||||
});
|
||||
}
|
||||
return jsonObjectSchema.parse({
|
||||
view: "summary",
|
||||
open,
|
||||
provider: options.status.provider,
|
||||
active_provider: activeProvider,
|
||||
target: open ? targetFrom(options.status) : null,
|
||||
alignment: options.serverIdentity.alignment,
|
||||
recommended_actions: recommendedActions(
|
||||
open,
|
||||
options.serverIdentity.alignment.state,
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const activeProviderFrom = (
|
||||
status: Readonly<Record<string, import("../domain/jsonValue.js").JsonValue>>,
|
||||
) => {
|
||||
const binding = jsonObjectSchema.safeParse(status.analysis_provider_binding);
|
||||
return binding.success ? (binding.data.provider ?? null) : null;
|
||||
};
|
||||
|
||||
const targetFrom = (
|
||||
status: Readonly<Record<string, import("../domain/jsonValue.js").JsonValue>>,
|
||||
) => ({
|
||||
path: status.path,
|
||||
format: status.format,
|
||||
kind: status.kind,
|
||||
sha256: status.sha256,
|
||||
architecture: status.architecture ?? null,
|
||||
});
|
||||
|
||||
const recommendedActions = (
|
||||
open: boolean,
|
||||
alignment: string,
|
||||
): readonly string[] => [
|
||||
...(alignment === "mcp_server_restart_required"
|
||||
? ["Restart the registered MCP server or client before continuing."]
|
||||
: []),
|
||||
...(!open
|
||||
? [
|
||||
"Route the supplied target directly: ASAR/JavaScript to analyze_javascript_application, packages to inventory_artifact, managed PE/CLI to inspect_managed_artifact, browser/Electron runtimes to their list-target tools, and native binaries to open_binary.",
|
||||
]
|
||||
: [
|
||||
"Continue from the active target with binary_overview or a bounded target-specific query.",
|
||||
]),
|
||||
];
|
||||
|
||||
@@ -11,6 +11,8 @@ import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
|
||||
interface ToolResultOptions {
|
||||
readonly evidenceResourcesAvailable?: boolean;
|
||||
readonly evidenceResultProjection?: JsonValue;
|
||||
readonly evidenceTextProjection?: JsonValue;
|
||||
readonly resourceLinks?: readonly {
|
||||
readonly uri: string;
|
||||
readonly name: string;
|
||||
@@ -53,7 +55,7 @@ const successResult = (
|
||||
options: ToolResultOptions,
|
||||
): CallToolResult => {
|
||||
const candidate =
|
||||
compactEvidence(value) ??
|
||||
compactEvidence(value, options.evidenceResultProjection) ??
|
||||
(contract.kind === "session" ? { result: value } : value);
|
||||
const parsed = contract.outputSchema.safeParse(candidate);
|
||||
if (!parsed.success) {
|
||||
@@ -78,7 +80,15 @@ const successResult = (
|
||||
}
|
||||
return {
|
||||
content: [
|
||||
{ type: "text", text: JSON.stringify(parsed.data) },
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(
|
||||
options.evidenceTextProjection === undefined
|
||||
? parsed.data
|
||||
: (compactEvidence(value, options.evidenceTextProjection) ??
|
||||
options.evidenceTextProjection),
|
||||
),
|
||||
},
|
||||
...evidenceResourceLinks(
|
||||
value,
|
||||
contract.kind === "session" ||
|
||||
@@ -94,7 +104,10 @@ const successResult = (
|
||||
};
|
||||
};
|
||||
|
||||
const compactEvidence = (value: JsonValue): JsonValue | undefined => {
|
||||
const compactEvidence = (
|
||||
value: JsonValue,
|
||||
resultProjection: JsonValue | undefined,
|
||||
): JsonValue | undefined => {
|
||||
if (
|
||||
typeof value !== "object" ||
|
||||
value === null ||
|
||||
@@ -105,7 +118,7 @@ const compactEvidence = (value: JsonValue): JsonValue | undefined => {
|
||||
)
|
||||
return undefined;
|
||||
return {
|
||||
result: value.normalized_result,
|
||||
result: resultProjection ?? value.normalized_result,
|
||||
evidence_id: value.evidence_id,
|
||||
evidence_uri: `rea://evidence/${value.evidence_id}`,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user