import assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { createInterface } from "node:readline"; import { fileURLToPath } from "node:url"; import { stringify } from "smol-toml"; import { spawnOwnedProviderProcess, ProviderProcessSupervisor, } from "../dist/process/ProviderProcess.js"; import { cleanupOwnedProcessGroup } from "../dist/process/ProcessOwnership.js"; import { createVerifierCommands } from "./lib/verify-commands.mjs"; import { VerifierFixture, withVerifierFixture, } from "./lib/verifier-fixture.mjs"; import { clientCatalogFixture } from "./verify/clients/catalog.mjs"; import { readClientVersion } from "./verify/clients/version.mjs"; const native = process.env.REA_VERIFY_CODEX_COMMAND ?? "codex"; assert.equal( process.argv[2] ?? "scoped-chat", "scoped-chat", "Usage: verify-codex-client.mjs scoped-chat", ); const fixture = clientCatalogFixture("scoped-chat"); const probe = fileURLToPath( new URL("./verify/clients/environment-probe.mjs", import.meta.url), ); const rea = fileURLToPath(new URL("../scripts/rea.mjs", import.meta.url)); await withVerifierFixture( await VerifierFixture.open({ prefix: "rea-codex-client-" }), async (lab) => { const home = lab.path; const config = join(home, ".codex"); await mkdir(config); const environment = { HOME: home, USERPROFILE: home, CODEX_HOME: config, PATH: process.env.PATH, LANG: "en_US.UTF-8", }; const command = { command: process.execPath, args: [probe] }; const env = { REA_MCP_TOOL_FAMILIES: "electron,javascript-runtime" }; await writeFile( join(config, "config.toml"), stringify({ mcp_servers: { plain: { ...command, env_vars: ["LANG"], env }, structured: { ...command, env_vars: [{ name: "LANG", source: "local" }], env, }, control: command, }, }), ); const commands = await createVerifierCommands(); lab.releaseAfter(() => commands.close()); const version = await readClientVersion(commands, native, environment, { cwd: home, }); const setup = await commands.exec( process.execPath, [ rea, "setup", "--client", "codex", "--skill=false", ...fixture.setupArguments, "--yes", "--json", ], { cwd: home, env: environment, timeout: 60_000 }, ); assert.equal(JSON.parse(setup.stdout).status, "ready"); const owned = await spawnOwnedProviderProcess({ command: native, arguments: ["app-server", "--listen", "stdio://"], stdin: "pipe", cwd: home, hostEnvironment: environment, runId: randomUUID(), expectedCommand: null, sweepTokenOwnedProcesses: true, }); const supervisor = new ProviderProcessSupervisor( { ...owned, ownsProcessLifetime: true, cleanup: owned.cleanup ?? (() => cleanupOwnedProcessGroup(owned.ownership)), }, { captureStdout: false, maxDiagnosticBytes: 64 * 1024, diagnosticRetention: "tail", }, ); lab.releaseAfter(async () => { const cleanup = await supervisor.stop(); assert.notEqual( cleanup.status, "incomplete", "Codex process cleanup must complete", ); supervisor.dispose(); }); // Codex app-server uses its own newline-framed protocol on this pipe. const lines = createInterface({ input: owned.process.stdout, signal: AbortSignal.timeout(60_000), }); const reader = lines[Symbol.asyncIterator](); const send = (message) => owned.process.stdin.write(JSON.stringify(message) + "\n"); let statusResponse = null; const request = async (id, method, params) => { send({ id, method, params }); for (;;) { const line = await reader.next(); assert( !line.done, `Codex closed the stream before replying to ${method}`, ); const message = JSON.parse(line.value); if (message.id !== id) continue; if (method === "mcpServerStatus/list") statusResponse = message; assert.equal(message.error, undefined, JSON.stringify(message.error)); return message.result; } }; try { await request(1, "initialize", { clientInfo: { name: "rea_registration_verifier", version: "1" }, capabilities: { experimentalApi: true }, }); send({ method: "initialized" }); const status = await request(2, "mcpServerStatus/list", { limit: 100 }); assert.equal( status.nextCursor, null, "Expected all four test registrations on the status page", ); const servers = new Map( status.data.map((row) => [row.name, Object.keys(row.tools)]), ); for (const name of ["plain", "structured"]) assert.deepEqual( servers.get(name), ["probe_environment_selected"], name, ); assert.deepEqual(servers.get("control"), ["probe_environment_absent"]); const tools = servers.get("rea"); assert(tools, "Codex must launch the REA registration"); fixture.assertNames(tools); process.stdout.write( JSON.stringify({ client: version, catalogSize: tools.length, checked: ["plain", "structured", "control", "rea"], }) + "\n", ); } catch (cause) { // Run after the supervisor drains stderr and before the fixture is removed. lab.releaseAfter(async () => { const path = process.env.REA_VERIFY_CODEX_FAILURE_PATH ?? join( ( await VerifierFixture.keepArtifacts({ prefix: "rea-codex-failure-", }) ).path, "codex-registration-failure.json", ); const report = { client: version, error: cause instanceof Error ? cause.message : String(cause), statusResponse, stderr: supervisor.snapshot().stderr, }; await writeFile(path, JSON.stringify(report, null, 2) + "\n"); process.stderr.write(`Codex registration failure report: ${path}\n`); }); throw cause; } finally { lines.close(); owned.process.stdin.end(); } }, );