OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(config): apply native profiles across scan workflows (#1018)
Michael D'Angelo22a95220e4a6
diff --git a/plugins/codex-security/.mcp.json b/plugins/codex-security/.mcp.jsonindex 6cabc05a0..c42b1fb3a 100644--- a/plugins/codex-security/.mcp.json+++ b/plugins/codex-security/.mcp.json@@ -42,6 +42,7 @@"CODEX_SECURITY_KNOWLEDGE_BASE","CODEX_SECURITY_CONFIG_PATH","CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",+ "CODEX_SECURITY_SCAN_DIR","CODEX_SECURITY_PLUGIN_ROOT","CODEX_SECURITY_SCAN_ROOT","CODEX_SECURITY_STATE_DIR",diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.tsindex 31cd89a76..6a49c11e4 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts@@ -418,7 +418,7 @@ function workerSubagentConfig(subagents: number, inheritedFeatures: unknown) {// V1 counts children; V2 counts the root plus its children. Keeping its// feature disabled lets the model choose either runtime without rejecting// inherited agents.max_threads configuration.- ...(subagents > 0 ? { agents: { max_threads: subagents } } : {}),+ ...(subagents > 0 ? { "agents.max_threads": subagents } : {}),features: {...(isRecord(inheritedFeatures) ? inheritedFeatures : {}),multi_agent_v2: {@@ -724,6 +724,28 @@ export async function workerRuntimeSettings(]) {delete settings.config[key];}+ const parentScanDirectory = environmentVariable(+ environment,+ "CODEX_SECURITY_SCAN_DIR",+ process.platform,+ );+ if (parentScanDirectory) {+ for (const key of [+ "model_instructions_file",+ "model_catalog_json",+ "experimental_compact_prompt_file",+ ]) {+ const value = settings.config[key];+ if (+ typeof value === "string" &&+ value.length > 0 &&+ !isAbsolute(value) &&+ !value.startsWith("~")+ ) {+ settings.config[key] = resolve(parentScanDirectory, value);+ }+ }+ }return settings;}diff --git a/plugins/codex-security/mcp-app/tests/assertions.ts b/plugins/codex-security/mcp-app/tests/assertions.tsindex d9460ea38..42ea2bf72 100644--- a/plugins/codex-security/mcp-app/tests/assertions.ts+++ b/plugins/codex-security/mcp-app/tests/assertions.ts@@ -34,7 +34,7 @@ export function nativeConfigOverrides(args: readonly string[]) {export function assertConfigOverrides(args: readonly string[],- values: Record<string, string | number | boolean | undefined>,+ values: Record<string, string | string[] | number | boolean | undefined>,) {const overrides = nativeConfigOverrides(args).map((value) =>parseToml(value),diff --git a/plugins/codex-security/mcp-app/tests/deep_scan_cancellation_cases.ts b/plugins/codex-security/mcp-app/tests/deep_scan_cancellation_cases.tsnew file mode 100644index 000000000..77c90e729--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/deep_scan_cancellation_cases.ts@@ -0,0 +1,203 @@+import assert from "node:assert/strict";+import childProcess, {+ type ChildProcess,+ type SpawnOptions,+} from "node:child_process";+import { randomUUID } from "node:crypto";+import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";+import { syncBuiltinESMExports } from "node:module";+import path from "node:path";+import { assertFlagPair } from "./assertions.ts";+import type { CodexSdkWorkerExecutor as WorkerExecutor } from "../src/deep-scan/executor.js";+import type { DeepWorkerParentSandbox } from "../src/deep-scan/parent-sandbox.js";++import { restoreEnv } from "./support/fake-codex-source.ts";++export function mockWorkerSpawn(+ executablePath: string,+ onExec: (+ child: ChildProcess,+ args: readonly string[],+ options: SpawnOptions,+ ) => void,+) {+ const previousPath = process.env.CODEX_CLI_PATH;+ process.env.CODEX_CLI_PATH = process.execPath;+ const originalSpawn = childProcess.spawn;+ childProcess.spawn = ((+ command: string,+ args: readonly string[] = [],+ options: SpawnOptions = {},+ ) => {+ const child = originalSpawn(+ command,+ command === process.execPath ||+ command === path.toNamespacedPath(process.execPath)+ ? [executablePath, ...args]+ : args,+ options,+ );+ if (args[0] === "exec") onExec(child, args, options);+ return child;+ }) as typeof childProcess.spawn;+ syncBuiltinESMExports();+ return () => {+ restoreEnv("CODEX_CLI_PATH", previousPath);+ childProcess.spawn = originalSpawn;+ syncBuiltinESMExports();+ };+}++export async function testWorkerCancellation({+ CodexSdkWorkerExecutor,+ fakeCodexFixture,+ trustedParentSandbox,+}: {+ CodexSdkWorkerExecutor: typeof WorkerExecutor;+ fakeCodexFixture: () => Promise<{+ root: string;+ executablePath: string;+ preflightMarkerPath: string;+ markerPath: string;+ }>;+ trustedParentSandbox: DeepWorkerParentSandbox;+}) {+ const fixture = await fakeCodexFixture();+ let worker: ChildProcess | undefined;+ let workerSignal: AbortSignal | undefined;+ let cancelDuringCleanup: (() => void) | undefined;+ let timeout: NodeJS.Timeout | undefined;+ const restoreSpawn = mockWorkerSpawn(+ fixture.executablePath,+ (child, args, options) => {+ assertFlagPair(args, "--thread-source", "security_scan");+ worker = child;+ workerSignal = options.signal;+ const kill = child.kill;+ child.kill = function (...args: Parameters<ChildProcess["kill"]>) {+ cancelDuringCleanup?.();+ return kill.apply(this, args);+ };+ },+ );+ try {+ const promptPath = path.join(fixture.root, "prompt.md");+ const workingDirectory = path.join(fixture.root, "artifacts");+ await mkdir(workingDirectory);+ const executor = new CodexSdkWorkerExecutor({+ parentSandbox: trustedParentSandbox,+ artifactContext: {+ pluginRoot: fixture.root,+ repoRoot: fixture.root,+ scanId: randomUUID(),+ includePaths: ["api"],+ },+ });+ const run = (controller: AbortController, onThreadStarted?: () => void) =>+ executor.run({+ kind: "discovery",+ promptPath,+ workingDirectory,+ subagents: 0,+ signal: controller.signal,+ onThreadStarted,+ artifactContext: { root: workingDirectory, layout: "worker" },+ });+ const preAborted = new AbortController();+ const beforeStartup = new Error(+ "coordinator canceled before worker startup",+ );+ preAborted.abort(beforeStartup);+ await assert.rejects(+ run(preAborted),+ (error: Error) => error === beforeStartup,+ );+ assert.equal(worker, undefined);+ assert.equal(+ (await readdir(fixture.root)).some((name) => name.startsWith("scope-")),+ false,+ );+ await assert.rejects(readFile(fixture.preflightMarkerPath), {+ code: "ENOENT",+ });+ await assert.rejects(readFile(fixture.markerPath), { code: "ENOENT" });++ for (const prompt of [+ "BLOCK_AFTER_START",+ "COMPLETE_THEN_HANG",+ "FAIL_THEN_HANG",+ ]) {+ await writeFile(promptPath, `${prompt}\n`);+ const controller = new AbortController();+ const cancellation = new Error(+ "coordinator canceled its remaining workers",+ );+ // Exercise cancellation inside the real SDK's iterator cleanup, before kill returns.+ cancelDuringCleanup =+ prompt === "COMPLETE_THEN_HANG"+ ? () => controller.abort(cancellation)+ : undefined;+ const deadline = new Promise<never>((_, reject) => {+ timeout = setTimeout(+ () => reject(new Error(`${prompt} worker did not settle`)),+ 10_000,+ );+ });+ const execution = Promise.race([+ run(controller, () => {+ if (prompt === "BLOCK_AFTER_START") controller.abort(cancellation);+ }),+ deadline,+ ]);+ if (prompt === "BLOCK_AFTER_START") {+ await assert.rejects(+ execution,+ (error: Error) =>+ error?.name === "AbortError" ||+ /abort|SIGTERM/i.test(error?.message ?? ""),+ );+ assert(workerSignal);+ assert.equal(workerSignal.aborted, true);+ assert.equal(workerSignal.reason, cancellation);+ } else {+ if (prompt === "FAIL_THEN_HANG") {+ await assert.rejects(execution, /fixture worker failed/);+ controller.abort(cancellation);+ } else {+ const result = await execution;+ assert.equal(result.threadId, "fixture-thread-id");+ }+ assert.equal(controller.signal.aborted, true);+ assert(workerSignal);+ assert.equal(workerSignal.aborted, false);+ }+ assert.equal(+ (await readdir(fixture.root)).some((name) => name.startsWith("scope-")),+ false,+ );+ assert.notEqual(workerSignal, controller.signal);+ const currentWorker = worker as ChildProcess | undefined;+ assert(currentWorker);+ assert.equal(currentWorker.killed, true);+ if (+ currentWorker.exitCode === null &&+ currentWorker.signalCode === null+ ) {+ await Promise.race([+ new Promise<void>((resolve) =>+ worker!.once("close", () => resolve()),+ ),+ deadline,+ ]);+ }+ clearTimeout(timeout);+ cancelDuringCleanup = undefined;+ }+ } finally {+ clearTimeout(timeout);+ cancelDuringCleanup = undefined;+ if (worker && worker.exitCode === null && worker.signalCode === null)+ worker.kill("SIGKILL");+ restoreSpawn();+ }+}diff --git a/plugins/codex-security/mcp-app/tests/deep_scan_profile_file_cases.ts b/plugins/codex-security/mcp-app/tests/deep_scan_profile_file_cases.tsnew file mode 100644index 000000000..7d97725fc--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/deep_scan_profile_file_cases.ts@@ -0,0 +1,533 @@+import assert from "node:assert/strict";+import childProcess, { type SpawnOptions } from "node:child_process";+import { mkdir, readFile, realpath, writeFile } from "node:fs/promises";+import { syncBuiltinESMExports } from "node:module";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { importModule } from "./import-module.ts";+import { parse as parseToml } from "smol-toml";+import { readJson } from "./support/json.ts";+import { assertConfigOverrides, assertFlagPair } from "./assertions.ts";+import {+ deniedWorkerPermissionProfile,+ trustedParentSandboxWithDenials,+} from "./support/fake-codex-fixture.ts";+import { restoreEnv } from "./support/fake-codex-source.ts";+import type { CodexSdkWorkerExecutor as WorkerExecutor } from "../src/deep-scan/executor.js";++export async function testWorkerSelectedProfileFiles({+ CodexSdkWorkerExecutor,+ fakeCodexFixture,+ workerPermissionProfileOverride,+ assertReadOnlyWorkerPolicy,+ assertWorkerSubagentPolicy,+}: {+ CodexSdkWorkerExecutor: typeof WorkerExecutor;+ fakeCodexFixture: (+ profile: typeof deniedWorkerPermissionProfile,+ allowed: boolean,+ account: { account: null; requiresOpenaiAuth: boolean },+ ) => Promise<{ root: string; executablePath: string }>;+ workerPermissionProfileOverride: (+ args: readonly string[],+ ) => string | undefined;+ assertReadOnlyWorkerPolicy: (args: readonly string[]) => void;+ assertWorkerSubagentPolicy: (+ args: readonly string[],+ subagents: number,+ codeMode?: { enabled: boolean; excluded_tool_namespaces: string[] },+ ) => void;+}) {+ const { mergedCodexConfig, resolveCodexProfile, writeCodexConfig } =+ await importModule({+ alias: {+ "smol-toml": fileURLToPath(import.meta.resolve("smol-toml")),+ },+ entryPoints: [+ fileURLToPath(+ new URL("../../../../sdk/typescript/src/config.ts", import.meta.url),+ ),+ ],+ });+ const cases: [string, string | undefined, boolean?][] = [+ ["", undefined],+ ['model_reasoning_summary = "none"\n', "none"],+ ['model_reasoning_summary = "auto"\n', "auto"],+ [+ 'model = "native-model"\nmodel_reasoning_summary = "concise"\n',+ "concise",+ ],+ [+ 'model_reasoning_summary = "none"\nprofile = "selected"\n[profiles.selected]\nmodel_reasoning_summary = "concise"\n',+ "concise",+ ],+ [+ 'model_reasoning_summary = "none"\nprofile = "selected"\n[profiles.selected]\nmodel = "fixture-model"\n[profiles.other]\nmodel_reasoning_summary = "detailed"\n',+ "none",+ ],+ [+ 'model_reasoning_summary = "concise"\n[features]\nshell_tool = false\nunified_exec = false\n',+ "concise",+ true,+ ],+ [+ 'model_reasoning_summary = "concise"\nmodel_instructions_file = "profile-instructions.md"\nmodel_verbosity = "high"\nweb_search = "disabled"\n[features]\nshell_tool = false\nunified_exec = false\n',+ "concise",+ true,+ ],+ [+ 'model_reasoning_summary = "concise"\nmodel_instructions_file = "profile-instructions.md"\nmodel_catalog_json = "profile-catalog.json"\nexperimental_compact_prompt_file = "profile-compact.md"\nmodel_verbosity = "high"\nweb_search = "disabled"\n',+ "concise",+ ],+ [+ 'model_reasoning_summary = "concise"\n[features.code_mode]\nenabled = true\nexcluded_tool_namespaces = ["synthetic_tools"]\n',+ "concise",+ ],+ [+ 'model_reasoning_summary = "concise"\nmodel_instructions_file = "relative-instructions.md"\nmodel_verbosity = "high"\nweb_search = "disabled"\n',+ "concise",+ ],+ ];+ const saved = [+ "PYTHON",+ "PATH",+ "CODEX_SECURITY_GIT",+ "GIT_SSH_COMMAND",+ "GIT_CONFIG_GLOBAL",+ "CODEX_CLI_PATH",+ "CODEX_HOME",+ "CODEX_SECURITY_CONFIG_PATH",+ "CODEX_SECURITY_SCAN_DIR",+ "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",+ "OPENAI_API_KEY",+ "CODEX_API_KEY",+ "SYNTHETIC_GATEWAY_KEY",+ ].map((name) => [name, process.env[name]] as const);+ const originalSpawn = childProcess.spawn;+ try {+ delete process.env.OPENAI_API_KEY;+ delete process.env.CODEX_API_KEY;+ for (const [configuration, expected, commandAuth] of cases) {+ const fixture = await fakeCodexFixture(+ deniedWorkerPermissionProfile,+ true,+ { account: null, requiresOpenaiAuth: false },+ );+ const python = path.join(fixture.root, "selected venv", "bin", "python");+ const helperPython = path.join(+ fixture.root,+ "helper venv",+ "bin",+ "python",+ );+ process.env.PYTHON = python;+ const gitEnvironment = {+ PATH: path.join(fixture.root, "selected tools"),+ CODEX_SECURITY_GIT: path.join(fixture.root, "selected tools", "git"),+ GIT_SSH_COMMAND: "synthetic-ssh --fixture",+ GIT_CONFIG_GLOBAL: path.join(fixture.root, "operator.gitconfig"),+ };+ Object.assign(process.env, gitEnvironment);+ const configPath = path.join(fixture.root, "active scan config.toml");+ const codexHome = path.join(fixture.root, "scan home");+ const promptPath = path.join(fixture.root, "prompt.md");+ await mkdir(codexHome);+ await writeFile(+ path.join(codexHome, "config.toml"),+ `model = "fixture-inherited-model"+model_reasoning_effort = "medium"+model_provider = "synthetic"+[model_providers.synthetic]+name = "Synthetic gateway"+base_url = "https://gateway.example.test/v1"+wire_api = "responses"+${commandAuth ? "" : 'env_key = "SYNTHETIC_GATEWAY_KEY"'}${+ commandAuth+ ? `+[model_providers.synthetic.auth]+command = "./synthetic-auth"+cwd = ${JSON.stringify(path.join(codexHome, "helpers"))}+refresh_interval_ms = 2000+[otel.exporter.otlp-http.tls]+ca-certificate = ${JSON.stringify(path.join(codexHome, "tls", "ca.pem"))}+client-certificate = ${JSON.stringify(path.join(codexHome, "tls", "client.pem"))}+client-private-key = ${JSON.stringify(path.join(codexHome, "tls", "client.key"))}`+ : ""+ }`,+ );+ await writeFile(configPath, configuration!);+ await writeFile(+ promptPath,+ commandAuth+ ? "CAPTURE_SYNTHETIC_CODEX_CONFIG"+ : "synthetic worker configuration fixture",+ );+ process.env.CODEX_CLI_PATH = process.execPath;+ process.env.CODEX_HOME = codexHome;+ process.env.CODEX_SECURITY_CONFIG_PATH = configPath;+ process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH = path.join(+ fixture.root,+ "deep settings.toml",+ );+ await writeFile(+ process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH!,+ "[worker_runtime]\n",+ );+ const launches: {+ command?: string;+ args: readonly string[];+ environment?: NodeJS.ProcessEnv;+ markerPath: string;+ }[] = [];+ childProcess.spawn = ((+ command: string,+ args: readonly string[],+ options: SpawnOptions,+ ) => {+ const markerPath = path.join(+ fixture.root,+ `invocation-${launches.length}.json`,+ );+ const environment = {+ ...options!.env,+ FAKE_CODEX_MARKER: markerPath,+ FAKE_CODEX_PREFLIGHT_MARKER: markerPath,+ };+ launches.push({ command, args, environment, markerPath });+ return originalSpawn(+ command,+ command === process.execPath ||+ command === path.toNamespacedPath(process.execPath)+ ? [fixture.executablePath, ...args]+ : args,+ { ...options, env: environment },+ );+ }) as typeof childProcess.spawn;+ syncBuiltinESMExports();+ const settings = [+ { model: "gpt-5.6-sol", reasoningEffort: "xhigh" },+ { model: "gpt-6-astra", reasoningEffort: "ultra" },+ { model: "gpt-6.1-sol", reasoningEffort: "max" },+ { model: "gpt-6-sol", reasoningEffort: "high" },+ { model: "fixture-future-model", reasoningEffort: "future-effort" },+ // Omitted settings preserve the model and effort in the Codex home.+ {},+ ];+ const instructions = configuration.includes("model_instructions_file");+ const relative = configuration.includes("relative-instructions.md");+ const modelFiles = configuration.includes("model_catalog_json");+ const codeMode = configuration.includes("[features.code_mode]");+ const scanRoot = path.join(fixture.root, "parent-scan");+ const workerDirectory = path.join(scanRoot, "artifacts");+ await mkdir(workerDirectory, { recursive: true });+ process.env.CODEX_SECURITY_SCAN_DIR = scanRoot;+ await Promise.all(+ settings.map(async (_, index) => {+ await writeFile(+ path.join(fixture.root, `instructions-${index}.md`),+ `synthetic instructions ${index}`,+ );+ }),+ );+ const scanConfigPaths = await Promise.all(+ settings.map(async (_, index) => {+ if (!instructions && !codeMode) return configPath;+ const selected = path.join(fixture.root, `scan-${index}.toml`);+ await writeFile(+ selected,+ configuration+ .replace(+ '"profile-instructions.md"',+ JSON.stringify(+ path.join(fixture.root, `instructions-${index}.md`),+ ),+ )+ .replace(+ '"relative-instructions.md"',+ JSON.stringify(`../instructions-${index}.md`),+ )+ .replace(+ '"profile-catalog.json"',+ JSON.stringify(+ path.join(fixture.root, `catalog-${index}.json`),+ ),+ )+ .replace(+ '"profile-compact.md"',+ JSON.stringify(path.join(fixture.root, `compact-${index}.md`)),+ )+ .replace(+ '["synthetic_tools"]',+ JSON.stringify([`synthetic_tools_${index}`]),+ )+ .replace("enabled = true", `enabled = ${index % 2 === 0}`)+ .replace(+ 'model_verbosity = "high"',+ `model_verbosity = ${JSON.stringify(index % 2 === 0 ? "high" : "low")}`,+ )+ .replace(+ 'web_search = "disabled"',+ `web_search = ${JSON.stringify(index % 2 === 0 ? "disabled" : "cached")}`,+ ),+ );+ if (modelFiles && index % 2 === 0) {+ // SDK replay clears file-profile values before the worker TOML is written.+ const profile = `replay-${index}`;+ await writeFile(+ path.join(codexHome, `${profile}.config.toml`),+ await readFile(selected, "utf8"),+ );+ await writeCodexConfig(+ selected,+ resolveCodexProfile(+ await mergedCodexConfig(+ {+ codexOverrides: {+ profile,+ model_instructions_file: null,+ model_catalog_json: null,+ experimental_compact_prompt_file: null,+ },+ },+ codexHome,+ ),+ ),+ );+ }+ return selected;+ }),+ );+ const providerKeys = settings.map((_, index) =>+ index < 2 ? `synthetic-gateway-key-${index}` : undefined,+ );+ const executors = settings.map(+ (modelSettings) =>+ new CodexSdkWorkerExecutor({+ ...modelSettings,+ parentSandbox: trustedParentSandboxWithDenials,+ artifactContext: {+ pluginRoot: fixture.root,+ repoRoot: fixture.root,+ scanId: `fixture-scan-${modelSettings.model ?? "inherited"}`,+ pythonCommand: helperPython,+ },+ }),+ );+ // A running coordinator retains its settings if the source file changes.+ for (const kind of ["discovery", "dedup"] as const) {+ for (const resumeThreadId of [undefined, "fixture-resumed-thread"]) {+ launches.length = 0;+ await Promise.all(+ executors.map((executor, index) => {+ // Each concurrent launch snapshots its own scan environment.+ process.env.CODEX_SECURITY_CONFIG_PATH = scanConfigPaths[index];+ if (providerKeys[index] === undefined) {+ delete process.env.SYNTHETIC_GATEWAY_KEY;+ } else {+ process.env.SYNTHETIC_GATEWAY_KEY = providerKeys[index];+ }+ return executor.run({+ kind,+ promptPath,+ workingDirectory: workerDirectory,+ subagents: 0,+ resumeThreadId,+ artifactContext: {+ root: fixture.root,+ layout: kind === "dedup" ? "reducer" : "worker",+ ...(kind === "dedup"+ ? {+ deepReducer: {+ scanRoot: fixture.root,+ claimedWorkers: [],+ },+ }+ : {}),+ },+ signal: new AbortController().signal,+ });+ }),+ );+ const workerLaunches = launches.filter(+ ({ args }) => args[0] === "exec",+ );+ assert.equal(workerLaunches.length, settings.length);+ for (const [+ index,+ { model, reasoningEffort },+ ] of settings.entries()) {+ const workerLaunch = workerLaunches.find(({ args }) =>+ model === undefined+ ? !args.includes("--model")+ : args[args.indexOf("--model") + 1] === model,+ );+ assert.ok(workerLaunch, `missing worker launch for ${model}`);+ assert.equal(+ workerLaunch.command,+ process.platform === "win32"+ ? path.toNamespacedPath(process.execPath)+ : process.execPath,+ );+ assert.equal(+ workerLaunch.environment!.CODEX_CLI_PATH,+ process.execPath,+ );+ assert.equal(+ workerLaunch.environment!.CODEX_HOME,+ await realpath(codexHome),+ );+ assert.equal(+ workerLaunch.environment!.CODEX_SECURITY_CONFIG_PATH,+ scanConfigPaths[index],+ );+ assert.equal(+ workerLaunch.environment!.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,+ process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,+ );+ assert.deepEqual(+ JSON.parse(+ JSON.stringify(+ parseToml(workerPermissionProfileOverride(workerLaunch.args)!)+ .permissions,+ ),+ ),+ {+ codex_security_deep_scan_worker: deniedWorkerPermissionProfile,+ },+ );+ const invocation = await readJson(workerLaunch.markerPath);+ assert.equal(invocation.providerKey, providerKeys[index]);+ assertFlagPair(invocation.argv, "--cd", workerDirectory);+ if (relative) {+ const argument = (invocation.argv as string[]).find((value) =>+ value.startsWith("model_instructions_file="),+ );+ assert.ok(argument);+ const selected = JSON.parse(+ argument.slice("model_instructions_file=".length),+ );+ assert.equal(+ await readFile(path.resolve(workerDirectory, selected), "utf8"),+ `synthetic instructions ${index}`,+ );+ }+ if (commandAuth) {+ assert.equal(+ invocation.codexConfig,+ await readFile(path.join(codexHome, "config.toml"), "utf8"),+ );+ }+ assert.equal(workerLaunch.environment!.CODEX_API_KEY, undefined);+ assert.equal(+ process.env.SYNTHETIC_GATEWAY_KEY,+ providerKeys.at(-1),+ );+ const clearedFiles = modelFiles && index % 2 === 0;+ assertConfigOverrides(invocation.argv, {+ model_reasoning_summary: expected,+ model_catalog_json:+ modelFiles && !clearedFiles+ ? path.join(fixture.root, `catalog-${index}.json`)+ : undefined,+ experimental_compact_prompt_file:+ modelFiles && !clearedFiles+ ? path.join(fixture.root, `compact-${index}.md`)+ : undefined,+ model_instructions_file:+ instructions && !clearedFiles+ ? path.join(fixture.root, `instructions-${index}.md`)+ : undefined,+ model_verbosity: instructions+ ? index % 2 === 0+ ? "high"+ : "low"+ : undefined,+ web_search: instructions+ ? index % 2 === 0+ ? "disabled"+ : "cached"+ : undefined,++ "features.shell_tool": commandAuth ? false : undefined,+ "features.unified_exec": commandAuth ? false : undefined,+ });+ assert.deepEqual(+ invocation.argv.filter((arg: string) =>+ arg.startsWith("model_reasoning_effort="),+ ),+ reasoningEffort === undefined+ ? []+ : [`model_reasoning_effort=${JSON.stringify(reasoningEffort)}`],+ );+ if (model === undefined) {+ assert.equal(invocation.argv.includes("--model"), false);+ } else {+ assertFlagPair(invocation.argv, "--model", model);+ }+ if (configuration.includes('model = "native-model"')) {+ assert.equal(+ invocation.argv.some((arg: string) =>+ arg.startsWith("profile="),+ ),+ false,+ );+ }+ assert.equal(+ invocation.argv.includes("resume"),+ resumeThreadId !== undefined,+ );+ assert.equal(invocation.configPath, scanConfigPaths[index]);+ assert.partialDeepStrictEqual(+ invocation.gitEnvironment,+ gitEnvironment,+ );+ for (const [name, value] of Object.entries(gitEnvironment)) {+ assert.equal(process.env[name], value);+ }+ assert.equal(invocation.python, python);+ assertConfigOverrides(invocation.argv, {+ "mcp_servers.cs_artifacts.env.CODEX_SECURITY_PYTHON_COMMAND":+ helperPython,+ });+ assert.equal(process.env.PYTHON, python);+ assert.equal(+ invocation.deepConfigPath,+ process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,+ );+ assertReadOnlyWorkerPolicy(invocation.argv);+ assertWorkerSubagentPolicy(+ invocation.argv,+ 0,+ codeMode+ ? {+ enabled: index % 2 === 0,+ excluded_tool_namespaces: [`synthetic_tools_${index}`],+ }+ : undefined,+ );+ }+ for (const launch of launches.filter(({ args }) =>+ args.includes("app-server"),+ )) {+ const preflight = await readJson(launch.markerPath);+ assert.partialDeepStrictEqual(+ preflight.gitEnvironment,+ gitEnvironment,+ );+ assert.equal(+ workerPermissionProfileOverride(launch.args),+ workerPermissionProfileOverride(workerLaunches[0].args),+ );+ }+ for (const selected of new Set(scanConfigPaths)) {+ await writeFile(selected, 'model_reasoning_summary = "detailed"\n');+ }+ }+ }+ }+ } finally {+ childProcess.spawn = originalSpawn;+ syncBuiltinESMExports();+ for (const [name, value] of saved) restoreEnv(name, value);+ }+}diff --git a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.tsindex 1a3409317..d8dad3f70 100644--- a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts+++ b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts@@ -9,15 +9,15 @@ export function fakeCodexSource(): string {return `#!/usr/bin/env nodeimport { existsSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";-import { spawnSync } from "node:child_process";import { join } from "node:path";+import { spawnSync } from "node:child_process";const preflightProfile = process.env.FAKE_CODEX_PREFLIGHT_PROFILE ? JSON.parse(process.env.FAKE_CODEX_PREFLIGHT_PROFILE) : ${JSON.stringify(preflightProfile)};const preflightAllowed = ${JSON.stringify(preflightAllowed)};const accountResult = ${JSON.stringify(accountResult)};const preflightMarkerPath = process.env.FAKE_CODEX_PREFLIGHT_MARKER ?? ${JSON.stringify(preflightMarkerPath)};const temporaryEnvironment = Object.fromEntries(['TEMP', 'TMP'].map(name => [name, process.env[name]]));if (process.argv.includes('app-server')) {- const preflight = { argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env.LD_LIBRARY_PATH, cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), requests: [] };+ const preflight = { argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env["LD_LIBRARY_PATH"], cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerHeader: process.env.SYNTHETIC_HEADER_VALUE, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), requests: [] };writeFileSync(preflightMarkerPath, JSON.stringify(preflight));${jsonLineInputSource(` if (message.method === 'initialized') continue;if (message.method === 'config/read' || message.method === 'permissionProfile/list') {@@ -65,6 +65,7 @@ const profileIndex = process.argv.indexOf('--profile');const profileContents = profileIndex === -1 ? undefined : readFileSync(join(process.env.CODEX_HOME, process.argv[profileIndex + 1] + '.config.toml'), 'utf8');const openaiAuthentication = stdin.includes('CAPTURE_SYNTHETIC_OPENAI_AUTH') ? { OPENAI_API_KEY: process.env.OPENAI_API_KEY, CODEX_API_KEY: process.env.CODEX_API_KEY } : undefined;const bedrockAuthentication = stdin.includes('CAPTURE_SYNTHETIC_BEDROCK_AUTH') ? Object.fromEntries(JSON.parse(process.env.FAKE_CODEX_BEDROCK_ENV_KEYS).map((name) => [name, process.env[name]])) : undefined;+const codexConfig = stdin.includes('CAPTURE_SYNTHETIC_CODEX_CONFIG') ? readFileSync(join(process.env.CODEX_HOME, 'config.toml'), 'utf8') : undefined;const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'CODEX_MCP_NODE_PATH', 'CODEX_BROWSER_USE_NODE_PATH', 'CODEX_ELECTRON_RESOURCES_PATH', 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]]));const toolProbe = stdin.includes('CAPTURE_SYNTHETIC_RG') ? spawnSync('rg', ['--version'], { encoding: 'utf8' }) : undefined;if (toolProbe && toolProbe.status !== 0) throw toolProbe.error ?? new Error(toolProbe.stderr);@@ -74,7 +75,7 @@ const pythonRuntime = pythonProbe ? JSON.parse(pythonProbe.stdout) : undefined;const knowledgePath = stdin.includes('synthetic worker configuration fixture') ? process.env.CODEX_SECURITY_KNOWLEDGE_BASE : undefined;const knowledgeDocuments = knowledgePath === undefined ? undefined : Object.fromEntries(readdirSync(knowledgePath).map(name => [name, readFileSync(join(knowledgePath, name), 'utf8')]));const deepConfig = process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH ? readFileSync(process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, 'utf8') : undefined;-writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));+writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'HOME', 'NODE_OPTIONS', 'NODE_DEBUG', 'NODE_EXTRA_CA_CERTS', 'CODEX_MCP_NODE_PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, codexConfig, providerHeaders: Object.fromEntries(['SYNTHETIC_HEADER_VALUE', 'OPENROUTER_API_KEY', 'FIREWORKS_API_KEY'].map(name => [name, process.env[name]])), providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));if (stdin.includes('COMPLETE_THEN_HANG')) process.on('SIGTERM', () => { if (!stdin.includes('IGNORE_TERMINATION')) setTimeout(() => process.exit(0), 100); });if (stdin.includes('THREAD_START_CONFIG_ERROR')) { console.error('Error: thread/start: thread/start failed: agents.max_threads cannot be set when features.multi_agent_v2 is enabled (code -32600)'); process.exit(1); }@@ -156,9 +157,9 @@ export function workerRuntimeEnvironment(root: string, virtualenv?: string) {: "python3",PYTHONUTF8: "1",LD_LIBRARY_PATH:- (process.env.LD_LIBRARY_PATH === undefined+ (process.env["LD_LIBRARY_PATH"] === undefined? ""- : process.env.LD_LIBRARY_PATH + path.delimiter) ++ : process.env["LD_LIBRARY_PATH"] + path.delimiter) +path.join(root, "libraries"),DYLD_LIBRARY_PATH: path.join(root, "dylibs"),DYLD_FALLBACK_LIBRARY_PATH: path.join(root, "fallback-libraries"),@@ -181,7 +182,7 @@ export const externalImports: {];export function workerScanEnvironment(root: string, index: number) {- const { override } = externalImports[index];+ const { override } = externalImports[index]!;return {...(override === undefined? {}diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.tsindex 35022da9d..a72fe3509 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts@@ -1,3 +1,7 @@+import {+ mockWorkerSpawn,+ testWorkerCancellation,+} from "./deep_scan_cancellation_cases.ts";import {workerGitEnvironment,workerRuntimeEnvironment,@@ -56,6 +60,7 @@ import type {CodexWorkerRequest,DeepScanWorkerKind,} from "../src/deep-scan/types.js";+import { testWorkerSelectedProfileFiles } from "./deep_scan_profile_file_cases.ts";import { testConcurrentWorkerExecutableAliases } from "./deep_scan_executable_alias_cases.ts";import { testDeepScanContextSnapshots } from "./deep_scan_context_snapshot_cases.ts";import { workerTelemetryFixture } from "./deep_scan_worker_telemetry_fixture.ts";@@ -110,7 +115,16 @@ const ipcFrameError =try {await test("Deep worker lifecycle", async (t) => {- await check(t, testWorkerCancellation);+ await check(+ t,+ () =>+ testWorkerCancellation({+ CodexSdkWorkerExecutor,+ fakeCodexFixture,+ trustedParentSandbox,+ }),+ "worker cancellation",+ );await check(t, testWorkerTerminalEvents);await check(t, testCompletedWorkerSettlesWithoutWaitingForProcessExit);if (process.platform !== "win32") {@@ -127,6 +141,18 @@ try {await test("Deep worker runtime settings", async (t) => {await check(t, testLargeScopeTransport);await check(t, testOpenAiCredentialsReachWorker);+ await check(+ t,+ () =>+ testWorkerSelectedProfileFiles({+ CodexSdkWorkerExecutor,+ fakeCodexFixture,+ workerPermissionProfileOverride,+ assertReadOnlyWorkerPolicy,+ assertWorkerSubagentPolicy,+ }),+ "selected profile files",+ );await check(t, testUnsupportedProviderSnapshotFailsBeforeLaunch);await check(t,@@ -1350,6 +1376,20 @@ async function testUnsupportedProviderSnapshotFailsBeforeLaunch() {}}+function expectedProviderHeaders(environment?: NodeJS.ProcessEnv) {+ return Object.fromEntries(+ Object.entries(environment ?? {}).filter(+ ([name, value]) =>+ value !== undefined &&+ [+ "SYNTHETIC_HEADER_VALUE",+ "OPENROUTER_API_KEY",+ "FIREWORKS_API_KEY",+ ].includes(name),+ ),+ );+}+async function testWorkerRuntimeSettings() {const cases: [string, string | undefined][] = [["", undefined],@@ -1389,6 +1429,8 @@ async function testWorkerRuntimeSettings() {"CODEX_API_KEY","SYNTHETIC_GATEWAY_KEY","SYNTHETIC_HEADER_VALUE",+ "OPENROUTER_API_KEY",+ "FIREWORKS_API_KEY","CODEX_SQLITE_HOME","XDG_CACHE_HOME","LD_LIBRARY_PATH",@@ -1404,6 +1446,8 @@ async function testWorkerRuntimeSettings() {delete process.env.CODEX_API_KEY;delete process.env.SYNTHETIC_GATEWAY_KEY;delete process.env.SYNTHETIC_HEADER_VALUE;+ delete process.env.OPENROUTER_API_KEY;+ delete process.env.FIREWORKS_API_KEY;delete process.env.CODEX_SQLITE_HOME;for (const [configuration, expected] of cases) {for (const [name, value] of saved) {@@ -1568,6 +1612,8 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,],globScanMaxDepth: trustedParentSandboxWithDenials.globScanMaxDepth,};+ const headerKey =+ index % 2 === 0 ? "OPENROUTER_API_KEY" : "FIREWORKS_API_KEY";const provider = index === 0 ? undefined : "synthetic.gateway";const providerConfig =index === 0@@ -1577,7 +1623,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,base_url: `https://gateway-${index}.example.test/v1`,wire_api: "responses",env_key: "SYNTHETIC_GATEWAY_KEY",- env_http_headers: { "X-Synthetic": "SYNTHETIC_HEADER_VALUE" },+ env_http_headers: {+ "X-Synthetic": "SYNTHETIC_HEADER_VALUE",+ "X-Synthetic-Canonical": headerKey,+ },aws: {region: index % 2 === 0 ? "us-east-2" : "us-west-2",profile: `synthetic-scan-${index}`,@@ -1632,6 +1681,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,...workerScanEnvironment(fixture.root, index),SYNTHETIC_GATEWAY_KEY: providerKeys[index],SYNTHETIC_HEADER_VALUE: providerHeaders[index],+ [headerKey]: ` synthetic-canonical-header-${index}\t`,CODEX_SQLITE_HOME: path.join(fixture.root,`native-state-${index}`,@@ -1669,6 +1719,47 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,webSearch,skills,features,+ agents:+ index === 0+ ? undefined+ : {+ max_depth: index + 2,+ reviewer: {+ description: `Synthetic reviewer ${index}`,+ config_file: path.join(+ fixture.root,+ `reviewer-${index}.toml`,+ ),+ },+ },+ otel:+ index === 0+ ? telemetry.otel+ : {+ ...telemetry.otel,+ exporter: {+ "otlp-http": {+ endpoint: `https://telemetry-${index}.example.test/v1`,+ tls: {+ "ca-certificate": path.join(+ fixture.root,+ `tls-${index}`,+ "ca.pem",+ ),+ "client-certificate": path.join(+ fixture.root,+ `tls-${index}`,+ "client.pem",+ ),+ "client-private-key": path.join(+ fixture.root,+ `tls-${index}`,+ "client.key",+ ),+ },+ },+ },+ },telemetry,workerTelemetry,configuration: {@@ -1799,8 +1890,11 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,native_profile: entry.nativeProfile,environment: entry.environment,windows: { sandbox: entry.windowsSandbox },+ skills: entry.skills,+ otel: entry.otel,shell_environment_policy: entry.shellPolicy,features: entry.features,+ agents: entry.agents,}),},}),@@ -1898,6 +1992,20 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,// A running coordinator retains its settings if the source file changes.for (const kind of ["discovery", "dedup"] as const) {for (const resumeThreadId of [undefined, "fixture-resumed-thread"]) {+ const subagents = kind === "discovery" ? 3 : 0;+ const workerDirectories = settings.map((_, index) =>+ path.join(+ fixture.root,+ `worker-${index}`,+ kind,+ resumeThreadId ?? "fresh",+ ),+ );+ await Promise.all(+ workerDirectories.map((directory) =>+ mkdir(directory, { recursive: true }),+ ),+ );launches.length = 0;await Promise.all(executors.map((executor, index) => {@@ -1935,8 +2043,9 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,workerConfigurations[index].workerConfigPath,);return executor.run(- workerRequest(promptPath, fixture.root, {+ workerRequest(promptPath, workerDirectories[index], {kind,+ subagents,resumeThreadId,...(resumeThreadId? {@@ -2027,6 +2136,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,workerConfigurations[index].knowledgePath,);const invocation = await readJson(workerLaunch.markerPath);+ assertFlagPair(invocation.argv, "--cd", workerDirectories[index]);assert.equal(invocation.runtimeEnvironment.CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS,@@ -2044,7 +2154,6 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,) {const acl = windowsAcl(workerLaunch.markerPath);assert.ok(!acl.includes(";;;WD)"));- assertFlagPair(invocation.argv, "--cd", fixture.root);}for (const name of ["LD_LIBRARY_PATH",@@ -2099,6 +2208,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,path.join(fixture.root, `state-${index}`),);assert.equal(invocation.providerKey, providerKeys[index]);+ assert.deepEqual(+ invocation.providerHeaders,+ expectedProviderHeaders(workerConfigurations[index].environment),+ );assert.equal(invocation.mcpNodePath,selectedProvider.environment?.CODEX_MCP_NODE_PATH ??@@ -2114,6 +2227,8 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,);assert.equal(process.env.SYNTHETIC_GATEWAY_KEY, undefined);assert.equal(process.env.SYNTHETIC_HEADER_VALUE, undefined);+ assert.equal(process.env.OPENROUTER_API_KEY, undefined);+ assert.equal(process.env.FIREWORKS_API_KEY, undefined);assertConfigOverrides(invocation.argv, {...workerConfigurations[index].authentication,openai_base_url: workerConfigurations[index].endpoint,@@ -2129,6 +2244,20 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,web_search: workerConfigurations[index].webSearch,"windows.sandbox": workerConfigurations[index].windowsSandbox,});+ assertFlagPair(invocation.argv, "--cd", workerDirectories[index]);+ const selectedRuntime = parseToml(+ invocation.argv+ .filter((arg: string) => /^(?:skills|otel)=/.test(arg))+ .join("\n"),+ );+ for (const key of ["skills", "otel"] as const) {+ assert.deepEqual(+ selectedRuntime[key] === undefined+ ? undefined+ : JSON.parse(JSON.stringify(selectedRuntime[key])),+ workerConfigurations[index][key],+ );+ }assert.deepEqual(nativeConfigOverrides(invocation.argv).filter((override) =>/^projects[.=]/.test(override),@@ -2165,6 +2294,9 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,),{...workerConfigurations[index].telemetry,+ ...(workerConfigurations[index].otel === undefined+ ? {}+ : { otel: workerConfigurations[index].otel }),responses_api_metadata: {codex_security_surface: "plugin",codex_security_command: "scan",@@ -2352,9 +2484,9 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,...workerConfigurations[index].features,multi_agent_v2: {enabled: false,- max_concurrent_threads_per_session: 1,+ max_concurrent_threads_per_session: subagents + 1,},- enable_fanout: false,+ ...(subagents === 0 ? { enable_fanout: false } : {}),});assertConfigOverrides(invocation.argv, {...selectedProvider.nativePaths,@@ -2362,7 +2494,14 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,"mcp_servers.parent": undefined,});assertReadOnlyWorkerPolicy(invocation.argv);- assertWorkerSubagentPolicy(invocation.argv, 0);+ assertConfigOverrides(invocation.argv, {+ "agents.max_threads": subagents > 0 ? subagents : undefined,+ "agents.max_depth": workerConfigurations[index].agents?.max_depth,+ "agents.reviewer.description":+ workerConfigurations[index].agents?.reviewer.description,+ "agents.reviewer.config_file":+ workerConfigurations[index].agents?.reviewer.config_file,+ });}for (const launch of launches.filter(({ args }) =>args.includes("app-server"),@@ -2375,15 +2514,15 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,selectedProvider,"worker preflight must use the same scan environment",);+ const index = workerConfigurations.indexOf(selectedProvider);assert.deepEqual(preflight.gitEnvironment,expectedGitEnvironment(gitEnvironment,- nodePaths[workerConfigurations.indexOf(selectedProvider)],+ nodePaths[index],selectedProvider.environment,),);- const index = workerConfigurations.indexOf(selectedProvider);assert.equal(preflight.codexHome, await realpath(codexHome));assert.equal(preflight.stateDirectory,@@ -2397,21 +2536,28 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,});assert.equal(launch.environment!.CODEX_SECURITY_STATE_DIR,- path.join(- fixture.root,- `state-${workerConfigurations.indexOf(selectedProvider)}`,- ),+ path.join(fixture.root, `state-${index}`),);assert.equal(preflight.providerKey,selectedProvider.environment?.SYNTHETIC_GATEWAY_KEY,);assert.equal(- preflight.providerHeader,- selectedProvider.environment?.SYNTHETIC_HEADER_VALUE,+ preflight.cwd,+ await realpath(workerDirectories[index]),+ );+ assert.deepEqual(+ preflight.providerHeaders,+ expectedProviderHeaders(selectedProvider.environment),);assertConfigOverrides(preflight.argv, {openai_base_url: selectedProvider.endpoint,+ "skills.config.0.path": selectedProvider.skills?.config[0]?.path,+ "skills.config.0.enabled":+ selectedProvider.skills?.config[0]?.enabled,+ "skills.config.1.path": selectedProvider.skills?.config[1]?.path,+ "skills.config.1.enabled":+ selectedProvider.skills?.config[1]?.enabled,model_instructions_file: selectedProvider.instructionsFile,...selectedProvider.nativePaths,model_verbosity: selectedProvider.verbosity,@@ -2423,10 +2569,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,});assert.equal(preflight.cacheDirectory,- path.join(- fixture.root,- `cache-${workerConfigurations.indexOf(selectedProvider)} `,- ),+ path.join(fixture.root, `cache-${index} `),);assert.deepEqual(preflight.argv.filter((arg: string) =>@@ -2497,7 +2640,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,),writeFile(entry.deepPath,- '[worker_runtime.features]\nshell_tool = true\nunified_exec = true\nview_image = true\n[worker_runtime]\nsqlite_home = "changed"\nopenai_base_url = "https://changed-snapshot.example.test/v1"\nweb_search = "live"\nmodel_provider = "changed"\nnative_profile = "changed"\nmodel_instructions_file = "changed-instructions.md"\nmodel_verbosity = "changed"\nmodel_context_window = 999000\nmodel_auto_compact_token_limit = 888000\n[worker_runtime.shell_environment_policy]\ninherit = "all"\n[worker_runtime.shell_environment_policy.set]\nSYNTHETIC_SHELL_MARKER = "changed"\n[worker_runtime.windows]\nsandbox = "changed"\n[worker_runtime.environment]\nSYNTHETIC_GATEWAY_KEY = "changed"\nSYNTHETIC_HEADER_VALUE = "changed"\n[worker_runtime.analytics]\nenabled = false\n[worker_runtime.responses_api_metadata]\ncustom_tag = "changed"\n',+ '[worker_runtime.features]\nshell_tool = true\nunified_exec = true\nview_image = true\n[worker_runtime]\nsqlite_home = "changed"\nopenai_base_url = "https://changed-snapshot.example.test/v1"\nweb_search = "live"\nmodel_provider = "changed"\nnative_profile = "changed"\nmodel_instructions_file = "changed-instructions.md"\nmodel_verbosity = "changed"\nmodel_context_window = 999000\nmodel_auto_compact_token_limit = 888000\n[worker_runtime.shell_environment_policy]\ninherit = "all"\n[worker_runtime.shell_environment_policy.set]\nSYNTHETIC_SHELL_MARKER = "changed"\n[worker_runtime.windows]\nsandbox = "changed"\n[worker_runtime.environment]\nSYNTHETIC_GATEWAY_KEY = "changed"\nSYNTHETIC_HEADER_VALUE = "changed"\nOPENROUTER_API_KEY = "changed"\nFIREWORKS_API_KEY = "changed"\n[worker_runtime.analytics]\nenabled = false\n[worker_runtime.responses_api_metadata]\ncustom_tag = "changed"\n',),]),),@@ -3502,41 +3645,6 @@ async function testAbortPropagation() {});}-function mockWorkerSpawn(- executablePath: string,- onExec: (- child: ChildProcess,- args: readonly string[],- options: SpawnOptions,- ) => void,-) {- const previousPath = process.env.CODEX_CLI_PATH;- process.env.CODEX_CLI_PATH = process.execPath;- const originalSpawn = childProcess.spawn;- childProcess.spawn = ((- command: string,- args: readonly string[] = [],- options: SpawnOptions = {},- ) => {- const child = originalSpawn(- command,- command === process.execPath ||- command === path.toNamespacedPath(process.execPath)- ? [executablePath, ...args]- : args,- options,- );- if (args[0] === "exec") onExec(child, args, options);- return child;- }) as typeof childProcess.spawn;- syncBuiltinESMExports();- return () => {- restoreEnv("CODEX_CLI_PATH", previousPath);- childProcess.spawn = originalSpawn;- syncBuiltinESMExports();- };-}-async function testCompletedWorkerSettlesWithoutWaitingForProcessExit() {await completedWorkerSettlesWithoutWaitingForProcessExit();for (const kind of ["discovery", "dedup"] as const) {@@ -3877,17 +3985,19 @@ function workerPermissionProfileOverride(args: readonly string[]) {function assertWorkerSubagentPolicy(args: readonly string[],subagents: number,+ codeMode?: { enabled: boolean; excluded_tool_namespaces: string[] },) {assertConfigOverrides(args, {"features.multi_agent_v2.enabled": false,"features.multi_agent_v2.max_concurrent_threads_per_session": subagents + 1,"features.multi_agent": undefined,- "features.code_mode.excluded_tool_namespaces": undefined,+ "features.code_mode.excluded_tool_namespaces":+ codeMode?.excluded_tool_namespaces,...(subagents === 0? {"agents.max_threads": undefined,"features.enable_fanout": false,- "features.code_mode.enabled": undefined,+ "features.code_mode.enabled": codeMode?.enabled,}: {"agents.max_threads": subagents,@@ -3918,147 +4028,6 @@ async function withWorkerFixture<Result>(}}-async function testWorkerCancellation() {- const fixture = await fakeCodexFixture();- let worker: ChildProcess | undefined;- let workerSignal: AbortSignal | undefined;- let cancelDuringCleanup: (() => void) | undefined;- let timeout: NodeJS.Timeout | undefined;- const restoreSpawn = mockWorkerSpawn(- fixture.executablePath,- (child, args, options) => {- assertFlagPair(args, "--thread-source", "security_scan");- worker = child;- workerSignal = options.signal;- const kill = child.kill;- child.kill = function (...args: Parameters<ChildProcess["kill"]>) {- cancelDuringCleanup?.();- return kill.apply(this, args);- };- },- );- try {- const promptPath = path.join(fixture.root, "prompt.md");- const workingDirectory = path.join(fixture.root, "artifacts");- await mkdir(workingDirectory);- const executor = new CodexSdkWorkerExecutor({- parentSandbox: trustedParentSandbox,- artifactContext: {- pluginRoot: fixture.root,- repoRoot: fixture.root,- scanId: randomUUID(),- includePaths: ["api"],- },- });- const run = (controller: AbortController, onThreadStarted?: () => void) =>- executor.run({- kind: "discovery",- promptPath,- workingDirectory,- subagents: 0,- signal: controller.signal,- onThreadStarted,- artifactContext: { root: workingDirectory, layout: "worker" },- });- const preAborted = new AbortController();- const beforeStartup = new Error(- "coordinator canceled before worker startup",- );- preAborted.abort(beforeStartup);- await assert.rejects(- run(preAborted),- (error: Error) => error === beforeStartup,- );- assert.equal(worker, undefined);- assert.equal(- (await readdir(fixture.root)).some((name) => name.startsWith("scope-")),- false,- );- await assert.rejects(readFile(fixture.preflightMarkerPath), {- code: "ENOENT",- });- await assert.rejects(readFile(fixture.markerPath), { code: "ENOENT" });-- for (const prompt of [- "BLOCK_AFTER_START",- "COMPLETE_THEN_HANG",- "FAIL_THEN_HANG",- ]) {- await writeFile(promptPath, `${prompt}\n`);- const controller = new AbortController();- const cancellation = new Error(- "coordinator canceled its remaining workers",- );- // Exercise cancellation inside the real SDK's iterator cleanup, before kill returns.- cancelDuringCleanup =- prompt === "COMPLETE_THEN_HANG"- ? () => controller.abort(cancellation)- : undefined;- const deadline = new Promise<never>((_, reject) => {- timeout = setTimeout(- () => reject(new Error(`${prompt} worker did not settle`)),- 10_000,- );- });- const execution = Promise.race([- run(controller, () => {- if (prompt === "BLOCK_AFTER_START") controller.abort(cancellation);- }),- deadline,- ]);- if (prompt === "BLOCK_AFTER_START") {- await assert.rejects(- execution,- (error: Error) =>- error?.name === "AbortError" ||- /abort|SIGTERM/i.test(error?.message ?? ""),- );- assert(workerSignal);- assert.equal(workerSignal.aborted, true);- assert.equal(workerSignal.reason, cancellation);- } else {- if (prompt === "FAIL_THEN_HANG") {- await assert.rejects(execution, /fixture worker failed/);- controller.abort(cancellation);- } else {- const result = await execution;- assert.equal(result.threadId, "fixture-thread-id");- }- assert.equal(controller.signal.aborted, true);- assert(workerSignal);- assert.equal(workerSignal.aborted, false);- }- assert.equal(- (await readdir(fixture.root)).some((name) => name.startsWith("scope-")),- false,- );- assert.notEqual(workerSignal, controller.signal);- const currentWorker = worker as ChildProcess | undefined;- assert(currentWorker);- assert.equal(currentWorker.killed, true);- if (- currentWorker.exitCode === null &&- currentWorker.signalCode === null- ) {- await Promise.race([- new Promise<void>((resolve) =>- worker!.once("close", () => resolve()),- ),- deadline,- ]);- }- clearTimeout(timeout);- cancelDuringCleanup = undefined;- }- } finally {- clearTimeout(timeout);- cancelDuringCleanup = undefined;- if (worker && worker.exitCode === null && worker.signalCode === null)- worker.kill("SIGKILL");- restoreSpawn();- }-}-async function testWorkerTerminalEvents() {const fixture = await fakeCodexFixture();const previousPath = process.env.CODEX_CLI_PATH;diff --git a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.tsindex 7616108d2..0c4b55e76 100644--- a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts+++ b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts@@ -105,6 +105,7 @@ assert.deepEqual("CODEX_SECURITY_KNOWLEDGE_BASE","CODEX_SECURITY_CONFIG_PATH","CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",+ "CODEX_SECURITY_SCAN_DIR","CODEX_SECURITY_PLUGIN_ROOT","CODEX_SECURITY_SCAN_ROOT","CODEX_SECURITY_STATE_DIR",diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex f9979b479..5eb372e05 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -879,6 +879,24 @@ explicit saved scan ID. Exact-path `latest` lookup still works without Git.Repeat `--codex KEY=VALUE` for supported native settings. Quote strings as TOML:`--codex 'model_reasoning_effort="high"'`. Repeated or conflicting keys arerejected, including a `--model` or `--effort` flag plus its native equivalent.++To select a Codex file profile, put its settings in+`$CODEX_HOME/review.config.toml` (or `~/.codex/review.config.toml` when+`CODEX_HOME` is unset), then run:++```bash+npx @openai/codex-security scan . --codex 'profile="review"'+```++In the SDK, set `codexOverrides: { profile: "review" }`. In a project config,+set `codex.profile: review`. The profile file uses top-level Codex TOML keys.+Its settings override scanner defaults. Explicit scan settings take precedence.+Relative file paths, including `model_instructions_file`, resolve from the+profile directory. Saved launches retain the profile name and reload its settings.+Include custom provider definitions in the file so the scan+can use them from its isolated Codex home. An absent file contributes no+settings. Existing inline `profiles` tables still work.+Choose plugins with `--plugin-path`; native plugin and marketplace overrides arerejected. New and resumed Deep Scans require the current plugin's direct engine,worker provider snapshot, and isolated worker configuration capabilities. Updatediff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex c46188d38..3fd15df41 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -54,6 +54,7 @@ import {import {createProfileCodex,createProviderProfile,+ privateReplayOverrides,providerPreflightCommand,type ProviderProfile,} from "./provider-profile.js";@@ -75,7 +76,6 @@ import {shellEnvironmentReference,} from "./codex-prompt.js";import {- DEFAULT_CODEX_CONFIG,EXTERNAL_CODEX_PROVIDERS,inlineToml,isExternalModelProvider,@@ -83,10 +83,13 @@ import {mergedCodexConfig,resolveCodexProfile,resolveCommandAuthConfig,+ MODEL_FILE_SETTINGS,+ resolveNestedConfigPaths,scanApprovalPolicy,scanCyberAccessConfig,scanModelConfiguration,scanModelProvider,+ scanProviderEnvKey,structuredCodexConfig,type CodexSecurityConfig,type JsonObject,@@ -317,7 +320,10 @@ interface PreparedSession {sessionConfig: JsonObject;modelProvider: unknown;externalProvider:- | (typeof EXTERNAL_CODEX_PROVIDERS)[keyof typeof EXTERNAL_CODEX_PROVIDERS]+ | (Omit<+ (typeof EXTERNAL_CODEX_PROVIDERS)[keyof typeof EXTERNAL_CODEX_PROVIDERS],+ "env_key"+ > & { env_key: string })| null;apiKey: string | null;scanEnvironment: ProcessEnvironment;@@ -1518,7 +1524,10 @@ export class CodexSecurity {);await knowledgeBase.cleanup();}- const configuration = await mergedCodexConfig(this.config);+ const configuration = await mergedCodexConfig(+ this.config,+ scanCodexHome(this.#dependencies.environment),+ );const model = scanModelConfiguration(configuration);const modelProvider = scanModelProvider(configuration);validateScanCostLimit(options.maxCostUsd, model.model);@@ -1546,6 +1555,7 @@ export class CodexSecurity {modelProvider,hasCommandAuth(configuration),true,+ scanProviderEnvKey(configuration),),...model,...(typeof modelProvider === "string" ? { modelProvider } : {}),@@ -1967,6 +1977,7 @@ export class CodexSecurity {let knowledgeBase: PreparedKnowledgeBase | null = null;let costTracker: ScanCostTracker | null = null;let scanProgressTracker: ScanProgressTracker | null = null;+ let savedProviderProfile: ProviderProfile | undefined;let artifactRestorationFailure: OutputDirectoryError | null = null;let customValidationComplete = false;let completionCost: ScanCost | null = null;@@ -2123,6 +2134,7 @@ export class CodexSecurity {runtime.environment,options.auth,modelProvider,+ session.externalProvider?.env_key,),};for (const root of [@@ -2184,6 +2196,7 @@ export class CodexSecurity {runtime.environment,options.auth,modelProvider,+ session.externalProvider?.env_key,),),...(session.apiKey === null@@ -2480,6 +2493,60 @@ export class CodexSecurity {onError: reportTrackingError,});costTracker = tracker;+ // Saved launches reload the native file; preflight uses resolved values.+ const profileName = effectiveConfig["profile"];+ const inlineProfiles = effectiveConfig["profiles"];+ const fileProfile =+ typeof profileName === "string" &&+ !(isRecord(inlineProfiles) && isRecord(inlineProfiles[profileName]));+ const overrides = this.config.codexOverrides ?? {};+ const recipeConfig: JsonObject = {+ ...(fileProfile+ ? scanPreflightCodexConfig(overrides)+ : preflightConfig),+ approval_policy: approvalPolicy,+ };+ // Reruns allocate a new output directory; retain the original file origins.+ for (const key of MODEL_FILE_SETTINGS) {+ const value = workerRuntimeConfig[key];+ if (+ typeof value !== "string" ||+ (fileProfile && !(key in recipeConfig))+ )+ continue;+ recipeConfig[key] = value;+ const profiles = recipeConfig["profiles"];+ if (+ typeof profileName === "string" &&+ isRecord(profiles) &&+ isRecord(profiles[profileName]) &&+ typeof profiles[profileName][key] === "string"+ ) {+ recipeConfig["profiles"] = {+ ...profiles,+ [profileName]: { ...profiles[profileName], [key]: value },+ };+ }+ }+ if (fileProfile) {+ recipeConfig["profile"] = profileName;+ delete recipeConfig["skills"];+ // Reload inherited file settings, retaining explicit refinements omitted+ // from the readable recipe in the existing private replay snapshot.+ delete recipeConfig["model_providers"];+ const replayOverrides = privateReplayOverrides(overrides, recipeConfig);+ resolveNestedConfigPaths(replayOverrides, scanDir);+ if (+ options.resumeScanId === undefined &&+ Object.keys(replayOverrides).length > 0+ ) {+ savedProviderProfile = await createProviderProfile(+ codexSecurityCredentialHome(this.#dependencies.environment),+ replayOverrides,+ { replay: true },+ );+ }+ }const scanKnowledge =knowledgeBase === null ? undefined : options.knowledgeBaseSnapshot;const recipe = scanRecipe({@@ -2488,7 +2555,7 @@ export class CodexSecurity {mode,repositoryRevision: expectation.repositoryRevision,pluginVersion: runtime.plugin.version,- config: { ...preflightConfig, approval_policy: approvalPolicy },+ config: recipeConfig,failOnSeverity: options.failureSeverity,knowledgeBasePaths: knowledgeBase?.sources,maxCostUsd: options.maxCostUsd,@@ -2498,6 +2565,12 @@ export class CodexSecurity {cyberAccessProgram: options.cyberAccessProgram,ownerSuggestions: options.ownerSuggestions,});+ if (savedProviderProfile !== undefined) {+ recipe["providerProfile"] = {+ name: savedProviderProfile.name,+ home: "managed",+ };+ }if (options.scanPrompt?.trim()) recipe["requiresScanPrompt"] = true;recipe["scanInputs"] = scanInputIdentity(options.scanPrompt,@@ -2542,7 +2615,51 @@ export class CodexSecurity {userContext: options.scanPrompt,workflowId: options.workflowId,}),- );+ ).catch(async (error: unknown) => {+ const profile = savedProviderProfile;+ if (profile !== undefined) {+ // Registration can commit before cancellation or an output error.+ // Delete the snapshot only after confirming no saved recipe owns it.+ savedProviderProfile = undefined;+ try {+ const lookupOptions = {+ ...workbenchOptions,+ signal: undefined,+ };+ const { scans } = await workbench(lookupOptions, [+ "list-scans",+ "--scan-root",+ scanDir,+ ]);+ let referenced = false;+ for (const scan of scans as JsonObject[]) {+ if (scan["recipeAvailable"] === false) continue;+ const { recipe: savedRecipe } = await workbench(+ lookupOptions,+ [+ "get-scan-recipe",+ "--scan-id",+ scan["scanId"] as string,+ ],+ );+ if (+ isRecord(savedRecipe) &&+ isRecord(savedRecipe["providerProfile"]) &&+ savedRecipe["providerProfile"]["name"] === profile.name+ ) {+ referenced = true;+ break;+ }+ }+ if (!referenced) savedProviderProfile = profile;+ } catch {+ // An unavailable receipt cannot establish that cleanup is safe.+ }+ }+ throw error;+ });+ // The registered recipe now owns the private snapshot, including after completion.+ savedProviderProfile = undefined;const scanId = registration["scanId"];const resumeThreadId =options.resumeScanId === undefined@@ -3536,6 +3653,7 @@ export class CodexSecurity {for (const cleanup of await Promise.allSettled([knowledgeBase?.cleanup(),removeTargetPathsFile(targetPathsFile),+ savedProviderProfile?.cleanup(),])) {if (cleanup.status === "rejected") {warnCleanupFailed(options, cleanup.reason);@@ -3874,6 +3992,7 @@ export class CodexSecurity {: runtime.environment,auth,modelProvider,+ externalProvider?.env_key,),),),@@ -3925,7 +4044,12 @@ export class CodexSecurity {configuredCodexPath === undefined? undefined: this.#codexCommand().command;- let sdkEnvironment = definedEnvironment(withoutOpenAiApiKeys(environment));+ let sdkEnvironment = definedEnvironment({+ ...withoutOpenAiApiKeys(environment),+ ...(externalProvider === null+ ? {}+ : { [externalProvider.env_key]: apiKey! }),+ });if (process.platform === "win32" &&(configuredCodexPath === undefined ||@@ -4035,24 +4159,36 @@ export class CodexSecurity {};try {const requestedConfig = resolveCommandAuthConfig(- await mergedCodexConfig(this.config),- configuredCodexHome(this.#dependencies.environment),+ await mergedCodexConfig(+ this.config,+ scanCodexHome(this.#dependencies.environment),+ ),+ scanCodexHome(this.#dependencies.environment),);const commandAuth = hasCommandAuth(requestedConfig);const modelProvider = scanModelProvider(requestedConfig);const externalProvider =!commandAuth && isExternalModelProvider(modelProvider)- ? EXTERNAL_CODEX_PROVIDERS[modelProvider]+ ? {+ ...EXTERNAL_CODEX_PROVIDERS[modelProvider],+ env_key: scanProviderEnvKey(requestedConfig)!,+ }: null;let authentication = scanAuthentication(this.#dependencies.environment,options.auth,modelProvider,commandAuth,+ false,+ externalProvider?.env_key,);const apiKey =authentication.method === "api_key"- ? environmentApiKey(this.#dependencies.environment, modelProvider)+ ? environmentApiKey(+ this.#dependencies.environment,+ modelProvider,+ externalProvider?.env_key,+ ): null;const scanEnvironment = selectedScanEnvironment(commandAuth@@ -4060,6 +4196,7 @@ export class CodexSecurity {: this.#dependencies.environment,options.auth,modelProvider,+ externalProvider?.env_key,);if (this.#dependencies.prepareRuntime === undefined) {const credentialHome = await prepareCodexSecurityCredentialHome(@@ -4188,6 +4325,7 @@ export class CodexSecurity {runtime.codexHome,options.auth,modelProvider,+ externalProvider?.env_key,);if (options.safetyIdentifier !== undefined &&@@ -4255,7 +4393,11 @@ export class CodexSecurity {async #providerPreflightCommand(config?: JsonObject): Promise<CodexCommand> {return await providerPreflightCommand(this.#codexCommand(),- config ?? (await mergedCodexConfig(this.config)),+ config ??+ (await mergedCodexConfig(+ this.config,+ scanCodexHome(this.#dependencies.environment),+ )),);}@@ -4308,7 +4450,12 @@ export class CodexSecurity {): Promise<LocalScanInputs & { policyPaths: string[]; gitMetadataPaths: string[] }> {- policyCodexConfig(await mergedCodexConfig(this.config));+ policyCodexConfig(+ await mergedCodexConfig(+ this.config,+ scanCodexHome(this.#dependencies.environment),+ ),+ );const sources = await inspectSecurityPolicySources(target, signal);const protectedRoots = [...new Set([@@ -4409,10 +4556,12 @@ export class CodexSecurity {notifyObserver(options, "onOutputDirReady")(scanDir);}const revision = await repositoryRevision(local.repository, signal);- const { model } = scanModelConfiguration({- ...DEFAULT_CODEX_CONFIG,- ...this.config.codexOverrides,- });+ const { model } = scanModelConfiguration(+ await mergedCodexConfig(+ this.config,+ scanCodexHome(this.#dependencies.environment),+ ),+ );const workbenchOptions: WorkbenchCommandOptions = {python,pluginRoot,@@ -4712,6 +4861,7 @@ export class CodexSecurity {: this.#dependencies.environment,auth,modelProvider,+ scanProviderEnvKey(requestedConfig),);const codexHome = await realpath(codexSecurityCredentialHome(processEnvironment),@@ -5587,6 +5737,7 @@ export function scanAuthentication(modelProvider?: unknown,commandAuth = false,preflight = false,+ providerEnvKey?: string,): ScanAuthentication {if (!SCAN_AUTH_MODES.includes(auth)) {throw new TypeError(@@ -5613,14 +5764,22 @@ export function scanAuthentication(if (auth === "chatgpt" && !isExternalModelProvider(modelProvider)) {return { method: "stored_credentials", verified: false };}- const key = environmentApiKeyEntry(environment, modelProvider);+ const key = environmentApiKeyEntry(+ environment,+ modelProvider,+ providerEnvKey,+ );if (key === null && isExternalModelProvider(modelProvider)) {const provider = EXTERNAL_CODEX_PROVIDERS[modelProvider];if (preflight && auth === "auto") {- return { method: "api_key", source: provider.env_key, verified: false };+ return {+ method: "api_key",+ source: providerEnvKey ?? provider.env_key,+ verified: false,+ };}throw new AuthenticationRequiredError(- `Set ${provider.env_key} to run a scan through ${provider.name}.`,+ `Set ${providerEnvKey ?? provider.env_key} to run a scan through ${provider.name}.`,);}if (@@ -5660,8 +5819,16 @@ export async function runtimeScanAuthentication(codexHome: string,auth: ScanAuthMode = "auto",modelProvider?: unknown,+ providerEnvKey?: string,): Promise<ScanAuthentication> {- const authentication = scanAuthentication(environment, auth, modelProvider);+ const authentication = scanAuthentication(+ environment,+ auth,+ modelProvider,+ false,+ false,+ providerEnvKey,+ );if (authentication.method !== "stored_credentials") return authentication;try {@@ -5689,17 +5856,28 @@ export function selectedScanEnvironment(environment: ProcessEnvironment,auth: ScanAuthMode = "auto",modelProvider?: unknown,+ providerEnvKey?: string,): ProcessEnvironment {- const selectedProviderKey = isExternalModelProvider(modelProvider)+ const standardProviderKey = isExternalModelProvider(modelProvider)? EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key: null;+ const selectedProviderKey =+ standardProviderKey === null+ ? null+ : (providerEnvKey ?? standardProviderKey);const bedrockProvider = modelProvider === "amazon-bedrock";if (auth !== "chatgpt" && selectedProviderKey === null && !bedrockProvider) {return environment;}- return Object.fromEntries(- Object.entries(withoutOpenAiApiKeys(environment)).filter(([name]) => {+ const selected = Object.fromEntries(+ Object.entries(environment).filter(([name]) => {const key = name.toUpperCase();+ if (key === "OPENAI_API_KEY" || key === "CODEX_API_KEY") {+ return (+ selectedProviderKey !== null &&+ key === selectedProviderKey.toUpperCase()+ );+ }if (key === "OPENROUTER_API_KEY" ||key === "FIREWORKS_API_KEY" ||@@ -5707,12 +5885,16 @@ export function selectedScanEnvironment() {return (!bedrockProvider &&- (selectedProviderKey === null || key === selectedProviderKey)+ (selectedProviderKey === null ||+ key === standardProviderKey ||+ key === selectedProviderKey.toUpperCase()));}return true;}),);+ forwardExternalImportSetting(environment, selected);+ return selected;}function notifyObserver<Name extends ScanObserverName>(@@ -5734,24 +5916,21 @@ function notifyObserver<Name extends ScanObserverName>(function environmentApiKey(environment: ProcessEnvironment,modelProvider?: unknown,+ providerEnvKey?: string,): string | null {- return environmentApiKeyEntry(environment, modelProvider)?.value ?? null;+ return (+ environmentApiKeyEntry(environment, modelProvider, providerEnvKey)?.value ??+ null+ );}function environmentApiKeyEntry(environment: ProcessEnvironment,modelProvider?: unknown,-): {- source:- | "OPENAI_API_KEY"- | "CODEX_API_KEY"- | "OPENROUTER_API_KEY"- | "FIREWORKS_API_KEY"- | "CHEAPER_INFERENCE_API_KEY";- value: string;-} | null {+ providerEnvKey?: string,+): { source: string; value: string } | null {const keys = isExternalModelProvider(modelProvider)- ? [EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key]+ ? [providerEnvKey ?? EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key]: (["OPENAI_API_KEY", "CODEX_API_KEY"] as const);for (const requested of keys) {const value = environmentValue(environment, requested)?.trim();@@ -5904,6 +6083,7 @@ export function scanRuntimeCodexConfig(delete profile["default_permissions"];delete profile["permissions"];delete profile["sandbox_mode"];+ delete profile["allow_login_shell"];}}return {@@ -6045,6 +6225,8 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {"cli_daybreak","api_key_cyber_access_programs","api_key_model_discovery",+ "shell_tool",+ "unified_exec",]) {if (typeof value[key] === "boolean") result[key] = value[key];}@@ -6064,8 +6246,22 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {result["multi_agent_v2"] = sanitized;}}+ const codeMode = value["code_mode"];+ if (typeof codeMode === "boolean" || isRecord(codeMode)) {+ result["code_mode"] = structuredClone(codeMode) as JsonObject[string];+ }return result;};+ const copyWorkerSettings = (result: JsonObject, source: JsonObject): void => {+ for (const key of [+ ...MODEL_FILE_SETTINGS,+ "model_verbosity",+ "web_search",+ ]) {+ const value = source[key];+ if (typeof value === "string") result[key] = value;+ }+ };const executionConfig = (source: JsonObject): JsonObject => {const result: JsonObject = {};if (typeof source["daybreak"] === "boolean") {@@ -6081,6 +6277,7 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {const value = source[key];if (safeString(value)) result[key] = value;}+ copyWorkerSettings(result, source);const features = capabilityFeatures(source["features"]);if (Object.keys(features).length > 0) result["features"] = features;const skills = source["skills"];@@ -6117,6 +6314,7 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {safeProfileName(config["profile"]) ? config : resolved,);// Keep effective execution settings even when preflight filters the profile name.+ copyWorkerSettings(result, resolved);for (const key of ["model_reasoning_summary", "service_tier"]) {const value = resolved[key];if (safeString(value)) result[key] = value;@@ -6126,9 +6324,12 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {}const resolvedFeatures = capabilityFeatures(resolved["features"]);for (const key of [+ "code_mode","cli_daybreak","api_key_cyber_access_programs","api_key_model_discovery",+ "shell_tool",+ "unified_exec",]) {if (resolvedFeatures[key] !== undefined) {result["features"] = {@@ -6137,19 +6338,24 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {};}}- const selectedProfile = safeProfileName(config["profile"])- ? config["profile"]- : undefined;+ const profileName = config["profile"];+ const profiles = config["profiles"];+ const selectedProfile =+ safeProfileName(profileName) &&+ isRecord(profiles) &&+ isRecord(profiles[profileName])+ ? profileName+ : undefined;if (selectedProfile !== undefined) {result["profile"] = selectedProfile;}- const profiles = config["profiles"];if (isRecord(profiles)) {const sanitized: JsonObject = {};for (const [name, profile] of Object.entries(profiles)) {if (!safeProfileName(name) || !isRecord(profile)) continue;const projected = executionConfig(profile as JsonObject);- if (Object.keys(projected).length === 0) continue;+ if (Object.keys(projected).length === 0 && name !== selectedProfile)+ continue;sanitized[name] = projected;}if (Object.keys(sanitized).length > 0) result["profiles"] = sanitized;@@ -6231,6 +6437,7 @@ function selectedWorkerRuntimeConfig(const provider =typeof selectedProvider === "string" ? selectedProvider : undefined;const resolved = resolveCodexProfile(config);+ resolveNestedConfigPaths(resolved, workingDirectory);const providers = resolved["model_providers"];const providerEnvironmentNames = isRecord(providers)? Object.values(providers)@@ -6259,12 +6466,7 @@ function selectedWorkerRuntimeConfig(}),);// Workers use separate directories; preserve the parent scan's native paths.- for (const key of [- "model_instructions_file",- "experimental_compact_prompt_file",- "model_catalog_json",- "sqlite_home",- ]) {+ for (const key of [...MODEL_FILE_SETTINGS, "sqlite_home"]) {const file = resolved[key];if (typeof file === "string") {resolved[key] = resolve(workingDirectory, expandHome(file, environment));diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 1f4b4dee5..abda71ca0 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -3,7 +3,10 @@ import { classificationRunsSchema } from "./severity-review.js";import { workbenchArgs } from "./workbench-arguments.js";import { listenForAbort } from "./cli-signals.js";import { appServerCyberAccessProgram } from "./cli-daybreak.js";-import { withCodexPreflightLock } from "./provider-profile.js";+import {+ restoreProviderProfile,+ withCodexPreflightLock,+} from "./provider-profile.js";import { isNonEmptyString, notify, parseJson } from "./value.js";import { compareTimestamps } from "./timestamps.js";@@ -182,9 +185,11 @@ import {resolveCommandAuthConfig,resolveCodexProfile,mergedCodexConfig,+ readCodexFileProfile,scanModel,scanModelConfiguration,scanModelProvider,+ scanProviderEnvKey,writeCodexConfig,type CodexSecurityConfig,type ExternalModelProvider,@@ -1627,6 +1632,7 @@ export async function runCodexSkillCommand(codexHome,output.auth,provider,+ providerEnvKey,);if (output.appServer !== undefined) {const controller = new AbortController();@@ -2664,6 +2670,7 @@ export async function main(: undefined,},dependencies.currentDirectory(),+ dependencies.environment,);scanArguments.resumeScanId = saved["scanId"];scanArguments.outputDir = resolveCliPath(@@ -2824,6 +2831,7 @@ export async function main(),},dependencies.currentDirectory(),+ dependencies.environment,);scanArguments.verbose = options.verbose;scanArguments.showCost = options.showCost;@@ -4448,6 +4456,14 @@ export async function main(try {if (argumentError !== undefined) return fail(argumentError, 2);const directory = dependencies.currentDirectory();+ const codexOverrides = await parseScanCodexOverrides(+ options.codex,+ options.model,+ options.effort,+ options.provider,+ undefined,+ scanCodexHome(dependencies.environment),+ );const outcome = await withTerminalErrorsHandled(errorOutput, () =>runPolicyCommand({@@ -4455,12 +4471,7 @@ export async function main(config: {pluginPath: options.pluginPath,pythonPath: options.python,- codexOverrides: parseCodexOverrides(- options.codex,- options.model,- options.effort,- options.provider,- ),+ codexOverrides,},generation: {auth: options.auth,@@ -4484,20 +4495,23 @@ export async function main(dependencies.createPolicySecurity ??((config) =>new CodexSecurity(config, undefined, { surface: "cli" })),- chooseAuthentication: (config, auth, signal) =>- chooseInteractiveAuthentication(+ chooseAuthentication: async (config, auth, signal) => {+ const effectiveConfig = await mergedCodexConfig(+ config,+ scanCodexHome(dependencies.environment),+ );+ if (hasCommandAuth(effectiveConfig)) return auth;+ return await chooseInteractiveAuthentication({auth,- provider: scanModelProvider({- ...DEFAULT_CODEX_CONFIG,- ...config.codexOverrides,- }),+ provider: scanModelProvider(effectiveConfig),command: "policy",signal,},errorOutput,dependencies,- ),+ );+ },prompt:dependencies.policyPrompt ??createTerminalPrompt(errorOutput),@@ -4747,12 +4761,13 @@ export async function main(failureSeverity: options.failOnSeverity,maxCostUsd: options.maxCost,maxTimeMinutes: options.maxTime,- codexOverrides: parseCodexOverrides(+ codexOverrides: await parseScanCodexOverrides(options.codex,options.model,options.effort,options.provider,project?.input.codex,+ scanCodexHome(dependencies.environment),),},directory,@@ -5375,12 +5390,13 @@ export async function main(...pickScanSettings({ ...options, workers: undefined }),knowledgeBasePaths: options.knowledgeBase,maxCostUsd: options.maxCost,- codexOverrides: parseCodexOverrides(+ codexOverrides: await parseScanCodexOverrides(options.codex,options.model,options.effort,options.provider,project?.input.codex,+ scanCodexHome(dependencies.environment),),},directory,@@ -5419,7 +5435,12 @@ export async function main(const candidate = new ScanDashboard(errorOutput, {repository,presentation: "components",- model: scanModelConfiguration(await mergedCodexConfig(config)),+ model: scanModelConfiguration(+ await mergedCodexConfig(+ config,+ scanCodexHome(dependencies.environment),+ ),+ ),mode: settings.mode,maxCostUsd: settings.maxCostUsd,showCost: options.showCost,@@ -5695,12 +5716,13 @@ export async function main(config: {codexOverrides: mergeCodexOverrides(resolved.config.codexOverrides,- parseCodexOverrides(+ await parseScanCodexOverrides(options.codex,options.model,options.effort,options.provider,project?.input.codex,+ scanCodexHome(dependencies.environment),),),pluginPath: options.pluginPath,@@ -5775,6 +5797,7 @@ export async function main(: undefined,},currentDirectory,+ dependencies.environment,);const security = dependencies.createSecurity({pluginPath: options.pluginPath,@@ -6841,7 +6864,10 @@ export async function main();const resolved = resolveScanSettings(project, {}, directory);deepScanOptions(resolved.options);- const codex = await mergedCodexConfig(resolved.config);+ const codex = await mergedCodexConfig(+ resolved.config,+ scanCodexHome(dependencies.environment),+ );const deep =resolved.options.mode === "deep"? await resolveDeepScanConfig(@@ -7418,6 +7444,7 @@ async function prepareScanArgumentsFromRecipe("scanPrompt" | "scanPromptFile" | "validationPromptFile">,directory: string,+ environment: CliDependencies["environment"],): Promise<ScanArguments> {if (recipe === undefined || !isJsonObject(recipe)) {throw new CodexSecurityError(@@ -7595,6 +7622,11 @@ async function prepareScanArgumentsFromRecipe("This scan used additional instructions. The --scan-prompt-file must not be empty.",);}+ const replayConfig = await restoreProviderProfile(+ config,+ recipe["providerProfile"],+ environment,+ );return {repository,auth: auth.data ?? DEFAULT_SCAN_AUTH,@@ -7622,9 +7654,9 @@ async function prepareScanArgumentsFromRecipe(mode,...deepScan.data,archiveExisting: false,- codexOverrides: Object.hasOwn(config, "approval_policy")- ? config- : { ...config, approval_policy: "never" },+ codexOverrides: Object.hasOwn(replayConfig, "approval_policy")+ ? replayConfig+ : { ...replayConfig, approval_policy: "never" },failureSeverity: threshold.data,maxCostUsd,maxTimeMinutes: maxTimeMinutes.data,@@ -8709,7 +8741,7 @@ async function runSkill(: { model_providers: { [provider]: providerConfiguration } }),},),- configuredCodexHome(options.environment ?? dependencies.environment),+ scanCodexHome(options.environment ?? dependencies.environment),);const directory = options.directory ?? dependencies.currentDirectory();const contextFile =@@ -9648,10 +9680,19 @@ async function executeScan(codexOverrides: arguments_.codexOverrides,};const selectedProfileName = config.codexOverrides?.["profile"];- const effectiveConfiguration = {- ...DEFAULT_CODEX_CONFIG,- ...config.codexOverrides,- };+ const inlineProfiles = config.codexOverrides?.["profiles"];+ // Saved recipes keep their existing validation path; file profiles need+ // an early merge so CLI reporting reflects the selected file.+ const effectiveConfiguration =+ typeof selectedProfileName === "string" &&+ (inlineProfiles === undefined ||+ !isJsonObject(inlineProfiles) ||+ !isJsonObject(inlineProfiles[selectedProfileName] ?? null))+ ? await mergedCodexConfig(+ config,+ scanCodexHome(dependencies.environment),+ )+ : { ...DEFAULT_CODEX_CONFIG, ...config.codexOverrides };({ model: effectiveModel, reasoningEffort: effectiveReasoningEffort } =scanModelConfiguration(effectiveConfiguration));const resolvedConfiguration = resolveCodexProfile(effectiveConfiguration);@@ -9715,6 +9756,7 @@ async function executeScan(provider,hasCommandAuth(effectiveConfiguration),arguments_.dryRun,+ scanProviderEnvKey(effectiveConfiguration),);diagnostic("scan.configuration", {cli_version: VERSION,@@ -9754,7 +9796,7 @@ async function executeScan(repository: resolveCliPath(directory, repository),mode: arguments_.mode,showCost,- model: scanModelConfiguration(await mergedCodexConfig(config)),+ model: scanModelConfiguration(effectiveConfiguration),...(arguments_.maxCostUsd === undefined? {}: { maxCostUsd: arguments_.maxCostUsd }),@@ -11264,6 +11306,52 @@ function resolveCliScope(};}+async function parseScanCodexOverrides(+ values: readonly string[],+ model: string | undefined,+ effort: ModelCliOptions["effort"],+ provider: "openai" | "amazon-bedrock" | ExternalModelProvider | undefined,+ defaults: JsonObject | undefined,+ profileHome: string,+): Promise<JsonObject> {+ if (!isExternalModelProvider(provider) && provider !== "amazon-bedrock") {+ return parseCodexOverrides(values, model, effort, provider, defaults);+ }+ const explicit = parseCodexOverrides(values, model, effort);+ const overrides = mergeCodexOverrides(defaults ?? {}, explicit);+ const profile = await readCodexFileProfile(overrides, profileHome);+ const result = parseCodexOverrides(+ values,+ model,+ effort,+ provider,+ mergeCodexOverrides(profile, defaults ?? {}),+ );+ const providers = profile["model_providers"];+ if (+ isExternalModelProvider(provider) &&+ isJsonObject(providers) &&+ isJsonObject(providers[provider])+ ) {+ // Fill missing defaults without replacing file settings or combining+ // native command auth with the generated env-key definition.+ const generated: JsonObject = { ...EXTERNAL_CODEX_PROVIDERS[provider] };+ for (const key of Object.keys(providers[provider])) delete generated[key];+ if (providers[provider]["auth"] !== undefined) delete generated["env_key"];+ delete result["model_providers"];+ if (Object.keys(generated).length > 0) {+ result["model_providers"] = { [provider]: generated };+ }+ if (explicit["model_providers"] !== undefined) {+ result["model_providers"] = mergeCodexOverrides(+ (result["model_providers"] as JsonObject | undefined) ?? {},+ explicit["model_providers"] as JsonObject,+ );+ }+ }+ return result;+}+export function parseCodexOverrides(values: readonly string[],model?: string,diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.tsindex f6076d578..df7c6ea9e 100644--- a/sdk/typescript/src/component-scan.ts+++ b/sdk/typescript/src/component-scan.ts@@ -6,6 +6,7 @@ import {CodexSecurity,DEFAULT_DEPENDENCIES,scanAuthentication,+ scanCodexHome,selectedScanEnvironment,type CodexSecuritySurface,type ScanAuthentication,@@ -21,6 +22,7 @@ import {hasCommandAuth,mergedCodexConfig,scanModelProvider,+ scanProviderEnvKey,type CodexSecurityConfig,} from "./config.js";import type {@@ -144,10 +146,26 @@ export async function runComponentScans(let environment = options.environment;if (auth !== undefined && auth !== "auto") {const source = environment ?? process.env;- const configuration = await mergedCodexConfig(options.config ?? {});+ const configuration = await mergedCodexConfig(+ options.config ?? {},+ scanCodexHome(source),+ );const provider = scanModelProvider(configuration);- scanAuthentication(source, auth, provider, hasCommandAuth(configuration));- environment = selectedScanEnvironment(source, auth, provider);+ const providerEnvKey = scanProviderEnvKey(configuration);+ scanAuthentication(+ source,+ auth,+ provider,+ hasCommandAuth(configuration),+ false,+ providerEnvKey,+ );+ environment = selectedScanEnvironment(+ source,+ auth,+ provider,+ providerEnvKey,+ );}const repository = await normalizeRepository(options.repository,diff --git a/sdk/typescript/src/config.ts b/sdk/typescript/src/config.tsindex 167fb54ad..7d18370bc 100644--- a/sdk/typescript/src/config.ts+++ b/sdk/typescript/src/config.ts@@ -1,5 +1,5 @@import { randomUUID } from "node:crypto";-import { mkdir, open, rename, unlink } from "node:fs/promises";+import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";import { dirname, join, resolve } from "node:path";import type { CyberAccessProgram } from "@openai/codex-sdk";import { parse, stringify } from "smol-toml";@@ -60,6 +60,12 @@ export function isExternalModelProvider();}+export const MODEL_FILE_SETTINGS = [+ "model_instructions_file",+ "model_catalog_json",+ "experimental_compact_prompt_file",+] as const;+export const DEFAULT_CODEX_CONFIG: Readonly<JsonObject> = Object.freeze({approval_policy: "on-request",approvals_reviewer: "auto_review",@@ -116,6 +122,19 @@ export function scanModelProvider(config: Readonly<JsonObject>): unknown {return selectedProfile?.["model_provider"] ?? config["model_provider"];}+/** @internal Use the selected native provider's configured credential key. */+export function scanProviderEnvKey(+ config: Readonly<JsonObject>,+): string | undefined {+ const selected = scanModelProvider(config);+ if (!isExternalModelProvider(selected)) return undefined;+ const providers = resolveCodexProfile(config)["model_providers"];+ const provider = isObject(providers) ? providers[selected] : undefined;+ return isObject(provider) && typeof provider["env_key"] === "string"+ ? provider["env_key"]+ : EXTERNAL_CODEX_PROVIDERS[selected].env_key;+}+/** @internal Native Codex validates the auth table, including invalid selections. */export function hasCommandAuth(config: Readonly<JsonObject>): boolean {const selected = scanModelProvider(config);@@ -239,74 +258,132 @@ export function scanCyberAccessConfig(};}-export async function mergedCodexConfig(- config: CodexSecurityConfig,+/** @internal Read file-profile settings before wrapper defaults or CLI model validation. */+export async function readCodexFileProfile(+ overrides: JsonObject,+ profileHome?: string,): Promise<JsonObject> {- if (config.codexOverrides !== undefined && !isObject(config.codexOverrides)) {- throw new ConfigurationError("codexOverrides must be an object.");- }- validateOverrideKeys(config.codexOverrides ?? {});- const overrides = structuredClone(config.codexOverrides ?? {});- validateOverrides(overrides);- const agents = overrides["agents"];- if (isObject(agents) && "max_threads" in agents) {- throw new ConfigurationError(- "The selected Codex Security plugin requires native multi-agent v2; " +- "agents.max_threads is a legacy v1 setting. Use " +- "features.multi_agent_v2.max_concurrent_threads_per_session instead.",- );+ let nativeProfile: JsonObject = {};+ const profileName = overrides["profile"];+ if (profileName != null && typeof profileName !== "string") {+ throw new ConfigurationError("Codex profile must be a name.");}- const features = overrides["features"];- if (isObject(features) && "multi_agent_v2" in features) {- const multiAgentV2 = features["multi_agent_v2"];- if (!isObject(multiAgentV2)) {- throw new ConfigurationError(- "The selected Codex Security plugin requires native multi-agent v2; " +- "features.multi_agent_v2 must remain a table with enabled = true.",- );+ if (+ profileHome !== undefined &&+ typeof profileName === "string" &&+ selectedScanProfile(overrides) === undefined+ ) {+ if (!/^[A-Za-z0-9_-]+$/u.test(profileName)) {+ throw new ConfigurationError("Codex profile must be a plain name.");}- if ("enabled" in multiAgentV2 && multiAgentV2["enabled"] !== true) {+ try {+ nativeProfile = parse(+ await readFile(join(profileHome, `${profileName}.config.toml`), "utf8"),+ ) as JsonObject;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {+ throw new ConfigurationError(+ `Could not read Codex profile ${profileName}.`,+ {+ cause: error,+ },+ );+ }+ }+ if ("profile" in nativeProfile || "profiles" in nativeProfile) {throw new ConfigurationError(- "The selected Codex Security plugin requires native multi-agent v2; " +- "features.multi_agent_v2.enabled cannot be disabled.",+ `Codex profile ${profileName} contains legacy profile settings.`,);}+ validateOverrideKeys(nativeProfile);+ validateOverrides(nativeProfile);+ // CLI overrides otherwise resolve this file against the scan directory.+ for (const key of [...MODEL_FILE_SETTINGS, "sqlite_home", "log_dir"]) {+ resolveConfigPath(nativeProfile, key, profileHome);+ }+ resolveNestedConfigPaths(nativeProfile, profileHome);+ normalizeLegacyWindowsSandboxOverride(nativeProfile);}+ return nativeProfile;+}- const profiles = Object.entries(- (overrides["profiles"] ?? {}) as Record<string, JsonObject>,- );- for (const [name, profile] of profiles) {- const profileAgents = profile["agents"];- if (isObject(profileAgents) && "max_threads" in profileAgents) {- throw new ConfigurationError(- `The selected Codex Security plugin requires native multi-agent v2; profile ${name} agents.max_threads is a legacy v1 setting.`,- );+function resolveConfigPath(+ config: JsonObject,+ key: string,+ directory: string,+): void {+ const path = config[key];+ if (typeof path === "string" && !/^~(?:[/\\]|$)/u.test(path)) {+ config[key] = resolve(directory, path);+ }+}++/** @internal Keep agent, skill, and TLS file paths anchored to their config directory. */+export function resolveNestedConfigPaths(+ config: JsonObject,+ directory: string,+): void {+ const agents = config["agents"];+ if (isObject(agents)) {+ for (const agent of Object.values(agents)) {+ if (isObject(agent)) resolveConfigPath(agent, "config_file", directory);}- const profileFeatures = profile["features"];- if (!isObject(profileFeatures) || !("multi_agent_v2" in profileFeatures)) {- continue;+ }+ const skills = config["skills"];+ if (isObject(skills) && Array.isArray(skills["config"])) {+ for (const skill of skills["config"]) {+ if (!isObject(skill)) continue;+ resolveConfigPath(skill, "path", directory);}- const profileV2 = profileFeatures["multi_agent_v2"];- if (- !isObject(profileV2) ||- ("enabled" in profileV2 && profileV2["enabled"] !== true)- ) {- throw new ConfigurationError(- `The selected Codex Security plugin requires native multi-agent v2; profile ${name} features.multi_agent_v2 cannot be disabled.`,- );+ }++ const otel = config["otel"];+ if (!isObject(otel)) return;+ for (const key of ["exporter", "trace_exporter", "metrics_exporter"]) {+ const exporter = otel[key];+ if (!isObject(exporter)) continue;+ for (const configuration of Object.values(exporter)) {+ if (!isObject(configuration) || !isObject(configuration["tls"])) continue;+ const tls = configuration["tls"];+ for (const field of [+ "ca-certificate",+ "client-certificate",+ "client-private-key",+ ]) {+ resolveConfigPath(tls, field, directory);+ }}}+}++export async function mergedCodexConfig(+ config: CodexSecurityConfig,+ profileHome?: string,+): Promise<JsonObject> {+ if (config.codexOverrides !== undefined && !isObject(config.codexOverrides)) {+ throw new ConfigurationError("codexOverrides must be an object.");+ }+ validateOverrideKeys(config.codexOverrides ?? {});+ const overrides = structuredClone(config.codexOverrides ?? {});+ validateOverrides(overrides);normalizeLegacyWindowsSandboxOverride(overrides);- for (const [, profile] of profiles) {- normalizeLegacyWindowsSandboxOverride(profile);+ const nativeProfile = await readCodexFileProfile(overrides, profileHome);+ const profiles = overrides["profiles"];+ if (isObject(profiles)) {+ for (const profile of Object.values(profiles)) {+ if (isObject(profile)) {+ normalizeLegacyWindowsSandboxOverride(profile);+ }+ }}const defaults: JsonObject = structuredClone(DEFAULT_CODEX_CONFIG);- if (scanModelProvider(overrides) === "amazon-bedrock") {+ const effectiveOverrides = deepMerge(nativeProfile, overrides);+ validateNativeMultiAgentV2Overrides(effectiveOverrides);+ if (scanModelProvider(effectiveOverrides) === "amazon-bedrock") {// Bedrock models can reject reasoning.summary before the scan starts.defaults["model_reasoning_summary"] = "none";}- return deepMerge(defaults, overrides);+ return deepMerge(defaults, effectiveOverrides);}/** @internal Preserve existing native Windows backend selections. */@@ -338,8 +415,6 @@ export async function writeCodexConfig(path: string,config: JsonObject,): Promise<void> {- const parent = dirname(path);- await mkdir(parent, { recursive: true, mode: 0o700 });let contents: string;try {contents = stringify(config);@@ -348,6 +423,16 @@ export async function writeCodexConfig(cause: error,});}+ await writePrivateConfig(path, contents);+}++/** @internal Write private configuration without changing its serialized contents. */+export async function writePrivateConfig(+ path: string,+ contents: string,+): Promise<void> {+ const parent = dirname(path);+ await mkdir(parent, { recursive: true, mode: 0o700 });const temporary = join(parent, `.${randomUUID()}.config.toml.tmp`);let created = false;try {@@ -434,6 +519,64 @@ function validateOverrides(overrides: JsonObject): void {}}+function validateNativeMultiAgentV2Overrides(overrides: JsonObject): void {+ const agents = overrides["agents"];+ if (isObject(agents) && "max_threads" in agents) {+ throw new ConfigurationError(+ "The selected Codex Security plugin requires native multi-agent v2; " ++ "agents.max_threads is a legacy v1 setting. Use " ++ "features.multi_agent_v2.max_concurrent_threads_per_session instead.",+ );+ }+ const features = overrides["features"];+ if (isObject(features)) {+ if ("multi_agent_v2" in features) {+ const multiAgentV2 = features["multi_agent_v2"];+ if (!isObject(multiAgentV2)) {+ throw new ConfigurationError(+ "The selected Codex Security plugin requires native multi-agent v2; " ++ "features.multi_agent_v2 must remain a table with enabled = true.",+ );+ }+ if ("enabled" in multiAgentV2 && multiAgentV2["enabled"] !== true) {+ throw new ConfigurationError(+ "The selected Codex Security plugin requires native multi-agent v2; " ++ "features.multi_agent_v2.enabled cannot be disabled.",+ );+ }+ }+ }++ const profiles = overrides["profiles"];+ if (!isObject(profiles)) {+ return;+ }+ for (const [name, profile] of Object.entries(profiles)) {+ if (!isObject(profile)) {+ continue;+ }+ const profileAgents = profile["agents"];+ if (isObject(profileAgents) && "max_threads" in profileAgents) {+ throw new ConfigurationError(+ `The selected Codex Security plugin requires native multi-agent v2; profile ${name} agents.max_threads is a legacy v1 setting.`,+ );+ }+ const profileFeatures = profile["features"];+ if (!isObject(profileFeatures) || !("multi_agent_v2" in profileFeatures)) {+ continue;+ }+ const profileV2 = profileFeatures["multi_agent_v2"];+ if (+ !isObject(profileV2) ||+ ("enabled" in profileV2 && profileV2["enabled"] !== true)+ ) {+ throw new ConfigurationError(+ `The selected Codex Security plugin requires native multi-agent v2; profile ${name} features.multi_agent_v2 cannot be disabled.`,+ );+ }+ }+}+export function mergeCodexOverrides(base: JsonObject,overrides: JsonObject,diff --git a/sdk/typescript/src/custom-validation-prompt.ts b/sdk/typescript/src/custom-validation-prompt.tsindex a1b5a9e3f..275263e7e 100644--- a/sdk/typescript/src/custom-validation-prompt.ts+++ b/sdk/typescript/src/custom-validation-prompt.ts@@ -1,7 +1,7 @@import { createHash } from "node:crypto";import { readFile } from "node:fs/promises";import { join, resolve } from "node:path";-import type { JsonObject } from "./config.js";+import { resolveCodexProfile, type JsonObject } from "./config.js";import { IncompleteScanError } from "./errors.js";import { PLUGIN_NAME } from "./runtime.js";@@ -111,6 +111,7 @@ export async function customValidationConfig(config: JsonObject,pluginRoot: string,): Promise<JsonObject> {+ config = resolveCodexProfile(config);const manifest = JSON.parse(await readFile(join(pluginRoot, ".mcp.json"), "utf8"),);diff --git a/sdk/typescript/src/provider-profile.ts b/sdk/typescript/src/provider-profile.tsindex def3dd0b6..41ace6c25 100644--- a/sdk/typescript/src/provider-profile.ts+++ b/sdk/typescript/src/provider-profile.ts@@ -1,14 +1,18 @@import { randomUUID } from "node:crypto";-import { lstat, mkdir, rm } from "node:fs/promises";+import { lstat, mkdir, readFile, rm } from "node:fs/promises";import { join } from "node:path";import { pathToFileURL } from "node:url";import type { Codex, CodexOptions } from "@openai/codex-sdk";+import { parse } from "smol-toml";import { configuredCodexHome } from "./auth.js";+import { CodexSecurityError } from "./errors.js";import {resolveCodexProfile,+ deepMerge,modelProviderConfigOverride,inlineToml,writeCodexConfig,+ writePrivateConfig,type JsonObject,} from "./config.js";import { isRecord } from "./record.js";@@ -16,10 +20,13 @@ import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";import {bundledPluginRoot,acquireCodexSecurityCredentialHomeLock,+ codexSecurityCredentialHome,executablePathForSpawn,requirePrivateCredentialHome,+ requireSecureCredentialHome,resolveCodexCommand,type CodexCommand,+ type ProcessEnvironment,} from "./runtime.js";export interface ProviderProfile {@@ -57,15 +64,40 @@ export async function providerPreflightCommand(};}+/** Retain explicit settings omitted from the readable recipe when its file reloads. */+export function privateReplayOverrides(+ config: JsonObject,+ recipe: JsonObject,+): JsonObject {+ const result: JsonObject = {};+ for (const [key, value] of Object.entries(config)) {+ const saved = recipe[key];+ if (value === null || saved === undefined) {+ result[key] = structuredClone(value);+ } else if (isRecord(value) && isRecord(saved)) {+ const nested = privateReplayOverrides(+ value as JsonObject,+ saved as JsonObject,+ );+ if (Object.keys(nested).length > 0) result[key] = nested;+ }+ }+ return result;+}+/** Provider definitions use a native file layer, never process arguments. */export async function createProviderProfile(codexHome: string,config: JsonObject,- options: Parameters<typeof requirePrivateCredentialHome>[2] = {},+ options: Parameters<typeof requirePrivateCredentialHome>[2] & {+ replay?: boolean;+ } = {},): Promise<ProviderProfile> {- const providers = resolveCodexProfile(config)["model_providers"];const name = `codex_security_${randomUUID()}`;- const path = join(codexHome, `${name}.config.toml`);+ const path = join(+ codexHome,+ `${name}.config.${options.replay ? "json" : "toml"}`,+ );if ((options.platform ?? process.platform) === "win32") {await mkdir(codexHome, { recursive: true, mode: 0o700 });await requirePrivateCredentialHome(@@ -74,12 +106,73 @@ export async function createProviderProfile(options,);}- await writeCodexConfig(path, {- model_providers: isRecord(providers) ? providers : {},- });+ if (options.replay) {+ await writePrivateConfig(path, JSON.stringify(config));+ } else {+ const providers = resolveCodexProfile(config)["model_providers"];+ await writeCodexConfig(path, {+ model_providers: isRecord(providers) ? providers : {},+ });+ }return { name, path, cleanup: () => rm(path, { force: true }) };}+/** Restore private replay settings from the credential home, never scan artifacts. */+export async function restoreProviderProfile(+ config: JsonObject,+ profile: unknown,+ environment: ProcessEnvironment,+): Promise<JsonObject> {+ if (profile === undefined) return config;+ if (+ !isRecord(profile) ||+ typeof profile["name"] !== "string" ||+ (profile["home"] !== "ambient" && profile["home"] !== "managed") ||+ !/^codex_security_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u.test(+ profile["name"],+ )+ ) {+ throw new CodexSecurityError(+ "The saved scan contains an invalid provider profile.",+ );+ }+ const codexHome =+ profile["home"] === "ambient"+ ? configuredCodexHome(environment)+ : codexSecurityCredentialHome(environment);+ if (profile["home"] === "managed")+ await requireSecureCredentialHome(codexHome);+ let saved: unknown;+ try {+ saved = JSON.parse(+ await readFile(join(codexHome, `${profile["name"]}.config.json`), "utf8"),+ );+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ saved = parse(+ await readFile(join(codexHome, `${profile["name"]}.config.toml`), "utf8"),+ );+ }+ if (+ !isRecord(saved) ||+ (saved["model_providers"] !== undefined &&+ saved["model_providers"] !== null &&+ !isRecord(saved["model_providers"]))+ ) {+ throw new CodexSecurityError(+ "The saved provider profile contains no provider configuration.",+ );+ }+ const { model_providers: providers, ...overrides } = saved;+ return {+ ...deepMerge({ ...config }, overrides as JsonObject),+ ...(providers === null ||+ (isRecord(providers) && Object.keys(providers).length > 0)+ ? { model_providers: providers as JsonObject | null }+ : {}),+ };+}+/** The pinned SDK lacks the native CLI's private profile-file option. */export async function createProfileCodex(options: CodexOptions,diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.tsindex acd1901cb..634ac7320 100644--- a/sdk/typescript/src/scan-comparison.ts+++ b/sdk/typescript/src/scan-comparison.ts@@ -12,8 +12,11 @@ import {type TurnOptions,} from "@openai/codex-sdk";import { z } from "zod";-import { parse, stringify } from "smol-toml";-import type { CodexSecuritySurface, ScanAuthMode } from "./api.js";+import {+ scanCodexHome,+ type CodexSecuritySurface,+ type ScanAuthMode,+} from "./api.js";import {accountStatus,configuredCodexHome,@@ -26,6 +29,7 @@ import {deepMerge,hasCommandAuth,mergedCodexConfig,+ readCodexFileProfile,normalizeLegacyWindowsSandboxOverride,resolveCodexProfile,resolveCommandAuthConfig,@@ -515,10 +519,14 @@ async function startReadOnlyCodexThread(thread: ReturnType<ReadOnlyCodex["startThread"]>;cleanup?: () => Promise<void>;}> {+ const source = {+ ...(options.environment ?? process.env),+ CODEX_HOME: scanCodexHome(options.environment ?? process.env),+ };const config =options.config === undefined? undefined- : await mergedCodexConfig(options.config);+ : await mergedCodexConfig(options.config, configuredCodexHome(source));const configuredModel =config === undefined ? undefined : scanModelConfiguration(config);const model = options.model ?? configuredModel?.model;@@ -539,16 +547,24 @@ async function startReadOnlyCodexThread(if (options.codex !== undefined) {return { thread: options.codex.startThread(threadOptions) };}- const source = options.environment ?? process.env;const homeConfig = await readCodexHomeConfig(source, options.signal);const homeExecutionConfig = resolveCodexProfile(homeConfig);normalizeLegacyWindowsSandboxOverride(homeExecutionConfig);const providerConfig = resolveCommandAuthConfig(- deepMerge(homeConfig, parse(stringify(config ?? {})) as JsonObject),+ deepMerge(+ structuredClone(homeExecutionConfig),+ resolveCodexProfile(config ?? {}),+ ),configuredCodexHome(source),);const suppliedConfig = resolveCodexProfile(- options.config?.codexOverrides ?? {},+ deepMerge(+ await readCodexFileProfile(+ options.config?.codexOverrides ?? {},+ configuredCodexHome(source),+ ),+ options.config?.codexOverrides ?? {},+ ),);normalizeLegacyWindowsSandboxOverride(suppliedConfig);const windows =@@ -591,7 +607,7 @@ async function startReadOnlyCodexThread(scanCyberAccessConfig(providerConfig, options.cyberAccessProgram),)["features"] as JsonObject | undefined;const environment = await comparisonEnvironment(- options.environment,+ source,accountStatus,options.signal,undefined,diff --git a/sdk/typescript/src/suggest-owners.ts b/sdk/typescript/src/suggest-owners.tsindex 31ffcd8db..23d7d7ba8 100644--- a/sdk/typescript/src/suggest-owners.ts+++ b/sdk/typescript/src/suggest-owners.ts@@ -1,5 +1,6 @@import { tmpdir } from "node:os";import { z } from "zod";+import { scanCodexHome } from "./api.js";import {ownerRepository,collectOwnerEvidence,@@ -98,7 +99,10 @@ export async function suggestOwnersInternal(options.signal,);const configured = scanModelConfiguration(- await mergedCodexConfig(options.config ?? {}),+ await mergedCodexConfig(+ options.config ?? {},+ scanCodexHome(options.environment ?? process.env),+ ),);const model = options.model ?? configured.model;const reasoningEffort = options.reasoningEffort ?? configured.reasoningEffort;diff --git a/sdk/typescript/tests-ts/api-credentials.test.ts b/sdk/typescript/tests-ts/api-credentials.test.tsindex a80bbec7b..e66e1b489 100644--- a/sdk/typescript/tests-ts/api-credentials.test.ts+++ b/sdk/typescript/tests-ts/api-credentials.test.ts@@ -1,3 +1,10 @@+import {+ mergedCodexConfig,+ EXTERNAL_CODEX_PROVIDERS,+ resolveCodexProfile,+ type JsonObject,+} from "../src/config.js";+import { rejecting } from "./support/errors.js";import { requestMetadata } from "./support/request-metadata.js";import { nodeCommand, runCommand } from "./support/shell.js";import { existsSync } from "node:fs";@@ -6,8 +13,9 @@ import { join, relative } from "node:path";import { pathToFileURL } from "node:url";import type { CodexOptions } from "@openai/codex-sdk";import { afterEach, describe, expect, test, mock } from "bun:test";-import { parse as parseToml } from "smol-toml";+import { parse as parseToml, stringify } from "smol-toml";import { initialCredentialsAvailable } from "../src/api.js";+import { restoreProviderProfile } from "../src/provider-profile.js";import { AuthenticationRequiredError } from "../src/errors.js";import { setCodexSecurityCredentialLogout } from "../src/runtime.js";import {@@ -15,7 +23,7 @@ import {copyCredentialTestPlugin,PLUGIN_ROOT,} from "./plugin-root.js";-import { TestClient } from "./support/api-client.js";+import { mockWorkbench, TestClient } from "./support/api-client.js";import {codexFactory,completedEvents,@@ -687,6 +695,104 @@ describe("CodexSecurity orchestration", () => {).resolves.toBe(true);});+ test.each([+ ["inline", "account"],+ ["file", "account"],+ ["inline", "api-key login"],+ ["file", "api-key login"],+ ["inline", "logout"],+ ["file", "logout"],+ ])(+ "loads %s provider metadata for the %s authentication command",+ async (selection, operation) => {+ const root = await temporaryDirectory();+ const home = join(root, "model-home");+ const state = join(root, "state");+ const script = join(root, "synthetic-codex.mjs");+ const observed = join(root, "native-arguments.jsonl");+ await mkdir(home, { mode: 0o700 });+ await mkdir(state, { mode: 0o700 });+ await writeFile(join(home, "auth.json"), '{"auth_mode":"chatgpt"}\n');+ const provider = {+ name: "Synthetic",+ wire_api: "responses",+ requires_openai_auth: true,+ http_headers: { "X-Synthetic": "synthetic-provider-header" },+ };+ const configuration = {+ model_provider: "synthetic_gateway",+ model_providers: { synthetic_gateway: provider },+ };+ await writeFile(+ join(home, "review.config.toml"),+ stringify(configuration),+ );+ await writeFile(+ script,+ `+import { appendFileSync } from "node:fs";+const args = process.argv.slice(2);+appendFileSync(${JSON.stringify(observed)}, JSON.stringify(args) + "\\n");+if (args.includes("--with-api-key")) {+ for await (const _chunk of process.stdin) {}+}+console.log("Logged in using ChatGPT");+`,+ );+ const client = new TestClient(+ {+ pluginPath: PLUGIN_ROOT,+ codexOverrides:+ selection === "file" ? { profile: "review" } : configuration,+ },+ {+ environment: {+ PATH: process.env["PATH"],+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: state,+ },+ resolveCodexCommand: () => ({ ...nodeCommand(), args: [script] }),+ },+ );+ try {+ if (operation === "account") {+ expect((await client.account()).authenticated).toBe(true);+ } else if (operation === "api-key login") {+ await client.loginApiKey("synthetic-login-token");+ } else {+ await client.logout();+ }+ const arguments_ = (await readFile(observed, "utf8"))+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line) as string[])+ .find((args) =>+ args.includes(operation === "logout" ? "logout" : "login"),+ );+ expect(arguments_).toBeDefined();+ const definitions = arguments_!.find((argument) =>+ argument.startsWith("model_providers="),+ );+ expect(definitions).toBeDefined();+ expect(parseToml(definitions!)).toEqual({+ model_providers: {+ synthetic_gateway: {+ name: "Synthetic",+ wire_api: "responses",+ requires_openai_auth: true,+ },+ },+ });+ expect(arguments_!.join("\n")).not.toContain(+ "synthetic-provider-header",+ );+ expect(arguments_!.join("\n")).not.toContain("synthetic-login-token");+ } finally {+ await client.close();+ }+ },+ );+test("respects another client's logout when switching from API-key to ChatGPT scans", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");@@ -827,4 +933,372 @@ process.exit(process.exitCode ?? 0);}},);+ test.each([+ ["openrouter", "generated"],+ ["fireworks", "generated"],+ ["openrouter", "file"],+ ["fireworks", "file"],+ ["openrouter", "refined"],+ ["fireworks", "refined"],+ ] as const)(+ "preserves %s provider settings in a %s file-profile recipe",+ async (provider, selection) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const home = join(root, "home");+ const runtimeHome = join(root, "runtime");+ const scanDir = join(root, "scan");+ for (const path of [repository, home, runtimeHome, scanDir])+ await mkdir(path, { mode: 0o700 });+ const fileProvider = {+ ...EXTERNAL_CODEX_PROVIDERS[provider],+ base_url: "https://file-provider.example.test/v1",+ };+ const explicitProvider: JsonObject | undefined =+ selection === "generated"+ ? { ...EXTERNAL_CODEX_PROVIDERS[provider] }+ : selection === "refined"+ ? {+ base_url: "https://caller-provider.example.test/v1",+ http_headers: { "X-Synthetic": "synthetic-caller-header" },+ }+ : undefined;+ await writeFile(+ join(home, "review.config.toml"),+ stringify({+ model: "synthetic-model",+ ...(selection === "generated"+ ? {}+ : {+ model_provider: provider,+ model_providers: { [provider]: fileProvider },+ }),+ }),+ );+ let savedRecipe: JsonObject | undefined;+ const environment = {+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ [EXTERNAL_CODEX_PROVIDERS[provider].env_key]: "synthetic-provider-key",+ };+ const client = new TestClient(+ {+ pluginPath: PLUGIN_ROOT,+ codexOverrides: {+ profile: "review",+ model_provider: provider,+ ...(explicitProvider === undefined+ ? {}+ : {+ model_providers: { [provider]: explicitProvider },+ }),+ },+ },+ {+ environment,+ resolvePluginPython: async () => "/managed/python",+ prepareRuntime: async () => preparedRuntime(runtimeHome),+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ runWorkbench: async (_runtime, args, input) => {+ if (args[0] === "register-cli-scan")+ savedRecipe = JSON.parse(input!).recipe as JsonObject;+ return mockWorkbench(args, input);+ },+ createCodex: async (options) => {+ const profile = parseToml(+ await readFile(+ join(runtimeHome, `${options.nativeProfile}.config.toml`),+ "utf8",+ ),+ );+ expect(profile["model_providers"]).toEqual({+ [provider]:+ selection === "generated"+ ? EXTERNAL_CODEX_PROVIDERS[provider]+ : { ...fileProvider, ...explicitProvider },+ });+ return {+ startThread: () => ({+ id: null,+ runStreamed: rejecting(+ "synthetic generated provider scan started",+ ),+ }),+ };+ },+ },+ );+ try {+ await expect(client.run(repository)).rejects.toThrow(+ "synthetic generated provider scan started",+ );+ const config = savedRecipe!["config"] as JsonObject;+ expect(config["profile"]).toBe("review");+ expect(JSON.stringify(savedRecipe)).not.toContain(+ "synthetic-caller-header",+ );+ const replay = resolveCodexProfile(+ await mergedCodexConfig(+ {+ codexOverrides: await restoreProviderProfile(+ config,+ savedRecipe!["providerProfile"],+ environment,+ ),+ },+ home,+ ),+ );+ expect(replay["model_provider"]).toBe(provider);+ expect(replay["model_providers"]).toEqual({+ [provider]:+ selection === "generated"+ ? EXTERNAL_CODEX_PROVIDERS[provider]+ : { ...fileProvider, ...explicitProvider },+ });+ } finally {+ await client.close();+ }+ },+ );++ test.each([+ "direct",+ "profile",+ "profile-partial",+ "native-profile",+ "native-openrouter",+ "native-fireworks",+ ])(+ "preserves file-profile command authentication through private profiles (%s)",+ async (selection) => {+ const profile = selection !== "direct";+ const nativeProfile = selection.startsWith("native-");+ const providerName =+ selection === "native-openrouter"+ ? "openrouter"+ : selection === "native-fireworks"+ ? "fireworks"+ : "synthetic.provider";+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const home = join(root, "model-home");+ const state = join(root, "state");+ const scanDir = join(root, "scan");+ await mkdir(repository);+ await mkdir(home);+ await mkdir(scanDir, { mode: 0o700 });+ const runtimeHome = join(state, "codex-home");+ if (profile) await mkdir(runtimeHome, { recursive: true, mode: 0o700 });+ await writeFile(join(home, "auth.json"), '{"auth_mode":"chatgpt"}\n');+ const auth = {+ command: "./synthetic-auth",+ args: ["token"],+ refresh_interval_ms: 1000,+ ...(profile ? { cwd: "helpers" } : {}),+ };+ const providerConfig = {+ name: "Synthetic",+ base_url: "https://provider.example/v1",+ wire_api: "responses",+ auth,+ };+ if (nativeProfile) {+ await writeFile(+ join(home, "compact.md"),+ "Synthetic compact prompt.\n",+ );+ await writeFile(+ join(home, "review.config.toml"),+ stringify({+ model: "native-model",+ model_reasoning_effort: "high",+ model_reasoning_summary: "concise",+ experimental_compact_prompt_file: "compact.md",+ model_catalog_json: "models.json",+ agents: {+ reviewer: {+ config_file: "agents/reviewer.toml",+ description: "Synthetic reviewer",+ },+ },+ model_provider: providerName,+ features: { shell_tool: false, unified_exec: false },+ model_providers: { [providerName]: providerConfig },+ }),+ );+ }+ const overrides = {+ ...(nativeProfile+ ? { profile: "review" }+ : profile+ ? {+ profile: "review",+ profiles: {+ review: {+ model_provider: providerName,+ features: { shell_tool: false, unified_exec: false },+ ...(selection === "profile-partial"+ ? {+ model_providers: {+ [providerName]: {+ auth: { refresh_interval_ms: 2000 },+ },+ },+ }+ : {}),+ },+ },+ }+ : { model_provider: providerName }),+ ...(nativeProfile+ ? {}+ : { model_providers: { [providerName]: providerConfig } }),+ };+ let captured: (CodexOptions & { nativeProfile?: string }) | undefined;+ let savedRecipe: JsonObject | undefined;+ const client = new TestClient(+ { pluginPath: PLUGIN_ROOT, codexOverrides: overrides },+ {+ environment: {+ CODEX_HOME: relative(process.cwd(), home),+ CODEX_SECURITY_STATE_DIR: state,+ ...(profile+ ? {+ OPENAI_API_KEY: "synthetic-ambient-key",+ CODEX_API_KEY: "synthetic-other-key",+ }+ : {}),+ },+ runWorkbench: async (_runtime, args, input) => {+ if (args[0] === "register-cli-scan") {+ savedRecipe = JSON.parse(input!).recipe as JsonObject;+ }+ return mockWorkbench(args, input);+ },+ resolvePluginPython: async () => "/managed/python",+ ...(profile && !nativeProfile+ ? {+ prepareRuntime: async () => ({+ ...preparedRuntime(runtimeHome),+ configPath: join(root, "scan-preflight.toml"),+ credentialsAvailable: false,+ }),+ }+ : {}),+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ createCodex: (options) => {+ captured = options;+ return {+ startThread: () => ({+ id: null,+ runStreamed: rejecting("synthetic command-auth scan started"),+ }),+ };+ },+ },+ );+ try {+ const preflight = await client.preflight(repository);+ expect(preflight.authentication).toEqual({+ method: "command",+ verified: false,+ });+ expect(JSON.stringify(preflight)).not.toContain("synthetic-auth");+ if (nativeProfile) {+ expect(preflight).toMatchObject({+ model: "native-model",+ reasoningEffort: "high",+ modelProvider: providerName,+ });+ }+ await expect(client.run(repository)).rejects.toThrow(+ "synthetic command-auth scan started",+ );+ expect(savedRecipe).toBeDefined();+ const savedConfig = savedRecipe!["config"] as JsonObject;+ expect(JSON.stringify(savedConfig)).not.toContain("synthetic-auth");+ if (nativeProfile) {+ expect(savedConfig["profile"]).toBe("review");+ const replay = resolveCodexProfile(+ await mergedCodexConfig({ codexOverrides: savedConfig }, home),+ );+ expect(replay["model_providers"]).toEqual({+ [providerName]: providerConfig,+ });+ }+ if (profile) {+ expect(captured?.config?.["features"]).toMatchObject({+ shell_tool: false,+ unified_exec: false,+ });+ const snapshot = parseToml(+ await readFile(+ captured!.env!["CODEX_SECURITY_CONFIG_PATH"]!,+ "utf8",+ ),+ );+ expect(snapshot["features"]).toMatchObject({+ shell_tool: false,+ unified_exec: false,+ });+ }+ expect(captured?.apiKey).toBeUndefined();+ expect(captured?.env).not.toHaveProperty("OPENAI_API_KEY");+ expect(captured?.env).not.toHaveProperty("CODEX_API_KEY");+ expect(captured?.env?.["CODEX_HOME"]).toBe(join(state, "codex-home"));+ const provider = {+ ...providerConfig,+ auth: {+ ...auth,+ cwd: profile ? join(home, "helpers") : home,+ ...(selection === "profile-partial"+ ? { refresh_interval_ms: 2000 }+ : {}),+ },+ };+ expect(+ parseToml(+ await readFile(+ join(runtimeHome, `${captured!.nativeProfile}.config.toml`),+ "utf8",+ ),+ ),+ ).toEqual({+ model_providers: { [providerName]: provider },+ });+ expect(captured?.config).not.toHaveProperty("profile");+ expect(captured?.config).not.toHaveProperty("profiles");+ expect(captured?.config?.["model_provider"]).toBe(providerName);+ if (nativeProfile) {+ expect(captured?.config).toMatchObject({+ model: "native-model",+ model_reasoning_effort: "high",+ model_reasoning_summary: "concise",+ experimental_compact_prompt_file: join(home, "compact.md"),+ model_catalog_json: join(home, "models.json"),+ agents: {+ reviewer: {+ config_file: join(home, "agents/reviewer.toml"),+ description: "Synthetic reviewer",+ },+ },+ });+ }+ if (!profile || nativeProfile) {+ const saved = parseToml(+ await readFile(join(runtimeHome, "config.toml"), "utf8"),+ );+ expect(saved).not.toHaveProperty("profile");+ expect(saved).not.toHaveProperty("profiles");+ expect(saved["model_providers"]).toBeUndefined();+ }+ expect(existsSync(join(state, "codex-home", "auth.json"))).toBe(false);+ } finally {+ await client.close();+ }+ },+ );});diff --git a/sdk/typescript/tests-ts/api-file-profile-replay.test.ts b/sdk/typescript/tests-ts/api-file-profile-replay.test.tsnew file mode 100644index 000000000..262d59939--- /dev/null+++ b/sdk/typescript/tests-ts/api-file-profile-replay.test.ts@@ -0,0 +1,528 @@+import { afterEach, expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { once } from "node:events";+import {+ cp,+ mkdir,+ readFile,+ readdir,+ stat,+ writeFile,+} from "node:fs/promises";+import { createServer, type Socket } from "node:net";+import { join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { stringify } from "smol-toml";+import { main } from "../src/cli.js";+import {+ mergedCodexConfig,+ resolveCodexProfile,+ type JsonObject,+} from "../src/config.js";+import {+ createProviderProfile,+ privateReplayOverrides,+ restoreProviderProfile,+} from "../src/provider-profile.js";+import { codexSecurityCredentialHome, runWorkbench } from "../src/runtime.js";+import { dependencies, capture } from "./cli-fixtures.js";+import { PLUGIN_ROOT } from "./plugin-root.js";+import { TestClient, mockWorkbench } from "./support/api-client.js";+import { preparedRuntime } from "./support/api-events.js";+import { rejecting } from "./support/errors.js";+import { pythonExecutable } from "./support/python.js";+import { createApiTestFixtures } from "./support/temporary-directories.js";++const { temporaryDirectory, cleanup } = createApiTestFixtures(+ "file-profile-replay-",+);+afterEach(cleanup);++test.each([+ "early",+ "precommit",+ "rejected",+ "postcommit",+ "unavailable-receipt",+ "success",+] as const)(+ "private replay ownership after %s registration",+ async (boundary) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const home = join(root, "home");+ const runtimeHome = join(root, "runtime");+ const scanDir = join(root, "scan");+ for (const path of [repository, home, runtimeHome, scanDir])+ await mkdir(path, { mode: 0o700 });+ await writeFile(join(repository, "fixture.txt"), "Synthetic scan input.\n");+ const profilePath = join(home, "review.config.toml");+ const fileProfile = (version: string) => ({+ model: "gpt-5.6-sol",+ model_provider: "openrouter",+ analytics: { enabled: true },+ shell_environment_policy: { set: { INHERITED: version } },+ model_providers: {+ openrouter: {+ name: "Synthetic provider",+ wire_api: "responses",+ request_max_retries: 4,+ },+ },+ });+ await writeFile(profilePath, stringify(fileProfile("first")));+ const explicit: JsonObject = {+ profile: "review",+ analytics: { enabled: false },+ shell_environment_policy: { inherit: "none", exclude: [] },+ model_providers: {+ openrouter: {+ base_url: "https://models.example.test/v1",+ env_key: "OPENROUTER_API_KEY",+ http_headers: { "X-Example": "synthetic-private-value" },+ },+ },+ };+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ TEMP: process.env["TEMP"],+ TMP: process.env["TMP"],+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ OPENROUTER_API_KEY: "synthetic-api-key",+ };+ const sockets = new Set<Socket>();+ const server = createServer((socket) => {+ sockets.add(socket);+ socket.once("close", () => sockets.delete(socket));+ socket.on("error", (error: NodeJS.ErrnoException) => {+ if (error.code !== "ECONNRESET") throw error;+ });+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ const address = server.address();+ if (address === null || typeof address === "string")+ throw new Error("Missing registration fixture port");+ const pluginRoot = join(root, "controlled-plugin");+ await cp(PLUGIN_ROOT, pluginRoot, { recursive: true });+ const paused = ["precommit", "postcommit", "unavailable-receipt"].includes(+ boundary,+ );+ await writeFile(+ join(pluginRoot, "scripts", "workbench_db.py"),+ [+ "import runpy, socket, sys",+ `workbench = runpy.run_path(${JSON.stringify(join(PLUGIN_ROOT, "scripts", "workbench_db.py"))})`,+ "namespace = workbench['main'].__globals__",+ ...(paused+ ? [+ `original = namespace[${JSON.stringify(boundary === "precommit" ? "insert_running_scan" : "register_cli_scan")}]`,+ "def pause():",+ ` with socket.create_connection(('127.0.0.1', ${address.port})) as connection:`,+ " connection.sendall(b'ready')",+ " connection.recv(1)",+ "def controlled(*args, **kwargs):",+ ...(boundary === "precommit" ? [" pause()"] : []),+ " result = original(*args, **kwargs)",+ ...(boundary === "precommit" ? [] : [" pause()"]),+ " return result",+ `namespace[${JSON.stringify(boundary === "precommit" ? "insert_running_scan" : "register_cli_scan")}] = controlled`,+ ]+ : []),+ "if __name__ == '__main__': workbench['main']()",+ ].join("\n"),+ );+ const python = pythonExecutable()!;+ const workbenchOptions = { python, pluginRoot: PLUGIN_ROOT, environment };+ const controller = new AbortController();+ const deadline = new AbortController();+ const timer = setTimeout(() => deadline.abort(), 10_000);+ const ready = paused+ ? once(server, "connection", { signal: deadline.signal }).then(+ async ([socket]) => {+ const [message] = await once(socket, "data", {+ signal: deadline.signal,+ });+ expect(String(message)).toBe("ready");+ },+ )+ : undefined;+ let submitted: JsonObject | undefined;+ const client = new TestClient(+ { pluginPath: pluginRoot, codexOverrides: explicit },+ {+ environment,+ resolvePluginPython: async () => python,+ prepareRuntime: async () => {+ const runtime = preparedRuntime(runtimeHome);+ runtime.plugin.pluginRoot = pluginRoot;+ return runtime;+ },+ prepareOutputDir: async () => scanDir,+ runWorkbench: async (options, args, input) => {+ if (args[0] === "register-cli-scan") {+ submitted = JSON.parse(input!).recipe;+ if (boundary === "rejected")+ args = [+ ...args,+ "--parent-scan-id",+ "00000000-0000-4000-8000-000000000001",+ ];+ }+ if (boundary === "unavailable-receipt" && args[0] === "list-scans")+ throw new Error("Synthetic unavailable registration receipt");+ return runWorkbench({ ...options, python }, args, input);+ },+ createCodex: async () => ({+ startThread: () => ({+ id: null,+ runStreamed: rejecting("synthetic stop after registration"),+ }),+ }),+ },+ );+ if (boundary === "early") controller.abort();+ const operation = client+ .run(repository, { signal: controller.signal })+ .catch((error: unknown) => error);+ try {+ if (ready !== undefined) {+ await Promise.race([+ ready,+ operation.then((error) => {+ throw error;+ }),+ ]);+ controller.abort();+ }+ const failure = await operation;+ expect(failure).toBeInstanceOf(Error);+ if (paused || boundary === "early")+ expect((failure as Error).message).toContain("interrupted");+ if (boundary === "success")+ expect((failure as Error).message).toContain(+ "synthetic stop after registration",+ );+ const { scans } = await runWorkbench(workbenchOptions, [+ "list-scans",+ "--scan-root",+ scanDir,+ ]);+ const committed = [+ "postcommit",+ "unavailable-receipt",+ "success",+ ].includes(boundary);+ expect(scans).toHaveLength(committed ? 1 : 0);+ if (!committed) {+ const names = await readdir(+ codexSecurityCredentialHome(environment),+ ).catch((error: NodeJS.ErrnoException) => {+ if (error.code === "ENOENT") return [];+ throw error;+ });+ expect(names.filter((name) => name.endsWith(".config.json"))).toEqual(+ [],+ );+ expect(submitted === undefined).toBe(boundary === "early");+ return;+ }+ const scanId = (scans as JsonObject[])[0]!["scanId"] as string;+ const { recipe } = await runWorkbench(workbenchOptions, [+ "get-scan-recipe",+ "--scan-id",+ scanId,+ ]);+ expect(recipe).toEqual(submitted!);+ expect(JSON.stringify(recipe)).not.toContain("synthetic-private-value");+ await writeFile(profilePath, stringify(fileProfile("reloaded")));+ let replay: JsonObject | undefined;+ const out = capture(),+ err = capture();+ const status = await main(+ ["scans", "rerun", scanId, "--json"],+ out.stream,+ err.stream,+ dependencies({+ currentDirectory: repository,+ environment,+ onWorkbench: (args, input) =>+ runWorkbench(workbenchOptions, args, input),+ onConfig: (config) => {+ replay = config.codexOverrides;+ },+ }),+ );+ expect(status, out.text() + err.text()).toBe(0);+ const restored = resolveCodexProfile(+ await mergedCodexConfig({ codexOverrides: replay }, home),+ );+ expect(restored).toMatchObject({+ analytics: { enabled: false },+ shell_environment_policy: {+ inherit: "none",+ exclude: [],+ set: { INHERITED: "reloaded" },+ },+ model_providers: {+ openrouter: {+ request_max_retries: 4,+ ...((explicit["model_providers"] as JsonObject)[+ "openrouter"+ ] as JsonObject),+ },+ },+ });+ const profile = submitted!["providerProfile"] as JsonObject;+ const privatePath = join(+ codexSecurityCredentialHome(environment),+ `${profile["name"]}.config.json`,+ );+ expect(await readFile(privatePath, "utf8")).toContain(+ "synthetic-private-value",+ );+ if (process.platform !== "win32")+ expect((await stat(privatePath)).mode & 0o777).toBe(0o600);+ } finally {+ clearTimeout(timer);+ controller.abort();+ for (const socket of sockets) socket.destroy();+ await operation;+ await client.close();+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ }+ },+);++test.each(+ (["rerun", "resume"] as const).flatMap((command) =>+ (["inherited", "explicit", "empty", "null"] as const).map(+ (skills) => [command, skills] as const,+ ),+ ),+)(+ "saved registration retains file-profile settings through CLI %s with %s skills",+ async (command, skills) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const home = join(root, "home");+ const runtimeHome = join(root, "runtime");+ const scanDir = join(root, "scan");+ for (const path of [repository, home, runtimeHome, scanDir])+ await mkdir(path, { mode: 0o700 });+ const profilePath = join(home, "review.config.toml");+ const fileProfile = (version: string) => ({+ model: version === "first" ? "initial-model" : "updated-model",+ model_reasoning_effort: version === "first" ? "low" : "high",+ analytics: { enabled: true },+ shell_environment_policy: {+ inherit: "all",+ exclude: ["FILE_SETTING"],+ set: { INHERITED: version },+ },+ otel: { exporter: "console", environment: version },+ agents: {+ reviewer: { config_file: "file-reviewer.toml", description: version },+ },+ skills: {+ config: [{ path: "file-skill", enabled: version === "first" }],+ },+ model_instructions_file: "file-instructions.md",+ model_catalog_json: "file-catalog.json",+ features: { view_image: true },+ });+ await writeFile(profilePath, stringify(fileProfile("first")));+ const explicit: JsonObject = {+ profile: "review",+ analytics: { enabled: false },+ shell_environment_policy: {+ inherit: "none",+ exclude: [],+ set: { EXPLICIT: "kept" },+ },+ otel: { exporter: "none" },+ agents: { reviewer: { config_file: "caller-reviewer.toml" } },+ model_instructions_file: null,+ model_catalog_json: "../caller-catalog.json",+ features: { view_image: false, shell_tool: false },+ };+ if (skills !== "inherited")+ explicit["skills"] =+ skills === "null"+ ? null+ : {+ config:+ skills === "empty"+ ? []+ : [{ path: "caller-skill", enabled: false }],+ };+ const environment = {+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ };+ let recipe: JsonObject | undefined;+ const client = new TestClient(+ { pluginPath: PLUGIN_ROOT, codexOverrides: explicit },+ {+ environment,+ resolvePluginPython: async () => "/managed/python",+ prepareRuntime: async () => preparedRuntime(runtimeHome),+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ runWorkbench: async (_runtime, args, input) => {+ if (args[0] === "register-cli-scan")+ recipe = JSON.parse(input!).recipe;+ return mockWorkbench(args, input);+ },+ createCodex: async () => ({+ startThread: () => ({+ id: null,+ runStreamed: rejecting("synthetic stop after registration"),+ }),+ }),+ },+ );+ try {+ await expect(client.run(repository, { mode: "deep" })).rejects.toThrow(+ "synthetic stop after registration",+ );+ expect(recipe).toBeDefined();+ await writeFile(profilePath, stringify(fileProfile("reloaded")));+ let replay: JsonObject | undefined;+ const out = capture(),+ err = capture();+ const status = await main(+ ["scans", command, "saved", "--json"],+ out.stream,+ err.stream,+ dependencies({+ currentDirectory: repository,+ environment,+ onWorkbench: () => ({ scanId: "saved", scanDir, recipe: recipe! }),+ onConfig: (config) => {+ replay = config.codexOverrides;+ },+ }),+ );+ expect(status, out.text() + err.text()).toBe(0);+ const restored = resolveCodexProfile(+ await mergedCodexConfig({ codexOverrides: replay }, home),+ );+ expect(restored).toMatchObject({+ model: "updated-model",+ model_reasoning_effort: "high",+ analytics: { enabled: false },+ shell_environment_policy: {+ inherit: "none",+ exclude: [],+ set: { INHERITED: "reloaded", EXPLICIT: "kept" },+ },+ otel: { exporter: "none", environment: "reloaded" },+ agents: {+ reviewer: {+ config_file: join(scanDir, "caller-reviewer.toml"),+ description: "reloaded",+ },+ },+ model_catalog_json: resolve(scanDir, "../caller-catalog.json"),+ features: { view_image: false, shell_tool: false },+ });+ expect(restored["skills"]).toEqual(+ skills === "inherited"+ ? { config: [{ path: join(home, "file-skill"), enabled: false }] }+ : skills === "explicit"+ ? {+ config: [+ { path: join(scanDir, "caller-skill"), enabled: false },+ ],+ }+ : skills === "empty"+ ? { config: [] }+ : undefined,+ );+ expect(restored).not.toHaveProperty("model_instructions_file");+ const workerResult = execFileSync(+ Bun.which("node")!,+ [+ "--experimental-strip-types",+ fileURLToPath(+ new URL("./support/replay-worker-boundary.ts", import.meta.url),+ ),+ root,+ ],+ { input: JSON.stringify(restored), encoding: "utf8" },+ );+ expect(JSON.parse(workerResult)).toEqual({ launches: 4 });+ const profile = recipe!["providerProfile"] as JsonObject;+ const privatePath = join(+ codexSecurityCredentialHome(environment),+ `${profile["name"]}.config.json`,+ );+ const saved = JSON.parse(await readFile(privatePath, "utf8"));+ expect(saved).not.toHaveProperty("model_catalog_json");+ expect(saved).not.toHaveProperty("features.shell_tool");+ expect(saved).toHaveProperty("model_instructions_file", null);+ expect(saved).not.toHaveProperty(+ "shell_environment_policy.set.INHERITED",+ );+ if (process.platform !== "win32")+ expect((await stat(privatePath)).mode & 0o777).toBe(0o600);+ expect(explicit["model_catalog_json"]).toBe("../caller-catalog.json");+ } finally {+ await client.close();+ }+ },+);++test("private replay preserves explicit clears over projected defaults and empty provider semantics", async () => {+ const home = await temporaryDirectory();+ const recipe: JsonObject = {+ model_provider: "openai",+ model_catalog_json: join(home, "original-catalog.json"),+ features: { shell_tool: true },+ };+ const providerCases: (JsonObject | null)[] = [+ null,+ {},+ { synthetic: { auth: null, http_headers: {} } },+ ];+ for (const providers of providerCases) {+ const overrides: JsonObject = {+ model_provider: null,+ model_catalog_json: "raw-relative-catalog.json",+ features: { shell_tool: null },+ shell_environment_policy: { exclude: [] },+ model_providers: providers,+ };+ const saved = await createProviderProfile(+ home,+ privateReplayOverrides(overrides, recipe),+ { replay: true },+ );+ try {+ const restored = await restoreProviderProfile(+ recipe,+ { name: saved.name, home: "ambient" },+ { CODEX_HOME: home },+ );+ expect(restored).toMatchObject({+ model_provider: null,+ model_catalog_json: recipe["model_catalog_json"],+ features: { shell_tool: null },+ shell_environment_policy: { exclude: [] },+ });+ if (providers === null || Object.keys(providers).length > 0)+ expect(restored["model_providers"]).toEqual(providers);+ else expect(restored).not.toHaveProperty("model_providers");+ } finally {+ await saved.cleanup();+ }+ await expect(readFile(saved.path)).rejects.toMatchObject({+ code: "ENOENT",+ });+ }+});diff --git a/sdk/typescript/tests-ts/api-preflight-config.test.ts b/sdk/typescript/tests-ts/api-preflight-config.test.tsindex 7d1d19392..686a1f06c 100644--- a/sdk/typescript/tests-ts/api-preflight-config.test.ts+++ b/sdk/typescript/tests-ts/api-preflight-config.test.ts@@ -1,4 +1,4 @@-import { mkdir, readFile } from "node:fs/promises";+import { mkdir, readFile, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, test } from "bun:test";@@ -7,6 +7,7 @@ import {scanRuntimeCodexConfig,} from "../src/api.js";import {+ mergedCodexConfig,CHEAPERINFERENCE_CODEX_PROVIDER,FIREWORKS_CODEX_PROVIDER,OPENROUTER_CODEX_PROVIDER,@@ -94,6 +95,83 @@ describe("CodexSecurity preflight configuration", () => {});});+ test.each([+ ["approval-only", { approval_policy: "never" }],+ ["windows-only", { windows: { sandbox: "unelevated" } }],+ ])(+ "preserves %s inline-profile identity in saved recipes",+ async (_name, profile) => {+ const home = await temporaryDirectory();+ await writeFile(+ join(home, "selected.config.toml"),+ 'model_provider = "fireworks"\n',+ );+ const original = await mergedCodexConfig(+ {+ codexOverrides: {+ profile: "selected",+ profiles: { selected: profile as JsonObject },+ },+ },+ home,+ );+ const saved = scanPreflightCodexConfig(original);+ const replayed = await mergedCodexConfig({ codexOverrides: saved }, home);+ expect(scanModelProvider(replayed)).toBe(scanModelProvider(original));+ expect(saved["profile"]).toBe("selected");+ expect(saved["profiles"]).toEqual({ selected: {} });+ },+ );++ test("preserves resolved file-profile model files and tool exclusions", async () => {+ const home = await temporaryDirectory();+ await writeFile(+ join(home, "review.config.toml"),+ 'model_catalog_json = "catalog.json"\nexperimental_compact_prompt_file = "compact.md"\n[features.code_mode]\nenabled = true\nexcluded_tool_namespaces = ["synthetic_tools"]\n',+ );+ const config = await mergedCodexConfig(+ { codexOverrides: { profile: "review" } },+ home,+ );+ const requested = {+ model_catalog_json: join(home, "catalog.json"),+ experimental_compact_prompt_file: join(home, "compact.md"),+ features: {+ code_mode: {+ enabled: true,+ excluded_tool_namespaces: ["synthetic_tools"],+ },+ },+ };+ expect(config).toMatchObject(requested);+ expect(scanPreflightCodexConfig(config)).toMatchObject(requested);+ });++ test.each([undefined, "low"])(+ "preserves resolved file-profile worker settings and explicit verbosity: %s",+ async (verbosity) => {+ const home = await temporaryDirectory();+ await writeFile(+ join(home, "review.config.toml"),+ 'model_instructions_file = "instructions.md"\nmodel_verbosity = "high"\nweb_search = "disabled"\n',+ );+ const config = await mergedCodexConfig(+ {+ codexOverrides: {+ profile: "review",+ ...(verbosity === undefined ? {} : { model_verbosity: verbosity }),+ },+ },+ home,+ );+ expect(scanPreflightCodexConfig(config)).toMatchObject({+ model_instructions_file: join(home, "instructions.md"),+ model_verbosity: verbosity ?? "high",+ web_search: "disabled",+ });+ },+ );+test.each([["model", { model: null }, true],["reasoning effort", { model_reasoning_effort: null }, true],@@ -504,6 +582,35 @@ describe("CodexSecurity preflight configuration", () => {).resolves.toBeUndefined();});+ test("keeps resolved tool disables in isolated worker settings", () => {+ expect(+ scanPreflightCodexConfig({+ profile: "review",+ features: { shell_tool: true, unified_exec: true },+ profiles: {+ review: { features: { shell_tool: false, unified_exec: false } },+ },+ })["features"],+ ).toEqual({ shell_tool: false, unified_exec: false });+ });++ test("uses resolved native file settings without a legacy profile selector", async () => {+ const root = await temporaryDirectory();+ const path = join(root, "config-preflight.toml");+ const snapshot = scanPreflightCodexConfig({+ profile: "review",+ model: "native-model",+ model_reasoning_summary: "concise",+ features: { goals: true },+ });+ expect(snapshot).toEqual({+ model: "native-model",+ model_reasoning_summary: "concise",+ features: { goals: true },+ });+ await writeCodexConfig(path, snapshot);+ });+test("keeps every valid profile, project, and root marker", () => {const activeProject = "/workspace/active";const profiles = Object.fromEntries([diff --git a/sdk/typescript/tests-ts/api-provider-isolation.test.ts b/sdk/typescript/tests-ts/api-provider-isolation.test.tsindex fb6b940c9..9b7a71f19 100644--- a/sdk/typescript/tests-ts/api-provider-isolation.test.ts+++ b/sdk/typescript/tests-ts/api-provider-isolation.test.ts@@ -259,6 +259,8 @@ test.each(["null profile","profile override","profile only",+ "file custom only",+ "file default key",] as const)("concurrent provider snapshots preserve %s credentials",async (selection) => {@@ -283,13 +285,63 @@ test.each([for (let index = 0; index < 2; index++) {const scan = join(root, `scan-${index}`);await mkdir(scan, { mode: 0o700 });+ const fileProfile = selection.startsWith("file ");+ const agentFile = fileProfile+ ? join(sourceHome, `reviewer-${index}.toml`)+ : join(scan, "reviewer.toml");+ await writeFile(agentFile, 'model_reasoning_effort = "high"\n');+ const agents = {+ max_depth: index + 2,+ reviewer: {+ description: `Synthetic reviewer ${index}`,+ config_file: fileProfile+ ? `reviewer-${index}.toml`+ : "reviewer.toml",+ },+ };+ const resolvedAgents = {+ ...agents,+ reviewer: { ...agents.reviewer, config_file: agentFile },+ };+ const explicitFileSkills = selection === "file default key";+ const skills = {+ config: [+ { path: `skill-${index}/SKILL.md`, enabled: index === 0 },+ { path: join(scan, "absolute-skill", "SKILL.md"), enabled: true },+ { path: "~/synthetic-skill/SKILL.md", enabled: false },+ ],+ };+ const resolvedSkills = {+ config: skills.config.map((skill, skillIndex) =>+ skillIndex === 0+ ? {+ ...skill,+ path: join(+ fileProfile && !explicitFileSkills ? sourceHome : scan,+ skill.path,+ ),+ }+ : skill,+ ),+ };+ const providerKey =+ selection === "file default key"+ ? "OPENROUTER_API_KEY"+ : "SYNTHETIC_CUSTOM_API_KEY";+ const canonicalHeader: Record<string, string> =+ selection === "root"+ ? { OPENROUTER_API_KEY: ` synthetic-canonical-header-${index} ` }+ : {};const provider = {name: `Synthetic ${index}`,base_url: `https://provider-${index}.example.test/v1`,wire_api: "responses",- env_key: "SYNTHETIC_CUSTOM_API_KEY",+ env_key: providerKey,env_http_headers: {"X-Synthetic-Token": "SYNTHETIC_CUSTOM_HEADER",+ ...(selection === "root"+ ? { "X-Synthetic-Canonical": "OPENROUTER_API_KEY" }+ : {}),"X-Synthetic-Missing": "SYNTHETIC_UNSET",},...(index === 1@@ -306,78 +358,122 @@ test.each([inherit: "none",set: { SYNTHETIC_WORKER_VALUE: `shell-value-${index}` },};- const providerEnvironment = {- SYNTHETIC_CUSTOM_API_KEY: ` synthetic-key-${index} `,+ const providerEnvironment: Record<string, string> = {+ [providerKey]: fileProfile+ ? `synthetic-key-${index}`+ : ` synthetic-key-${index} `,SYNTHETIC_CUSTOM_HEADER: ` synthetic-header-${index} `,+ ...canonicalHeader,SYNTHETIC_REQUIRED_KEY: `synthetic-required-${index}`,};+ // Authentication trims the selected API key; other inherited provider+ // variables, including header values, retain their original bytes.+ const workerEnvironment = {+ ...providerEnvironment,+ [providerKey]: providerEnvironment[providerKey]!.trim(),+ };+ if (fileProfile) {+ await writeFile(+ join(sourceHome, `review-${index}.config.toml`),+ stringifyToml({+ model: "gpt-5.6-terra",+ model_provider: "openrouter",+ model_providers: {+ openrouter: provider,+ "required.gateway": {+ name: "Managed selection",+ wire_api: "responses",+ env_key: "SYNTHETIC_REQUIRED_KEY",+ },+ },+ features: featureOverrides,+ agents,+ skills,+ web_search: webSearch,+ shell_environment_policy: shellPolicy,+ }),+ );+ }clients.push(new TestClient({pluginPath: PLUGIN_ROOT,- codexOverrides: {- model_provider: "openrouter",- web_search: selection === "root" ? webSearch : "live",- shell_environment_policy:- selection === "root" ? shellPolicy : { inherit: "all" },- features: selection === "root" ? featureOverrides : {},- ...(selection === "profile only"- ? {}- : {- model_providers: {- openrouter:- selection === "profile override"- ? {- ...provider,- env_key: "SYNTHETIC_UNUSED_KEY",- }- : provider,- "required.gateway": {- name: "Managed selection",- wire_api: "responses",- env_key: "SYNTHETIC_REQUIRED_KEY",- },- },- }),- ...(selection === "root"- ? {}- : {- profile: "selected",- profiles: {- selected: {- features: featureOverrides,- web_search: webSearch,- shell_environment_policy: shellPolicy,- ...(selection === "null profile"- ? {- model_provider: null,- model: null,- model_reasoning_effort: null,- }- : selection === "selected profile"- ? {}- : {- model_provider: "openrouter",- model_providers: {- openrouter: provider,- "required.gateway": {- name: "Managed selection",- wire_api: "responses",- env_key: "SYNTHETIC_REQUIRED_KEY",- },- },- }),- },- },- }),- },+ codexOverrides: fileProfile+ ? {+ profile: `review-${index}`,+ ...(explicitFileSkills ? { skills } : {}),+ }+ : {+ model_provider: "openrouter",+ web_search: selection === "root" ? webSearch : "live",+ shell_environment_policy:+ selection === "root" ? shellPolicy : { inherit: "all" },+ features: selection === "root" ? featureOverrides : {},+ agents: selection === "root" ? agents : {},+ skills: selection === "root" ? skills : {},+ ...(selection === "profile only"+ ? {}+ : {+ model_providers: {+ openrouter:+ selection === "profile override"+ ? {+ ...provider,+ env_key: "SYNTHETIC_UNUSED_KEY",+ }+ : provider,+ "required.gateway": {+ name: "Managed selection",+ wire_api: "responses",+ env_key: "SYNTHETIC_REQUIRED_KEY",+ },+ },+ }),+ ...(selection === "root"+ ? {}+ : {+ profile: "selected",+ profiles: {+ selected: {+ features: featureOverrides,+ agents,+ skills,+ web_search: webSearch,+ shell_environment_policy: shellPolicy,+ ...(selection === "null profile"+ ? {+ model_provider: null,+ model: null,+ model_reasoning_effort: null,+ }+ : selection === "selected profile"+ ? {}+ : {+ model_provider: "openrouter",+ model_providers: {+ openrouter: provider,+ "required.gateway": {+ name: "Managed selection",+ wire_api: "responses",+ env_key: "SYNTHETIC_REQUIRED_KEY",+ },+ },+ }),+ },+ },+ }),+ },},{environment: {- CODEX_HOME: sourceHome,+ [selection === "file custom only"+ ? "codex_home"+ : "CODEX_HOME"]: sourceHome,CODEX_SECURITY_STATE_DIR: state,OPENAI_API_KEY: "synthetic-account-key",- OPENROUTER_API_KEY: "synthetic-sdk-account-key",+ ...(selection === "file custom only"+ ? {}+ : { OPENROUTER_API_KEY: "synthetic-sdk-account-key" }),...providerEnvironment,SYNTHETIC_UNUSED_KEY: "synthetic-unused-key",},@@ -422,11 +518,31 @@ test.each([await readFile(workerSnapshotPath, "utf8"),);expect(workerSnapshot["worker_runtime"]).toMatchObject({- environment: providerEnvironment,+ environment: workerEnvironment,shell_environment_policy: shellPolicy,features: featureOverrides,+ agents: resolvedAgents,+ skills: {+ config: expect.arrayContaining(resolvedSkills.config),+ },web_search: webSearch,});+ if (fileProfile)+ expect(options.config!["model"]).toBe("gpt-5.6-terra");+ expect(options.config!["agents"]).toEqual(+ fileProfile ? resolvedAgents : agents,+ );+ expect(options.config!["skills"]).toMatchObject({+ config: expect.arrayContaining(+ (fileProfile && !explicitFileSkills+ ? resolvedSkills+ : skills+ ).config,+ ),+ });+ expect(skills.config[0]!.path).toBe(+ `skill-${index}/SKILL.md`,+ );expect(options.config!["web_search"]).toBe(webSearch);expect(options.config!["shell_environment_policy"]).toEqual(shellPolicy,@@ -438,7 +554,7 @@ test.each([(workerSnapshot["worker_runtime"] as JsonObject)["environment"],- ).toEqual(providerEnvironment);+ ).toEqual(workerEnvironment);if (process.platform !== "win32") {expect((await stat(workerSnapshotPath)).mode & 0o777).toBe(0o600,@@ -451,7 +567,7 @@ test.each([}),).not.toContain("synthetic-key-");const settings = await workerRuntimeSettings(environment);- expect(settings.environment).toEqual(providerEnvironment);+ expect(settings.environment).toEqual(workerEnvironment);expect(settings.config["features"]).toMatchObject(featureOverrides,);@@ -459,6 +575,7 @@ test.each([expect(settings.config["shell_environment_policy"]).toEqual(shellPolicy,);+ expect(settings.config["agents"]).toEqual(resolvedAgents);expect(settings.config["model_provider"]).toBe("openrouter");expect(settings.nativeProfile).toBeDefined();expect(settings.nativeProfile).toBe(options.nativeProfile);@@ -482,9 +599,15 @@ test.each([expect(actual["http_headers"] ?? {}).toEqual(provider.http_headers ?? {},);- expect(environment["SYNTHETIC_CUSTOM_API_KEY"]).toBe(- providerEnvironment.SYNTHETIC_CUSTOM_API_KEY,+ expect(environment[providerKey]).toBe(+ workerEnvironment[providerKey],);+ expect(environment["SYNTHETIC_CUSTOM_HEADER"]).toBe(+ workerEnvironment["SYNTHETIC_CUSTOM_HEADER"],+ );+ for (const [name, value] of Object.entries(canonicalHeader)) {+ expect(environment[name]).toBe(value);+ }const saved = await readFile(join(sharedHome, "config.toml"),"utf8",@@ -498,6 +621,16 @@ test.each([),);}+ if (selection.startsWith("file ")) {+ for (const client of clients) {+ expect(+ await client.preflight(repository, { mode: "deep" }),+ ).toMatchObject({+ model: "gpt-5.6-terra",+ modelProvider: "openrouter",+ });+ }+ }// A's snapshot exists before B updates the shared credential home.runs.push(clients[0]!.run(repository, { mode: "deep" }));await Promise.race([ready[0]!.promise, runs[0]]);@@ -527,6 +660,231 @@ test.each([},);+const fileProviderKeyCases = [+ ["openrouter", "default", "OPENROUTER_API_KEY"],+ ["openrouter", "custom only", "SYNTHETIC_CUSTOM_API_KEY"],+ ["openrouter", "canonical header", "SYNTHETIC_CUSTOM_API_KEY"],+ ["openrouter", "missing custom primary", "SYNTHETIC_CUSTOM_API_KEY"],+ ["fireworks", "default", "FIREWORKS_API_KEY"],+ ["fireworks", "custom only", "SYNTHETIC_CUSTOM_API_KEY"],+ ["fireworks", "canonical header", "SYNTHETIC_CUSTOM_API_KEY"],+ ["fireworks", "missing custom primary", "SYNTHETIC_CUSTOM_API_KEY"],+ ["openrouter", "custom Codex key", "CODEX_API_KEY"],+ ["openrouter", "other external key", "FIREWORKS_API_KEY"],+] as const;++test.each(["openrouter", "fireworks"] as const)(+ "native file profile accepts the %s custom environment key",+ async (providerId) => {+ const root = await temporaryDirectory();+ const home = join(root, "home");+ await mkdir(home, { mode: 0o700 });+ await writeFile(+ join(home, "review.config.toml"),+ stringifyToml({+ model_provider: providerId,+ model: "synthetic-model",+ model_providers: {+ [providerId]: {+ name: "Synthetic provider",+ wire_api: "responses",+ base_url: "https://provider.example.test/v1",+ env_key: "SYNTHETIC_CUSTOM_API_KEY",+ },+ },+ }),+ );+ const selected = await effectiveProvider(+ { CODEX_HOME: home, SYNTHETIC_CUSTOM_API_KEY: "synthetic-custom-key" },+ root,+ [],+ "review",+ );+ expect(selected).toMatchObject({ env_key: "SYNTHETIC_CUSTOM_API_KEY" });+ },+ 30_000,+);++for (const mode of ["standard", "deep"] as const) {+ test.each(fileProviderKeyCases)(+ `file provider %s preserves %s authentication for ${mode} preflight and children`,+ async (providerId, _selection, providerKey) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const scan = join(root, "scan");+ const sourceHome = join(root, "source-home");+ const report = join(root, "environment.json");+ await mkdir(repository);+ await mkdir(scan, { mode: 0o700 });+ await mkdir(sourceHome, { mode: 0o700 });+ const plugin = await createPluginProbe(root, report);+ const canonicalKey = `${providerId.toUpperCase()}_API_KEY`;+ const headerEnvironment =+ _selection === "canonical header" ||+ _selection === "missing custom primary"+ ? { [canonicalKey]: " synthetic-header-key " }+ : {};+ const inheritedEnvironment = {+ ...(_selection === "custom Codex key" ||+ _selection === "other external key"+ ? Object.fromEntries(+ [+ "OPENAI_API_KEY",+ "CODEX_API_KEY",+ "OPENROUTER_API_KEY",+ "FIREWORKS_API_KEY",+ ]+ .filter((name) => name !== providerKey)+ .map((name) => [name, "synthetic-unrelated-key"]),+ )+ : {}),+ ...headerEnvironment,+ ...(_selection === "missing custom primary"+ ? {}+ : { [providerKey]: "synthetic-file-key" }),+ };+ const workerEnvironment = {+ ...headerEnvironment,+ [providerKey]: "synthetic-file-key",+ };+ const provider = {+ name: "Synthetic file provider",+ wire_api: "responses",+ base_url: "https://provider.example.test/v1",+ env_key: providerKey,+ ...(_selection === "canonical header"+ ? { env_http_headers: { "X-Synthetic-Token": canonicalKey } }+ : {}),+ };+ const original = stringifyToml({+ model: "synthetic-model",+ model_provider: providerId,+ model_providers: { [providerId]: provider },+ features: { shell_tool: false, unified_exec: false },+ });+ await writeFile(join(sourceHome, "review.config.toml"), original);+ let launched = false;+ const client = new TestClient(+ { pluginPath: plugin, codexOverrides: { profile: "review" } },+ {+ environment: {+ CODEX_HOME: sourceHome,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ ...inheritedEnvironment,+ },+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scan,+ repositoryRevision: async () => "deadbeef",+ createCodex: (options) => {+ launched = true;+ return {+ startThread: () => ({+ id: null,+ async runStreamed() {+ expect(options.apiKey).toBeUndefined();+ const environment = options.env!;+ expect(environment[providerKey]).toBe("synthetic-file-key");+ for (const name of [+ "OPENAI_API_KEY",+ "CODEX_API_KEY",+ "OPENROUTER_API_KEY",+ "FIREWORKS_API_KEY",+ ]) {+ expect(environment[name]).toBe(+ name === providerKey || name === canonicalKey+ ? inheritedEnvironment[name]+ : undefined,+ );+ }+ if (mode === "deep") {+ const settings = await workerRuntimeSettings(environment);+ expect(settings.environment).toEqual(workerEnvironment);+ expect(+ await effectiveProvider(+ environment,+ repository,+ profileConfigOverrides(settings.config),+ settings.nativeProfile,+ ),+ ).toMatchObject(provider);+ const status = await nativeRequest(+ environment,+ repository,+ [],+ "mcpServerStatus/list",+ {+ serverName: "codex-security",+ detail: "toolsAndAuthOnly",+ },+ );+ expect(status.data[0].toolsError).toBeNull();+ expect(status.data[0].tools).toHaveProperty(+ "synthetic_environment",+ );+ expect(+ JSON.parse(await readFile(report, "utf8")).recovered,+ ).toEqual(workerEnvironment);+ const snapshot =+ environment["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!;+ if (process.platform !== "win32")+ expect((await stat(snapshot)).mode & 0o777).toBe(0o600);+ expect(await readFile(snapshot, "utf8")).toContain(+ '"synthetic-file-key"',+ );+ }+ for (const text of [+ await readFile(+ environment["CODEX_SECURITY_CONFIG_PATH"]!,+ "utf8",+ ),+ JSON.stringify({+ config: options.config,+ overrides: options.configOverrides,+ }),+ ]) {+ expect(text).not.toContain("synthetic-file-key");+ expect(text).not.toContain("synthetic-header-key");+ }+ throw new Error("synthetic file provider child checked");+ },+ }),+ };+ },+ },+ );+ try {+ const preflight = await client.preflight(repository, { mode });+ expect(preflight.authentication).toEqual({+ method: "api_key",+ source: providerKey,+ verified: false,+ });+ expect(preflight.modelProvider).toBe(providerId);+ if (_selection === "missing custom primary") {+ await expect(+ client.preflight(repository, { mode, auth: "api-key" }),+ ).rejects.toThrow(providerKey);+ await expect(client.run(repository, { mode })).rejects.toThrow(+ providerKey,+ );+ expect(launched).toBe(false);+ return;+ }+ await expect(client.run(repository, { mode })).rejects.toThrow(+ "synthetic file provider child checked",+ );+ expect(launched).toBe(true);+ expect(+ await readFile(join(sourceHome, "review.config.toml"), "utf8"),+ ).toBe(original);+ } finally {+ await client.close();+ }+ },+ 30_000,+ );+}+test("workers preserve native provider inheritance without an explicit selection", async () => {const root = await temporaryDirectory();const home = join(root, "native-home");@@ -865,68 +1223,74 @@ test.each([resolvePluginPython: async () => "/managed/python",prepareOutputDir: async () => scan,repositoryRevision: async () => "deadbeef",- createCodex: (options) =>- codexFactory(async function runStreamed() {- expect(options.apiKey).toBe(- external ? undefined : "synthetic-account-key",- );- const status = await nativeRequest(- {- ...options.env!,- ...(options.apiKey === undefined- ? {}- : { CODEX_API_KEY: options.apiKey }),- },- repository,- [],- // Tool enumeration starts the real MCP child without a model turn.- "mcpServerStatus/list",- { serverName: "codex-security", detail: "toolsAndAuthOnly" },- );- expect(status.data).toHaveLength(1);- expect(status.data[0].name).toBe("codex-security");- expect(status.data[0].toolsError).toBeNull();- expect(status.data[0].tools).toHaveProperty(- "synthetic_environment",- );- expect(JSON.parse(await readFile(report, "utf8"))).toEqual({- inherited: {- SYNTHETIC_CUSTOM_API_KEY: null,- SYNTHETIC_CUSTOM_HEADER: null,- SYNTHETIC_REQUIRED_KEY: null,- SYNTHETIC_UNUSED_KEY: null,- },- recovered: {- ...providerEnvironment,- ...(process.platform === "win32"- ? { [headerKey]: " synthetic-child-header " }- : {}),- ...(external ? { [providerKey]: "synthetic-custom-key" } : {}),- ...(providerKey === "CODEX_API_KEY"- ? { CODEX_API_KEY: "synthetic-account-key" }- : {}),- },- });- for (const text of [- await readFile(- options.env!["CODEX_SECURITY_CONFIG_PATH"]!,- "utf8",- ),- await readFile(- join(options.env!["CODEX_HOME"]!, "config.toml"),- "utf8",- ),- JSON.stringify({- config: options.config,- overrides: options.configOverrides,- }),- ]) {- for (const marker of Object.values(providerEnvironment)) {- expect(text).not.toContain(marker);+ createCodex: (options) => ({+ startThread: () => ({+ id: null,+ async runStreamed() {+ expect(options.apiKey).toBe(+ external ? undefined : "synthetic-account-key",+ );+ const status = await nativeRequest(+ {+ ...options.env!,+ ...(options.apiKey === undefined+ ? {}+ : { CODEX_API_KEY: options.apiKey }),+ },+ repository,+ [],+ // Tool enumeration starts the real MCP child without a model turn.+ "mcpServerStatus/list",+ { serverName: "codex-security", detail: "toolsAndAuthOnly" },+ );+ expect(status.data).toHaveLength(1);+ expect(status.data[0].name).toBe("codex-security");+ expect(status.data[0].toolsError).toBeNull();+ expect(status.data[0].tools).toHaveProperty(+ "synthetic_environment",+ );+ expect(JSON.parse(await readFile(report, "utf8"))).toEqual({+ inherited: {+ SYNTHETIC_CUSTOM_API_KEY: null,+ SYNTHETIC_CUSTOM_HEADER: null,+ SYNTHETIC_REQUIRED_KEY: null,+ SYNTHETIC_UNUSED_KEY: null,+ },+ recovered: {+ ...providerEnvironment,+ ...(process.platform === "win32"+ ? { [headerKey]: " synthetic-child-header " }+ : {}),+ ...(external+ ? { [providerKey]: "synthetic-custom-key" }+ : {}),+ ...(providerKey === "CODEX_API_KEY"+ ? { CODEX_API_KEY: "synthetic-account-key" }+ : {}),+ },+ });+ for (const text of [+ await readFile(+ options.env!["CODEX_SECURITY_CONFIG_PATH"]!,+ "utf8",+ ),+ await readFile(+ join(options.env!["CODEX_HOME"]!, "config.toml"),+ "utf8",+ ),+ JSON.stringify({+ config: options.config,+ overrides: options.configOverrides,+ }),+ ]) {+ for (const marker of Object.values(providerEnvironment)) {+ expect(text).not.toContain(marker);+ }}- }- throw new Error("synthetic native plugin environment checked");- })(),+ throw new Error("synthetic native plugin environment checked");+ },+ }),+ }),},);try {diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 0cc8c4d8a..263d3f97f 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -20,7 +20,16 @@ import { execFileSync } from "node:child_process";import * as childProcess from "node:child_process";import { hash } from "node:crypto";import { existsSync } from "node:fs";-import { basename, delimiter, dirname, join, relative, win32 } from "node:path";+import {+ basename,+ delimiter,+ dirname,+ join,+ relative,+ resolve,+ sep,+ win32,+} from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import {Codex,@@ -1445,6 +1454,35 @@ describe("CodexSecurity orchestration", () => {{model_reasoning_summary: "auto",service_tier: "flex",+ model_instructions_file: join(root, "instructions-1.md"),+ model_catalog_json: join(root, "catalog-1.json"),+ experimental_compact_prompt_file: join(root, "compact-1.md"),+ features: {+ code_mode: {+ enabled: true,+ excluded_tool_namespaces: ["synthetic_first"],+ },+ },+ model_verbosity: "high",+ web_search: "disabled",+ skills: {+ config: [+ { path: join(root, "skill-1", "SKILL.md"), enabled: false },+ ],+ },+ otel: {+ exporter: {+ "otlp-http": {+ endpoint: "https://telemetry.example.test/first",+ protocol: "binary",+ tls: {+ "ca-certificate": "tls-1/ca.pem",+ "client-certificate": "tls-1/client.pem",+ "client-private-key": "tls-1/client.key",+ },+ },+ },+ },model_context_window: 64_000,model_auto_compact_token_limit: 48_000,windows: { sandbox: "unelevated" },@@ -1470,6 +1508,17 @@ describe("CodexSecurity orchestration", () => {},model_reasoning_summary: "concise",service_tier: "fast",+ model_instructions_file: join(root, "instructions-2.md"),+ model_catalog_json: join(root, "catalog-2.json"),+ experimental_compact_prompt_file: join(root, "compact-2.md"),+ features: {+ code_mode: {+ enabled: false,+ excluded_tool_namespaces: ["synthetic_second"],+ },+ },+ model_verbosity: "low",+ web_search: "cached",model_context_window: 96_000,model_auto_compact_token_limit: 72_000,windows: { sandbox: "elevated" },@@ -1492,6 +1541,8 @@ describe("CodexSecurity orchestration", () => {model_reasoning_summary: "concise",service_tier: "fast",model_instructions_file: "profile-instructions.md",+ model_catalog_json: "profile-catalog.json",+ experimental_compact_prompt_file: "profile-compact.md",model_verbosity: "high",model_auto_compact_token_limit: 112_000,windows: { sandbox: "unelevated" },@@ -1502,6 +1553,15 @@ describe("CodexSecurity orchestration", () => {"fast",],];+ const originalScenarios = structuredClone(scenarios);+ const bundledSkillNames = (+ await readdir(join(PLUGIN_ROOT, "skills"), {+ withFileTypes: true,+ })+ )+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name)+ .sort();let started = 0;const allStarted = Promise.withResolvers<void>();const configPaths = new Set<string>();@@ -1524,7 +1584,20 @@ describe("CodexSecurity orchestration", () => {resolveCodexProfile(overrides)["model_instructions_file"];const instructions = `Synthetic instructions for scan ${index}.\n`;if (typeof instructionsFile === "string") {- await writeFile(join(scanDir, instructionsFile), instructions);+ await writeFile(resolve(scanDir, instructionsFile), instructions);+ }+ for (const key of [+ "model_catalog_json",+ "experimental_compact_prompt_file",+ ]) {+ const path = resolveCodexProfile(overrides)[key];+ if (typeof path === "string")+ await writeFile(+ resolve(scanDir, path),+ key === "model_catalog_json"+ ? '{"models":[]}\n'+ : `Synthetic compact prompt for scan ${index}.\n`,+ );}const authentication: Record<string, string> =index === 0@@ -1591,7 +1664,6 @@ describe("CodexSecurity orchestration", () => {expect(workerConfig["analytics"]).toEqual(selected["analytics"],);- expect(workerConfig["otel"]).toEqual(selected["otel"]);expect(workerConfig["responses_api_metadata"]).toMatchObject({...(selected["responses_api_metadata"] asJsonObject | undefined),@@ -1607,6 +1679,59 @@ describe("CodexSecurity orchestration", () => {windows,);expect(options.config?.["windows"]).toEqual(windows);+ const requestedSkills =+ (+ selected["skills"] as+ | { config: { path: string; enabled: boolean }[] }+ | undefined+ )?.config ?? [];+ const effectiveSkills = options.config?.["skills"] as {+ config: { path: string; enabled: boolean }[];+ };+ const requestedPaths = new Set(+ requestedSkills.map((entry) => entry.path),+ );+ const cachedSkills = effectiveSkills.config.filter(+ (entry) => !requestedPaths.has(entry.path),+ );+ expect(effectiveSkills.config).toEqual([+ ...requestedSkills,+ ...cachedSkills,+ ]);+ expect(+ cachedSkills+ .map((entry) => basename(dirname(entry.path)))+ .sort(),+ ).toEqual(bundledSkillNames);+ for (const entry of cachedSkills) {+ expect(entry.enabled).toBe(false);+ expect(basename(entry.path)).toBe("SKILL.md");+ expect(+ relative(options.env!["CODEX_HOME"]!, entry.path),+ ).toStartWith(join("plugins", "cache") + sep);+ }+ expect(workerConfig["skills"]).toEqual(effectiveSkills);+ expect(options.config?.["otel"] as unknown).toEqual(+ selected["otel"],+ );+ const expectedOtel = structuredClone(selected["otel"]);+ if (index === 1) {+ const exporter = (expectedOtel as JsonObject)[+ "exporter"+ ] as JsonObject;+ const exporterSettings = exporter[+ "otlp-http"+ ] as JsonObject;+ const tls = exporterSettings["tls"] as JsonObject;+ for (const field of [+ "ca-certificate",+ "client-certificate",+ "client-private-key",+ ]) {+ tls[field] = join(scanDir, tls[field] as string);+ }+ }+ expect(workerConfig["otel"]).toEqual(expectedOtel);for (const key of ["cli_auth_credentials_store","forced_login_method",@@ -1631,7 +1756,7 @@ describe("CodexSecurity orchestration", () => {);expect(workerConfig["model_instructions_file"]).toBe(typeof instructionsFile === "string"- ? join(scanDir, instructionsFile)+ ? resolve(scanDir, instructionsFile): undefined,);if (typeof instructionsFile === "string") {@@ -1642,6 +1767,21 @@ describe("CodexSecurity orchestration", () => {),).toBe(instructions);}+ for (const key of [+ "model_catalog_json",+ "experimental_compact_prompt_file",+ ]) {+ const path = resolveCodexProfile(overrides)[key];+ expect(workerConfig[key]).toBe(+ typeof path === "string"+ ? resolve(scanDir, path)+ : undefined,+ );+ if (typeof path === "string")+ expect(+ await readFile(workerConfig[key] as string, "utf8"),+ ).toBe(await readFile(resolve(scanDir, path), "utf8"));+ }const config = parseToml(await readFile(configPath!, "utf8"),) as JsonObject;@@ -1650,7 +1790,35 @@ describe("CodexSecurity orchestration", () => {model_reasoning_summary: expected,model_provider: "amazon-bedrock",});- expect(config["service_tier"]).toBe(expectedTier);+ expect(resolveCodexProfile(config)["service_tier"]).toBe(+ expectedTier,+ );+ const requested = resolveCodexProfile(overrides);+ for (const key of [+ "model_instructions_file",+ "model_catalog_json",+ "experimental_compact_prompt_file",+ "model_verbosity",+ "web_search",+ ]) {+ expect(resolveCodexProfile(config)[key]).toBe(+ requested[key],+ );+ }+ expect(+ (+ resolveCodexProfile(config)["features"] as+ JsonObject | undefined+ )?.["code_mode"],+ ).toEqual(+ (requested["features"] as JsonObject | undefined)?.[+ "code_mode"+ ],+ );+ if (index === 1 || index === 2)+ expect(mcpEnvironment["CODEX_SECURITY_SCAN_DIR"]).toBe(+ scanDir,+ );expect(mcpEnvironment["AWS_BEARER_TOKEN_BEDROCK"]).toBe(`synthetic-bedrock-key-${index}`,);@@ -1695,6 +1863,7 @@ describe("CodexSecurity orchestration", () => {expect(started).toBe(scenarios.length);expect(configPaths.size).toBe(scenarios.length);expect(deepConfigPaths.size).toBe(scenarios.length);+ expect(scenarios).toEqual(originalScenarios);} finally {allStarted.resolve();await Promise.all(clients.map((client) => client.close()));@@ -4317,6 +4486,7 @@ if __name__ == "__main__":undefined,],["managed provider selection retains matching", "managed", undefined],+ ["relative model files preserve scan origin", "model-files", undefined],] as const)("keeps a completed scan when %s",async (_scenario, failure, warning) => {@@ -4351,7 +4521,24 @@ if __name__ == "__main__":requires_openai_auth: false,http_headers: { "X-Synthetic-Key": "synthetic-managed-secret" },};+ const modelFiles: Record<string, string> =+ failure === "model-files"+ ? {+ model_instructions_file: "../instructions.md",+ model_catalog_json: "../catalog.json",+ experimental_compact_prompt_file: "../compact.md",+ }+ : {};+ for (const [name, contents] of [+ ["instructions.md", "Synthetic instructions.\n"],+ ["catalog.json", '{"models":[]}\n'],+ ["compact.md", "Synthetic compact prompt.\n"],+ ]) {+ if (failure === "model-files")+ await writeFile(join(root, name!), contents!);+ }const providerConfig = {+ ...modelFiles,features: { shell_tool: false, unified_exec: false, view_image: false },windows: { sandbox: "unelevated" },model_provider: "synthetic.provider",@@ -4507,7 +4694,11 @@ if __name__ == "__main__":if (args[0] === "list-global-findings") {expect(progressSignal?.aborted).toBe(true);if (failure === "index") throw new Error("index unavailable");- if (failure === "dismissed" || failure === "managed") {+ if (+ failure === "dismissed" ||+ failure === "managed" ||+ failure === "model-files"+ ) {return {findings: args.includes("--status")? matched@@ -4545,6 +4736,12 @@ if __name__ == "__main__":if (failure !== "managed")expect(options?.config?.codexOverrides).toMatchObject({...providerConfig,+ ...Object.fromEntries(+ Object.entries(modelFiles).map(([key, value]) => [+ key,+ resolve(scanDir, value),+ ]),+ ),features: {...providerConfig.features,...(failure === "budget-context"@@ -4570,6 +4767,17 @@ if __name__ == "__main__":value.includes("synthetic-comparison-header"),),).toBe(false);+ for (const [key, path] of Object.entries(modelFiles)) {+ expect(options?.config?.codexOverrides?.[key]).toBe(+ resolve(scanDir, path),+ );+ expect(+ await readFile(+ options?.config?.codexOverrides?.[key] as string,+ "utf8",+ ),+ ).toBe(await readFile(resolve(scanDir, path), "utf8"));+ }modelCalled = true;observedSingleTurn = runtimeOptions.singleTurn;if (failure === "matcher") throw new Error("matcher unavailable");@@ -4702,7 +4910,9 @@ if __name__ == "__main__":).toEqual(failure === "budget"? ["another-open-finding"]- : failure === "dismissed" || failure === "managed"+ : failure === "dismissed" ||+ failure === "managed" ||+ failure === "model-files"? []: undefined,);@@ -4724,7 +4934,11 @@ if __name__ == "__main__":expect(commands.some(([command]) => command === "list-global-findings"),).toBe(true);- if (failure === "dismissed" || failure === "managed") {+ if (+ failure === "dismissed" ||+ failure === "managed" ||+ failure === "model-files"+ ) {expect(JSON.parse(savedComparisonInput!)).toMatchObject({matches: [{diff --git a/sdk/typescript/tests-ts/cli-policy.test.ts b/sdk/typescript/tests-ts/cli-policy.test.tsindex 24172d812..ae9f6b788 100644--- a/sdk/typescript/tests-ts/cli-policy.test.ts+++ b/sdk/typescript/tests-ts/cli-policy.test.ts@@ -117,6 +117,52 @@ function policyDependencies(}describe("policy CLI", () => {+ test.each(["openai", "openrouter", "amazon-bedrock", "command"] as const)(+ "uses the file-profile %s provider before interactive policy authentication",+ async (provider) => {+ const f = await fixture();+ const home = join(f.root, "profile-home");+ await mkdir(home, { mode: 0o700 });+ await writeFile(+ join(home, "review.config.toml"),+ provider === "command"+ ? 'model_provider = "synthetic-command"\n[model_providers.synthetic-command]\nname = "Synthetic"\nwire_api = "responses"\n[model_providers.synthetic-command.auth]\ncommand = "synthetic-auth"\n'+ : `model_provider = "${provider}"\n`,+ );+ const draft = await f.generate();+ let authPrompts = 0;+ const deps = {+ ...policyDependencies(f, {+ draft,+ prompt: prompt({ isInteractive: () => true }),+ }),+ environment: {+ CODEX_HOME: home,+ OPENAI_API_KEY: "synthetic-openai-key",+ },+ hasStoredChatGPTSignIn: async () => true,+ scanAuthenticationPrompt: {+ isInteractive: () => true,+ select: async <T>(+ _message: string,+ choices: readonly { value: T }[],+ ) => {+ authPrompts += 1;+ return choices[0]!.value;+ },+ },+ };+ const code = await main(+ ["policy", "--codex", 'profile="review"'],+ capture().stream,+ capture(true).stream,+ deps,+ );+ expect(code).toBe(0);+ expect(authPrompts).toBe(provider === "openai" ? 1 : 0);+ },+ );+test("documents the policy workflow in help", async () => {const stdout = captureCli(main, "stdout");expect(await stdout.run(["policy", "--help"], dependencies())).toBe(0);diff --git a/sdk/typescript/tests-ts/cli-project-config.test.ts b/sdk/typescript/tests-ts/cli-project-config.test.tsindex 3fa014281..838dbac46 100644--- a/sdk/typescript/tests-ts/cli-project-config.test.ts+++ b/sdk/typescript/tests-ts/cli-project-config.test.ts@@ -1240,6 +1240,34 @@ test("dry-run uses the real SDK without initializing its runtime and reports pro},failOnSeverity: "high",});+ const nativeProject = JSON.parse(+ await readFile(input.config, "utf8"),+ ) as Record<string, JsonObject>;+ delete nativeProject["codex"]!["profiles"];+ delete nativeProject["codex"]!["model"];+ await writeFile(input.config, JSON.stringify(nativeProject));+ await writeFile(+ join(ambient, "review.config.toml"),+ 'model = "synthetic-native-model"\nmodel_provider = "openrouter"\nmodel_reasoning_effort = "high"\n',+ );+ Object.assign(environment, {+ OPENROUTER_API_KEY: "synthetic-cli-provider-key",+ });+ const nativeCli = createCliTest(main);+ expect(+ await nativeCli.runCli(+ ["scan", "-c", input.config, "--dry-run", "--json"],+ deps,+ ),+ nativeCli.stderr.text(),+ ).toBe(0);+ expect(JSON.parse(nativeCli.stdout.text())).toMatchObject({+ model: "synthetic-native-model",+ modelProvider: "openrouter",+ reasoningEffort: "high",+ });+ expect(createCodex).not.toHaveBeenCalled();+ expect(prepareRuntime).not.toHaveBeenCalled();});test.each([diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex ea9d880bc..f2454e2ba 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -55,6 +55,7 @@ import {FIREWORKS_CODEX_PROVIDER,OPENROUTER_CODEX_PROVIDER,scanModelConfiguration,+ mergedCodexConfig,} from "../src/config.js";import {warningResult,@@ -3900,6 +3901,227 @@ describe("CLI", () => {}});+ test("reports settings from a selected Codex file profile", async () => {+ const home = await temporaryDirectory("codex-security-profile-");+ try {+ await writeFile(+ join(home, "review.config.toml"),+ 'model = "native-model"\nmodel_reasoning_effort = "high"\n',+ );+ const stderr = capture();+ expect(+ await main(+ ["scan", ".", "--codex", 'profile="review"', "--verbose", "--json"],+ capture().stream,+ stderr.stream,+ dependencies({ environment: { CODEX_HOME: home } }),+ ),+ ).toBe(0);+ const configuration = stderr+ .text()+ .split("\n")+ .find((line) =>+ line.startsWith("codex-security: debug: scan.configuration"),+ );+ expect(configuration).toContain('model="native-model"');+ expect(configuration).toContain('reasoning_effort="high"');+ } finally {+ await rm(home, { recursive: true, force: true });+ }+ });++ test.each(["amazon-bedrock", "openrouter", "fireworks"])(+ "uses the selected file-profile model before validating --provider %s",+ async (provider) => {+ const home = await temporaryDirectory("codex-security-provider-profile-");+ const stderr = capture();+ await writeFile(+ join(home, "review.config.toml"),+ 'model = "file-profile-model"\nmodel_reasoning_effort = "high"\n',+ );+ for (const model of [undefined, "explicit-model"]) {+ const selected = model ?? "file-profile-model";+ const args = [+ "scan",+ ".",+ "--provider",+ provider,+ "--codex",+ 'profile="review"',+ "--verbose",+ "--json",+ ...(model === undefined ? [] : ["--model", model]),+ ];+ expect(+ await main(+ args,+ capture().stream,+ stderr.stream,+ dependencies({+ environment: {+ CODEX_HOME: home,+ OPENROUTER_API_KEY: "synthetic-openrouter-key",+ FIREWORKS_API_KEY: "synthetic-fireworks-key",+ },+ }),+ ),+ ).toBe(0);+ expect(stderr.text()).toContain(`model=${JSON.stringify(selected)}`);+ }+ await writeFile(+ join(home, "review.config.toml"),+ 'model_reasoning_effort = "high"\n',+ );+ for (const profile of ["review", "missing"]) {+ const missingModel = capture();+ expect(+ await main(+ [+ "scan",+ ".",+ "--provider",+ provider,+ "--codex",+ `profile="${profile}"`,+ "--json",+ ],+ capture().stream,+ missingModel.stream,+ dependencies({+ environment: {+ CODEX_HOME: home,+ OPENROUTER_API_KEY: "synthetic-openrouter-key",+ FIREWORKS_API_KEY: "synthetic-fireworks-key",+ },+ }),+ ),+ ).toBe(2);+ expect(missingModel.text()).toContain(+ `--model is required when using --provider ${provider}`,+ );+ }+ },+ );++ test.each(["openrouter", "fireworks"])(+ "keeps file-profile command authentication with --provider %s",+ async (provider) => {+ const home = await temporaryDirectory("codex-security-auth-profile-");+ await writeFile(+ join(home, "review.config.toml"),+ `model="synthetic-model"\n[model_providers.${provider}]\nname="Synthetic"\nwire_api="responses"\nbase_url="http://127.0.0.1:1/v1"\n[model_providers.${provider}.auth]\ncommand="synthetic-auth"\n`,+ );+ for (const explicit of [undefined, 4321]) {+ let selected: CodexSecurityConfig | undefined;+ const stderr = capture();+ const args = [+ "scan",+ ".",+ "--provider",+ provider,+ "--codex",+ 'profile="review"',+ "--json",+ ...(explicit === undefined+ ? []+ : [+ "--codex",+ `model_providers.${provider}.auth.refresh_interval_ms=${explicit}`,+ ]),+ ];+ expect(+ await main(+ args,+ capture().stream,+ stderr.stream,+ dependencies({+ environment: { CODEX_HOME: home },+ onConfig: (config) => {+ selected = config;+ },+ }),+ ),+ stderr.text(),+ ).toBe(0);+ const effective = await mergedCodexConfig(selected!, home);+ expect(effective["model_providers"]).toEqual({+ [provider]: {+ name: "Synthetic",+ wire_api: "responses",+ base_url: "http://127.0.0.1:1/v1",+ auth: {+ command: "synthetic-auth",+ ...(explicit === undefined+ ? {}+ : { refresh_interval_ms: explicit }),+ },+ },+ });+ expect(selected!.codexOverrides?.["model_provider"]).toBe(provider);+ }+ },+ );++ test.each([+ ["openrouter", OPENROUTER_CODEX_PROVIDER],+ ["fireworks", FIREWORKS_CODEX_PROVIDER],+ ] as const)(+ "fills missing file-profile %s defaults without replacing refinements",+ async (provider, defaults) => {+ const home = await temporaryDirectory("codex-security-partial-provider-");+ for (const refinement of [+ { request_max_retries: 4 },+ {+ request_max_retries: 4,+ base_url: "http://127.0.0.1:1/v1",+ env_key: "SYNTHETIC_FILE_PROVIDER_KEY",+ },+ ]) {+ await writeFile(+ join(home, "review.config.toml"),+ `model="synthetic-model"\n[model_providers.${provider}]\n` ++ Object.entries(refinement)+ .map(([key, value]) => `${key}=${JSON.stringify(value)}\n`)+ .join(""),+ );+ let selected: CodexSecurityConfig | undefined;+ const stderr = capture();+ expect(+ await main(+ [+ "scan",+ ".",+ "--provider",+ provider,+ "--codex",+ 'profile="review"',+ "--json",+ ],+ capture().stream,+ stderr.stream,+ dependencies({+ environment: {+ CODEX_HOME: home,+ OPENROUTER_API_KEY: "synthetic-openrouter-key",+ FIREWORKS_API_KEY: "synthetic-fireworks-key",+ SYNTHETIC_FILE_PROVIDER_KEY: "synthetic-file-provider-key",+ },+ onConfig: (config) => {+ selected = config;+ },+ }),+ ),+ stderr.text(),+ ).toBe(0);+ expect(+ (await mergedCodexConfig(selected!, home))["model_providers"],+ ).toEqual({+ [provider]: { ...defaults, ...refinement },+ });+ }+ },+ );+test("reports saved model and reasoning effort for verbose scan reruns", async () => {const { stdout, stderr, runCli } = createCliTest(main);diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.tsindex eb263f07f..932357ed6 100644--- a/sdk/typescript/tests-ts/component-scan.test.ts+++ b/sdk/typescript/tests-ts/component-scan.test.ts@@ -1774,27 +1774,45 @@ test.each(["auto", "chatgpt", "api-key"] as const)();test.each([- ["openrouter", "api-key"],- ["openrouter", "chatgpt"],- ["fireworks", "api-key"],- ["fireworks", "chatgpt"],+ ["openrouter", "api-key", "inline"],+ ["openrouter", "chatgpt", "inline"],+ ["fireworks", "api-key", "inline"],+ ["fireworks", "chatgpt", "inline"],+ ["openrouter", "api-key", "CODEX_HOME"],+ ["openrouter", "api-key", "codex_home"],] as const)(- "component planning honors command authentication for %s with %s selection",- async (provider, auth) => {+ "component planning honors command authentication for %s with %s selection via %s",+ async (provider, auth, homeKey) => {const paths = await fixture();+ const sourceHome =+ homeKey === "inline" ? undefined : join(paths.root, "home");+ if (sourceHome !== undefined) {+ await mkdir(sourceHome);+ await writeFile(+ join(sourceHome, "review.config.toml"),+ `model = "synthetic-component-model"+model_provider = "${provider}"+[model_providers.${provider}.auth]+command = "synthetic-auth-helper"+`,+ );+ }const plan = mock(async () => ({ components }));const result = await scan(paths, {components: undefined,auto: true,planOnly: true,- environment: {},+ environment: sourceHome === undefined ? {} : { [homeKey]: sourceHome },config: {- codexOverrides: {- model_provider: provider,- model_providers: {- [provider]: { auth: { command: "synthetic-auth-helper" } },- },- },+ codexOverrides:+ sourceHome === undefined+ ? {+ model_provider: provider,+ model_providers: {+ [provider]: { auth: { command: "synthetic-auth-helper" } },+ },+ }+ : { profile: "review" },},scanOptions: { auth },planComponents: plan,diff --git a/sdk/typescript/tests-ts/config.test.ts b/sdk/typescript/tests-ts/config.test.tsindex 56b3d4900..7e710fa84 100644--- a/sdk/typescript/tests-ts/config.test.ts+++ b/sdk/typescript/tests-ts/config.test.ts@@ -10,6 +10,7 @@ import {quoteTomlString,modelProviderConfigOverride,resolveCodexProfile,+ resolveCommandAuthConfig,scanModelConfiguration,scanModelProvider,} from "../src/config.js";@@ -71,6 +72,25 @@ test("inline Codex overrides preserve literal keys and string values", () => {}});+test.each([+ ["absent", undefined],+ ["null", null],+])(+ "omits an optional %s profile selector before native configuration",+ async (_name, profile) => {+ const config = await mergedCodexConfig({+ codexOverrides: {+ ...(profile === undefined ? {} : { profile }),+ model: "synthetic-selected-model",+ },+ });+ expect(resolveCodexProfile(config)).toMatchObject({+ model: "synthetic-selected-model",+ });+ expect(resolveCodexProfile(config)).not.toHaveProperty("profile");+ },+);+test("inline Codex overrides omit optional null fields like the file writer", async () => {for (const value of [null, { args: ["fixture", null] }]) {expect(() => inlineToml(value)).toThrow(ConfigurationError);@@ -294,6 +314,273 @@ describe("Codex configuration", () => {}});+ test("loads a native profile below explicit scan overrides", async () => {+ const home = await temporaryDirectory();+ await writeFile(+ join(home, "review.config.toml"),+ 'model = "profile-model"\nmodel_reasoning_effort = "high"\nmodel_provider = "synthetic"\n',+ );+ const config = await mergedCodexConfig(+ {+ codexOverrides: {+ profile: "review",+ model: "explicit-model",+ },+ },+ home,+ );++ expect(scanModelConfiguration(config)).toEqual({+ model: "explicit-model",+ reasoningEffort: "high",+ });+ expect(scanModelProvider(config)).toBe("synthetic");+ expect(resolveCodexProfile(config)).not.toHaveProperty("profile");+ });++ test.each(+ [+ "model_instructions_file",+ "experimental_compact_prompt_file",+ "model_catalog_json",+ "sqlite_home",+ "log_dir",+ ].flatMap((key) =>+ [undefined, "explicit.md"].map((explicit) => ({ key, explicit })),+ ),+ )(+ "resolves file-profile paths before explicit overrides: %j",+ async ({ key, explicit }) => {+ const home = await temporaryDirectory();+ await writeFile(+ join(home, "review.config.toml"),+ `${key} = "instructions.md"\n`,+ );+ const overrides = {+ profile: "review",+ ...(explicit === undefined ? {} : { [key]: explicit }),+ };+ const config = await mergedCodexConfig(+ { codexOverrides: overrides },+ home,+ );+ expect(config[key]).toBe(explicit ?? join(home, "instructions.md"));+ expect(overrides).toEqual({+ profile: "review",+ ...(explicit === undefined ? {} : { [key]: explicit }),+ });+ },+ );++ test.each([undefined, "explicit.toml"])(+ "resolves file-profile agent paths before explicit overrides: %j",+ async (explicit) => {+ const home = await temporaryDirectory();+ await writeFile(+ join(home, "review.config.toml"),+ '[agents.reviewer]\ndescription = "Synthetic reviewer"\nconfig_file = "agents/reviewer.toml"\n',+ );+ const overrides = {+ profile: "review",+ ...(explicit === undefined+ ? {}+ : { agents: { reviewer: { config_file: explicit } } }),+ };+ const config = await mergedCodexConfig(+ { codexOverrides: overrides },+ home,+ );+ expect(config["agents"]).toMatchObject({+ reviewer: {+ description: "Synthetic reviewer",+ config_file: explicit ?? join(home, "agents/reviewer.toml"),+ },+ });+ expect(overrides).toEqual({+ profile: "review",+ ...(explicit === undefined+ ? {}+ : { agents: { reviewer: { config_file: explicit } } }),+ });+ },+ );++ test.each([undefined, "explicit/SKILL.md", "~/native/SKILL.md"])(+ "preserves native skill path origins before explicit overrides (%s)",+ async (explicit) => {+ const home = await temporaryDirectory("codex-security-skill-profile-");+ await writeFile(+ join(home, "review.config.toml"),+ '[[skills.config]]\npath="skill/SKILL.md"\nenabled=false\n',+ );+ const config = await mergedCodexConfig(+ {+ codexOverrides: {+ profile: "review",+ ...(explicit === undefined+ ? {}+ : { skills: { config: [{ path: explicit, enabled: true }] } }),+ },+ },+ home,+ );+ expect(config["skills"]).toEqual({+ config: [+ {+ path: explicit ?? join(home, "skill/SKILL.md"),+ enabled: explicit !== undefined,+ },+ ],+ });+ },+ );++ test("validates effective native multi-agent settings after file overrides", async () => {+ const home = await temporaryDirectory();+ await writeFile(+ join(home, "review.config.toml"),+ "[features.multi_agent_v2]\nenabled = false\n",+ );+ await expect(+ mergedCodexConfig({ codexOverrides: { profile: "review" } }, home),+ ).rejects.toThrow("cannot be disabled");+ await expect(+ mergedCodexConfig(+ {+ codexOverrides: {+ profile: "review",+ features: { multi_agent_v2: { enabled: true } },+ },+ },+ home,+ ),+ ).resolves.toMatchObject({+ features: { multi_agent_v2: { enabled: true } },+ });+ });++ test.each(+ ["exporter", "trace_exporter", "metrics_exporter"].flatMap((exporter) =>+ ["otlp-http", "otlp-grpc"].flatMap((protocol) =>+ [undefined, "explicit-client.key", "~/native/client.key"].map(+ (explicit) => ({+ exporter,+ protocol,+ explicit,+ }),+ ),+ ),+ ),+ )(+ "preserves OTEL file origins before explicit TLS overrides: %j",+ async ({ exporter, protocol, explicit }) => {+ const home = await temporaryDirectory();+ const paths = {+ "ca-certificate": "tls/ca.pem",+ "client-certificate": "tls/client.pem",+ "client-private-key": "tls/client.key",+ };+ await writeFile(+ join(home, "review.config.toml"),+ `[otel.${exporter}.${protocol}.tls]\n` ++ Object.entries(paths)+ .map(([key, value]) => `${key}=${JSON.stringify(value)}\n`)+ .join(""),+ );+ const overrides = {+ profile: "review",+ ...(explicit === undefined+ ? {}+ : {+ otel: {+ [exporter]: {+ [protocol]: { tls: { "client-private-key": explicit } },+ },+ },+ }),+ };+ const original = structuredClone(overrides);+ const config = await mergedCodexConfig(+ { codexOverrides: overrides },+ home,+ );+ expect(config["otel"]).toEqual({+ [exporter]: {+ [protocol]: {+ tls: {+ "ca-certificate": join(home, paths["ca-certificate"]),+ "client-certificate": join(home, paths["client-certificate"]),+ "client-private-key":+ explicit ?? join(home, paths["client-private-key"]),+ },+ },+ },+ });+ expect(overrides).toEqual(original);+ },+ );++ test.each([undefined, "other helpers", "~/helpers"])(+ "retains inherited command auth cwd unless the profile overrides it: %s",+ async (cwd) => {+ const home = await temporaryDirectory();+ const config: JsonObject = {+ profile: "review",+ model_provider: "synthetic",+ model_providers: {+ synthetic: {+ auth: {+ command: "./token",+ cwd: "helpers",+ refresh_interval_ms: 1000,+ },+ },+ },+ profiles: {+ review: {+ model_providers: {+ synthetic: {+ auth: {+ refresh_interval_ms: 2000,+ ...(cwd === undefined ? {} : { cwd }),+ },+ },+ },+ },+ },+ };+ const saved = structuredClone(config);+ expect(+ resolveCodexProfile(resolveCommandAuthConfig(config, home)),+ ).toMatchObject({+ model_providers: {+ synthetic: {+ auth: {+ command: "./token",+ cwd: cwd?.startsWith("~") ? cwd : join(home, cwd ?? "helpers"),+ refresh_interval_ms: 2000,+ },+ },+ },+ });+ expect(config).toEqual(saved);+ },+ );++ test("rejects invalid native profile names and owned settings", async () => {+ const home = await temporaryDirectory();+ await writeFile(+ join(home, "review.config.toml"),+ "[features]\nplugins = false\n",+ );+ await expect(+ mergedCodexConfig({ codexOverrides: { profile: "../review" } }, home),+ ).rejects.toThrow("plain name");+ await expect(+ mergedCodexConfig({ codexOverrides: { profile: "review" } }, home),+ ).rejects.toThrow("owns plugin loading configuration");+ });+test("ignores model overrides from unselected Codex profiles", async () => {const config = await mergedCodexConfig({codexOverrides: {diff --git a/sdk/typescript/tests-ts/custom-validation.test.ts b/sdk/typescript/tests-ts/custom-validation.test.tsindex fc1a13ae1..d657e4856 100644--- a/sdk/typescript/tests-ts/custom-validation.test.ts+++ b/sdk/typescript/tests-ts/custom-validation.test.ts@@ -1,4 +1,5 @@import { execFileSync } from "node:child_process";+import { resolveCodexProfile } from "../src/config.js";import { randomUUID } from "node:crypto";import {chmod,@@ -1282,50 +1283,61 @@ describe("custom validation", () => {).rejects.toThrow("incompatible");});- test("the bundled Codex honors the invocation-only completion restriction", async () => {- const home = await temporaryDirectory();- const marketplace = await createMarketplace(home, PLUGIN_ROOT);- const command = resolveCodexCommand({}).command;- const run = (args: string[]) =>- execFileSync(command, args, {- env: {- PATH: process.env["PATH"],- SystemRoot: process.env["SystemRoot"],- TEMP: process.env["TEMP"],- TMP: process.env["TMP"],- CODEX_HOME: home,- },- encoding: "utf8",- windowsHide: true,- });- run(["plugin", "marketplace", "add", marketplace]);- run(["plugin", "add", "--json", "codex-security@codex-security-sdk"]);- const config = await customValidationConfig(- {+ for (const profiled of [false, true]) {+ test(`the bundled Codex honors the invocation-only completion restriction with inline profile: ${profiled}`, async () => {+ const home = await temporaryDirectory();+ const marketplace = await createMarketplace(home, PLUGIN_ROOT);+ const command = resolveCodexCommand({}).command;+ const run = (args: string[]) =>+ execFileSync(command, args, {+ env: {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ TEMP: process.env["TEMP"],+ TMP: process.env["TMP"],+ CODEX_HOME: home,+ },+ encoding: "utf8",+ windowsHide: true,+ });+ run(["plugin", "marketplace", "add", marketplace]);+ run(["plugin", "add", "--json", "codex-security@codex-security-sdk"]);+ const settings = {mcp_servers: {"codex-security": { disabled_tools: ["user_disabled_tool"] },},- },- PLUGIN_ROOT,- );- const server = (config["mcp_servers"] as Record<string, unknown>)[- "codex-security"- ] as Record<string, unknown>;- const overrides = Object.entries(server).flatMap(([key, value]) => [- "-c",- `mcp_servers.codex-security.${key}=${JSON.stringify(value)}`,- ]);- const effective = JSON.parse(- run([...overrides, "mcp", "get", "codex-security", "--json"]),- );- expect(effective.disabled_tools).toContain("complete_codex_security_scan");- expect(effective.disabled_tools).toContain("user_disabled_tool");- expect(effective.transport.cwd).toBe(resolve(PLUGIN_ROOT));- const ordinary = JSON.parse(- run(["mcp", "get", "codex-security", "--json"]),- );- expect(ordinary.disabled_tools).toBeNull();- });+ };+ const config = resolveCodexProfile(+ await customValidationConfig(+ profiled+ ? { profile: "review", profiles: { review: settings } }+ : settings,+ PLUGIN_ROOT,+ ),+ );+ const server = (config["mcp_servers"] as Record<string, unknown>)[+ "codex-security"+ ] as Record<string, unknown>;+ const overrides = Object.entries(server).flatMap(([key, value]) => [+ "-c",+ `mcp_servers.codex-security.${key}=${JSON.stringify(value)}`,+ ]);+ const effective = JSON.parse(+ run([...overrides, "mcp", "get", "codex-security", "--json"]),+ );+ expect(effective.disabled_tools).toContain(+ "complete_codex_security_scan",+ );+ expect(effective.disabled_tools).toContain("user_disabled_tool");+ expect(config).not.toHaveProperty("profile");+ expect(config).not.toHaveProperty("profiles");+ expect(effective.transport.cwd).toBe(resolve(PLUGIN_ROOT));+ const ordinary = JSON.parse(+ run(["mcp", "get", "codex-security", "--json"]),+ );+ expect(ordinary.disabled_tools).toBeNull();+ });+ }});const unexpectedValidation = rejecting("unexpected validation");diff --git a/sdk/typescript/tests-ts/provider-profile.test.ts b/sdk/typescript/tests-ts/provider-profile.test.tsindex 2c2b46bab..f71dec38c 100644--- a/sdk/typescript/tests-ts/provider-profile.test.ts+++ b/sdk/typescript/tests-ts/provider-profile.test.ts@@ -19,11 +19,13 @@ import {createProfileCodex,createProviderProfile,providerPreflightCommand,+ restoreProviderProfile,} from "../src/provider-profile.js";import { CodexLoginHandle } from "../src/auth.js";-import { structuredCodexConfig } from "../src/config.js";+import { mergeCodexOverrides, structuredCodexConfig } from "../src/config.js";import {bundledPluginRoot,+ codexSecurityCredentialHome,resolveCodexCommand,runCodexCommand,} from "../src/runtime.js";@@ -59,6 +61,81 @@ const startupProviders = {"synthetic.gateway": startupProvider,};+test.each([false, true])(+ "saved managed provider profiles remain isolated across concurrent scans (replay: %p)",+ async (replay) => {+ const root = await temporaryDirectory();+ const environment = {+ CODEX_HOME: join(root, "ambient"),+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ };+ const home = codexSecurityCredentialHome(environment);+ const providers = ["first", "second"].map((name) => ({+ openrouter: {+ base_url: `https://${name}.example.invalid/`,+ http_headers: { "X-Synthetic-Token": `synthetic-${name}-value` },+ ...(replay ? { auth: null } : {}),+ },+ }));+ const profiles = await Promise.all(+ providers.map((model_providers) =>+ createProviderProfile(home, { model_providers }, { replay }),+ ),+ );+ expect(profiles[0]!.name).not.toBe(profiles[1]!.name);+ const restore = (index: number) =>+ restoreProviderProfile(+ { model_provider: "openrouter" },+ { name: profiles[index]!.name, home: "managed" },+ environment,+ );+ const restored = await Promise.all([restore(0), restore(1)]);+ for (const [index, profile] of profiles.entries()) {+ expect(restored[index]).toEqual({+ model_provider: "openrouter",+ model_providers: providers[index]!,+ });+ if (process.platform !== "win32")+ expect((await stat(profile.path)).mode & 0o777).toBe(0o600);+ }+ await profiles[0]!.cleanup();+ expect(await restore(1)).toEqual(restored[1]);+ await expect(+ restoreProviderProfile(+ {},+ { name: "../outside", home: "managed" },+ environment,+ ),+ ).rejects.toThrow("invalid provider profile");+ },+);++test("saved provider reads preserve JSON parse and permission failures", async () => {+ const root = await temporaryDirectory();+ const environment = { CODEX_SECURITY_STATE_DIR: join(root, "state") };+ const home = codexSecurityCredentialHome(environment);+ const profile = await createProviderProfile(home, config);+ const reference = { name: profile.name, home: "managed" };+ const jsonPath = join(home, `${profile.name}.config.json`);+ expect(await restoreProviderProfile({}, reference, environment)).toEqual({+ model_providers: config.model_providers,+ });+ await writeFile(jsonPath, "{", { mode: 0o600 });+ await expect(+ restoreProviderProfile({}, reference, environment),+ ).rejects.toBeInstanceOf(SyntaxError);+ if (process.platform !== "win32" && process.geteuid?.() !== 0) {+ await chmod(jsonPath, 0o000);+ try {+ await expect(+ restoreProviderProfile({}, reference, environment),+ ).rejects.toMatchObject({ code: "EACCES" });+ } finally {+ await chmod(jsonPath, 0o600);+ }+ }+});+test.each([["explicit custom",@@ -226,13 +303,47 @@ test.each([test("native profile turns omit optional null fields and retain array errors", async () => {const home = await temporaryDirectory();+ const saved = await createProviderProfile(+ home,+ {+ model_providers: {+ "synthetic.gateway": { http_headers: null, auth: null },+ },+ },+ { replay: true },+ );+ const replay = await restoreProviderProfile(+ {},+ { name: saved.name, home: "ambient" },+ { CODEX_HOME: home },+ );+ const native = await createProviderProfile(+ home,+ mergeCodexOverrides(+ {+ model_providers: {+ "synthetic.gateway": {+ name: "Synthetic",+ wire_api: "responses",+ http_headers: { "X-Synthetic": "synthetic-inherited-header" },+ auth: { command: "synthetic-inherited-auth" },+ },+ },+ },+ replay,+ ),+ );const script = join(home, "profile child.mjs");await writeFile(script,- `for await (const chunk of process.stdin) {}+ `import { readFile } from "node:fs/promises";+ import { join } from "node:path";+ for await (const chunk of process.stdin) {}+ const args = process.argv.slice(1);+ const profile = await readFile(join(process.env.CODEX_HOME, args[args.indexOf("--profile") + 1] + ".config.toml"), "utf8");console.log(JSON.stringify({ type: "thread.started", thread_id: "synthetic-thread" }));console.log(JSON.stringify({ type: "item.completed", item: {- type: "agent_message", id: "answer", text: JSON.stringify(process.argv.slice(1)),+ type: "agent_message", id: "answer", text: JSON.stringify({ args, profile }),} }));console.log(JSON.stringify({ type: "turn.completed", usage: { input_tokens: 1, output_tokens: 1 } }));process.exit(0);`,@@ -259,14 +370,21 @@ test("native profile turns omit optional null fields and retain array errors", anested: [{ enabled: true, optional: null }],}) as CodexOptions["config"],},- "synthetic-profile",+ native.name,);for (const resumed of [false, true]) {const thread = resumed? codex.resumeThread("synthetic-thread"): codex.startThread();const result = await thread.run("synthetic prompt");- const args: string[] = JSON.parse(result.finalResponse);+ const observed = JSON.parse(result.finalResponse);+ const args: string[] = observed.args;+ expect(parse(observed.profile)).toEqual({+ model_providers: {+ "synthetic.gateway": { name: "Synthetic", wire_api: "responses" },+ },+ });+ expect(args.join(" ")).not.toContain("synthetic-inherited");const overrides = args.flatMap((arg, index) =>arg === "--config" ? [args[index + 1]!] : [],);diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.tsindex 5d492ba0f..0cc0b97a7 100644--- a/sdk/typescript/tests-ts/scan-comparison.test.ts+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts@@ -333,13 +333,20 @@ describe("semantic scan comparison", () => {expect(calls.threadOptions?.threadSource).toBe("security_scan_comparison");});- test.each(["synthetic.gateway", "fireworks", "amazon-bedrock", "command"])(+ test.each([+ "synthetic.gateway",+ "fireworks",+ "amazon-bedrock",+ "command",+ "file-command-shadow",+ "file-command-shadow-lowercase",+ ])("automatic matching retains the per-scan %s provider",async (selection) => {const home = await temporaryDirectory();- await writeFile(join(home, "config.toml"), "");- const providerName =- selection === "command" ? "synthetic.command" : selection;+ const commandProfile =+ selection === "command" || selection.startsWith("file-command-shadow");+ const providerName = commandProfile ? "synthetic.command" : selection;const provider = {...(selection === "amazon-bedrock"? { aws: { region: "us-east-1" } }@@ -350,7 +357,7 @@ describe("semantic scan comparison", () => {}),base_url: "https://provider.example.test/v1",http_headers: { "X-Synthetic-Secret": "synthetic-header-marker" },- ...(selection === "command"+ ...(commandProfile? {auth: {command: "synthetic-auth",@@ -362,6 +369,33 @@ describe("semantic scan comparison", () => {? {}: { env_key: "SYNTHETIC_PROVIDER_KEY" }),};+ const homeConfig = selection.startsWith("file-command-shadow")+ ? stringify({+ profiles: {+ review: {+ model_provider: providerName,+ model_providers: {+ [providerName]: {+ ...provider,+ auth: {+ command: "synthetic-ambient-auth",+ },+ },+ },+ },+ },+ })+ : "";+ await writeFile(join(home, "config.toml"), homeConfig);+ if (selection.startsWith("file-command-shadow")) {+ await writeFile(+ join(home, "review.config.toml"),+ stringify({+ model_provider: providerName,+ model_providers: { [providerName]: provider },+ }),+ );+ }const parentProfile =selection === "fireworks"? await providerProfiles.createProviderProfile(home, {@@ -400,21 +434,26 @@ describe("semantic scan comparison", () => {environment: {PATH: process.env["PATH"],SystemRoot: process.env["SystemRoot"],- CODEX_HOME: home,+ [selection.endsWith("lowercase") ? "codex_home" : "CODEX_HOME"]:+ home,CODEX_SECURITY_SCAN_ID: "current",OPENAI_API_KEY: "synthetic-ambient-key",SYNTHETIC_PROVIDER_KEY: "synthetic-provider-key",},config: {codexOverrides: {- profile: "selected",- profiles: {- selected: {- model_provider: providerName,- model_providers: { [providerName]: provider },- },- },- model_providers: { [providerName]: provider },+ ...(selection.startsWith("file-command-shadow")+ ? { profile: "review" }+ : {+ profile: "selected",+ profiles: {+ selected: {+ model_provider: providerName,+ model_providers: { [providerName]: provider },+ },+ },+ model_providers: { [providerName]: provider },+ }),default_permissions: "codex_security_scan",permissions: {codex_security_scan: { filesystem: { [home]: "write" } },@@ -518,7 +557,7 @@ describe("semantic scan comparison", () => {]) {expect(captured?.config).not.toHaveProperty(key);}- if (selection === "command") {+ if (commandProfile) {expect(captured?.apiKey).toBeUndefined();expect(captured?.env).not.toHaveProperty("OPENAI_API_KEY");}@@ -528,7 +567,9 @@ describe("semantic scan comparison", () => {});expect(calls.threadOptions?.sandboxMode).toBeUndefined();expect(saved).toBe(true);- expect(await readFile(join(home, "config.toml"), "utf8")).toBe("");+ expect(await readFile(join(home, "config.toml"), "utf8")).toBe(+ homeConfig,+ );} finally {nativeCommand.mockRestore();profileClient.spy.mockRestore();@@ -1513,22 +1554,50 @@ describe("semantic scan comparison", () => {expect(startThread).toHaveBeenCalledTimes(1);startThread.mockClear();- // An ambient profile must not replace that explicitly selected provider.+ // An ambient profile must not replace the caller's selected profile.await writeFile(join(home, "config.toml"),stringify({profile: "ambient",- profiles: { ambient: { model_provider: "other" } },+ profiles: {+ ambient: { model_provider: "other" },+ caller: { model_provider: "other" },+ },model_providers: { other: provider },}),);- await expect(- matchScanFindings(- { before: [finding("before")], after: [finding("after")] },- { ...options, config: { codexOverrides: config } },- ),- ).rejects.toThrow("conflicts with command authentication");- expect(startThread).not.toHaveBeenCalled();+ await writeFile(join(home, "caller.config.toml"), stringify(config));+ const nativeCommand = spyOn(runtimeCommands, "runCodexCommand");+ try {+ for (const [selected, codexOverrides] of [+ ["synthetic", { profile: "caller", profiles: { caller: config } }],+ [+ "openai",+ {+ profile: "caller",+ profiles: { caller: { model_provider: "openai" } },+ },+ ],+ ["synthetic", { profile: "caller" }],+ ["synthetic", config],+ ] as [string, JsonObject][]) {+ nativeCommand.mockClear();+ await expect(+ matchScanFindings(+ { before: [finding("before")], after: [finding("after")] },+ { ...options, config: { codexOverrides } },+ ),+ ).rejects.toThrow("Could not read MCP configuration");+ // Native Codex rejects the legacy home selector after caller selection.+ expect(nativeCommand).toHaveBeenCalledTimes(1);+ expect(nativeCommand.mock.calls[0]![0].args).toContain(+ `model_provider="${selected}"`,+ );+ expect(startThread).not.toHaveBeenCalled();+ }+ } finally {+ nativeCommand.mockRestore();+ }} finally {profileClient.spy.mockRestore();startThread.mockRestore();@@ -1538,6 +1607,12 @@ describe("semantic scan comparison", () => {test.each([["default", {}, "elevated"],+ ["file", { profile: "selected" }, "unelevated"],+ [+ "file-explicit",+ { profile: "selected", windows: { sandbox: "elevated" } },+ "elevated",+ ],["elevated", { windows: { sandbox: "elevated" } }, "elevated"],["unelevated", { windows: { sandbox: "unelevated" } }, "unelevated"],["legacy", { features: { elevated_windows_sandbox: false } }, "unelevated"],@@ -1556,10 +1631,20 @@ describe("semantic scan comparison", () => {await writeFile(join(home, "config.toml"),stringify({- ...(name === "profile" ? {} : homeConfig),+ ...(name === "profile"+ ? {}+ : name.startsWith("file")+ ? { windows: { sandbox: "elevated" } }+ : homeConfig),mcp_servers: { inherited: { command: "synthetic-inherited" } },}),);+ if (name.startsWith("file")) {+ await writeFile(+ join(home, "selected.config.toml"),+ '[windows]\nsandbox = "unelevated"\n',+ );+ }const executable = join(home,process.platform === "win32" ? "custom-codex.exe" : "custom-codex",@@ -1591,7 +1676,9 @@ describe("semantic scan comparison", () => {workingDirectory: home,config: {codexOverrides: {- ...(name === "profile" ? homeConfig : {}),+ ...(name === "profile" || name.startsWith("file")+ ? homeConfig+ : {}),mcp_servers: {synthetic: {command: "synthetic-integration",@@ -2781,4 +2868,270 @@ describe("semantic scan comparison", () => {),).rejects.toThrow(error);});+ test("disables explicit and inherited MCP servers for read-only helper turns", async () => {+ const home = await temporaryDirectory("codex-security-comparison-");+ await writeFile(+ join(home, "config.toml"),+ '[mcp_servers.inherited]\ncommand = "synthetic-inherited"\n',+ );+ const executable = join(+ home,+ process.platform === "win32" ? "custom-codex.exe" : "custom-codex",+ );+ await copyFile(resolveCodexCommand({}).command, executable);+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ TEMP: process.env["TEMP"],+ TMP: process.env["TMP"],+ CODEX_HOME: home,+ CODEX_CLI_PATH: executable,+ OPENAI_API_KEY: "synthetic-key",+ };+ const { codex } = fakeCodex({ matches: [], uncertain: [] });+ let config: CodexOptions["config"];+ let codexPath: string | undefined;+ let codexEnvironment: CodexOptions["env"];+ const startThread = spyOn(+ Codex.prototype,+ "startThread",+ ).mockImplementation(function (this: Codex, options) {+ config = (this as unknown as { options: CodexOptions }).options.config;+ codexPath = (this as unknown as { options: CodexOptions }).options+ .codexPathOverride;+ codexEnvironment = (this as unknown as { options: CodexOptions }).options+ .env;+ return codex.startThread(options!) as ReturnType<Codex["startThread"]>;+ });+ try {+ await matchScanFindings(+ { before: [finding("before")], after: [finding("after")] },+ {+ environment,+ workingDirectory: home,+ config: {+ codexOverrides: {+ mcp_servers: {+ synthetic: { command: "synthetic-integration", enabled: true },+ },+ },+ },+ },+ );+ expect(config?.["mcp_servers"]).toEqual({+ synthetic: { command: "synthetic-integration", enabled: false },+ inherited: { enabled: false },+ });+ expect(codexPath).toBe(+ process.platform === "win32"+ ? win32.toNamespacedPath(executable)+ : executable,+ );+ expect(codexEnvironment?.["CODEX_CLI_PATH"]).toBe(executable);+ const effective = await runCodexCommand(+ resolveCodexCommand(environment),+ [+ "-C",+ home,+ "-c",+ 'mcp_servers.synthetic.command="synthetic-integration"',+ ...Object.keys(config!["mcp_servers"]!).flatMap((name) => [+ "-c",+ `mcp_servers.${name}.enabled=false`,+ ]),+ "mcp",+ "list",+ "--json",+ ],+ environment,+ );+ expect(effective.success).toBe(true);+ expect(+ JSON.parse(effective.stdout).map(+ (server: { name: string; enabled: boolean }) => ({+ name: server.name,+ enabled: server.enabled,+ }),+ ),+ ).toEqual([+ { name: "inherited", enabled: false },+ { name: "synthetic", enabled: false },+ ]);+ } finally {+ startThread.mockRestore();+ }+ });++ test.each([+ "home",+ "profile",+ "profile-only",+ "profile-partial",+ "native",+ "overrides",+ "override-away",+ ])(+ "preserves selected file and partial command auth in private matcher profiles: %s",+ async (selection) => {+ const home = await temporaryDirectory(+ "codex-security-command-comparison-",+ );+ const commandAuth = selection !== "override-away";+ const provider = {+ name: "Synthetic",+ wire_api: "responses",+ base_url: "https://provider.example/v1",+ auth: {+ command: "./synthetic-auth",+ args: ["original"],+ refresh_interval_ms: 1234,+ },+ };+ const config = {+ model_provider:+ selection === "overrides" ||+ selection.startsWith("profile") ||+ selection === "native"+ ? "openai"+ : "synthetic.provider",+ model_providers: { "synthetic.provider": provider },+ };+ const contents = stringify(+ selection === "profile-only" ? { model_provider: "openai" } : config,+ );+ await writeFile(join(home, "config.toml"), contents);+ if (selection === "native") {+ await writeFile(+ join(home, "review.config.toml"),+ 'model_provider = "synthetic.provider"\n',+ );+ }+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_HOME: relative(process.cwd(), home),+ OPENAI_API_KEY: "synthetic-ambient-key",+ CODEX_API_KEY: "synthetic-other-key",+ };+ let captured: CodexOptions | undefined;+ let threadOptions: ThreadOptions | undefined;+ const profileClient = captureProfileClient();+ const { codex } = fakeCodex({ matches: [], uncertain: [] });+ const startThread = spyOn(+ Codex.prototype,+ "startThread",+ ).mockImplementation(function (this: Codex, options) {+ captured = (this as unknown as { options: CodexOptions }).options;+ threadOptions = options;+ return codex.startThread(options!) as ReturnType<Codex["startThread"]>;+ });+ try {+ await matchScanFindings(+ { before: [finding("before")], after: [finding("after")] },+ {+ environment,+ workingDirectory: home,+ ...(selection === "overrides"+ ? {+ config: {+ codexOverrides: {+ model_provider: "synthetic.provider",+ model_providers: {+ "synthetic.provider": {+ auth: { args: ["override"], cwd: "~/helpers" },+ },+ },+ },+ },+ }+ : selection === "override-away"+ ? { config: { codexOverrides: { model_provider: "openai" } } }+ : selection.startsWith("profile")+ ? {+ config: {+ codexOverrides: {+ profile: "review",+ profiles: {+ review: {+ model_provider: "synthetic.provider",+ ...(selection === "profile-only"+ ? {+ model_providers: {+ "synthetic.provider": provider,+ },+ }+ : selection === "profile-partial"+ ? {+ model_providers: {+ "synthetic.provider": {+ auth: { refresh_interval_ms: 4567 },+ },+ },+ }+ : {}),+ },+ },+ },+ },+ }+ : selection === "native"+ ? { config: { codexOverrides: { profile: "review" } } }+ : {}),+ },+ );+ expect(captured?.env?.["CODEX_HOME"]).toBe(home);+ if (selection.startsWith("profile") || selection === "native") {+ expect(captured?.config).not.toHaveProperty("profile");+ expect(captured?.config?.["model_provider"]).toBe(+ "synthetic.provider",+ );+ }+ if (commandAuth) {+ expect(captured?.env).not.toHaveProperty("OPENAI_API_KEY");+ expect(captured?.env).not.toHaveProperty("CODEX_API_KEY");+ expect(captured?.apiKey).toBeUndefined();+ expect(profileClient.profiles[0]!.config).toEqual({+ model_providers: {+ "synthetic.provider": {+ ...provider,+ auth: {+ ...provider.auth,+ cwd: selection === "overrides" ? "~/helpers" : home,+ args: selection === "overrides" ? ["override"] : ["original"],+ refresh_interval_ms:+ selection === "profile-partial" ? 4567 : 1234,+ },+ },+ },+ });+ } else {+ expect(captured?.env?.["OPENAI_API_KEY"]).toBe(+ "synthetic-ambient-key",+ );+ expect(parse(captured!.configOverrides!.join("\n"))).toEqual({+ responses_api_metadata: {+ codex_security_surface: "sdk",+ codex_security_command: "compare",+ codex_security_package_version: VERSION,+ codex_security_provider: "openai",+ },+ });+ }+ expect(threadOptions).toMatchObject({+ workingDirectory: home,+ approvalPolicy: "never",+ networkAccessEnabled: false,+ });+ expect(threadOptions?.sandboxMode).toBe(+ commandAuth ? undefined : "read-only",+ );+ expect(await readFile(join(home, "config.toml"), "utf8")).toBe(+ contents,+ );+ } finally {+ profileClient.spy.mockRestore();+ startThread.mockRestore();+ }+ },+ );});diff --git a/sdk/typescript/tests-ts/scan-recipe.test.ts b/sdk/typescript/tests-ts/scan-recipe.test.tsindex 9a03e5f94..8f994c008 100644--- a/sdk/typescript/tests-ts/scan-recipe.test.ts+++ b/sdk/typescript/tests-ts/scan-recipe.test.ts@@ -1,20 +1,372 @@import { createCliTest } from "./support/cli-run.js";+import { writeSession } from "./support/usage-rollout.js";+import { PLUGIN_ROOT } from "./plugin-root.js";import { workbenchCommand } from "./support/workbench-command.js";-import { mkdir, rm, writeFile } from "node:fs/promises";-import { join } from "node:path";+import {+ mkdir,+ readFile,+ readdir,+ rm,+ stat,+ writeFile,+} from "node:fs/promises";+import { join, relative, resolve } from "node:path";import { afterEach, expect, test } from "bun:test";+import { parse as parseToml } from "smol-toml";import { scanPreflightCodexConfig } from "../src/api.js";import { main } from "../src/cli.js";-import { runWorkbench } from "../src/runtime.js";-import { resolveCodexProfile } from "../src/config.js";+import { codexSecurityCredentialHome, runWorkbench } from "../src/runtime.js";+import { restoreProviderProfile } from "../src/provider-profile.js";import { dependencies } from "./cli-fixtures.js";-import { TestClient } from "./support/api-client.js";-import { preparedRuntime } from "./support/api-events.js";+import { mockWorkbench, TestClient } from "./support/api-client.js";+import {+ completedCodex,+ preparedRuntime,+ scanRuntimeDependencies,+} from "./support/api-events.js";import { createApiTestFixtures } from "./support/temporary-directories.js";+import {+ EXTERNAL_CODEX_PROVIDERS,+ mergedCodexConfig,+ resolveCodexProfile,+ type JsonObject,+} from "../src/config.js";const { temporaryDirectory, cleanup } = createApiTestFixtures();afterEach(cleanup);+test.each(+ [true, false].flatMap((rejected) =>+ [true, false].map((providers) => ({ rejected, providers })),+ ),+)(+ "private replay lifetime follows registration: %j",+ async ({ rejected, providers }) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const home = join(root, "profile-home");+ const runtimeHome = join(root, "runtime-home");+ const scanDir = join(root, "scan");+ await Promise.all([mkdir(repository), mkdir(home), mkdir(runtimeHome)]);+ await mkdir(scanDir, { mode: 0o700 });+ await writeFile(join(repository, "source.py"), "value = 1\n");+ await writeFile(+ join(home, "review.config.toml"),+ 'model="synthetic-model"\nmodel_provider="openrouter"\n[model_providers.openrouter]\nname="Synthetic"\nwire_api="responses"\n',+ );+ const environment = {+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ OPENROUTER_API_KEY: "synthetic-launch-key",+ PATH: process.env["PATH"],+ };+ const savedHome = codexSecurityCredentialHome(environment);+ let completed = false;+ const client = new TestClient(+ {+ pluginPath: PLUGIN_ROOT,+ codexOverrides: {+ profile: "review",+ ...(providers+ ? {+ model_providers: {+ openrouter: { base_url: "https://custom.example.invalid/" },+ },+ }+ : { model_instructions_file: null }),+ },+ },+ {+ environment,+ ...scanRuntimeDependencies(runtimeHome, scanDir),+ createCodex: completedCodex(root),+ runWorkbench: async (_runtime, args, input) => {+ if (args[0] === "register-cli-scan") {+ expect(+ (await readdir(savedHome)).filter((name) =>+ name.endsWith(".config.json"),+ ),+ ).toHaveLength(1);+ if (rejected) throw new Error("Synthetic registration rejected");+ }+ if (args[0] === "complete-scan") completed = true;+ if (args[0] === "list-scans") return { scans: [] };+ return mockWorkbench(args, input);+ },+ },+ );+ try {+ if (rejected) {+ await expect(client.run(repository)).rejects.toThrow(+ "Synthetic registration rejected",+ );+ } else {+ await client.run(repository);+ expect(completed).toBe(true);+ }+ await client.close();+ expect(+ (await readdir(savedHome)).filter((name) =>+ name.endsWith(".config.json"),+ ),+ ).toHaveLength(rejected ? 0 : 1);+ } finally {+ await client.close();+ }+ },+);++test.each(+ (["openrouter", "fireworks", "gateway"] as const).flatMap((provider) =>+ (["standard", "deep"] as const).flatMap((mode) =>+ [+ "partial",+ "different-key",+ "model-only",+ "clear-fields",+ "clear-agent",+ "clear-table",+ ].map((profileKind) => ({+ provider,+ mode,+ profileKind,+ })),+ ),+ ),+)(+ "saved launches retain explicit provider refinements: %j",+ async ({ provider, mode, profileKind }) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const home = join(root, "profile-home");+ const runtimeHome = join(root, "runtime-home");+ await Promise.all([mkdir(repository), mkdir(home), mkdir(runtimeHome)]);+ await writeFile(join(repository, "fixture.py"), "value = 1\n");+ await writeFile(+ join(home, "review.config.toml"),+ `model="synthetic-model"\nmodel_provider="${provider}"\n` ++ (profileKind === "model-only"+ ? ""+ : `[model_providers.${provider}]\n` ++ (profileKind === "partial"+ ? "request_max_retries=4\n"+ : 'env_key="SYNTHETIC_OLD_PROVIDER_KEY"\n')) ++ (profileKind.startsWith("clear-")+ ? `[model_providers.${provider}.http_headers]\nX-Inherited="synthetic-inherited-header"\n` ++ `[model_providers.${provider}.auth]\ncommand="synthetic-auth"\n` ++ '[model_providers.agent]\nname="Inherited agent"\nwire_api="responses"\n'+ : ""),+ );+ const python = Bun.which("python3") ?? Bun.which("python");+ if (python === null) throw new Error("Python is required for this test.");+ const standard =+ provider === "gateway"+ ? {+ name: "Synthetic gateway",+ env_key: "SYNTHETIC_PROVIDER_KEY",+ wire_api: "responses",+ }+ : EXTERNAL_CODEX_PROVIDERS[provider];+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ SYNTHETIC_PROVIDER_KEY: "synthetic-launch-key",+ };+ const command = (args: readonly string[], input?: string) =>+ runWorkbench(+ { python, pluginRoot: PLUGIN_ROOT, environment },+ args,+ input,+ );+ const header = "synthetic-provider-header";+ const customEndpoint = "https://provider.example.invalid/custom";+ const explicitProvider = {+ ...standard,+ env_key: "SYNTHETIC_PROVIDER_KEY",+ base_url: customEndpoint,+ http_headers:+ profileKind === "clear-fields"+ ? null+ : { "X-Synthetic-Credential": header },+ ...(profileKind.startsWith("clear-") ? { auth: null } : {}),+ };+ const alternateProvider = {+ name: "Synthetic agent provider",+ base_url: "https://agent.example.invalid/v1",+ env_key: "SYNTHETIC_AGENT_KEY",+ wire_api: "responses",+ };+ const explicitProviders =+ profileKind === "clear-table"+ ? null+ : {+ [provider]: explicitProvider,+ agent: profileKind === "clear-agent" ? null : alternateProvider,+ };+ const overrides = {+ profile: "review",+ model_provider: profileKind === "clear-table" ? "openai" : provider,+ model_providers: explicitProviders,+ };+ const initial = await mergedCodexConfig(+ { codexOverrides: overrides },+ home,+ );+ let providerProfilePath: string | undefined;+ const client = new TestClient(+ {+ pluginPath: PLUGIN_ROOT,+ codexOverrides: overrides,+ },+ {+ environment,+ prepareRuntime: async () => ({+ ...preparedRuntime(runtimeHome),+ deepScanConfigPath: join(runtimeHome, "deep-scan-config.toml"),+ }),+ resolvePluginPython: async () => python,+ runWorkbench: async (_runtime, args, input) => {+ if (mode === "deep" && args[0] === "fail-scan")+ throw new Error("Synthetic disconnected workbench");+ return command(args, input);+ },+ createCodex: async (options) => {+ if (profileKind === "clear-table") {+ expect(options.nativeProfile).toBeUndefined();+ } else {+ expect(typeof options.nativeProfile).toBe("string");+ providerProfilePath = join(+ options.env!["CODEX_HOME"]!,+ `${options.nativeProfile}.config.toml`,+ );+ expect<unknown>(+ parseToml(await readFile(providerProfilePath, "utf8")),+ ).toEqual({+ model_providers: resolveCodexProfile(initial)["model_providers"],+ });+ }+ return {+ startThread: () => ({+ id: "synthetic-recipe-thread",+ async runStreamed() {+ return {+ events: (async function* () {+ yield {+ type: "thread.started" as const,+ thread_id: "synthetic-recipe-thread",+ };+ throw new Error("Synthetic stop after registration");+ })(),+ };+ },+ }),+ };+ },+ },+ );+ try {+ await expect(+ client.run(repository, { mode, outputDir: join(root, "scan") }),+ ).rejects.toThrow("Synthetic stop after registration");+ const scans = (await command(["list-scans", "--repository", repository]))[+ "scans"+ ] as Array<{ scanId: string }>;+ expect(scans).toHaveLength(1);+ const recipe = (+ await command(["get-scan-recipe", "--scan-id", scans[0]!.scanId])+ )["recipe"] as {+ config: JsonObject;+ providerProfile: { name: string; home: string };+ };+ expect(recipe.config).toMatchObject({ profile: "review" });+ expect(recipe.config).not.toHaveProperty("model_providers");+ expect(recipe.providerProfile.home).toBe("managed");+ const savedProfilePath = join(+ codexSecurityCredentialHome(environment),+ `${recipe.providerProfile.name}.config.json`,+ );+ if (process.platform !== "win32")+ expect((await stat(savedProfilePath)).mode & 0o777).toBe(0o600);+ await client.close();+ expect(JSON.parse(await readFile(savedProfilePath, "utf8"))).toEqual({+ model_providers: explicitProviders,+ });+ const replay = await mergedCodexConfig(+ {+ codexOverrides: await restoreProviderProfile(+ recipe.config,+ recipe.providerProfile,+ environment,+ ),+ },+ home,+ );+ expect(replay["model_providers"]).toEqual(initial["model_providers"]);+ const { runCli, stderr } = createCliTest(main);+ let replayOverrides: JsonObject | undefined;+ for (const operation of mode === "deep"+ ? ["rerun", "resume"]+ : ["rerun"]) {+ expect(+ await runCli(["scans", operation, scans[0]!.scanId, "--json"], {+ ...dependencies({+ environment,+ currentDirectory: root,+ onConfig: ({ codexOverrides }) => {+ replayOverrides = codexOverrides;+ },+ }),+ runWorkbench: command,+ }),+ `${operation}: ${stderr.text()}`,+ ).toBe(0);+ expect(replayOverrides).toBeDefined();+ expect(+ (await mergedCodexConfig({ codexOverrides: replayOverrides }, home))[+ "model_providers"+ ],+ ).toEqual(initial["model_providers"]);+ }+ await writeFile(+ join(home, "review.config.toml"),+ `model="synthetic-model"\nmodel_provider="${provider}"\n[model_providers.${provider}]\nrequest_max_retries=8\nbase_url="https://changed.example.invalid/"\n`,+ );+ expect(+ (await mergedCodexConfig({ codexOverrides: replayOverrides }, home))[+ "model_providers"+ ],+ ).toEqual(+ explicitProviders === null+ ? null+ : {+ [provider]: { ...explicitProvider, request_max_retries: 8 },+ agent: profileKind === "clear-agent" ? null : alternateProvider,+ },+ );+ expect(JSON.stringify(recipe)).not.toContain(header);+ expect(JSON.stringify(recipe)).not.toContain(customEndpoint);+ expect(+ JSON.stringify(+ await command(["get-scan", "--scan-id", scans[0]!.scanId]),+ ),+ ).not.toContain(header);+ expect(JSON.stringify(recipe)).not.toContain("synthetic-launch-key");+ expect(JSON.stringify(recipe)).not.toContain(+ "SYNTHETIC_OLD_PROVIDER_KEY",+ );+ } finally {+ await client.close();+ if (providerProfilePath !== undefined) {+ await expect(readFile(providerProfilePath)).rejects.toMatchObject({+ code: "ENOENT",+ });+ }+ }+ },+);+const selected = {model: "synthetic-selected-model",model_reasoning_effort: "high",@@ -161,3 +513,205 @@ test.each([).toBe(0);},);++const modelFileRecipeKeys = [+ "model_instructions_file",+ "model_catalog_json",+ "experimental_compact_prompt_file",+] as const;+test.each(+ modelFileRecipeKeys.flatMap((key) => [+ ...["root-relative", "inline-relative", "root-absolute"].map((kind) => ({+ key,+ kind,+ mode: "standard" as const,+ })),+ ...(["standard", "deep"] as const).map((mode) => ({+ key,+ kind: "file-cleared",+ mode,+ })),+ ]),+)(+ "saved launch retains model file paths and explicit clears: %j",+ async ({ key, kind, mode }) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const home = join(root, "codex-home");+ const originalOutput = join(root, "original-output");+ const rerunOutput = join(root, "reruns", "next-output");+ const modelFiles = join(root, "model-files");+ await Promise.all(+ [repository, home, modelFiles, rerunOutput].map((path) =>+ mkdir(path, { recursive: true }),+ ),+ );+ await writeFile(join(repository, "fixture.py"), "value = 1\n");+ const modelFile = join(modelFiles, key + ".txt");+ const contents =+ key === "model_catalog_json"+ ? '{"models":[]}\n'+ : `Synthetic saved model file ${key}\n`;+ await writeFile(modelFile, contents);+ const value =+ kind === "root-absolute"+ ? modelFile+ : relative(originalOutput, modelFile);+ const cleared = kind === "file-cleared";+ if (cleared) {+ await writeFile(+ join(home, "review.config.toml"),+ `model="synthetic-model"\n${key}="inherited.txt"\n[analytics]\nenabled=true\n[agents.reviewer]\nconfig_file="reviewer.toml"\ndescription="initial reviewer"\n`,+ );+ }+ const overrides: JsonObject = cleared+ ? {+ profile: "review",+ [key]: null,+ analytics: null,+ agents: { reviewer: { config_file: null } },+ }+ : kind === "inline-relative"+ ? {+ profile: "active",+ profiles: {+ active: { [key]: value },+ unused: { [key]: "keep-unused-relative.txt" },+ },+ }+ : { [key]: value };+ const python = Bun.which("python3") ?? Bun.which("python");+ if (python === null) throw new Error("Python is required for this test.");+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_HOME: home,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ OPENAI_API_KEY: "synthetic-launch-key",+ };+ const command = (args: readonly string[], input?: string) =>+ runWorkbench(+ { python, pluginRoot: PLUGIN_ROOT, environment },+ args,+ input,+ );+ let launches = 0;+ const runtimeDependencies = {+ environment,+ prepareRuntime: async () => ({+ ...preparedRuntime(home),+ deepScanConfigPath: join(home, "deep-scan-config.toml"),+ }),+ resolvePluginPython: async () => python,+ runWorkbench: async (+ _options: unknown,+ args: readonly string[],+ input?: string,+ ) => {+ if (mode === "deep" && args[0] === "fail-scan")+ throw new Error("Synthetic disconnected workbench");+ return command(args, input);+ },+ createCodex: ({ config }: { config?: JsonObject }) => {+ launches++;+ if (cleared) {+ expect(config).not.toHaveProperty(key);+ expect(config).not.toHaveProperty("analytics");+ expect(config).not.toHaveProperty("agents.reviewer.config_file");+ }+ const thread = (id: string, cwd?: string) => ({+ id,+ async runStreamed() {+ await writeSession(home, id, {}, { cwd });+ return {+ events: (async function* () {+ yield {+ type: "thread.started" as const,+ thread_id: id,+ };+ throw new Error("Synthetic stop after registration");+ })(),+ };+ },+ });+ return {+ startThread: (options?: { workingDirectory?: string }) =>+ thread(+ `synthetic-model-file-thread-${launches}`,+ options?.workingDirectory,+ ),+ resumeThread: (id: string, options?: { workingDirectory?: string }) =>+ thread(id, options?.workingDirectory),+ };+ },+ };+ const client = new TestClient(+ { pluginPath: PLUGIN_ROOT, codexOverrides: overrides },+ runtimeDependencies,+ );+ try {+ await expect(+ client.run(repository, { mode, outputDir: originalOutput }),+ ).rejects.toThrow("Synthetic stop after registration");+ const scans = (await command(["list-scans", "--repository", repository]))[+ "scans"+ ] as Array<{ scanId: string }>;+ expect(scans).toHaveLength(1);+ const recipe = (+ await command(["get-scan-recipe", "--scan-id", scans[0]!.scanId])+ )["recipe"] as { config: JsonObject; providerProfile?: unknown };+ const replayOverrides = await restoreProviderProfile(+ recipe.config,+ recipe.providerProfile,+ environment,+ );+ const replay = resolveCodexProfile(+ await mergedCodexConfig({ codexOverrides: replayOverrides }, home),+ );+ if (cleared) {+ await client.close();+ await writeFile(+ join(home, "review.config.toml"),+ `model="synthetic-model"\n${key}="changed.txt"\n[analytics]\nenabled=false\n[agents.reviewer]\nconfig_file="changed-reviewer.toml"\ndescription="updated reviewer"\n`,+ );+ for (const operation of mode === "deep"+ ? ["rerun", "resume"]+ : ["rerun"]) {+ const { runCli, stderr } = createCliTest(main);+ expect(+ await runCli(["scans", operation, scans[0]!.scanId, "--json"], {+ ...dependencies({ environment, currentDirectory: root }),+ runWorkbench: command,+ createSecurity: (config) =>+ new TestClient(config, runtimeDependencies),+ }),+ ).toBe(2);+ expect(stderr.text()).toContain("Synthetic stop after registration");+ const reloaded = resolveCodexProfile(+ await mergedCodexConfig({ codexOverrides: replayOverrides }, home),+ );+ expect(reloaded).toMatchObject({+ agents: { reviewer: { description: "updated reviewer" } },+ });+ }+ expect(launches).toBe(mode === "deep" ? 3 : 2);+ expect(replay).not.toHaveProperty(key);+ expect(replay).not.toHaveProperty("analytics");+ expect(replay).not.toHaveProperty("agents.reviewer.config_file");+ return;+ }+ expect(replay[key]).toBe(modelFile);+ expect(+ await readFile(resolve(rerunOutput, replay[key] as string), "utf8"),+ ).toBe(contents);+ if (kind === "inline-relative") {+ expect(recipe.config["profile"]).toBe("active");+ expect(recipe.config["profiles"]).toMatchObject({+ unused: { [key]: "keep-unused-relative.txt" },+ });+ }+ } finally {+ await client.close();+ }+ },+);diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.tsindex 24e2261bc..8643ee03e 100644--- a/sdk/typescript/tests-ts/scan-resume.test.ts+++ b/sdk/typescript/tests-ts/scan-resume.test.ts@@ -22,7 +22,7 @@ import { afterEach, expect, test } from "bun:test";import { parse as parseToml } from "smol-toml";import { main } from "../src/cli.js";import { scanPreflightCodexConfig, type ScanOptions } from "../src/api.js";-import type { JsonObject } from "../src/config.js";+import { writeCodexConfig, type JsonObject } from "../src/config.js";import { runWorkbench } from "../src/runtime.js";import { readKnowledgeBaseSnapshot } from "../src/knowledge-base.js";import { saveScanKnowledge, scanInputIdentity } from "../src/scan-inputs.js";@@ -48,7 +48,7 @@ async function interruptedScan(| "auth"| "knowledgeBasePaths"| "cyberAccessProgram"- > & { config?: JsonObject } = {},+ > & { config?: JsonObject; providerProfile?: JsonObject } = {},resolvedDeep = false,modelProvider?: string,knowledgeState: "saved" | "legacy" = "saved",@@ -533,6 +533,106 @@ test("CLI resumes through native execution with current permissions and preserveexpect((await stat(f.scanDir)).mode & 0o777).toBe(0o755);});+test.each([false, true])(+ "resume restores private provider refinements (bulk: %p)",+ async (bulk) => {+ const name = `codex_security_${randomUUID()}`;+ const f = await interruptedScan("deep", bulk, {+ config: {+ profile: "review",+ model_provider: "openrouter",+ model: "synthetic-model",+ approval_policy: "never",+ },+ providerProfile: { name, home: "managed" },+ });+ await chmod(f.codexHome, 0o700);+ const savedProvider = {+ base_url: "https://saved.example.invalid/custom",+ env_key: "SYNTHETIC_REPLAY_KEY",+ http_headers: { "X-Synthetic-Token": "synthetic-private-replay-value" },+ };+ const savedPath = join(f.codexHome, `${name}.config.toml`);+ await writeCodexConfig(savedPath, {+ model_providers: { openrouter: savedProvider },+ });+ const original = await readFile(savedPath, "utf8");+ const ambient = join(f.root, "ambient-home");+ await mkdir(ambient);+ await writeFile(+ join(ambient, "review.config.toml"),+ 'model_provider="openrouter"\n[model_providers.openrouter]\nname="Synthetic"\nwire_api="responses"\nbase_url="https://old.example.invalid/"\nrequest_max_retries=4\n',+ );+ f.environment.CODEX_HOME = ambient;+ Object.assign(f.environment, {+ SYNTHETIC_REPLAY_KEY: "synthetic-replay-key",+ });+ let restored = false;+ const { stderr, runCli } = createCliTest(main);+ const code = await runCli(+ bulk+ ? ["bulk-scan", f.input, "--output-dir", f.root, "--recover", "--json"]+ : ["scans", "resume", f.scanId, "--json"],+ resumeDependencies(+ f,+ async (options) => {+ const providerProfile = parseToml(+ await readFile(+ join(f.codexHome, `${options.nativeProfile}.config.toml`),+ "utf8",+ ),+ );+ expect(providerProfile).toMatchObject({+ model_providers: {+ openrouter: { ...savedProvider, request_max_retries: 4 },+ },+ });+ expect(options.env?.["SYNTHETIC_REPLAY_KEY"]).toBe(+ "synthetic-replay-key",+ );+ const worker = parseToml(+ await readFile(+ options.env!["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!,+ "utf8",+ ),+ ) as { worker_runtime: Record<string, unknown> };+ expect(worker.worker_runtime["native_profile"]).toBe(+ options.nativeProfile,+ );+ expect(worker.worker_runtime["environment"]).toEqual({+ SYNTHETIC_REPLAY_KEY: "synthetic-replay-key",+ });+ restored = true;+ return {+ startThread: () => fail("Resume must use the original session."),+ resumeThread: (threadId) => ({+ id: threadId,+ runStreamed: async () => {+ throw new Error("Synthetic private resume checked");+ },+ }),+ };+ },+ { deepScanConfigPath: join(f.codexHome, "worker-runtime.toml") },+ ),+ );+ expect(code).not.toBe(0);+ expect(restored, stderr.text()).toBe(true);+ expect(await readFile(savedPath, "utf8")).toBe(original);+ expect(+ (await readdir(f.codexHome)).filter((path) =>+ path.endsWith(".config.toml"),+ ),+ ).toEqual([`${name}.config.toml`]);+ const saved = await f.command(["get-scan-recipe", "--scan-id", f.scanId]);+ expect(saved["recipe"]).toEqual(f.recipe);+ expect(JSON.stringify(saved)).not.toContain(savedProvider.base_url);+ expect(JSON.stringify(saved)).not.toContain(+ "synthetic-private-replay-value",+ );+ },+);+test("resumed Bedrock scans retain provider context for the account advisory", async () => {const f = await interruptedScan("deep", false, {}, false, "amazon-bedrock");const { stderr, runCli } = createCliTest(main);diff --git a/sdk/typescript/tests-ts/suggest-owners.test.ts b/sdk/typescript/tests-ts/suggest-owners.test.tsindex 9f91d15d2..dd17b1031 100644--- a/sdk/typescript/tests-ts/suggest-owners.test.ts+++ b/sdk/typescript/tests-ts/suggest-owners.test.ts@@ -488,43 +488,66 @@ exec "$SYNTHETIC_REAL_GIT" "$@");}-test("keeps renamed-file blame citations at HEAD and inherits SDK model settings", async () => {- const repo = await repository();- const path = "record [1].ts";- await repo.git("mv", "handler.ts", path);- await repo.git("commit", "-qm", "Rename record handler");- const { codex, calls } = fakeCodex();- const report = await suggestOwners(- repo.path,- [{ ...finding, locations: [{ path, startLine: 2, endLine: 3 }] }],- {- codex,- config: {- codexOverrides: {- model: "configured-model",- model_reasoning_effort: "low",+test.each(["inline", "CODEX_HOME", "codex_home"])(+ "keeps renamed-file blame citations at HEAD and inherits SDK model settings via %s",+ async (homeKey) => {+ const repo = await repository();+ const path = "record [1].ts";+ await repo.git("mv", "handler.ts", path);+ await repo.git("commit", "-qm", "Rename record handler");+ const { codex, calls } = fakeCodex();+ const sourceHome =+ homeKey === "inline" ? undefined : await temporaryDirectory();+ if (sourceHome !== undefined)+ await writeFile(+ join(sourceHome, "review.config.toml"),+ 'model = "configured-model"\nmodel_reasoning_effort = "low"\n',+ );+ const report = await suggestOwners(+ repo.path,+ [{ ...finding, locations: [{ path, startLine: 2, endLine: 3 }] }],+ {+ codex,+ ...(sourceHome === undefined+ ? {}+ : {+ environment: {+ ...process.env,+ CODEX_HOME: undefined,+ codex_home: undefined,+ [homeKey]: sourceHome,+ },+ }),+ config: {+ codexOverrides:+ sourceHome === undefined+ ? {+ model: "configured-model",+ model_reasoning_effort: "low",+ }+ : { profile: "review" },},},- },- );- expect(report.results[0]!.status).toBe("identified");- expect(- report.results[0]!.evidence.find(({ kind }) => kind === "blame"),- ).toMatchObject({- path,- commit: await repo.git("rev-parse", "HEAD"),- startLine: 2,- endLine: 3,- });- expect(calls[0]!.thread).toMatchObject({- model: "configured-model",- modelReasoningEffort: "low",- });- expect(report).toMatchObject({- model: "configured-model",- reasoningEffort: "low",- });-});+ );+ expect(report.results[0]!.status).toBe("identified");+ expect(+ report.results[0]!.evidence.find(({ kind }) => kind === "blame"),+ ).toMatchObject({+ path,+ commit: await repo.git("rev-parse", "HEAD"),+ startLine: 2,+ endLine: 3,+ });+ expect(calls[0]!.thread).toMatchObject({+ model: "configured-model",+ modelReasoningEffort: "low",+ });+ expect(report).toMatchObject({+ model: "configured-model",+ reasoningEffort: "low",+ });+ },+);test.each(["author", "checkout"] as const)("scan hints after a rename validate the %s commit against blame",diff --git a/sdk/typescript/tests-ts/support/replay-worker-boundary.ts b/sdk/typescript/tests-ts/support/replay-worker-boundary.tsnew file mode 100644index 000000000..bde682302--- /dev/null+++ b/sdk/typescript/tests-ts/support/replay-worker-boundary.ts@@ -0,0 +1,154 @@+import assert from "node:assert/strict";+import childProcess, { type SpawnOptions } from "node:child_process";+import { mkdir, readFile, writeFile } from "node:fs/promises";+import { join, toNamespacedPath } from "node:path";+import { fileURLToPath } from "node:url";+import { syncBuiltinESMExports } from "node:module";+import { parse, stringify } from "smol-toml";+import type { JsonObject } from "../../src/config.js";+import { fakeCodexSource } from "../../../../plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts";+const { importModule } = await import(+ new URL(+ "../../../../plugins/codex-security/mcp-app/tests/import-module.ts",+ import.meta.url,+ ).href+);++const executorSource = new URL(+ "../../../../plugins/codex-security/mcp-app/src/deep-scan/executor.ts",+ import.meta.url,+);+const { CodexSdkWorkerExecutor } = await importModule({+ entryPoints: [fileURLToPath(executorSource)],+ define: { "import.meta.url": JSON.stringify(executorSource.href) },+});+const { deepMerge } = await importModule({+ entryPoints: [fileURLToPath(new URL("../../src/config.ts", import.meta.url))],+});+const chunks: Buffer[] = [];+for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));+await assertWorkerReplay(+ process.argv[2]!,+ JSON.parse(Buffer.concat(chunks).toString()),+);+process.stdout.write(JSON.stringify({ launches: 4 }));++async function assertWorkerReplay(+ root: string,+ config: JsonObject,+): Promise<void> {+ const home = join(root, "worker-home");+ await mkdir(home);+ await writeFile(join(home, "config.toml"), "");+ const workerConfig = join(root, "worker-runtime.toml");+ await writeFile(workerConfig, stringify({ worker_runtime: config }));+ const marker = join(root, "worker-invocation.json");+ const fake = join(root, "worker-codex.mjs");+ const profile = {+ extends: ":read-only",+ filesystem: { ":root": "read" },+ network: { enabled: false },+ };+ await writeFile(+ fake,+ fakeCodexSource(+ profile,+ true,+ { account: null, requiresOpenaiAuth: false },+ join(root, "worker-preflight.json"),+ ),+ );+ const prompt = join(root, "worker-prompt.md");+ await writeFile(prompt, "Synthetic replay settings check.");+ const node = process.execPath;+ const environment = {+ CODEX_CLI_PATH: node,+ CODEX_HOME: home,+ CODEX_SECURITY_CONFIG_PATH: join(home, "config.toml"),+ CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH: workerConfig,+ CODEX_SECURITY_SCAN_DIR: join(root, "scan"),+ FAKE_CODEX_MARKER: marker,+ OPENAI_API_KEY: undefined,+ CODEX_API_KEY: undefined,+ };+ const previous = Object.fromEntries(+ Object.keys(environment).map((name) => [name, process.env[name]]),+ );+ const spawn = childProcess.spawn;+ try {+ for (const [key, value] of Object.entries(environment)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ childProcess.spawn = ((+ command: string,+ args: readonly string[],+ options: SpawnOptions,+ ) =>+ spawn(+ command,+ command === node || command === toNamespacedPath(node)+ ? [fake, ...args]+ : args,+ options,+ )) as typeof childProcess.spawn;+ syncBuiltinESMExports();+ const executor = new CodexSdkWorkerExecutor({+ parentSandbox: { filesystemDenies: [] },+ });+ for (const kind of ["discovery", "dedup"] as const) {+ for (const resumeThreadId of [undefined, "replayed-thread"]) {+ const result = await executor.run({+ kind,+ promptPath: prompt,+ workingDirectory: root,+ subagents: 0,+ resumeThreadId,+ signal: new AbortController().signal,+ });+ assert.equal(result.threadId, resumeThreadId ?? "fixture-thread-id");+ const { argv } = JSON.parse(await readFile(marker, "utf8")) as {+ argv: string[];+ };+ let selected: JsonObject = {};+ for (let index = 0; index < argv.length; index++)+ if (argv[index] === "-c" || argv[index] === "--config")+ selected = deepMerge(selected, parse(argv[++index]!) as JsonObject);+ for (const key of [+ "analytics",+ "shell_environment_policy",+ "otel",+ "skills",+ "model_catalog_json",+ ])+ assert.deepEqual(selected[key], config[key]);+ assert.deepEqual(+ (selected["agents"] as JsonObject)["reviewer"],+ (config["agents"] as JsonObject)["reviewer"],+ );+ assert.equal((selected["features"] as JsonObject)["view_image"], false);+ assert.equal((selected["features"] as JsonObject)["shell_tool"], false);+ assert.equal(selected["approval_policy"], "never");+ assert.deepEqual(+ (selected["permissions"] as JsonObject)[+ "codex_security_deep_scan_worker"+ ],+ profile,+ );+ assert.equal(argv.includes("resume"), resumeThreadId !== undefined);+ // Existing coordinators retain their launch snapshot when a source file changes.+ await writeFile(+ workerConfig,+ "[worker_runtime.analytics]\nenabled=true\n",+ );+ }+ }+ } finally {+ childProcess.spawn = spawn;+ syncBuiltinESMExports();+ for (const [key, value] of Object.entries(previous)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+}