chore: sync current main into the CI baseline repair
Validate the formatting and reconstruction assertion repairs against the latest merged feature and correctness changes. Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveAppBundleExecutable } from "./AppBundleExecutable.js";
|
||||
|
||||
describe("app bundle Info.plist magic", () => {
|
||||
it("does not decode a high-bit fold of bplist as a binary Info.plist", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-bplist-fold-"));
|
||||
try {
|
||||
const bundle = join(root, "Fixture.app");
|
||||
const plistPath = join(bundle, "Contents", "Info.plist");
|
||||
await mkdir(join(bundle, "Contents"), { recursive: true });
|
||||
const plist = Buffer.from("bplist00");
|
||||
plist[0] = (plist[0] ?? 0) | 0x80;
|
||||
await writeFile(plistPath, plist);
|
||||
let decoded = false;
|
||||
const result = await resolveAppBundleExecutable(bundle, {
|
||||
readFile: async () => plist,
|
||||
realpath: async (path) => path,
|
||||
decodeBinaryPlist: async () => {
|
||||
decoded = true;
|
||||
return "Fixture";
|
||||
},
|
||||
});
|
||||
expect(decoded).toBe(false);
|
||||
expect(result.ok).toBe(false);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -110,9 +110,12 @@ const parseDocument = (
|
||||
return requireObject(parseToml(text), "The configuration root");
|
||||
// Pi loads `mcp.json` with a strict `JSON.parse` and no BOM tolerance, so
|
||||
// comments, trailing commas, a BOM, or an empty existing file must be
|
||||
// rejected instead of registering into a document Pi cannot load.
|
||||
if (format === "pi")
|
||||
// rejected instead of registering into a document the client cannot load.
|
||||
// Kimi also reads mcp.json with JSON.parse and an empty-file fallback.
|
||||
if (format === "pi" || format === "kimi") {
|
||||
if (format === "kimi" && text.trim().length === 0) return {};
|
||||
return requireObject(JSON.parse(text), "The configuration root");
|
||||
}
|
||||
// An empty file, which some clients create before any server is added,
|
||||
// holds no settings to preserve.
|
||||
if (isEmptyClientConfigurationText(text)) return {};
|
||||
@@ -1446,6 +1449,13 @@ export const clientRegistrationEntry = (
|
||||
? {}
|
||||
: { environment: { ...environment } }),
|
||||
};
|
||||
case "kimi":
|
||||
// Kimi infers stdio from command; it uses `transport`, not `type`.
|
||||
return {
|
||||
command: executable,
|
||||
args,
|
||||
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
|
||||
};
|
||||
case "opencode_v2":
|
||||
// V2 connects servers unless `disabled` is true.
|
||||
return {
|
||||
|
||||
@@ -66,6 +66,8 @@ const registrationSchema = z
|
||||
command: z.string().min(1),
|
||||
args: z.array(z.string()).default([]),
|
||||
startup_timeout_sec: z.number().positive().optional(),
|
||||
startupTimeoutMs: z.number().positive().optional(),
|
||||
toolTimeoutMs: z.number().positive().optional(),
|
||||
type: z.string().optional(),
|
||||
transport: z.string().optional(),
|
||||
serverName: z.string().optional(),
|
||||
@@ -258,6 +260,21 @@ const registrationAligned = (
|
||||
MCP_STARTUP_POLICY.codexStartupTimeoutSeconds
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
client.name === "kimi" &&
|
||||
(registration.startupTimeoutMs !==
|
||||
MCP_STARTUP_POLICY.kimiStartupTimeoutMs ||
|
||||
registration.toolTimeoutMs !== MCP_STARTUP_POLICY.kimiToolTimeoutMs)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
(client.format === "kimi" ||
|
||||
client.format === "omp" ||
|
||||
client.format === "pi") &&
|
||||
registration.type !== undefined &&
|
||||
registration.type !== "stdio"
|
||||
)
|
||||
return false;
|
||||
if (client.format === "vscode" && registration.type !== "stdio") return false;
|
||||
// A Harness registration only connects as the rea stdio server; another
|
||||
// server name or transport leaves the session without REA tools.
|
||||
@@ -266,13 +283,6 @@ const registrationAligned = (
|
||||
(registration.serverName !== "rea" || registration.transport !== "stdio")
|
||||
)
|
||||
return false;
|
||||
// OMP and Pi infer stdio for a command entry without an explicit type.
|
||||
if (
|
||||
(client.format === "omp" || client.format === "pi") &&
|
||||
registration.type !== undefined &&
|
||||
registration.type !== "stdio"
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
client.format === "copilot_cli" &&
|
||||
(registration.type !== "stdio" ||
|
||||
@@ -331,6 +341,12 @@ const parseRegistration = (
|
||||
});
|
||||
}
|
||||
const registration = registrationSchema.parse(value);
|
||||
if (
|
||||
client.format === "kimi" &&
|
||||
registration.transport !== undefined &&
|
||||
registration.transport !== "stdio"
|
||||
)
|
||||
throw new TypeError("Expected an stdio registration");
|
||||
if (
|
||||
(client.format === "vscode" || client.format === "copilot_cli") &&
|
||||
registration.type !== "stdio"
|
||||
@@ -339,7 +355,9 @@ const parseRegistration = (
|
||||
if (client.format === "commandcode" && registration.transport !== "stdio")
|
||||
throw new TypeError("Expected an stdio registration");
|
||||
if (
|
||||
(client.format === "omp" || client.format === "pi") &&
|
||||
(client.format === "kimi" ||
|
||||
client.format === "omp" ||
|
||||
client.format === "pi") &&
|
||||
registration.type !== undefined &&
|
||||
registration.type !== "stdio"
|
||||
)
|
||||
|
||||
@@ -60,6 +60,7 @@ type DirectAnalysisTool =
|
||||
| "annotate_native_function"
|
||||
| "inspect_native_load_image"
|
||||
| "read_bytes"
|
||||
| "search_bytes"
|
||||
| "address_to_file_offset"
|
||||
| "binary_overview"
|
||||
| "procedure_pseudo_code"
|
||||
|
||||
@@ -74,7 +74,7 @@ describe("doctor", () => {
|
||||
),
|
||||
).toEqual({
|
||||
node: `Install ${SUPPORTED_NODE_VERSION_PROSE}.`,
|
||||
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, Omarchy, and the experimental Windows x64 Ghidra P0 boundary.",
|
||||
host: "REA supports macOS 12+, Linux distributions with a recognized apt, dnf, or pacman package family, and the experimental Windows x64 Ghidra P0 boundary; automated Hopper setup additionally requires Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, or Omarchy.",
|
||||
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
|
||||
target: "Supply a readable local app or program path.",
|
||||
});
|
||||
@@ -418,10 +418,9 @@ describe("doctor scoped readiness", () => {
|
||||
platform: "linux",
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "debian",
|
||||
versionId: "13",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
id: "nixos",
|
||||
packageFamily: undefined,
|
||||
hopperSetupSupported: false,
|
||||
}),
|
||||
clientRegistrations: () =>
|
||||
Promise.resolve([
|
||||
@@ -451,6 +450,31 @@ describe("doctor scoped readiness", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts a Debian-family host that has no tested Hopper package", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "kali",
|
||||
versionId: "2026.3",
|
||||
packageFamily: "deb",
|
||||
hopperSetupSupported: false,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.checks).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "host",
|
||||
ok: true,
|
||||
detail: "kali 2026.3",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("requires explicitly selected providers instead of any available provider", async () => {
|
||||
const ghidra = {
|
||||
id: "ghidra",
|
||||
@@ -502,7 +526,7 @@ describe("doctor Linux and Hopper discovery", () => {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
}),
|
||||
configuredHopperPath: path,
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
@@ -522,7 +546,7 @@ describe("doctor Linux and Hopper discovery", () => {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
}),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
@@ -554,7 +578,7 @@ describe("doctor Linux and Hopper discovery", () => {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
}),
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
supportedLinuxHopper: () => Promise.resolve(false),
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
SUPPORTED_NODE_VERSION_PROSE,
|
||||
supportsNodeVersion,
|
||||
} from "../domain/runtimeVersion.js";
|
||||
import { linuxHopperLauncherPath } from "./LinuxHopper.js";
|
||||
import { linuxHopperLauncherPath, supportsReaHost } from "./LinuxHopper.js";
|
||||
import type {
|
||||
DoctorCheck,
|
||||
DoctorHost,
|
||||
@@ -129,7 +129,7 @@ const hostCheck = async (host: DoctorHost): Promise<DoctorCheck> => {
|
||||
host.platform === "linux" ? await host.linuxDistribution() : undefined;
|
||||
const supported =
|
||||
(host.platform === "darwin" && parseMajor(macosVersion) >= 12) ||
|
||||
(host.platform === "linux" && linuxDistribution?.supported === true) ||
|
||||
(host.platform === "linux" && supportsReaHost(linuxDistribution)) ||
|
||||
(host.platform === "win32" && host.architecture === "x64");
|
||||
const detail =
|
||||
macosVersion ??
|
||||
@@ -138,7 +138,7 @@ const hostCheck = async (host: DoctorHost): Promise<DoctorCheck> => {
|
||||
: `${linuxDistribution.id} ${linuxDistribution.versionId ?? "unknown"}`);
|
||||
return check("host", supported, detail, {
|
||||
remediation:
|
||||
"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, Omarchy, and the experimental Windows x64 Ghidra P0 boundary.",
|
||||
"REA supports macOS 12+, Linux distributions with a recognized apt, dnf, or pacman package family, and the experimental Windows x64 Ghidra P0 boundary; automated Hopper setup additionally requires Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, or Omarchy.",
|
||||
classification: "unsupported_host",
|
||||
});
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
linuxPackageManagerCommands,
|
||||
linuxSharedLibrariesAvailable,
|
||||
parseLinuxDistribution,
|
||||
supportsReaHost,
|
||||
type LinuxDistribution,
|
||||
type LinuxHopperDownload,
|
||||
type LinuxHopperInstallHost,
|
||||
@@ -19,7 +20,7 @@ class RecordingLinuxHost implements LinuxHopperInstallHost {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
};
|
||||
archive = new Uint8Array([1, 2, 3]);
|
||||
archiveOk = true;
|
||||
@@ -66,7 +67,7 @@ describe("Linux Hopper host classification", () => {
|
||||
(document, family) => {
|
||||
expect(parseLinuxDistribution(document)).toMatchObject({
|
||||
packageFamily: family,
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -99,8 +100,32 @@ describe("Linux Hopper host classification", () => {
|
||||
"ID=garuda\nID_LIKE=arch\n",
|
||||
"ID=omarchy\n",
|
||||
"ID=omarchy\nID_LIKE=debian\n",
|
||||
])("rejects unsupported vendor/version combinations", (document) => {
|
||||
expect(parseLinuxDistribution(document).supported).toBe(false);
|
||||
])(
|
||||
"rejects vendor/version combinations without a tested Hopper installer",
|
||||
(document) => {
|
||||
expect(parseLinuxDistribution(document).hopperSetupSupported).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
'ID=kali\nVERSION_ID="2026.3"\nID_LIKE=debian\n',
|
||||
'ID=debian\nVERSION_ID="13"\nID_LIKE=debian\n',
|
||||
'ID=linuxmint\nVERSION_ID="22.1"\nID_LIKE="ubuntu debian"\n',
|
||||
"ID=manjaro\nID_LIKE=arch\n",
|
||||
"ID=derivative\nID_LIKE='debian'\n",
|
||||
"ID='debian'\nVERSION_ID='13'\n",
|
||||
])(
|
||||
"hosts REA on a distribution Hopper has no tested package for: %s",
|
||||
(document) => {
|
||||
const distribution = parseLinuxDistribution(document);
|
||||
expect(distribution.hopperSetupSupported).toBe(false);
|
||||
expect(supportsReaHost(distribution)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it("withholds host support from a distribution with no package family", () => {
|
||||
expect(supportsReaHost(parseLinuxDistribution("ID=nixos\n"))).toBe(false);
|
||||
expect(supportsReaHost(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -166,7 +191,7 @@ describe("Linux Hopper installation", () => {
|
||||
host.distributionValue = {
|
||||
id: family,
|
||||
packageFamily: family,
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
};
|
||||
const result = await installFixture(host);
|
||||
expect(result).toEqual({
|
||||
@@ -194,7 +219,7 @@ describe("Linux Hopper installation", () => {
|
||||
host.distributionValue = {
|
||||
id: "debian",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
hopperSetupSupported: false,
|
||||
};
|
||||
if (scenario === "package request failure") host.archiveOk = false;
|
||||
if (scenario === "checksum mismatch") host.archive = new Uint8Array([9]);
|
||||
|
||||
@@ -76,19 +76,35 @@ interface LinuxDistributionIdentity {
|
||||
readonly versionId?: string;
|
||||
}
|
||||
|
||||
/** Parsed Linux distribution information used for support and package selection. */
|
||||
/**
|
||||
* Parsed Linux distribution information used for package selection.
|
||||
*
|
||||
* `hopperSetupSupported` is the automated Hopper installer's tested list. It is
|
||||
* narrower than the hosts where REA itself runs, which {@link supportsReaHost}
|
||||
* answers from the package family.
|
||||
*/
|
||||
export type LinuxDistribution = LinuxDistributionIdentity &
|
||||
(
|
||||
| {
|
||||
readonly packageFamily: LinuxPackageFamily;
|
||||
readonly supported: true;
|
||||
readonly hopperSetupSupported: true;
|
||||
}
|
||||
| {
|
||||
readonly packageFamily: LinuxPackageFamily | undefined;
|
||||
readonly supported: false;
|
||||
readonly hopperSetupSupported: false;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Whether REA's analysis providers run on this distribution. A recognized
|
||||
* package family means a glibc host with a known package layout, which is what
|
||||
* the providers need; downloading and installing the official Hopper package
|
||||
* additionally requires a distribution on its tested list.
|
||||
*/
|
||||
export const supportsReaHost = (
|
||||
distribution: LinuxDistribution | undefined,
|
||||
): boolean => distribution?.packageFamily !== undefined;
|
||||
|
||||
/** Download response kept independent of Node's global fetch implementation. */
|
||||
export interface LinuxHopperDownload {
|
||||
readonly ok: boolean;
|
||||
@@ -141,16 +157,19 @@ export const parseLinuxDistribution = (text: string): LinuxDistribution => {
|
||||
const key = match[1];
|
||||
const encoded = match[2];
|
||||
if (key === undefined || encoded === undefined) continue;
|
||||
const value =
|
||||
encoded.startsWith('"') && encoded.endsWith('"')
|
||||
? encoded.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
|
||||
: encoded;
|
||||
const quote = encoded[0];
|
||||
const quoted = (quote === "'" || quote === '"') && encoded.endsWith(quote);
|
||||
const value = !quoted
|
||||
? encoded
|
||||
: quote === "'"
|
||||
? encoded.slice(1, -1)
|
||||
: encoded.slice(1, -1).replace(/\\(["\\$`])/gu, "$1");
|
||||
fields.set(key, value);
|
||||
}
|
||||
const id = (fields.get("ID") ?? "unknown").toLowerCase();
|
||||
const versionId = fields.get("VERSION_ID");
|
||||
const packageFamily = packageFamilyFor(id, fields.get("ID_LIKE"));
|
||||
const supported =
|
||||
const hopperSetupSupported =
|
||||
packageFamily !== undefined &&
|
||||
(id === "arch" ||
|
||||
id === "cachyos" ||
|
||||
@@ -162,9 +181,9 @@ export const parseLinuxDistribution = (text: string): LinuxDistribution => {
|
||||
id,
|
||||
...(versionId === undefined ? {} : { versionId }),
|
||||
};
|
||||
return supported
|
||||
? { ...identity, packageFamily, supported: true }
|
||||
: { ...identity, packageFamily, supported: false };
|
||||
return hopperSetupSupported
|
||||
? { ...identity, packageFamily, hopperSetupSupported: true }
|
||||
: { ...identity, packageFamily, hopperSetupSupported: false };
|
||||
};
|
||||
|
||||
/** Read and classify the current Linux distribution. */
|
||||
@@ -193,7 +212,7 @@ export const installLinuxHopper = async (
|
||||
if (options.signal?.aborted === true)
|
||||
return { status: "failed", reason: "cancelled" };
|
||||
const distribution = await host.distribution();
|
||||
if (distribution?.supported !== true)
|
||||
if (distribution?.hopperSetupSupported !== true)
|
||||
return { status: "failed", reason: "unsupported_host" };
|
||||
let temporary: string | undefined;
|
||||
try {
|
||||
|
||||
@@ -57,7 +57,7 @@ describe("setup workflow", () => {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
};
|
||||
host.hopper = "/opt/hopper/bin/Hopper";
|
||||
host.linuxDemoRuntimeMissing = true;
|
||||
@@ -79,7 +79,7 @@ describe("setup workflow", () => {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
};
|
||||
host.hopper = "/custom/Hopper";
|
||||
host.unsupportedHopperVersion = true;
|
||||
|
||||
@@ -70,7 +70,7 @@ describe("setup workflow", () => {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
};
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
@@ -162,7 +162,7 @@ describe("setup workflow", () => {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
};
|
||||
const result = await runSetup(options(true, true), host);
|
||||
expect(result.appliedActions).toEqual(["installed_hopper"]);
|
||||
@@ -236,7 +236,7 @@ describe("setup workflow lifecycle and provider planning", () => {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
};
|
||||
host.ghidra = "/opt/ghidra_12.1.4_PUBLIC";
|
||||
host.javaHome = "/usr/lib/jvm/jdk-21";
|
||||
|
||||
@@ -310,7 +310,7 @@ describe("setup scoped readiness", () => {
|
||||
id: "debian",
|
||||
versionId: "13",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
hopperSetupSupported: false,
|
||||
};
|
||||
const result = await runSetup(options(true, true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
@@ -326,7 +326,7 @@ describe("setup scoped readiness", () => {
|
||||
id: "debian",
|
||||
versionId: "13",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
hopperSetupSupported: false,
|
||||
};
|
||||
host.ghidra = "/opt/ghidra_12.1.4_PUBLIC";
|
||||
host.javaHome = "/usr/lib/jvm/jdk-21";
|
||||
|
||||
@@ -704,6 +704,14 @@ const clientConfigurationDesired = (
|
||||
launcher,
|
||||
environment.value,
|
||||
);
|
||||
const previous = parsed?.servers[PRODUCT_IDENTITY.mcpServerKey];
|
||||
if (
|
||||
client.name === "kimi" &&
|
||||
typeof previous === "object" &&
|
||||
previous !== null &&
|
||||
"enabledTools" in previous
|
||||
)
|
||||
registration.enabledTools = previous.enabledTools;
|
||||
return {
|
||||
...registration,
|
||||
...(client.name === "codex" || client.name === "grok_build"
|
||||
@@ -711,5 +719,11 @@ const clientConfigurationDesired = (
|
||||
startup_timeout_sec: MCP_STARTUP_POLICY.codexStartupTimeoutSeconds,
|
||||
}
|
||||
: {}),
|
||||
...(client.name === "kimi"
|
||||
? {
|
||||
startupTimeoutMs: MCP_STARTUP_POLICY.kimiStartupTimeoutMs,
|
||||
toolTimeoutMs: MCP_STARTUP_POLICY.kimiToolTimeoutMs,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -124,7 +124,8 @@ export const hostRemediation = async (
|
||||
? "Upgrade to macOS 12 or newer."
|
||||
: undefined;
|
||||
}
|
||||
if ((await host.linuxDistribution())?.supported === true) return undefined;
|
||||
if ((await host.linuxDistribution())?.hopperSetupSupported === true)
|
||||
return undefined;
|
||||
return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, Nobara 44+, 64-bit Arch Linux, CachyOS, and Omarchy; configure an existing supported provider instead.";
|
||||
};
|
||||
|
||||
|
||||
@@ -56,7 +56,8 @@ export const discoverSetupState = async (input: {
|
||||
const hopperInstallSupported =
|
||||
(input.host.platform === "darwin" &&
|
||||
majorVersion((await input.host.macosVersion()) ?? "0") >= 12) ||
|
||||
(input.host.platform === "linux" && linuxDistribution?.supported === true);
|
||||
(input.host.platform === "linux" &&
|
||||
linuxDistribution?.hopperSetupSupported === true);
|
||||
const installHopper =
|
||||
input.forceHopperInstall ||
|
||||
(hopperInstallSupported &&
|
||||
|
||||
@@ -72,6 +72,15 @@ interface CanonicalSkillFile {
|
||||
readonly original: SkillFileState | undefined;
|
||||
}
|
||||
|
||||
const canonicalSkillContent = (relativePath: string): Promise<string> =>
|
||||
readFile(
|
||||
new URL(
|
||||
`../../skills/${PRODUCT_IDENTITY.skillName}/${relativePath}`,
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
export interface SkillInstallFileOperations {
|
||||
readonly mkdir: (path: string) => Promise<void>;
|
||||
readonly backup: (source: string, destination: string) => Promise<void>;
|
||||
@@ -244,19 +253,36 @@ const canonicalSkillFiles = async (
|
||||
const destination = join(root, relativePath);
|
||||
return {
|
||||
destination,
|
||||
content: await readFile(
|
||||
new URL(
|
||||
`../../skills/${PRODUCT_IDENTITY.skillName}/${relativePath}`,
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
content: await canonicalSkillContent(relativePath),
|
||||
original: await readOptionalSkillState(destination, resources),
|
||||
};
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const canonicalSkillNeedsInstallByReading = async (
|
||||
home: string,
|
||||
clientIds: readonly string[],
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
platform: NodeJS.Platform,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<boolean> => {
|
||||
for (const { path: root } of skillDestinations(
|
||||
home,
|
||||
clientIds,
|
||||
environment,
|
||||
platform,
|
||||
)) {
|
||||
for (const relativePath of MANAGED_SKILL_FILES) {
|
||||
const destination = join(root, relativePath);
|
||||
const content = await canonicalSkillContent(relativePath);
|
||||
const original = await readOptionalSkillState(destination, resources);
|
||||
if (original?.content !== content) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/** Report whether setup would change any file in the managed REA skill bundle. */
|
||||
export const canonicalSkillNeedsInstall = async (
|
||||
home: string,
|
||||
@@ -266,15 +292,13 @@ export const canonicalSkillNeedsInstall = async (
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
return (
|
||||
await canonicalSkillFiles(
|
||||
home,
|
||||
clientIds,
|
||||
environment,
|
||||
platform,
|
||||
resources,
|
||||
)
|
||||
).some(({ content, original }) => original?.content !== content);
|
||||
return await canonicalSkillNeedsInstallByReading(
|
||||
home,
|
||||
clientIds,
|
||||
environment,
|
||||
platform,
|
||||
resources,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof RegularFileCleanupFailure ||
|
||||
|
||||
@@ -45,6 +45,7 @@ export interface SetupClient {
|
||||
| "grok"
|
||||
| "omp"
|
||||
| "pi"
|
||||
| "kimi"
|
||||
| "hermes"
|
||||
| "zcode"
|
||||
| "dsh"
|
||||
@@ -165,6 +166,10 @@ const claudeCodeMarkerDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
const codexDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.CODEX_HOME || join(home, ".codex");
|
||||
|
||||
/** Kimi Code stores MCP declarations beside the rest of its home data. */
|
||||
const kimiDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.KIMI_CODE_HOME || join(home, ".kimi-code");
|
||||
|
||||
const qoderDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.QODER_CONFIG_DIR || join(home, ".qoder");
|
||||
|
||||
@@ -576,6 +581,14 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
markerPath: qwenCodeDirectory,
|
||||
format: "json",
|
||||
},
|
||||
{
|
||||
name: "kimi",
|
||||
displayName: "Kimi Code",
|
||||
configPath: (context: ClientPathContext) =>
|
||||
join(kimiDirectory(context), "mcp.json"),
|
||||
markerPath: kimiDirectory,
|
||||
format: "kimi",
|
||||
},
|
||||
{
|
||||
name: "vscode",
|
||||
displayName: "VS Code",
|
||||
|
||||
@@ -627,11 +627,16 @@ const removeManagedSkills = async (
|
||||
platform: NodeJS.Platform,
|
||||
writeBlocker?: (path: string) => string | undefined,
|
||||
): Promise<UninstallItem> => {
|
||||
// Every destination shares one summary item, so each result is labeled by
|
||||
// the directory it refers to.
|
||||
// Every destination shares one summary item; preserve both client and path.
|
||||
const results = await Promise.all(
|
||||
skillDestinations(home, undefined, environment, platform).map(({ path }) =>
|
||||
removeManagedSkill(path, path, fileSystem, writeBlocker),
|
||||
skillDestinations(home, undefined, environment, platform).map(
|
||||
({ client, path }) =>
|
||||
removeManagedSkill(
|
||||
path,
|
||||
`${client} (${path})`,
|
||||
fileSystem,
|
||||
writeBlocker,
|
||||
),
|
||||
),
|
||||
);
|
||||
const failed = results.find(({ status }) => status === "failed");
|
||||
|
||||
@@ -100,4 +100,10 @@ const parameters = (
|
||||
...(input.source_paths === undefined
|
||||
? {}
|
||||
: { source_paths: input.source_paths }),
|
||||
...(input.max_heap_mb === undefined
|
||||
? {}
|
||||
: { max_heap_mb: input.max_heap_mb }),
|
||||
...(input.analysis_timeout_ms === undefined
|
||||
? {}
|
||||
: { analysis_timeout_ms: input.analysis_timeout_ms }),
|
||||
});
|
||||
|
||||
@@ -62,26 +62,7 @@ export const analyzeJavaScriptApplicationValidated = async (
|
||||
});
|
||||
await checkpointJavaScriptAnalysis(options.signal);
|
||||
reconstructed = await reconstructJavaScriptArtifact(
|
||||
{
|
||||
input_path: input.input_path,
|
||||
format: input.format,
|
||||
integrity_policy: input.integrity_policy,
|
||||
...(input.max_semantic_nodes === undefined
|
||||
? {}
|
||||
: { max_semantic_nodes: input.max_semantic_nodes }),
|
||||
...(input.max_semantic_nodes_per_file === undefined
|
||||
? {}
|
||||
: { max_semantic_nodes_per_file: input.max_semantic_nodes_per_file }),
|
||||
...(input.source_paths === undefined
|
||||
? {}
|
||||
: { source_paths: input.source_paths }),
|
||||
...(input.max_heap_mb === undefined
|
||||
? {}
|
||||
: { max_heap_mb: input.max_heap_mb }),
|
||||
...(input.analysis_timeout_ms === undefined
|
||||
? {}
|
||||
: { analysis_timeout_ms: input.analysis_timeout_ms }),
|
||||
},
|
||||
input,
|
||||
scope,
|
||||
options.signal,
|
||||
options.progress,
|
||||
|
||||
@@ -457,9 +457,8 @@ const bareModuleCandidate = (
|
||||
dependencyDirectory = posix.dirname(confined);
|
||||
}
|
||||
const source = input.files.get(input.sourcePath);
|
||||
let directory = posix.dirname(input.sourcePath);
|
||||
let nearestNotFound: CandidateResolution | null = null;
|
||||
while (true) {
|
||||
for (const directory of packageLookupDirectories(input)) {
|
||||
const candidate = posix.join(directory, dependencyDirectory);
|
||||
const metadata = readPackageMetadata(input, candidate);
|
||||
const continueCommonJsLookup =
|
||||
@@ -487,8 +486,6 @@ const bareModuleCandidate = (
|
||||
nearestNotFound ??= packageResolution;
|
||||
} else return packageResolution;
|
||||
}
|
||||
if (directory === "." || directory === "") break;
|
||||
directory = posix.dirname(directory);
|
||||
}
|
||||
if (nearestNotFound !== null) return nearestNotFound;
|
||||
return unresolvedCandidate("external", [
|
||||
@@ -496,6 +493,21 @@ const bareModuleCandidate = (
|
||||
]);
|
||||
};
|
||||
|
||||
function* packageLookupDirectories(
|
||||
input: ResolveArtifactPathInput,
|
||||
): Generator<string> {
|
||||
let directory = posix.dirname(input.sourcePath);
|
||||
while (true) {
|
||||
if (
|
||||
input.moduleKind !== "require" ||
|
||||
posix.basename(directory) !== "node_modules"
|
||||
)
|
||||
yield directory;
|
||||
if (directory === "." || directory === "") return;
|
||||
directory = posix.dirname(directory);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Nearest same-container package.json, stopping at a `node_modules` directory
|
||||
* so a nested package cannot inherit an ancestor's map.
|
||||
@@ -960,15 +972,29 @@ const resolveCandidate = (
|
||||
candidate: string,
|
||||
packageChain: ReadonlySet<string>,
|
||||
emittedSourceCandidates: readonly TypeScriptEmittedSourceCandidate[] = [],
|
||||
): CandidateResolution =>
|
||||
resolveFileCandidates(input, fileCandidates(candidate, input.moduleKind)) ??
|
||||
resolveRuntimeSourceCandidates(input, candidate, emittedSourceCandidates) ??
|
||||
resolveDirectory(
|
||||
): CandidateResolution => {
|
||||
if (!commonJsDirectoryRequest(input)) {
|
||||
const file =
|
||||
resolveFileCandidates(
|
||||
input,
|
||||
fileCandidates(candidate, input.moduleKind),
|
||||
) ??
|
||||
resolveRuntimeSourceCandidates(input, candidate, emittedSourceCandidates);
|
||||
if (file !== null) return file;
|
||||
}
|
||||
return resolveDirectory(
|
||||
input,
|
||||
candidate,
|
||||
readPackageMetadata(input, candidate),
|
||||
packageChain,
|
||||
);
|
||||
};
|
||||
|
||||
const commonJsDirectoryRequest = (input: ResolveArtifactPathInput): boolean =>
|
||||
input.context === "module-specifier" &&
|
||||
input.moduleKind === "require" &&
|
||||
(input.declaredPath.endsWith("/") ||
|
||||
/(?:^|\/)\.{1,2}$/u.test(input.declaredPath));
|
||||
|
||||
const resolveDirectory = (
|
||||
input: ResolveArtifactPathInput,
|
||||
|
||||
@@ -277,15 +277,9 @@ export const reconstructJavaScriptArtifact = async (
|
||||
limitations: completed.graph.limitations,
|
||||
}),
|
||||
);
|
||||
const { max_heap_mb, analysis_timeout_ms, ...coreInput } = input;
|
||||
const parameters = {
|
||||
...coreInput,
|
||||
...(max_heap_mb === undefined ? {} : { max_heap_mb }),
|
||||
...(analysis_timeout_ms === undefined ? {} : { analysis_timeout_ms }),
|
||||
};
|
||||
const evidence =
|
||||
await createOwnedJavaScriptApplicationEvidenceCooperatively(
|
||||
parameters,
|
||||
input,
|
||||
partial,
|
||||
);
|
||||
throw interruption.retainPartialObservation(evidence);
|
||||
|
||||
@@ -17,6 +17,46 @@ export const registerCoreNativeCommands = (
|
||||
runDirectAnalysis: DirectAnalysis["runDirectAnalysis"],
|
||||
): void => {
|
||||
registerAnnotationCommand(cli, logger, runDirectAnalysis);
|
||||
cli.command(CLI_COMMANDS.searchBytes, {
|
||||
description: "Find masked byte patterns in initialized provider memory",
|
||||
args: z.object({
|
||||
path: z.string().describe("Local executable path"),
|
||||
pattern: z.string().describe("Hexadecimal byte pairs with ?? wildcards"),
|
||||
}),
|
||||
options: z.object({
|
||||
mask: z.string().optional().describe("Equal-length hexadecimal bit mask"),
|
||||
start: z.string().optional().describe("Inclusive start address"),
|
||||
end: z.string().optional().describe("Inclusive end address"),
|
||||
cursor: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Continuation from the same query's next_cursor"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(1000)
|
||||
.default(100)
|
||||
.describe("Maximum matches on this page"),
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.searchBytes, () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
"search_bytes",
|
||||
{
|
||||
pattern: args.pattern,
|
||||
limit: options.limit,
|
||||
...(options.mask === undefined ? {} : { mask: options.mask }),
|
||||
...(options.start === undefined ? {} : { start: options.start }),
|
||||
...(options.end === undefined ? {} : { end: options.end }),
|
||||
...(options.cursor === undefined ? {} : { cursor: options.cursor }),
|
||||
},
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.inspectNativeLoadImage, {
|
||||
description:
|
||||
"Verify loaded native bytes, source mappings, relocations and entry",
|
||||
|
||||
@@ -39,6 +39,7 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
inspectNativeDataType: "inspect-native-data-type",
|
||||
inspectNativeLoadImage: "inspect-native-load-image",
|
||||
readBytes: "read-bytes",
|
||||
searchBytes: "search-bytes",
|
||||
addressToFileOffset: "address-to-file-offset",
|
||||
traceNativeValues: "trace-native-values",
|
||||
inspectNativeInstruction: "inspect-native-instruction",
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
import { z } from "zod";
|
||||
import { address, document } from "./toolContractHelpers.js";
|
||||
import {
|
||||
bytePatternFields,
|
||||
validateBytePattern,
|
||||
} from "../domain/native/bytePattern.js";
|
||||
|
||||
/** Hopper memory and file-mapping contracts. */
|
||||
export const HOPPER_MEMORY_TOOL_DEFINITIONS = [
|
||||
{
|
||||
name: "search_bytes",
|
||||
description:
|
||||
"Find masked byte signatures in initialized analyzed memory. Hex byte pairs and ?? wildcards are supported; an optional equal-length hex mask selects bits. Bounds are inclusive. Matches are ordered by provider address and never span blocks. Coverage describes this page; reuse the same query with next_cursor to continue. Uninitialized blocks are listed separately. Ghidra only; Hopper is unavailable.",
|
||||
inputSchema: z
|
||||
.strictObject({
|
||||
...bytePatternFields,
|
||||
document,
|
||||
start: address.optional(),
|
||||
end: address.optional(),
|
||||
limit: z.number().int().min(1).max(1000).default(100),
|
||||
cursor: z.string().min(1).optional(),
|
||||
})
|
||||
.superRefine(validateBytePattern),
|
||||
},
|
||||
{
|
||||
name: "read_bytes",
|
||||
description:
|
||||
|
||||
@@ -26,6 +26,7 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
resolve_native_call_targets: { address: "0x1000" },
|
||||
read_function_instructions: { procedure: "main" },
|
||||
read_bytes: { address: "0x1000", length: 16 },
|
||||
search_bytes: { pattern: "48 8B ?? ?? 89" },
|
||||
address_to_file_offset: { address: "0x1000" },
|
||||
procedure_references: { procedure: "main" },
|
||||
procedure_pseudo_code: { procedure: "main" },
|
||||
|
||||
@@ -438,6 +438,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
inspect_native_data_type: evidence,
|
||||
resolve_native_call_targets: evidence,
|
||||
read_bytes: evidence,
|
||||
search_bytes: evidence,
|
||||
address_to_file_offset: evidence,
|
||||
procedure_references: evidence,
|
||||
procedure_pseudo_code: evidence,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { byteSearchResultSchema } from "../domain/native/bytePattern.js";
|
||||
import {
|
||||
artifactInventorySummaryViewResultSchema,
|
||||
machoSummaryViewResultSchema,
|
||||
@@ -108,6 +109,7 @@ const bookmarkFacetSchema = z.discriminatedUnion("state", [
|
||||
|
||||
/** Exact structured-content schemas shared by direct analysis providers. */
|
||||
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
search_bytes: evidenceResultOf(byteSearchResultSchema),
|
||||
annotate_native_function: evidenceResultOf(nativeFunctionAnnotationsSchema),
|
||||
inspect_native_load_image: evidenceResultOf(nativeLoadImageSchema),
|
||||
inspect_native_data_type: evidenceResultOf(nativeDataTypeSchema),
|
||||
|
||||
@@ -417,6 +417,34 @@ describe("Apple bundle layouts and containers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Apple IPA components", () => {
|
||||
it("excludes AppleDouble sidecars from IPA components", () => {
|
||||
const result = project(
|
||||
inventoryEvidence("ipa", "Fixture.ipa", [
|
||||
{ path: "Payload/Fixture.app/Info.plist" },
|
||||
macho("Payload/Fixture.app/Fixture"),
|
||||
{ path: "Payload/Fixture.app/Contents/Resources/._libfoo.dylib" },
|
||||
{ path: "Payload/Fixture.app/Frameworks/Foo.framework/._Foo" },
|
||||
{ path: "__MACOSX/Payload/Fixture.app/libghost.dylib" },
|
||||
macho("Payload/Fixture.app/Contents/Resources/libreal.dylib"),
|
||||
macho("SwiftSupport/iphoneos/libswiftCore.dylib"),
|
||||
]),
|
||||
);
|
||||
expect(result.components.native_libraries.map(({ path }) => path)).toEqual([
|
||||
"Payload/Fixture.app/Contents/Resources/libreal.dylib",
|
||||
"SwiftSupport/iphoneos/libswiftCore.dylib",
|
||||
]);
|
||||
expect(result.components.frameworks).toEqual([]);
|
||||
expect(result.components.executables.map(({ path }) => path)).toEqual([
|
||||
"Payload/Fixture.app/Contents/Resources/libreal.dylib",
|
||||
"Payload/Fixture.app/Fixture",
|
||||
]);
|
||||
expect(result.limitations).toContainEqual(
|
||||
expect.stringContaining("AppleDouble sidecar entries"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("macOS application scope", () => {
|
||||
it("attributes only components inside the application roots", () => {
|
||||
const result = project(
|
||||
|
||||
@@ -218,8 +218,9 @@ export const appleProjectionId = (projection: unknown): string =>
|
||||
`aap_${digest(projection)}`;
|
||||
|
||||
/**
|
||||
* IPA projection keeps every archive component, as before. Directory, ZIP,
|
||||
* and DMG inventories can hold installers and other siblings, so only
|
||||
* AppleDouble sidecars describe neighbouring files and are never components.
|
||||
* IPA projection keeps every other archive component, as before. Directory,
|
||||
* ZIP, and DMG inventories can hold installers and other siblings, so only
|
||||
* components inside an application root are attributed to it.
|
||||
*/
|
||||
const attributeComponents = (
|
||||
@@ -227,8 +228,8 @@ const attributeComponents = (
|
||||
roots: readonly string[],
|
||||
rootFormat: RootFormat,
|
||||
): { readonly all: Component[]; readonly unattributed: number } => {
|
||||
if (rootFormat === "ipa") return { all: [...inventoried], unattributed: 0 };
|
||||
const visible = inventoried.filter(({ path }) => !isSidecar(path));
|
||||
if (rootFormat === "ipa") return { all: visible, unattributed: 0 };
|
||||
const all = visible.filter(({ path }) =>
|
||||
roots.some((root) => isWithin(path, root)),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { addressCoordinate } from "./native/addressCoordinate.js";
|
||||
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
@@ -38,16 +39,6 @@ export const addressDistance = (start: string, end: string): number => {
|
||||
);
|
||||
};
|
||||
|
||||
const addressCoordinate = (
|
||||
value: string,
|
||||
): { readonly space: string; readonly offset: bigint } | null => {
|
||||
const separator = value.lastIndexOf(":0x");
|
||||
const space = separator < 0 ? "default" : value.slice(0, separator);
|
||||
const offset = separator < 0 ? value : value.slice(separator + 1);
|
||||
if (!/^0x[0-9a-f]+$/u.test(offset)) return null;
|
||||
return { space, offset: BigInt(offset) };
|
||||
};
|
||||
|
||||
const procedureMapSchema = z.record(z.string(), z.string());
|
||||
const addressedNamesSchema = z.array(
|
||||
z.object({ address: z.string(), name: z.string() }),
|
||||
@@ -128,9 +119,9 @@ export const functionBodySchema = z.discriminatedUnion("available", [
|
||||
})
|
||||
.superRefine((body, context) => {
|
||||
let total = 0n;
|
||||
const bounds = new Map<string, { start: bigint; end: bigint }>();
|
||||
const closedSpaces = new Set<string>();
|
||||
let previousSpace: string | null = null;
|
||||
const bounds = new Map<string | null, { start: bigint; end: bigint }>();
|
||||
const closedSpaces = new Set<string | null>();
|
||||
let previousSpace: string | null | undefined;
|
||||
for (const range of body.ranges) {
|
||||
const start = addressCoordinate(range.start);
|
||||
const end = addressCoordinate(range.end);
|
||||
@@ -146,7 +137,7 @@ export const functionBodySchema = z.discriminatedUnion("available", [
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (previousSpace !== null && previousSpace !== start.space)
|
||||
if (previousSpace !== undefined && previousSpace !== start.space)
|
||||
closedSpaces.add(previousSpace);
|
||||
const previous = bounds.get(start.space);
|
||||
if (
|
||||
|
||||
@@ -339,7 +339,10 @@ const spawnOptions = (candidate: SpawnCandidate): t.ObjectExpression | null => {
|
||||
const spawnArgvCount = (candidate: SpawnCandidate): number | null => {
|
||||
if (candidate.method === "exec") return null;
|
||||
const args = candidate.node.arguments[1];
|
||||
return t.isArrayExpression(args) ? args.elements.length : null;
|
||||
return t.isArrayExpression(args) &&
|
||||
!args.elements.some((element) => t.isSpreadElement(element))
|
||||
? args.elements.length
|
||||
: null;
|
||||
};
|
||||
|
||||
const objectHasProperty = (
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Parse canonical native offsets without discarding their address space. */
|
||||
export const addressCoordinate = (
|
||||
value: string,
|
||||
): { readonly space: string | null; readonly offset: bigint } | null => {
|
||||
const separator = value.lastIndexOf(":0x");
|
||||
if (separator === 0) return null;
|
||||
const space = separator < 0 ? null : value.slice(0, separator);
|
||||
const offset = separator < 0 ? value : value.slice(separator + 1);
|
||||
if (!/^0x[0-9a-f]+$/u.test(offset)) return null;
|
||||
return { space, offset: BigInt(offset) };
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseBytePattern } from "./bytePattern.js";
|
||||
|
||||
describe("masked byte patterns", () => {
|
||||
it("preserves whole-byte wildcards and combines explicit bit masks", () => {
|
||||
const parsed = parseBytePattern("48 8b\t??89", "ff f0 ff 0f");
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
expect(parsed.value).toEqual({
|
||||
bytes: [0x48, 0x8b, 0, 0x89],
|
||||
masks: [255, 240, 0, 15],
|
||||
});
|
||||
const exact = parseBytePattern("Aa\u00a000");
|
||||
if (!exact.ok) throw exact.error;
|
||||
expect(exact.value).toEqual({ bytes: [170, 0], masks: [255, 255] });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["", undefined, "pattern"],
|
||||
["4", undefined, "pattern"],
|
||||
["4?", undefined, "pattern"],
|
||||
["gg", undefined, "pattern"],
|
||||
["?? ??", undefined, "pattern"],
|
||||
["ff", "00", "pattern"],
|
||||
["ffff", "ff", "mask"],
|
||||
["ff", "??", "mask"],
|
||||
])("rejects invalid pattern %s with typed issues", (pattern, mask, field) => {
|
||||
const parsed = parseBytePattern(pattern, mask);
|
||||
if (parsed.ok) throw new Error("Expected a rejected pattern");
|
||||
expect(parsed.error.issues).toMatchObject([
|
||||
{ path: [field], reason: "invalid_value" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import { z } from "zod";
|
||||
import { addressCoordinate } from "./addressCoordinate.js";
|
||||
import { AnalysisInputError } from "../analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
|
||||
/** Byte pairs, with whole-byte wildcards; explicit masks can select individual bits. */
|
||||
export const bytePatternFields = {
|
||||
pattern: z
|
||||
.string()
|
||||
.regex(/^([0-9a-fA-F]{2}|\?\?)(\s*([0-9a-fA-F]{2}|\?\?))*$/u),
|
||||
mask: z
|
||||
.string()
|
||||
.regex(/^[0-9a-fA-F]{2}(\s*[0-9a-fA-F]{2})*$/u)
|
||||
.optional(),
|
||||
};
|
||||
|
||||
/** Parse once at the input boundary, retaining typed correction issues. */
|
||||
export const parseBytePattern = (
|
||||
pattern: string,
|
||||
mask?: string,
|
||||
): Result<{ bytes: number[]; masks: number[] }, AnalysisInputError> => {
|
||||
const invalid = (field: string, message: string) =>
|
||||
err(
|
||||
new AnalysisInputError("search_bytes", undefined, [
|
||||
{ path: [field], reason: "invalid_value", message },
|
||||
]),
|
||||
);
|
||||
if (!bytePatternFields.pattern.safeParse(pattern).success)
|
||||
return invalid("pattern", "Use hexadecimal byte pairs or ?? wildcards");
|
||||
if (mask !== undefined && !bytePatternFields.mask.safeParse(mask).success)
|
||||
return invalid("mask", "Use hexadecimal mask byte pairs");
|
||||
const pairs = pattern.replace(/\s/gu, "").match(/../gu) ?? [];
|
||||
const maskPairs = mask?.replace(/\s/gu, "").match(/../gu);
|
||||
if (maskPairs && maskPairs.length !== pairs.length)
|
||||
return invalid("mask", "Mask length must equal pattern length");
|
||||
const bytes = pairs.map((pair) =>
|
||||
pair === "??" ? 0 : Number.parseInt(pair, 16),
|
||||
);
|
||||
const masks = pairs.map((pair, index) =>
|
||||
pair === "??" ? 0 : Number.parseInt(maskPairs?.[index] ?? "ff", 16),
|
||||
);
|
||||
if (!masks.some((value) => value !== 0))
|
||||
return invalid("pattern", "Pattern must constrain at least one bit");
|
||||
return ok({ bytes, masks });
|
||||
};
|
||||
|
||||
/** Shared semantic validation for public and provider inputs. */
|
||||
export const validateBytePattern = (
|
||||
value: { pattern: string; mask?: string | undefined },
|
||||
context: z.RefinementCtx,
|
||||
): void => {
|
||||
const parsed = parseBytePattern(value.pattern, value.mask);
|
||||
if (!parsed.ok)
|
||||
for (const issue of parsed.error.issues)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: [...issue.path],
|
||||
message: issue.message ?? "Invalid byte pattern",
|
||||
});
|
||||
};
|
||||
|
||||
const coverageBlock = z
|
||||
.strictObject({
|
||||
segment: z.string(),
|
||||
start: z.string(),
|
||||
end: z.string(),
|
||||
bytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
const start = addressCoordinate(value.start);
|
||||
const end = addressCoordinate(value.end);
|
||||
if (
|
||||
start === null ||
|
||||
end === null ||
|
||||
start.space !== end.space ||
|
||||
start.offset > end.offset ||
|
||||
end.offset - start.offset + 1n !== BigInt(value.bytes)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Byte coverage must equal its inclusive address range in one space",
|
||||
});
|
||||
});
|
||||
|
||||
/** Inclusive page coverage; matches never span memory blocks. */
|
||||
export const byteSearchResultSchema = z
|
||||
.strictObject({
|
||||
matches: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
address: z.string(),
|
||||
segment: z.string(),
|
||||
file_offset: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.nullable(),
|
||||
procedure: z
|
||||
.strictObject({ address: z.string(), name: z.string() })
|
||||
.nullable(),
|
||||
}),
|
||||
)
|
||||
.max(1000),
|
||||
searched: z.strictObject({
|
||||
blocks: z.array(coverageBlock),
|
||||
bytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
skipped_uninitialized: z.array(coverageBlock),
|
||||
skipped_not_loaded: z.array(coverageBlock),
|
||||
}),
|
||||
complete: z.boolean(),
|
||||
next_cursor: z.string().min(1).nullable(),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (
|
||||
value.complete !== (value.next_cursor === null) ||
|
||||
value.searched.bytes !==
|
||||
value.searched.blocks.reduce((sum, block) => sum + block.bytes, 0)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Byte search coverage and continuation disagree",
|
||||
});
|
||||
});
|
||||
@@ -53,6 +53,7 @@ const source = (
|
||||
digit: string,
|
||||
observation: Partial<EvidenceObservation> = {},
|
||||
hasSubject = true,
|
||||
hasCoverage = true,
|
||||
): Evidence =>
|
||||
createEvidence(
|
||||
hasSubject
|
||||
@@ -69,7 +70,9 @@ const source = (
|
||||
result: dossier,
|
||||
confidence: "derived",
|
||||
authority: "shipped-artifact",
|
||||
relationshipCoverage: { status: "complete" },
|
||||
...(hasCoverage
|
||||
? { relationshipCoverage: { status: "complete" as const } }
|
||||
: {}),
|
||||
...observation,
|
||||
},
|
||||
);
|
||||
@@ -197,6 +200,118 @@ describe("function reconstruction source parameters", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("historical calls-only reconstruction changes", () => {
|
||||
it.each(["missing", "unknown", "partial", "unresolved"] as const)(
|
||||
"keeps historical calls-only changes unknown with %s call coverage",
|
||||
(coverage) => {
|
||||
const changedDossier = functionDossierSchema.parse({
|
||||
...functionDossierSchema.parse(dossier),
|
||||
callees: [
|
||||
{
|
||||
address: "0x2000",
|
||||
name: "puts",
|
||||
classification: null,
|
||||
body: { available: false, reason: "External function." },
|
||||
},
|
||||
],
|
||||
});
|
||||
const complete = source("8", {
|
||||
result: jsonValueSchema.parse(changedDossier),
|
||||
});
|
||||
const incomplete = source(
|
||||
"9",
|
||||
{
|
||||
result: jsonValueSchema.parse({
|
||||
...changedDossier,
|
||||
...(coverage === "unresolved"
|
||||
? {
|
||||
unresolved_calls: [
|
||||
{
|
||||
address: "0x1004",
|
||||
reason: "Computed target unresolved.",
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
...(coverage === "missing"
|
||||
? {}
|
||||
: {
|
||||
relationshipCoverage:
|
||||
coverage === "unknown"
|
||||
? { status: "unknown", reason: "Call graph unavailable." }
|
||||
: coverage === "partial"
|
||||
? {
|
||||
status: "partial",
|
||||
limitations: ["Additional edges omitted."],
|
||||
}
|
||||
: { status: "complete" },
|
||||
}),
|
||||
},
|
||||
true,
|
||||
coverage !== "missing",
|
||||
);
|
||||
const historicalResult = compareFunctions(left, complete);
|
||||
expect(historicalResult).toMatchObject({
|
||||
status: "changed",
|
||||
summary: { changed: 1 },
|
||||
});
|
||||
expect(historicalResult.changes).toMatchObject([
|
||||
{ dimension: "calls", status: "changed" },
|
||||
]);
|
||||
const completeComparison = comparison(
|
||||
{
|
||||
left_evidence_id: left.evidence_id,
|
||||
right_evidence_id: complete.evidence_id,
|
||||
},
|
||||
{},
|
||||
[left, complete],
|
||||
{},
|
||||
historicalResult,
|
||||
);
|
||||
expect(
|
||||
admittedVerification(completeComparison, [left, complete], "overall")()
|
||||
.status,
|
||||
).toBe("fail");
|
||||
const evidence = comparison(
|
||||
{
|
||||
left_evidence_id: left.evidence_id,
|
||||
right_evidence_id: incomplete.evidence_id,
|
||||
},
|
||||
{},
|
||||
[left, incomplete],
|
||||
{},
|
||||
historicalResult,
|
||||
);
|
||||
const before = JSON.stringify(evidence);
|
||||
for (const dimension of ["calls", "overall"] as const) {
|
||||
expect(
|
||||
admittedVerification(evidence, [left, incomplete], dimension)(),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
summary: { total: 1, passed: 0, failed: 0, unknown: 1 },
|
||||
claims: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
status: "unknown",
|
||||
observed_status: "changed",
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(`Source ${incomplete.evidence_id}:`),
|
||||
]),
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
expect(
|
||||
admittedVerification(evidence, [left, incomplete], "pseudocode")()
|
||||
.status,
|
||||
).toBe("pass");
|
||||
expect(JSON.stringify(evidence)).toBe(before);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("function reconstruction call coverage", () => {
|
||||
it("rechecks old unchanged comparisons without affecting unrelated finite dimensions", () => {
|
||||
const incomplete = source("7", {
|
||||
|
||||
@@ -144,10 +144,15 @@ const evaluateClaim = (
|
||||
return source;
|
||||
});
|
||||
const functionSourceFacts = readValidatedSourceFacts(claim, sources);
|
||||
const observed = observedStatus(claim, comparison);
|
||||
const observation = comparisonObservation(claim, comparison);
|
||||
const observed = observation.status;
|
||||
const limitations = [
|
||||
...authorityLimitations(claim, sources, sides),
|
||||
...sourceCallCoverageLimitations(claim, functionSourceFacts, observed),
|
||||
...sourceCallCoverageLimitations(
|
||||
claim,
|
||||
functionSourceFacts,
|
||||
observation.hasIndependentFunctionChange === true,
|
||||
),
|
||||
];
|
||||
const relatedUnknowns = reconstructionClaimUnknowns(
|
||||
heads,
|
||||
@@ -235,21 +240,40 @@ const validateComparisonIdentity = (claim: Claim, evidence: Evidence): void => {
|
||||
throw new TypeError("Comparison Evidence identity or authority disagrees");
|
||||
};
|
||||
|
||||
const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
|
||||
const comparisonObservation = (
|
||||
claim: Claim,
|
||||
evidence: Evidence,
|
||||
): {
|
||||
readonly status: ObservedStatus;
|
||||
readonly hasIndependentFunctionChange?: boolean;
|
||||
} => {
|
||||
if (claim.kind === "behavioral") {
|
||||
const result = processCaptureComparisonSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
validateProcessStatus(result);
|
||||
return claim.dimension === "overall"
|
||||
? result.status
|
||||
: result[claim.dimension];
|
||||
return {
|
||||
status:
|
||||
claim.dimension === "overall" ? result.status : result[claim.dimension],
|
||||
};
|
||||
}
|
||||
if (claim.kind === "structural-function") {
|
||||
const result = functionComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
if (claim.dimension === "overall") return result.status;
|
||||
if (claim.dimension === "overall")
|
||||
return {
|
||||
status: result.status,
|
||||
// Historical overall changes may come solely from incomplete call sets.
|
||||
hasIndependentFunctionChange:
|
||||
result.function_match.status === "mismatched" ||
|
||||
(result.function_match.status === "matched" &&
|
||||
result.dimensions.some(
|
||||
(dimension) =>
|
||||
dimension.dimension !== "calls" &&
|
||||
dimension.status === "changed",
|
||||
)),
|
||||
};
|
||||
const dimension = result.dimensions.find(
|
||||
(item) => item.dimension === claim.dimension,
|
||||
);
|
||||
@@ -263,7 +287,7 @@ const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
|
||||
throw new TypeError(
|
||||
"Function dimension cites Evidence outside comparison closure",
|
||||
);
|
||||
return dimension.status;
|
||||
return { status: dimension.status };
|
||||
}
|
||||
const result = artifactComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
@@ -276,7 +300,7 @@ const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
|
||||
throw new TypeError(
|
||||
"Artifact change cites Evidence outside comparison closure",
|
||||
);
|
||||
return result.status;
|
||||
return { status: result.status };
|
||||
};
|
||||
|
||||
const validateProcessStatus = (
|
||||
@@ -340,12 +364,12 @@ const authorityLimitations = (
|
||||
const sourceCallCoverageLimitations = (
|
||||
claim: Claim,
|
||||
functionSources: readonly FunctionSourceFacts[],
|
||||
observed: ObservedStatus,
|
||||
hasIndependentFunctionChange: boolean,
|
||||
): string[] => {
|
||||
if (
|
||||
claim.kind !== "structural-function" ||
|
||||
(claim.dimension !== "calls" &&
|
||||
!(claim.dimension === "overall" && observed !== "changed"))
|
||||
!(claim.dimension === "overall" && !hasIndependentFunctionChange))
|
||||
)
|
||||
return [];
|
||||
return functionSources.flatMap(({ evidence_id, callCoverageLimitations }) =>
|
||||
|
||||
@@ -8,6 +8,48 @@ import { createWebTextArtifact } from "./webContentArtifact.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
it.each([
|
||||
{
|
||||
kind: "recovered",
|
||||
source: "function legacy(a, a) { return a; } fetch('/partial');",
|
||||
parsed: 2,
|
||||
failures: 0,
|
||||
reason: "recovered",
|
||||
endpoints: ["/partial", "/complete"],
|
||||
},
|
||||
{
|
||||
kind: "failed",
|
||||
source: "function broken( {",
|
||||
parsed: 1,
|
||||
failures: 1,
|
||||
reason: "could not be parsed",
|
||||
endpoints: ["/complete"],
|
||||
},
|
||||
])(
|
||||
"attributes $kind parse uncertainty only to its affected source",
|
||||
({ source, parsed, failures, reason, endpoints }) => {
|
||||
const captured = inspection(source);
|
||||
const good = inspection("fetch('/complete');").scripts.items[0];
|
||||
if (good === undefined) throw new Error("Missing valid script fixture");
|
||||
captured.scripts.items.push({ ...good, script_key: "valid-script" });
|
||||
captured.scripts.total += 1;
|
||||
const result = analyzeCapturedWebBundle(captured);
|
||||
expect(result.completeness).toMatchObject({
|
||||
status: "partial",
|
||||
parsed_scripts: parsed,
|
||||
parse_failures: failures,
|
||||
});
|
||||
expect(result.unknowns).toContainEqual({
|
||||
dimension: "javascript_ast",
|
||||
reason: expect.stringContaining(reason),
|
||||
affected_script_keys: [captured.scripts.items[0]?.script_key],
|
||||
});
|
||||
expect(result.observations.endpoints.map(({ value }) => value)).toEqual(
|
||||
endpoints,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
describe("web bundle analyzer", () => {
|
||||
it("extracts graph, route, endpoint, vendor, and WebMCP evidence", () => {
|
||||
const source = `
|
||||
@@ -714,3 +756,54 @@ it("keeps RPC lexical identity and bundled factory recognition in captured scrip
|
||||
]);
|
||||
expect(result.completeness.status).toBe("complete");
|
||||
});
|
||||
|
||||
it("retains distinct WebMCP descriptions and names while deduplicating equivalent properties", () => {
|
||||
const result = analyzeCapturedWebBundle(
|
||||
inspection(`
|
||||
document.modelContext.registerTool({ name: "lookup", description: "first", inputSchema: { properties: { alpha: {} } } });
|
||||
document.modelContext.registerTool({ name: "lookup", description: "second", inputSchema: { properties: { alpha: {} } } });
|
||||
document.modelContext.registerTool({ name: "equivalent", inputSchema: { properties: { alpha: {}, beta: {} } } });
|
||||
document.modelContext.registerTool({ name: "equivalent", inputSchema: { properties: { beta: {}, alpha: {}, alpha: {} } } });
|
||||
document.modelContext.registerTool({ description: "unnamed" });
|
||||
document.modelContext.registerTool({ name: "", description: "unnamed" });
|
||||
`),
|
||||
);
|
||||
|
||||
expect(
|
||||
result.observations.webmcp_declarations.map(
|
||||
({ name, description, schema_property_names }) => ({
|
||||
name,
|
||||
description,
|
||||
schema_property_names,
|
||||
}),
|
||||
),
|
||||
).toEqual([
|
||||
{
|
||||
name: "lookup",
|
||||
description: "first",
|
||||
schema_property_names: ["alpha"],
|
||||
},
|
||||
{
|
||||
name: "lookup",
|
||||
description: "second",
|
||||
schema_property_names: ["alpha"],
|
||||
},
|
||||
{
|
||||
name: "equivalent",
|
||||
description: null,
|
||||
schema_property_names: ["alpha", "beta"],
|
||||
},
|
||||
{ name: null, description: "unnamed", schema_property_names: [] },
|
||||
{ name: "", description: "unnamed", schema_property_names: [] },
|
||||
]);
|
||||
expect(result.observations.webmcp_declarations[2]?.location).toEqual({
|
||||
script_key: `scr_${"1".repeat(64)}`,
|
||||
line: 4,
|
||||
column: 6,
|
||||
});
|
||||
expect(
|
||||
result.observations.webmcp_declarations.every(
|
||||
({ trust }) => trust === "page-declared-untrusted",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
@@ -50,7 +50,8 @@ export interface AnalysisAccumulator {
|
||||
readonly seen: Set<string>;
|
||||
visitedNodes: number;
|
||||
parsedScripts: number;
|
||||
parseFailures: number;
|
||||
readonly failedScripts: string[];
|
||||
readonly recoveredScripts: string[];
|
||||
}
|
||||
|
||||
export const analyzeScript = (
|
||||
@@ -67,10 +68,12 @@ export const analyzeScript = (
|
||||
} catch (cause: unknown) {
|
||||
// Unparseable scripts are counted; the failure needs no extra detail.
|
||||
void cause;
|
||||
accumulator.parseFailures += 1;
|
||||
accumulator.failedScripts.push(script.script_key);
|
||||
return;
|
||||
}
|
||||
accumulator.parsedScripts += 1;
|
||||
if ((file.errors?.length ?? 0) > 0)
|
||||
accumulator.recoveredScripts.push(script.script_key);
|
||||
detectVendorFingerprints(script, accumulator);
|
||||
const openReceiverFacts = classifyParsedJavaScriptOpenReceivers(file);
|
||||
const rpc = createJavaScriptRpcScan(
|
||||
@@ -293,19 +296,18 @@ const addWebMcpDeclaration = (
|
||||
: [],
|
||||
)
|
||||
: [];
|
||||
const metadata = {
|
||||
name: name ?? null,
|
||||
description: description ?? null,
|
||||
schema_property_names: [...new Set(schemaPropertyNames)].sort(),
|
||||
};
|
||||
// Deduplicate the metadata we return, preserving omission and descriptions.
|
||||
// Property names are a variable-length source-derived list: NUL-joins
|
||||
// would collapse ["a\0b"] with ["a", "b"] and drop a declaration.
|
||||
const key = compositeKey([
|
||||
"webmcp",
|
||||
script.script_key,
|
||||
name ?? "",
|
||||
schemaPropertyNames,
|
||||
]);
|
||||
const key = compositeKey(["webmcp", script.script_key, metadata]);
|
||||
addUnique(accumulator, key, () =>
|
||||
accumulator.webMcp.push({
|
||||
name: name ?? null,
|
||||
description: description ?? null,
|
||||
schema_property_names: [...new Set(schemaPropertyNames)].sort(),
|
||||
...metadata,
|
||||
trust: "page-declared-untrusted",
|
||||
location: location(script.script_key, node),
|
||||
}),
|
||||
@@ -387,7 +389,8 @@ export const emptyAccumulator = (): AnalysisAccumulator => ({
|
||||
seen: new Set(),
|
||||
visitedNodes: 0,
|
||||
parsedScripts: 0,
|
||||
parseFailures: 0,
|
||||
failedScripts: [],
|
||||
recoveredScripts: [],
|
||||
});
|
||||
|
||||
export const isIncludedScript = (
|
||||
|
||||
@@ -25,7 +25,8 @@ export const buildWebBundleAnalysis = (
|
||||
const sourceMapIncomplete =
|
||||
sourceMaps.status === "partial" || sourceMaps.status === "unavailable";
|
||||
const partial =
|
||||
accumulator.parseFailures > 0 ||
|
||||
accumulator.failedScripts.length > 0 ||
|
||||
accumulator.recoveredScripts.length > 0 ||
|
||||
unavailable.length > 0 ||
|
||||
sourceMapIncomplete ||
|
||||
omittedScripts !== undefined ||
|
||||
@@ -44,9 +45,9 @@ export const buildWebBundleAnalysis = (
|
||||
},
|
||||
inferences: accumulator.inferences,
|
||||
unknowns: buildUnknowns({
|
||||
sourceScripts,
|
||||
unavailable,
|
||||
parseFailures: accumulator.parseFailures,
|
||||
failedScripts: accumulator.failedScripts,
|
||||
recoveredScripts: accumulator.recoveredScripts,
|
||||
sourceMaps,
|
||||
omittedScripts,
|
||||
omittedSourceMaps,
|
||||
@@ -54,7 +55,7 @@ export const buildWebBundleAnalysis = (
|
||||
completeness: buildCompleteness({
|
||||
partial,
|
||||
parsedScripts: accumulator.parsedScripts,
|
||||
parseFailures: accumulator.parseFailures,
|
||||
parseFailures: accumulator.failedScripts.length,
|
||||
visitedNodes: accumulator.visitedNodes,
|
||||
}),
|
||||
limitations: bundleLimitations(),
|
||||
@@ -88,9 +89,9 @@ const chunkNode = (script: IncludedScript) => {
|
||||
};
|
||||
|
||||
interface UnknownsInput {
|
||||
readonly sourceScripts: IncludedScript[];
|
||||
readonly unavailable: string[];
|
||||
readonly parseFailures: number;
|
||||
readonly failedScripts: readonly string[];
|
||||
readonly recoveredScripts: readonly string[];
|
||||
readonly sourceMaps: WebBundleAnalysis["observations"]["source_maps"];
|
||||
readonly omittedScripts: number | null | undefined;
|
||||
readonly omittedSourceMaps: number | null | undefined;
|
||||
@@ -115,15 +116,23 @@ const buildUnknowns = (input: UnknownsInput): WebBundleAnalysis["unknowns"] => [
|
||||
affected_script_keys: input.unavailable,
|
||||
},
|
||||
]),
|
||||
...(input.parseFailures === 0
|
||||
...(input.failedScripts.length === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
dimension: "javascript_ast" as const,
|
||||
reason: "One or more source artifacts could not be parsed",
|
||||
affected_script_keys: input.sourceScripts.map(
|
||||
({ script_key }) => script_key,
|
||||
),
|
||||
affected_script_keys: [...input.failedScripts],
|
||||
},
|
||||
]),
|
||||
...(input.recoveredScripts.length === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
dimension: "javascript_ast" as const,
|
||||
reason:
|
||||
"The parser recovered from errors in one or more source artifacts; findings may be incomplete",
|
||||
affected_script_keys: [...input.recoveredScripts],
|
||||
},
|
||||
]),
|
||||
...(input.omittedSourceMaps === undefined
|
||||
|
||||
@@ -8,7 +8,19 @@ import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import type { ApplicationNode } from "../domain/javascript/javascriptApplicationGraphSchemas.js";
|
||||
import { javaScriptExportShapeComparisonResultSchema } from "../domain/javascript/javascriptExportShapeComparisonSchemas.js";
|
||||
import type { FixtureClaimExpectation } from "./KnownAnswerEvaluation.js";
|
||||
import {
|
||||
managedArtifactInspectionSchema,
|
||||
managedMemberInspectionSchema,
|
||||
} from "../domain/managed/managedArtifact.js";
|
||||
import {
|
||||
managedTokenScopesMatch,
|
||||
parseManagedInspectionEvidence,
|
||||
} from "../domain/managed/managedInspectionEvidence.js";
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
import type {
|
||||
FixtureClaimContext,
|
||||
FixtureClaimExpectation,
|
||||
} from "./KnownAnswerEvaluation.js";
|
||||
|
||||
/** Source-owned artifact paths used by the configured known-answer benchmarks. */
|
||||
export interface AgentEvaluationFixtureTargets {
|
||||
@@ -16,6 +28,8 @@ export interface AgentEvaluationFixtureTargets {
|
||||
readonly javascriptSha256: string;
|
||||
readonly javascriptShapeLeft: string;
|
||||
readonly javascriptShapeRight: string;
|
||||
readonly managed?: string;
|
||||
readonly managedSha256?: string;
|
||||
}
|
||||
|
||||
const desktopFixtureFiles = {
|
||||
@@ -277,17 +291,122 @@ const parserClaims = (
|
||||
];
|
||||
};
|
||||
|
||||
const managedMembers = ({ evidence }: FixtureClaimContext) => {
|
||||
const { result } = parseManagedInspectionEvidence(
|
||||
evidence,
|
||||
"inspect_managed_members",
|
||||
managedMemberInspectionSchema,
|
||||
);
|
||||
if (
|
||||
result.coverage.state !== "complete" ||
|
||||
result.metadata.status !== "complete" ||
|
||||
!managedTokenScopesMatch(
|
||||
result.identity_scope.requires_mvid,
|
||||
result.module?.mvid ?? null,
|
||||
)
|
||||
)
|
||||
return undefined;
|
||||
return result;
|
||||
};
|
||||
|
||||
const managedClaims = (
|
||||
targets: AgentEvaluationFixtureTargets,
|
||||
): readonly FixtureClaimExpectation[] => {
|
||||
if (targets.managed === undefined || targets.managedSha256 === undefined)
|
||||
throw new TypeError(
|
||||
"Managed fixture grading requires the built DLL path and SHA-256",
|
||||
);
|
||||
const source = {
|
||||
operation: "inspect_managed_members",
|
||||
authority: "shipped-artifact",
|
||||
confidence: "observed",
|
||||
subject: { path: targets.managed, sha256: targets.managedSha256 },
|
||||
} satisfies Omit<FixtureClaimExpectation["source"], "select">;
|
||||
return [
|
||||
{
|
||||
id: "public_types",
|
||||
expectedValue: ["AgentEval.Profile", "AgentEval.Program"],
|
||||
source: {
|
||||
...source,
|
||||
select: (_value, context) => {
|
||||
const members = managedMembers(context);
|
||||
if (
|
||||
members === undefined ||
|
||||
members.selection !== null ||
|
||||
Object.hasOwn(context.evidence.parameters, "type_names")
|
||||
)
|
||||
return undefined;
|
||||
return members.types
|
||||
.filter((type) => (type.flags & 7) === 1)
|
||||
.map((type) => type.full_name)
|
||||
.sort(compareUnicodeCodePoints);
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "entry_point",
|
||||
expectedValue: { declaring_type: "AgentEval.Program", name: "Main" },
|
||||
source: {
|
||||
...source,
|
||||
select: (_value, context) => {
|
||||
const members = managedMembers(context);
|
||||
if (members === undefined) return undefined;
|
||||
const artifacts = context.deliveredEvidence.filter(
|
||||
(evidence) =>
|
||||
evidence.operation === "inspect_managed_artifact" &&
|
||||
evidence.authority === source.authority &&
|
||||
evidence.confidence === source.confidence &&
|
||||
evidence.subject?.local_path === source.subject.path &&
|
||||
evidence.subject.digest.sha256 === source.subject.sha256,
|
||||
);
|
||||
if (artifacts.length !== 1) return undefined;
|
||||
const { result: artifact } = parseManagedInspectionEvidence(
|
||||
artifacts[0],
|
||||
"inspect_managed_artifact",
|
||||
managedArtifactInspectionSchema,
|
||||
);
|
||||
if (
|
||||
artifact.coverage.state !== "complete" ||
|
||||
artifact.metadata.status !== "complete" ||
|
||||
!managedTokenScopesMatch(
|
||||
artifact.module?.mvid ?? null,
|
||||
members.module?.mvid ?? null,
|
||||
) ||
|
||||
artifact.pe.cli?.entry_point.kind !== "metadata-token"
|
||||
)
|
||||
return undefined;
|
||||
const methods = members.methods.filter(
|
||||
(method) => method.token === artifact.pe.cli?.entry_point.value,
|
||||
);
|
||||
const method = methods.length === 1 ? methods[0] : undefined;
|
||||
return method === undefined
|
||||
? undefined
|
||||
: {
|
||||
declaring_type: method.declaring_type,
|
||||
name: method.name,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
/** Return the closed known-answer rubric, or undefined for routing-only scenarios. */
|
||||
export const agentFixtureClaims = (
|
||||
scenarioId: string,
|
||||
targets: AgentEvaluationFixtureTargets,
|
||||
): readonly FixtureClaimExpectation[] | undefined => {
|
||||
if (scenarioId === "asar") return asarClaims(targets);
|
||||
if (scenarioId === "managed") return managedClaims(targets);
|
||||
if (scenarioId === "javascript-export-shape") return parserClaims(targets);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const answerValueDescriptions: Readonly<Record<string, readonly string[]>> = {
|
||||
managed: [
|
||||
"public_types: string[], listing the exact public top-level type full names in Unicode code-point order from unfiltered member Evidence (omit type_names).",
|
||||
'entry_point: {"declaring_type": string, "name": string}, resolving the CLI metadata entry-point token against the member inventory from the same artifact SHA-256 and module MVID. Cite member Evidence; both artifact and member Evidence must be delivered.',
|
||||
],
|
||||
asar: [
|
||||
'renderer_api: {"key": string, "members": string[], "world": string, "source": string}, describing the exposed bridge API, its members, world, and source file.',
|
||||
'renderer_ipc: {"channel": string, "operation": string, "source": string}, describing the renderer-side IPC operation and its source file.',
|
||||
|
||||
@@ -5,6 +5,12 @@ import { parseEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { canonicalJson } from "../domain/comparisonSemantics.js";
|
||||
|
||||
/** Only authenticated, successful, non-conflicting transcript deliveries. */
|
||||
export interface FixtureClaimContext {
|
||||
readonly evidence: Evidence;
|
||||
readonly deliveredEvidence: readonly Evidence[];
|
||||
}
|
||||
|
||||
/** One closed fixture assertion and the producer facts that must support it. */
|
||||
export interface FixtureClaimExpectation {
|
||||
readonly id: string;
|
||||
@@ -20,7 +26,10 @@ export interface FixtureClaimExpectation {
|
||||
readonly path: string;
|
||||
readonly sha256?: string;
|
||||
}[];
|
||||
readonly select: (normalizedResult: JsonValue) => JsonValue | undefined;
|
||||
readonly select: (
|
||||
normalizedResult: JsonValue,
|
||||
context: FixtureClaimContext,
|
||||
) => JsonValue | undefined;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -430,7 +439,12 @@ const assessClaim = (
|
||||
try {
|
||||
if (
|
||||
!sameJson(
|
||||
expected.source.select(evidence.normalized_result),
|
||||
expected.source.select(evidence.normalized_result, {
|
||||
evidence,
|
||||
deliveredEvidence: [...delivered.records.values()].filter(
|
||||
(record) => !delivered.conflicts.has(record.evidence_id),
|
||||
),
|
||||
}),
|
||||
expected.expectedValue,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -61,7 +61,7 @@ const doctorHost = (
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
hopperSetupSupported: true,
|
||||
}),
|
||||
validTarget: () => Promise.resolve(true),
|
||||
executable: (path) =>
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
bytePatternFields,
|
||||
validateBytePattern,
|
||||
byteSearchResultSchema,
|
||||
} from "../domain/native/bytePattern.js";
|
||||
import { nativeLoadImageObservationSchema } from "../domain/native/nativeLoadImage.js";
|
||||
|
||||
import {
|
||||
@@ -20,6 +25,7 @@ import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"
|
||||
export const GHIDRA_INVENTORY_OPERATIONS = [
|
||||
"inspect_native_load_image",
|
||||
"read_bytes",
|
||||
"search_bytes",
|
||||
"address_to_file_offset",
|
||||
"address_name",
|
||||
"list_documents",
|
||||
@@ -72,6 +78,16 @@ const searchInput = {
|
||||
};
|
||||
|
||||
const inputSchemas = {
|
||||
search_bytes: z
|
||||
.strictObject({
|
||||
...bytePatternFields,
|
||||
document,
|
||||
start: explicitAddress.optional(),
|
||||
end: explicitAddress.optional(),
|
||||
limit: z.number().int().min(1).max(1000).default(100),
|
||||
cursor: z.string().min(1).optional(),
|
||||
})
|
||||
.superRefine(validateBytePattern),
|
||||
inspect_native_load_image: z.strictObject({}),
|
||||
read_bytes: z.strictObject({
|
||||
document,
|
||||
@@ -271,6 +287,24 @@ const containingProcedure = z.discriminatedUnion("found", [
|
||||
]);
|
||||
|
||||
const resultSchemas = {
|
||||
search_bytes: byteSearchResultSchema.superRefine((value, context) => {
|
||||
const addresses = [
|
||||
...value.matches.flatMap((match) => [
|
||||
match.address,
|
||||
...(match.procedure === null ? [] : [match.procedure.address]),
|
||||
]),
|
||||
...[
|
||||
...value.searched.blocks,
|
||||
...value.searched.skipped_uninitialized,
|
||||
...value.searched.skipped_not_loaded,
|
||||
].flatMap((block) => [block.start, block.end]),
|
||||
];
|
||||
if (addresses.some((value) => !canonicalAddress.safeParse(value).success))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Byte search addresses must be canonical",
|
||||
});
|
||||
}),
|
||||
inspect_native_load_image: nativeLoadImageObservationSchema,
|
||||
read_bytes: z
|
||||
.strictObject({
|
||||
|
||||
@@ -90,6 +90,11 @@ export const limitationsFor = (operation: string): readonly string[] => {
|
||||
...common,
|
||||
"Bytes reflect Ghidra's initialized memory, including loader fixups. Reads stop at an unmapped or uninitialized byte and report completeness explicitly.",
|
||||
];
|
||||
case "search_bytes":
|
||||
return [
|
||||
...common,
|
||||
"Searches initialized loader-adjusted memory independently per block, in provider address order. Bounds and page coverage ends are inclusive. Uninitialized blocks are listed separately. Overlapping matches are included; patterns never cross block boundaries. A cursor resumes the same target, profile and query. Cancellation discards the active search and returns no successful partial page.",
|
||||
];
|
||||
case "address_to_file_offset":
|
||||
return [
|
||||
...common,
|
||||
|
||||
@@ -62,12 +62,16 @@ const MUTATING_OPERATIONS = new Set<string>([
|
||||
|
||||
/** Source-owned capabilities without acquiring or probing a Hopper session. */
|
||||
export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
HOPPER_OPERATIONS.map((operation) =>
|
||||
[...HOPPER_OPERATIONS, "search_bytes" as const].map((operation) =>
|
||||
Object.freeze({
|
||||
provider: HOPPER_PROVIDER_IDENTITY,
|
||||
operation,
|
||||
available: true,
|
||||
reason: null,
|
||||
...(operation === "search_bytes"
|
||||
? {
|
||||
available: false as const,
|
||||
reason: "Masked byte search has not been verified for Hopper.",
|
||||
}
|
||||
: { available: true as const, reason: null }),
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: MUTATING_OPERATIONS.has(operation),
|
||||
launchesProcess: true,
|
||||
|
||||
@@ -279,6 +279,11 @@ describe("native IDA provider observations", () => {
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.provider.name).toBe("IDA MCP adapter");
|
||||
if (operation === "xrefs")
|
||||
expect(
|
||||
result.value.referencesTruncated,
|
||||
"the native producer's explicit cap flag is forwarded",
|
||||
).toBe(false);
|
||||
if (operation === "procedure_assembly")
|
||||
expect(result.value.result).toBe("0x1000: ret");
|
||||
if (operation === "procedure_pseudo_code") {
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
*/
|
||||
export const MCP_STARTUP_POLICY = {
|
||||
codexStartupTimeoutSeconds: 30,
|
||||
kimiStartupTimeoutMs: 30_000,
|
||||
kimiToolTimeoutMs: 120_000,
|
||||
initializeBudgetMs: 15_000,
|
||||
toolsListBudgetMs: 5_000,
|
||||
firstCatalogBudgetMs: 20_000,
|
||||
|
||||
@@ -278,8 +278,13 @@ class ErrorEvidenceTransport implements Transport {
|
||||
// Count the provenance marker exactly as the projected error did, and keep
|
||||
// it on the replacement: the retained original may hold target content.
|
||||
const targetContent = carriesTargetContentMarker(message.result);
|
||||
// The delivered error omits structuredContent, so only its text counts.
|
||||
const encoded = encodeToolResult(structured, budget, "text", targetContent);
|
||||
// The delivered error omits structuredContent, so its text and error flag count.
|
||||
const encoded = encodeToolResult(
|
||||
structured,
|
||||
budget,
|
||||
"error-text",
|
||||
targetContent,
|
||||
);
|
||||
if (encoded.ok) return message;
|
||||
const operation = tool ?? "mcp_tool_error";
|
||||
const originalError = analysisErrorProjectionSchema.safeParse(
|
||||
|
||||
@@ -139,7 +139,7 @@ export class ToolResultDelivery {
|
||||
const encoded = encodeToolResult(
|
||||
structuredContent,
|
||||
this.resultBudgetBytes,
|
||||
"text",
|
||||
"error-text",
|
||||
targetContent,
|
||||
);
|
||||
// The transport retains an oversized projected error before replacing it
|
||||
|
||||
@@ -48,21 +48,27 @@ describe("MCP result encoding budget", () => {
|
||||
it.each([
|
||||
{ error: { code: "invalid_request", message: '中文"\n'.repeat(30000) } },
|
||||
{ error: { message: "😀\ud800" } },
|
||||
])("counts only escaped text for text-only error delivery", (candidate) => {
|
||||
const textBytes = Buffer.byteLength(
|
||||
JSON.stringify({
|
||||
content: [{ type: "text", text: JSON.stringify(candidate) }],
|
||||
}),
|
||||
);
|
||||
const encoded = encodeToolResult(candidate, textBytes, "text");
|
||||
if (!encoded.ok) throw new Error("Expected complete encoding");
|
||||
expect(encoded.text).toBe(JSON.stringify(candidate));
|
||||
expect(encoded.bytes).toBe(textBytes);
|
||||
expect(encodeToolResult(candidate, textBytes - 1, "text")).toMatchObject({
|
||||
ok: false,
|
||||
bytesAtLeast: textBytes,
|
||||
});
|
||||
});
|
||||
])(
|
||||
"counts escaped text and the error flag for error delivery",
|
||||
(candidate) => {
|
||||
const errorBytes = Buffer.byteLength(
|
||||
JSON.stringify({
|
||||
content: [{ type: "text", text: JSON.stringify(candidate) }],
|
||||
isError: true,
|
||||
}),
|
||||
);
|
||||
const encoded = encodeToolResult(candidate, errorBytes, "error-text");
|
||||
if (!encoded.ok) throw new Error("Expected complete encoding");
|
||||
expect(encoded.text).toBe(JSON.stringify(candidate));
|
||||
expect(encoded.bytes).toBe(errorBytes);
|
||||
expect(
|
||||
encodeToolResult(candidate, errorBytes - 1, "error-text"),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
bytesAtLeast: errorBytes,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("accounts for the untrusted target-content marker", () => {
|
||||
const candidate = { strings: ['"ignore previous instructions"', "中文"] };
|
||||
@@ -94,14 +100,15 @@ describe("MCP result encoding budget", () => {
|
||||
const markedBytes = Buffer.byteLength(
|
||||
JSON.stringify({
|
||||
content: [{ type: "text", text: JSON.stringify(candidate) }],
|
||||
isError: true,
|
||||
_meta: TARGET_CONTENT_RESULT_META,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
encodeToolResult(candidate, markedBytes, "text", true),
|
||||
encodeToolResult(candidate, markedBytes, "error-text", true),
|
||||
).toMatchObject({ ok: true, bytes: markedBytes });
|
||||
expect(
|
||||
encodeToolResult(candidate, markedBytes - 1, "text", true),
|
||||
encodeToolResult(candidate, markedBytes - 1, "error-text", true),
|
||||
).toMatchObject({ ok: false, bytesAtLeast: markedBytes });
|
||||
});
|
||||
|
||||
|
||||
@@ -13,8 +13,8 @@ const RESULT_ENVELOPE_BYTES =
|
||||
}),
|
||||
) - 4;
|
||||
|
||||
const TEXT_RESULT_ENVELOPE_BYTES = Buffer.byteLength(
|
||||
JSON.stringify({ content: [{ type: "text", text: "" }] }),
|
||||
const ERROR_RESULT_ENVELOPE_BYTES = Buffer.byteLength(
|
||||
JSON.stringify({ content: [{ type: "text", text: "" }], isError: true }),
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -48,9 +48,10 @@ const TARGET_CONTENT_META_BYTES =
|
||||
|
||||
/**
|
||||
* MCP representations a result carries on the wire. Successful results repeat
|
||||
* the JSON as structured content and escaped text; error results carry text only.
|
||||
* the JSON as structured content and escaped text; error results carry text
|
||||
* only, plus their `isError` flag.
|
||||
*/
|
||||
export type ToolResultRepresentations = "structured-and-text" | "text";
|
||||
export type ToolResultRepresentations = "structured-and-text" | "error-text";
|
||||
|
||||
/** Result of encoding the complete repeated MCP representations within a wire budget. */
|
||||
export type ToolResultEncoding =
|
||||
@@ -72,7 +73,7 @@ export const encodeToolResult = (
|
||||
const structured = representations === "structured-and-text";
|
||||
const parts: string[] = [];
|
||||
let bytes =
|
||||
(structured ? RESULT_ENVELOPE_BYTES : TEXT_RESULT_ENVELOPE_BYTES) +
|
||||
(structured ? RESULT_ENVELOPE_BYTES : ERROR_RESULT_ENVELOPE_BYTES) +
|
||||
(targetContent ? TARGET_CONTENT_META_BYTES : 0);
|
||||
let codeUnits = bytes;
|
||||
for (const part of bufferedJsonParts(jsonParts(value))) {
|
||||
|
||||
Reference in New Issue
Block a user