Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

refactor(scan): run API-key and Bedrock Deep Scans directly (#1555)

mldangelo-oaic2dfedb7646f
diff --git a/plugins/codex-security/.codex-plugin/plugin.json b/plugins/codex-security/.codex-plugin/plugin.json
index 9d333b0ed..ed4eeceb5 100644
--- a/plugins/codex-security/.codex-plugin/plugin.json
+++ b/plugins/codex-security/.codex-plugin/plugin.json
@@ -19,6 +19,7 @@
"apps": "./.app.json",
"mcpServers": "./.mcp.json",
"codexSecurity": {
+ "directDeepScanEngine": 1,
"workerProviderSnapshot": 4
},
"interface": {
diff --git a/plugins/codex-security/mcp-app/deep-scan-main.ts b/plugins/codex-security/mcp-app/deep-scan-main.ts
new file mode 100644
index 000000000..60d6109ec
--- /dev/null
+++ b/plugins/codex-security/mcp-app/deep-scan-main.ts
@@ -0,0 +1,95 @@
+import { join, resolve } from "node:path";
+import { createInterface } from "node:readline";
+import { runWorkbench as runWorkbenchCommand } from "./server.js";
+import { resolvePythonCommand } from "./src/python_command.js";
+import { startDeepScanEngine } from "./src/deep-scan/engine.js";
+import { resolveDeepWorkerParentSandbox } from "./src/deep-scan/parent-sandbox.js";
+import { DeepScanCoordinatorRegistry } from "./src/deep-scan/registry.js";
+import { WorkbenchDeepScanStore } from "./src/deep-scan/store.js";
+
+/** Private SDK entry point. The child process isolates each scan's environment. */
+export async function runCliDeepScan(): Promise<void> {
+ const runWorkbench = (args: string[], input?: string | Buffer) =>
+ runWorkbenchCommand(args, input, { isolatedPython: true });
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
+ const registry = new DeepScanCoordinatorRegistry();
+ const controller = new AbortController();
+ let scanId: string | undefined;
+ const stop = () => {
+ controller.abort();
+ registry.shutdown("cli_interrupted");
+ };
+ lines.once("close", stop);
+ process.once("SIGINT", stop);
+ process.once("SIGTERM", stop);
+ try {
+ const first = await lines[Symbol.asyncIterator]().next();
+ if (first.done)
+ throw new Error("Deep Scan engine input closed before startup.");
+ const input = JSON.parse(first.value) as {
+ scanId: string;
+ threadId: string;
+ model: string;
+ reasoningEffort?: string;
+ permissionProfile: unknown;
+ };
+ scanId = input.scanId;
+ const pluginRoot =
+ process.env.CODEX_SECURITY_PLUGIN_ROOT || resolve(__dirname, "..");
+ process.chdir(pluginRoot);
+ const store = new WorkbenchDeepScanStore(runWorkbench);
+ const parentSandbox = resolveDeepWorkerParentSandbox({
+ _meta: {
+ "codex/sandbox-state-meta": {
+ permissionProfile: input.permissionProfile,
+ },
+ },
+ });
+ if (controller.signal.aborted)
+ throw new Error("Deep Scan canceled before coordinator startup.");
+ const run = await store.begin({
+ scanId: input.scanId,
+ threadId: input.threadId,
+ model: input.model,
+ reasoningEffort: input.reasoningEffort,
+ scanRoot: join(process.env.CODEX_SECURITY_STATE_DIR!, "scans"),
+ });
+ if (controller.signal.aborted)
+ throw new Error("Deep Scan canceled before coordinator startup.");
+ let terminal = run;
+ if (run.status === "running") {
+ const started = await startDeepScanEngine({
+ run,
+ store,
+ registry,
+ runWorkbench,
+ pluginRoot,
+ pythonCommand: await resolvePythonCommand(),
+ parentSandbox,
+ threadId: input.threadId,
+ model: input.model,
+ reasoningEffort: input.reasoningEffort,
+ });
+ if (controller.signal.aborted) stop();
+ terminal = await started.coordinator.wait(controller.signal);
+ }
+ if (terminal.status !== "succeeded") {
+ throw new Error(terminal.error ?? `Deep Scan ${terminal.status}.`);
+ }
+ process.stdout.write(
+ JSON.stringify({
+ scanId: terminal.scanId,
+ manifestPath: terminal.manifestPath,
+ }) + "\n",
+ );
+ } finally {
+ const coordinator = scanId === undefined ? undefined : registry.get(scanId);
+ registry.shutdown("cli_engine_closed");
+ process.removeListener("SIGINT", stop);
+ process.removeListener("SIGTERM", stop);
+ lines.removeListener("close", stop);
+ lines.close();
+ process.stdin.destroy();
+ await coordinator?.settled();
+ }
+}
diff --git a/plugins/codex-security/mcp-app/main.ts b/plugins/codex-security/mcp-app/main.ts
index 8a3316112..4ec8dbaf4 100644
--- a/plugins/codex-security/mcp-app/main.ts
+++ b/plugins/codex-security/mcp-app/main.ts
@@ -1,8 +1,13 @@
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { createCodexSecurityArtifactWriterServer } from "./artifact-writer-main.js";
import { createCodexSecurityServer } from "./server.js";
+import { runCliDeepScan } from "./deep-scan-main.js";
async function main(): Promise<void> {
+ if (process.argv.includes("--deep-scan-engine")) {
+ await runCliDeepScan();
+ return;
+ }
const artifactWriter = process.argv.includes("--artifact-writer");
const server = artifactWriter
? await createCodexSecurityArtifactWriterServer()
@@ -29,9 +34,11 @@ async function main(): Promise<void> {
main().catch((error) => {
console.error(
- process.argv.includes("--artifact-writer")
- ? "Codex Security artifact writer failed to start:"
- : "Codex Security MCP server failed to start:",
+ process.argv.includes("--deep-scan-engine")
+ ? "Codex Security Deep Scan failed:"
+ : process.argv.includes("--artifact-writer")
+ ? "Codex Security artifact writer failed to start:"
+ : "Codex Security MCP server failed to start:",
error,
);
process.exitCode = 1;
diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.ts
index 1fd560d6a..c3b80b6ea 100644
--- a/plugins/codex-security/mcp-app/server.ts
+++ b/plugins/codex-security/mcp-app/server.ts
@@ -23,14 +23,11 @@ import {
type HandoffWorkspaceState as WorkspaceState,
} from "./src/server/handoff-tools.js";
import { registerCompactArtifactTools } from "./src/server/compact-artifact-tools.js";
-import { createScanArtifactContext } from "./src/artifact-context.js";
-import { recordCodexSecurityScanDraftViaWorkbench } from "./src/artifact-scan-draft.js";
import {
DeepScanCoordinatorRegistry,
AsyncLock,
- startOrJoinDeepScanCoordinator,
} from "./src/deep-scan/registry.js";
-import { CodexSdkWorkerExecutor } from "./src/deep-scan/executor.js";
+import { startDeepScanEngine } from "./src/deep-scan/engine.js";
import {
CODEX_SANDBOX_STATE_META_CAPABILITY,
resolveDeepWorkerParentSandbox,
@@ -1024,64 +1021,18 @@ export function createCodexSecurityServer(): McpServer {
}
const immediate = deepScanTerminalResult(begun);
if (immediate) return { begun, immediate };
- const started = await startOrJoinDeepScanCoordinator({
+ const started = await startDeepScanEngine({
run: begun,
registry: deepScanCoordinators,
- options: {
- store: deepScanStore,
- executor: new CodexSdkWorkerExecutor({
- ...modelSettings,
- parentSandbox,
- artifactContext: {
- pluginRoot: PLUGIN_ROOT,
- repoRoot: begun.targetPath,
- scanId: begun.scanId,
- scope: begun.scope,
- pythonCommand: await resolvePythonCommand(),
- },
- }),
- pluginRoot: PLUGIN_ROOT,
- log: logDeepScanEvent,
- handoffClaimToken,
- threadId,
- onComplete: async (draft, signal) => {
- const context = await createScanArtifactContext(
- begun.scanId,
- runWorkbench,
- {
- requireRunning: true,
- requireClaim: true,
- handoffClaimToken,
- pluginRoot: PLUGIN_ROOT,
- },
- );
- await recordCodexSecurityScanDraftViaWorkbench(
- context,
- {
- ...draft,
- ...(handoffClaimToken === undefined
- ? {}
- : { handoffClaimToken }),
- },
- runWorkbench,
- signal,
- );
- },
- onStopped: async (run) => {
- await runWorkbench([
- "preserve-scan-results",
- "--scan-id",
- run.scanId,
- "--thread-id",
- threadId,
- ...optionalArg("--claim-token", handoffClaimToken),
- ...optionalArg(
- "--coordinator-generation",
- run.coordinatorGeneration?.toString(),
- ),
- ]);
- },
- },
+ store: deepScanStore,
+ runWorkbench,
+ ...modelSettings,
+ parentSandbox,
+ pythonCommand: await resolvePythonCommand(),
+ pluginRoot: PLUGIN_ROOT,
+ log: logDeepScanEvent,
+ handoffClaimToken,
+ threadId,
});
return { begun, ...started };
})
@@ -2207,14 +2158,19 @@ function logDeepScanEvent(event: {
);
}
-async function runWorkbench(
+interface WorkbenchOptions {
+ isolatedPython?: boolean;
+}
+
+export async function runWorkbench(
args: string[],
input?: string | Buffer,
+ options: WorkbenchOptions = {},
): Promise<JsonObject> {
let pythonCommand: string | undefined;
try {
pythonCommand = await resolvePythonCommand();
- return await executeWorkbench(pythonCommand, args, input);
+ return await executeWorkbench(pythonCommand, args, input, options);
} catch (error) {
const launchError = pythonCommand
? missingPythonHelperMessage(error, pythonCommand)
@@ -2233,6 +2189,7 @@ async function executeWorkbench(
pythonCommand: string,
args: string[],
input?: string | Buffer,
+ options: WorkbenchOptions = {},
): Promise<JsonObject> {
const timeout = [
"begin-deep-scan",
@@ -2264,7 +2221,12 @@ async function executeWorkbench(
: 30_000;
const execution = execFileAsync(
pythonCommand,
- ["-c", WORKBENCH_PYTHON, workbenchScriptPath()],
+ [
+ ...(options.isolatedPython ? ["-I", "-X", "utf8", "-B"] : []),
+ "-c",
+ WORKBENCH_PYTHON,
+ workbenchScriptPath(),
+ ],
{
cwd: PLUGIN_ROOT,
windowsHide: true,
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/engine.ts b/plugins/codex-security/mcp-app/src/deep-scan/engine.ts
new file mode 100644
index 000000000..de3106229
--- /dev/null
+++ b/plugins/codex-security/mcp-app/src/deep-scan/engine.ts
@@ -0,0 +1,91 @@
+import { createScanArtifactContext } from "../artifact-context.js";
+import { recordCodexSecurityScanDraftViaWorkbench } from "../artifact-scan-draft.js";
+import { CodexSdkWorkerExecutor } from "./executor.js";
+import type { DeepWorkerParentSandbox } from "./parent-sandbox.js";
+import {
+ DeepScanCoordinatorRegistry,
+ startOrJoinDeepScanCoordinator,
+} from "./registry.js";
+import type { WorkbenchDeepScanStore } from "./store.js";
+import type { DeepScanLogger, DeepScanRunState } from "./types.js";
+
+/** Shared execution behind the SDK engine and the plugin's MCP adapter. */
+export function startDeepScanEngine(options: {
+ run: DeepScanRunState;
+ store: WorkbenchDeepScanStore;
+ registry: DeepScanCoordinatorRegistry;
+ runWorkbench: Parameters<typeof createScanArtifactContext>[1];
+ pluginRoot: string;
+ pythonCommand: string;
+ parentSandbox: DeepWorkerParentSandbox;
+ threadId: string;
+ handoffClaimToken?: string;
+ model?: string;
+ reasoningEffort?: string;
+ log?: DeepScanLogger;
+}) {
+ const { run, runWorkbench, pluginRoot, threadId, handoffClaimToken } =
+ options;
+ return startOrJoinDeepScanCoordinator({
+ run,
+ registry: options.registry,
+ options: {
+ store: options.store,
+ executor: new CodexSdkWorkerExecutor({
+ model: options.model,
+ reasoningEffort: options.reasoningEffort,
+ parentSandbox: options.parentSandbox,
+ artifactContext: {
+ pluginRoot,
+ repoRoot: run.targetPath,
+ scanId: run.scanId,
+ scope: run.scope,
+ pythonCommand: options.pythonCommand,
+ },
+ }),
+ pluginRoot,
+ log: options.log,
+ handoffClaimToken,
+ threadId,
+ onComplete: async (draft, signal) => {
+ const context = await createScanArtifactContext(
+ run.scanId,
+ runWorkbench,
+ {
+ requireRunning: true,
+ requireClaim: true,
+ handoffClaimToken,
+ pluginRoot,
+ },
+ );
+ await recordCodexSecurityScanDraftViaWorkbench(
+ context,
+ {
+ ...draft,
+ ...(handoffClaimToken === undefined ? {} : { handoffClaimToken }),
+ },
+ runWorkbench,
+ signal,
+ );
+ },
+ onStopped: async (stopped) => {
+ await runWorkbench([
+ "preserve-scan-results",
+ "--scan-id",
+ stopped.scanId,
+ "--thread-id",
+ threadId,
+ ...(handoffClaimToken === undefined
+ ? []
+ : ["--claim-token", handoffClaimToken]),
+ ...(stopped.coordinatorGeneration === undefined
+ ? []
+ : [
+ "--coordinator-generation",
+ String(stopped.coordinatorGeneration),
+ ]),
+ ]);
+ },
+ },
+ });
+}
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
index f416ca556..4578b2b47 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
@@ -2,6 +2,7 @@ import type { JsonObject as JsonRecord } from "../types.js";
import { asRecord as record } from "../record.js";
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { createInterface, type Interface } from "node:readline";
+import { createReadStream } from "node:fs";
import { isDeepStrictEqual } from "node:util";
import { version as MCP_APP_VERSION } from "../../package.json";
import { DeepScanNonRetryableError } from "./errors.js";
@@ -66,6 +67,74 @@ export async function readDeepScanRuntimeConfig(
});
}
+/** Persist the owning session and obtain native permissions without a model turn. */
+export async function prepareCliDeepScanSession(
+ options: RuntimeConfigReadOptions & {
+ prompt: string;
+ },
+): Promise<{
+ threadId: string;
+ model: string;
+ reasoningEffort?: string;
+ permissionProfile: unknown;
+}> {
+ return withPreflightClient(options, async (client) => {
+ const response = await client.request("thread/start", {
+ cwd: options.cwd,
+ threadSource: "security_scan",
+ ephemeral: false,
+ });
+ const thread = record(response.thread);
+ if (
+ typeof thread?.id !== "string" ||
+ typeof thread.path !== "string" ||
+ typeof response.model !== "string"
+ ) {
+ throw new Error("Codex did not return the owning Deep Scan session.");
+ }
+ // Native history persistence records the effective turn context, including
+ // managed filesystem denials. No turn/start or model request is needed.
+ await client.request("thread/inject_items", {
+ threadId: thread.id,
+ items: [
+ {
+ type: "message",
+ role: "user",
+ content: [{ type: "input_text", text: options.prompt }],
+ },
+ ],
+ });
+ let permissionProfile: unknown;
+ const input = createReadStream(thread.path, { encoding: "utf8" });
+ const lines = createInterface({ input, crlfDelay: Infinity });
+ try {
+ for await (const line of lines) {
+ if (!line.trim()) continue;
+ const entry = record(JSON.parse(line));
+ if (entry?.type === "turn_context") {
+ permissionProfile = record(entry.payload)?.permission_profile;
+ }
+ }
+ } finally {
+ lines.close();
+ input.destroy();
+ }
+ if (permissionProfile === undefined) {
+ throw new Error(
+ "Codex did not persist the Deep Scan session's effective permissions.",
+ );
+ }
+ return {
+ threadId: thread.id,
+ model: response.model,
+ ...(typeof response.reasoningEffort === "string"
+ ? { reasoningEffort: response.reasoningEffort }
+ : {}),
+ permissionProfile,
+ };
+ });
+}
+
/**
* Verify the worker profile with the same executable, effective worker cwd,
* Codex home, and permission overrides that the real worker will use. App-server must
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts
index 63d217561..eb5c219e6 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts
@@ -35,6 +35,7 @@ const {
deepScanPermissionProfileFallbackError,
preflightDeepScanWorkerPermissionProfile,
readDeepScanRuntimeConfig,
+ prepareCliDeepScanSession,
} = await importSource(
path.join(
import.meta.dirname,
@@ -84,6 +85,78 @@ await testSpawnErrorFailsClosed();
await testMissingWorkerDirectoryRemainsRetryable();
await testAbortKillsPreflightChild();
await testAbortPreservesCallerReason();
+await testDirectScanSession();
+
+async function testDirectScanSession() {
+ const permissionProfile = {
+ type: "managed",
+ file_system: {
+ type: "restricted",
+ entries: [
+ { path: { type: "special", value: { kind: "root" } }, access: "read" },
+ {
+ path: {
+ type: "path",
+ path: path.resolve("synthetic", "private [home]"),
+ },
+ access: "deny",
+ },
+ ],
+ },
+ network: "restricted",
+ };
+ await withFakeCodex(
+ { parentPermissionProfile: permissionProfile },
+ async (fixture) => {
+ const result = await prepareCliDeepScanSession({
+ codexPath: fixture.codexPath,
+ commandArgs: ["--config", 'model_provider="synthetic_provider"'],
+ cwd: fixture.cwd,
+ configOverrides: ['model_reasoning_effort="high"'],
+ prompt: "Review the supplied synthetic repository.",
+ signal: new AbortController().signal,
+ });
+ assert.deepEqual(result, {
+ threadId: "new-scan-thread",
+ model: "synthetic-model",
+ reasoningEffort: "high",
+ permissionProfile,
+ });
+ const calls = await readJsonLines(fixture.callsPath);
+ assert.deepEqual(
+ calls.map((call) => call.method),
+ ["initialize", "initialized", "thread/start", "thread/inject_items"],
+ );
+ assert.deepEqual(calls[2].params, {
+ cwd: fixture.cwd,
+ threadSource: "security_scan",
+ ephemeral: false,
+ });
+ assert.equal(
+ calls[3].params.items[0].content[0].text,
+ "Review the supplied synthetic repository.",
+ );
+ const argv = await readJson(fixture.argvPath);
+ assert.equal(
+ argv[argv.indexOf("--config") + 1],
+ 'model_provider="synthetic_provider"',
+ );
+ assert.equal(argv.includes("--profile"), false);
+ },
+ );
+ await withFakeCodex({ parentPermissionProfile: null }, async (fixture) => {
+ await assert.rejects(
+ prepareCliDeepScanSession({
+ codexPath: fixture.codexPath,
+ cwd: fixture.cwd,
+ configOverrides: [],
+ prompt: "Synthetic scan.",
+ signal: new AbortController().signal,
+ }),
+ /effective permissions/,
+ );
+ });
+}
async function testAllowedProfileAndRawArgv() {
await withFakeCodex(
@@ -1079,6 +1152,20 @@ function handle(message) {
send(message.id, { userAgent: "fixture", codexHome: "/fixture", platformFamily: "unix", platformOs: "macos" });
return;
}
+ if (message.method === "thread/start") {
+ send(message.id, {
+ thread: { id: 'new-scan-thread', path: scenario.callsPath + '.session.jsonl' },
+ model: 'synthetic-model', reasoningEffort: 'high',
+ });
+ return;
+ }
+ if (message.method === "thread/inject_items") {
+ writeFileSync(scenario.callsPath + '.session.jsonl', JSON.stringify({
+ type: 'turn_context', payload: scenario.parentPermissionProfile ? { permission_profile: scenario.parentPermissionProfile } : {},
+ }) + "\\n");
+ send(message.id, {});
+ return;
+ }
if (message.method === "config/read") {
send(message.id, scenario.configResult);
return;
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts
index 8ab8fbaed..9ba889938 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts
@@ -944,7 +944,7 @@ model_reasoning_summary = "none"
assert.ok(launches.length > 0);
for (const launch of launches) {
assert.equal(launch.args[0], "-c");
- assert.equal(launch.args[2], workbenchPath);
+ assert.equal(launch.args.at(-1), workbenchPath);
assert.equal(launch.args.length, 3);
assert.equal(launch.cwd, pluginRoot);
}
@@ -990,6 +990,13 @@ model_reasoning_summary = "none"
} finally {
await restartedServer.stop();
}
+ await testCliDeepScanEngine({
+ fixtureRoot,
+ environment,
+ serverBundlePath,
+ codexHome,
+ restartControlPath,
+ });
} catch (error) {
(error as Error).message += `\nMCP stderr:\n${server.stderrText()}`;
throw error;
@@ -1001,6 +1008,216 @@ model_reasoning_summary = "none"
}
}
+async function testCliDeepScanEngine({
+ fixtureRoot,
+ environment,
+ serverBundlePath,
+ codexHome,
+ restartControlPath,
+}: {
+ fixtureRoot: string;
+ environment: NodeJS.ProcessEnv;
+ serverBundlePath: string;
+ codexHome: string;
+ restartControlPath: string;
+}) {
+ const canonicalRoot = await realpath(fixtureRoot);
+ const repository = path.join(canonicalRoot, "cli-engine-target");
+ await mkdir(repository);
+ await writeFile(
+ path.join(repository, "fixture.py"),
+ "print('engine fixture')\n",
+ );
+ const threadId = "cli-engine-session";
+ const register = async (name: string) => {
+ const scanDir = path.join(canonicalRoot, name);
+ await mkdir(scanDir, { mode: 0o700 });
+ const registration = await runWorkbench(environment, [
+ "register-cli-scan",
+ "--repository",
+ repository,
+ "--scan-dir",
+ scanDir,
+ "--recipe-json",
+ JSON.stringify({
+ repository,
+ mode: "deep",
+ target: { kind: "repository", paths: [] },
+ config: { model: "gpt-6.1-sol", model_reasoning_effort: "max" },
+ }),
+ ]);
+ await runWorkbench(environment, [
+ "set-scan-thread",
+ "--scan-id",
+ registration.scanId,
+ "--thread-id",
+ threadId,
+ ]);
+ return { scanId: registration.scanId as string, scanDir };
+ };
+ const launch = (scanId: string, overrides: NodeJS.ProcessEnv = {}) => {
+ const execution = execFileAsync(
+ process.execPath,
+ [serverBundlePath, "--deep-scan-engine"],
+ {
+ env: { ...environment, ...overrides },
+ encoding: "utf8",
+ timeout: 30_000,
+ },
+ );
+ execution.child.stdin!.write(
+ JSON.stringify({
+ scanId,
+ threadId,
+ model: "gpt-6.1-sol",
+ reasoningEffort: "max",
+ permissionProfile: (
+ parentSandboxState as { permissionProfile: unknown }
+ ).permissionProfile,
+ }) + "\n",
+ );
+ return execution;
+ };
+ const completed = await register("cli-engine-completed");
+ const startIndex = (await readLogLines(environment.FAKE_CODEX_START_LOG!))
+ .length;
+ const helperStartIndex = (
+ await readLogLines(environment.FAKE_WORKBENCH_LAUNCH_LOG!)
+ ).length;
+ const result = await launch(completed.scanId);
+ const helperLaunches = (
+ await readLogLines(environment.FAKE_WORKBENCH_LAUNCH_LOG!)
+ ).slice(helperStartIndex);
+ assert.ok(helperLaunches.length > 0);
+ for (const launch of helperLaunches) {
+ assert.deepEqual(launch.args.slice(0, 5), ["-I", "-X", "utf8", "-B", "-c"]);
+ assert.equal(launch.args.at(-1), workbenchPath);
+ assert.equal(launch.args.length, 7);
+ assert.equal(launch.cwd, pluginRoot);
+ }
+ assert.deepEqual(JSON.parse(result.stdout), {
+ scanId: completed.scanId,
+ manifestPath: path.join(completed.scanDir, "scan-manifest.json"),
+ });
+ const starts = (await readLogLines(environment.FAKE_CODEX_START_LOG!)).slice(
+ startIndex,
+ );
+ assert.ok(
+ starts.some((entry) => discoveryPromptContext(entry.stdin).workerLabel),
+ );
+ assert.ok(
+ starts.some(
+ (entry) => discoveryPromptContext(entry.stdin).claimedWorkerIds,
+ ),
+ );
+ for (const entry of starts) {
+ assertReadOnlyWorkerInvocation(entry.argv, codexHome);
+ assertFlagPair(entry.argv, "--model", "gpt-6.1-sol");
+ assert.ok(entry.argv.includes('model_reasoning_effort="max"'));
+ assert.equal(entry.hasExpectedApiKey, true);
+ }
+ const count = (await readLogLines(environment.FAKE_CODEX_START_LOG!)).length;
+ await launch(completed.scanId);
+ assert.equal(
+ (await readLogLines(environment.FAKE_CODEX_START_LOG!)).length,
+ count,
+ );
+ await runWorkbench(environment, [
+ "complete-scan",
+ "--scan-id",
+ completed.scanId,
+ ]);
+ const manifest = await readJson(
+ path.join(completed.scanDir, "scan-manifest.json"),
+ );
+ assert.equal(manifest.scan.status, "completed");
+ assert.ok(manifest.scan.sealedAt);
+ assert.ok(
+ (await readFile(path.join(completed.scanDir, "report.md"), "utf8")).length >
+ 0,
+ );
+
+ await rm(restartControlPath);
+ const canceled = await register("cli-engine-canceled");
+ const execution = launch(canceled.scanId);
+ const outcome = execution.then(
+ () => undefined,
+ (error) => error,
+ );
+ try {
+ await waitForJsonLines(environment.FAKE_CODEX_START_LOG!, count + 1);
+ await waitForDeepScanWorker({
+ environment,
+ scanId: canceled.scanId,
+ threadId,
+ });
+ const running = (
+ await readLogLines(environment.FAKE_CODEX_START_LOG!)
+ ).slice(count);
+ assert.ok(running.length > 0);
+ const observerLog = path.join(
+ canonicalRoot,
+ "cli-observer-workbench.jsonl",
+ );
+ const observer = launch(canceled.scanId, {
+ FAKE_WORKBENCH_LAUNCH_LOG: observerLog,
+ });
+ const observerOutcome = observer.then(
+ () => undefined,
+ (error) => error,
+ );
+ try {
+ await waitFor(
+ async () =>
+ (await readLogLines(observerLog)).some(
+ (entry) => entry.workbenchArgs[0] === "get-deep-scan",
+ ),
+ "second CLI engine to observe the active coordinator",
+ );
+ observer.child.stdin!.end();
+ const error = await observerOutcome;
+ assert.ok(error);
+ assert.equal(error.killed, false);
+ for (const worker of running) assertProcessAlive(worker.pid);
+ assert.equal(
+ (await readLogLines(environment.FAKE_CODEX_START_LOG!)).length,
+ count + running.length,
+ );
+ } finally {
+ if (
+ observer.child.exitCode === null &&
+ observer.child.signalCode === null
+ )
+ observer.child.kill("SIGKILL");
+ await observerOutcome;
+ }
+ execution.child.stdin!.end();
+ assert.ok(await outcome);
+ for (const worker of running) {
+ assert.throws(() => process.kill(worker.pid, 0), /ESRCH/);
+ }
+ const saved = await getDeepScan({
+ environment,
+ scanId: canceled.scanId,
+ threadId,
+ });
+ assert.notEqual(saved.status, "succeeded");
+ assert.equal(
+ saved.workers.filter(
+ (worker: PersistedDeepScanWorker) => worker.status === "running",
+ ).length,
+ 0,
+ );
+ } finally {
+ if (
+ execution.child.exitCode === null &&
+ execution.child.signalCode === null
+ )
+ execution.child.kill("SIGKILL");
+ await outcome;
+ }
+}
+
function startServer(serverPath: string, env: NodeJS.ProcessEnv) {
return startRpcServer(
{
diff --git a/plugins/codex-security/mcp-app/tests/test_workbench_process.ts b/plugins/codex-security/mcp-app/tests/test_workbench_process.ts
index 750a0db30..7521156c6 100644
--- a/plugins/codex-security/mcp-app/tests/test_workbench_process.ts
+++ b/plugins/codex-security/mcp-app/tests/test_workbench_process.ts
@@ -2,7 +2,9 @@ import assert from "node:assert/strict";
import { test } from "node:test";
import { randomUUID } from "node:crypto";
import path from "node:path";
-import { mkdir, rm, stat } from "node:fs/promises";
+import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
import { temporaryDirectory } from "./support/temporary-directories.ts";
import { loadWorkbenchProcess } from "./support/workbench-process.ts";
import { PassThrough } from "node:stream";
@@ -25,6 +27,7 @@ interface WorkbenchModule {
python: string,
args: string[],
input?: string | Buffer,
+ options?: { isolatedPython?: boolean },
): Promise<Record<string, unknown>>;
}
const invocations: {
@@ -92,6 +95,121 @@ try {
}
const { executeWorkbench } = await loadWorkbenchProcess();
+async function userSitePython(): Promise<string> {
+ // A caller's virtualenv may intentionally disable user-site imports.
+ const { stdout } = await promisify(execFile)(
+ process.env.PYTHON?.trim() || "python3",
+ ["-I", "-X", "utf8", "-B", "-c", "import sys; print(sys._base_executable)"],
+ );
+ return stdout.trim();
+}
+
+async function fixtureWorkbench(root: string, source: string) {
+ const script = path.join(root, "workbench_db.py");
+ await writeFile(script, source);
+ const { executeWorkbench } = await loadWorkbenchProcess((source) =>
+ source.replace(
+ 'return join(PLUGIN_ROOT, "scripts", "workbench_db.py");',
+ `return ${JSON.stringify(script)};`,
+ ),
+ );
+ return executeWorkbench as WorkbenchModule["executeWorkbench"];
+}
+
+for (const variable of ["PYTHONPATH", "PYTHONUSERBASE"]) {
+ await test(`isolated workbench ignores ${variable} startup hooks and preserves its environment`, async () => {
+ const root = await temporaryDirectory("workbench-python-startup-");
+ const marker = path.join(root, "startup-ran");
+ const python = await userSitePython();
+ const original = process.env[variable];
+ try {
+ process.env[variable] = path.join(root, "startup-hooks");
+ const hooks =
+ variable === "PYTHONPATH"
+ ? process.env[variable]
+ : (
+ await promisify(execFile)(python, [
+ "-E",
+ "-X",
+ "utf8",
+ "-B",
+ "-c",
+ "import site; print(site.getusersitepackages())",
+ ])
+ ).stdout.trim();
+ await mkdir(hooks, { recursive: true });
+ await writeFile(
+ path.join(
+ hooks,
+ variable === "PYTHONPATH" ? "sitecustomize.py" : "usercustomize.py",
+ ),
+ `from pathlib import Path\nPath(${JSON.stringify(marker)}).write_text("startup hook ran")\n`,
+ );
+ await promisify(execFile)(python, ["-X", "utf8", "-B", "-c", "pass"]);
+ assert.equal(await readFile(marker, "utf8"), "startup hook ran");
+ await rm(marker);
+
+ const executeFixture = await fixtureWorkbench(
+ root,
+ 'import json\ndef main():\n print(json.dumps({"scans": []}))\n',
+ );
+ const result = await executeFixture(
+ python,
+ ["list-scans", "--limit", "1"],
+ undefined,
+ { isolatedPython: true },
+ );
+ assert.deepEqual(result.scans, []);
+ await assert.rejects(stat(marker), { code: "ENOENT" });
+ assert.equal(process.env[variable], path.join(root, "startup-hooks"));
+ } finally {
+ if (original === undefined) delete process.env[variable];
+ else process.env[variable] = original;
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+}
+await test("workbench can import dependencies installed in the Python user site", async () => {
+ const root = await temporaryDirectory("workbench-python-user-site-");
+ const originalUserBase = process.env.PYTHONUSERBASE;
+ try {
+ const python = await userSitePython();
+ process.env.PYTHONUSERBASE = path.join(root, "user-base");
+ const { stdout: userSite } = await promisify(execFile)(python, [
+ "-E",
+ "-X",
+ "utf8",
+ "-B",
+ "-c",
+ "import site; print(site.getusersitepackages())",
+ ]);
+ await mkdir(userSite.trim(), { recursive: true });
+ await writeFile(
+ path.join(userSite.trim(), "synthetic_dependency.py"),
+ 'VALUE = "user-site dependency"\n',
+ );
+ const { stdout: imported } = await promisify(execFile)(python, [
+ "-E",
+ "-X",
+ "utf8",
+ "-B",
+ "-c",
+ "from synthetic_dependency import VALUE; print(VALUE)",
+ ]);
+ assert.equal(imported.trim(), "user-site dependency");
+ const executeFixture = await fixtureWorkbench(
+ root,
+ 'import json\nfrom synthetic_dependency import VALUE\ndef main():\n print(json.dumps({"dependency": VALUE}))\n',
+ );
+ assert.deepEqual(await executeFixture(python, ["list-scans"]), {
+ dependency: "user-site dependency",
+ });
+ } finally {
+ if (originalUserBase === undefined) delete process.env.PYTHONUSERBASE;
+ else process.env.PYTHONUSERBASE = originalUserBase;
+ await rm(root, { recursive: true, force: true });
+ }
+});
const root = await temporaryDirectory("workbench-framing-", true);
const stateDir = path.join(root, "state");
const previousStateDir = process.env.CODEX_SECURITY_STATE_DIR;
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index 6d72937e7..89122d9ef 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -166,6 +166,7 @@ const allowedFiles = new Set([
"custom-validation-prompt",
"custom-publish",
"deep-progress",
+ "deep-scan",
"deep-config",
"deep-scan-defaults",
"project-config",
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 9a76f340b..cefad44f9 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -88,6 +88,7 @@ import {
type DeepScanProgress,
} from "./deep-progress.js";
import { findScanSession } from "./scan-logs.js";
+import { runDeepScan, supportsDirectDeepScan } from "./deep-scan.js";
import {
deepScanOptions,
resolveDeepScanConfig,
@@ -492,6 +493,8 @@ interface ClientDependencies {
probeCodexSandbox?: typeof probeCodexSandbox;
runWorkbench?: typeof runWorkbench;
matchFindings?: typeof matchScanFindingsInternal;
+ runDeepScan?: typeof runDeepScan;
+ supportsDirectDeepScan?: typeof supportsDirectDeepScan;
}
const DEFAULT_DEPENDENCIES: ClientDependencies = {
@@ -1458,6 +1461,20 @@ export class CodexSecurity {
);
}
const skillName = skillNameFor(normalized, mode);
+ // Native no-turn resume retains saved permissions; exec refreshes them.
+ // Keep the parent for its ChatGPT advisory and configured Node launcher.
+ const directDeepScan =
+ mode === "deep" &&
+ options.resumeScanId === undefined &&
+ environmentValue(runtime.environment, "CODEX_MCP_NODE_PATH") ===
+ undefined &&
+ (modelProvider === "amazon-bedrock" ||
+ authentication.method === "api_key" ||
+ (authentication.method === "stored_credentials" &&
+ authentication.credentialType === "api_key")) &&
+ (await (
+ this.#dependencies.supportsDirectDeepScan ?? supportsDirectDeepScan
+ )(runtime.plugin.pluginRoot));
const discoveryPrompt =
options.validationPrompt === undefined
? undefined
@@ -1961,13 +1978,14 @@ export class CodexSecurity {
? {}
: { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),
};
- const { codex, environment } = await this.#createSessionCodex(
- session,
- "scan",
- runtimePaths,
- options.auth,
- git,
- );
+ const { codex, environment, codexOptions } =
+ await this.#createSessionCodex(
+ session,
+ "scan",
+ runtimePaths,
+ options.auth,
+ git,
+ );
const threadOptions: ThreadOptions = {
threadSource: CODEX_SECURITY_THREAD_SOURCES.scan,
workingDirectory: scanDir,
@@ -2009,7 +2027,19 @@ export class CodexSecurity {
if (postScanPrompt?.trim()) {
runPostScan = () => thread.runStreamed(postScanPrompt, turnOptions);
}
- const { events } = await thread.runStreamed(prompt, turnOptions);
+ const events = directDeepScan
+ ? (this.#dependencies.runDeepScan ?? runDeepScan)({
+ codexOptions,
+ preflightCommand:
+ await this.#providerPreflightCommand(effectiveConfig),
+ pluginRoot: runtime.plugin.pluginRoot,
+ repository: repo,
+ scanDir,
+ scanId,
+ prompt,
+ signal,
+ })
+ : (await thread.runStreamed(prompt, turnOptions)).events;
checkOpen();
let result = await runScanEvents({
@@ -2026,12 +2056,23 @@ export class CodexSecurity {
workbenchValidated: true,
model,
onThreadStarted: async (threadId) => {
+ if (resumeThreadId !== undefined && threadId !== resumeThreadId) {
+ throw new CodexSecurityError(
+ "Codex did not resume the original scan session.",
+ );
+ }
+ if (directDeepScan && postScanPrompt?.trim()) {
+ runPostScan = () => {
+ if (codex.resumeThread === undefined)
+ throw new CodexSecurityError(
+ "The configured Codex client does not support resuming sessions.",
+ );
+ return codex
+ .resumeThread(threadId, threadOptions)
+ .runStreamed(postScanPrompt, turnOptions);
+ };
+ }
if (resumeThreadId !== undefined) {
- if (threadId !== resumeThreadId) {
- throw new CodexSecurityError(
- "Codex did not resume the original scan session.",
- );
- }
return;
}
if (budgetRecovery !== null) budgetRecovery.threadId = threadId;
@@ -2190,6 +2231,17 @@ export class CodexSecurity {
: ["--cost-json", JSON.stringify(completionCost)]),
]);
activeScan = null;
+ if (directDeepScan) {
+ result = new ScanResult({
+ ...result,
+ turnResult: {
+ ...result.turnResult,
+ finalResponse: (
+ await readScanFile(scanDir, "report.md", "report.md", signal)
+ ).toString("utf8"),
+ },
+ });
+ }
const completedScan = completion["scan"];
if (isRecord(completedScan) && Array.isArray(completedScan["warnings"])) {
const targetWarnings = new Set([
@@ -2740,7 +2792,11 @@ export class CodexSecurity {
git?: InspectedExecutable,
config?: JsonObject,
configOverrides: string[] = [],
- ): Promise<{ codex: CodexClientLike; environment: ProcessEnvironment }> {
+ ): Promise<{
+ codex: CodexClientLike;
+ environment: ProcessEnvironment;
+ codexOptions: CodexOptions & { nativeProfile?: string };
+ }> {
const {
runtime,
runtimeHome,
@@ -2820,7 +2876,7 @@ export class CodexSecurity {
sdkEnvironment,
);
}
- const codex = await this.#dependencies.createCodex({
+ const codexOptions: CodexOptions & { nativeProfile?: string } = {
...(codexPathOverride === undefined
? {}
: { codexPathOverride: executablePathForSpawn(codexPathOverride) }),
@@ -2845,8 +2901,9 @@ export class CodexSecurity {
),
},
},
- });
- return { codex, environment };
+ };
+ const codex = await this.#dependencies.createCodex(codexOptions);
+ return { codex, environment, codexOptions };
}
async #prepareSession(
diff --git a/sdk/typescript/src/deep-scan.ts b/sdk/typescript/src/deep-scan.ts
new file mode 100644
index 000000000..3eea454e5
--- /dev/null
+++ b/sdk/typescript/src/deep-scan.ts
@@ -0,0 +1,173 @@
+import { readFile } from "node:fs/promises";
+import { spawn } from "node:child_process";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import type { CodexOptions } from "@openai/codex-sdk";
+import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";
+import { CodexSecurityError } from "./errors.js";
+import { executablePathForSpawn, type CodexCommand } from "./runtime.js";
+import { resolveTrustedExecutable } from "./trusted-executable.js";
+import { withCodexPreflightLock } from "./provider-profile.js";
+
+/** Older custom plugins retain their existing prompt-driven launch path. */
+export async function supportsDirectDeepScan(
+ pluginRoot: string,
+): Promise<boolean> {
+ // The native parent keeps the plugin's configured Node selection under Bun.
+ if (process.versions["bun"]) return false;
+ const manifest = JSON.parse(
+ await readFile(join(pluginRoot, ".codex-plugin", "plugin.json"), "utf8"),
+ );
+ return manifest.codexSecurity?.directDeepScanEngine === 1;
+}
+
+export interface DirectDeepScanOptions {
+ codexOptions: CodexOptions & { nativeProfile?: string };
+ preflightCommand: CodexCommand;
+ pluginRoot: string;
+ repository: string;
+ scanDir: string;
+ scanId: string;
+ prompt: string;
+ signal: AbortSignal;
+}
+
+/** Run the same coordinator as the plugin, without a parent model turn. */
+export async function* runDeepScan(
+ options: DirectDeepScanOptions,
+): AsyncGenerator<{
+ type: string;
+ [key: string]: unknown;
+}> {
+ const native = await import(
+ pathToFileURL(
+ join(options.pluginRoot, "mcp", "permission-profile-preflight.mjs"),
+ ).href
+ );
+ const profile = await import(
+ pathToFileURL(join(options.pluginRoot, "scripts", "codex_profile.mjs")).href
+ );
+ const configured = options.codexOptions;
+ const command = options.preflightCommand;
+ const environment = bundledCodexSdkEnvironment(command.command, {
+ ...configured.env,
+ ...(configured.apiKey === undefined
+ ? {}
+ : { CODEX_API_KEY: configured.apiKey }),
+ });
+ const session = (await withCodexPreflightLock(
+ environment,
+ options.signal,
+ () =>
+ native.prepareCliDeepScanSession({
+ codexPath: command.command,
+ commandArgs: command.args,
+ cwd: options.scanDir,
+ env: environment,
+ configOverrides: [
+ ...profile.profileConfigOverrides(configured.config ?? {}),
+ ...(configured.configOverrides ?? []),
+ // This session only records native context; workers keep their own snapshot.
+ "features.plugins=false",
+ ],
+ signal: options.signal,
+ prompt:
+ options.prompt +
+ "\n\nThe host runs this Deep Scan coordinator directly and owns finalization. This saved request supplies context for later follow-up; do not start a replacement scan.",
+ }),
+ )) as {
+ threadId: string;
+ model: string;
+ reasoningEffort?: string;
+ permissionProfile: unknown;
+ };
+ yield { type: "thread.started", thread_id: session.threadId };
+ options.signal.throwIfAborted();
+ const node = process.versions["bun"]
+ ? await resolveTrustedExecutable("node", environment, [options.repository])
+ : undefined;
+ if (node === null)
+ throw new CodexSecurityError("Node.js is not available on PATH.");
+ const output = await runEngine(
+ node?.executable ?? process.execPath,
+ [join(options.pluginRoot, "mcp", "server.mjs"), "--deep-scan-engine"],
+ node?.environment ?? environment,
+ JSON.stringify({ scanId: options.scanId, ...session }),
+ options.signal,
+ );
+ const completed = JSON.parse(output);
+ if (
+ completed.scanId !== options.scanId ||
+ completed.manifestPath !== join(options.scanDir, "scan-manifest.json")
+ ) {
+ throw new CodexSecurityError(
+ "Deep Scan engine returned results for a different scan.",
+ );
+ }
+ // The control session makes no model calls. Worker usage is read by the
+ // existing scan tracker from the native sessions below this scan directory.
+ yield {
+ type: "turn.completed",
+ usage: {
+ input_tokens: 0,
+ cached_input_tokens: 0,
+ cache_write_input_tokens: 0,
+ output_tokens: 0,
+ },
+ };
+}
+
+function runEngine(
+ command: string,
+ args: string[],
+ env: NodeJS.ProcessEnv,
+ request: string,
+ signal: AbortSignal,
+): Promise<string> {
+ signal.throwIfAborted();
+ const child = spawn(executablePathForSpawn(command), args, {
+ env,
+ windowsHide: true,
+ });
+ // EOF requests graceful coordinator/worker cleanup on Windows as well as Unix.
+ // Keep the control pipe open until completion or explicit cancellation.
+ const cancel = () => child.stdin.end();
+ let stdout = "";
+ let stderr = "";
+ let processError: Error | undefined;
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
+ stdout += chunk;
+ });
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
+ stderr += chunk;
+ });
+ child.once("error", (error) => {
+ processError = error;
+ });
+ child.stdin.on("error", (error: NodeJS.ErrnoException) => {
+ if (
+ !["EPIPE", "ECONNRESET", "EOF", "ERR_STREAM_DESTROYED"].includes(
+ error.code ?? "",
+ )
+ )
+ processError = error;
+ });
+ const result = new Promise<string>((resolve, reject) => {
+ child.once("close", (code) => {
+ signal.removeEventListener("abort", cancel);
+ if (signal.aborted) reject(signal.reason);
+ else if (processError) reject(processError);
+ else if (code !== 0)
+ reject(
+ new CodexSecurityError(
+ stderr.trim() || `Deep Scan engine exited with code ${code}.`,
+ ),
+ );
+ else resolve(stdout);
+ });
+ });
+ child.stdin.write(request + "\n");
+ signal.addEventListener("abort", cancel, { once: true });
+ if (signal.aborted) cancel();
+ return result;
+}
diff --git a/sdk/typescript/src/provider-profile.ts b/sdk/typescript/src/provider-profile.ts
index 22e9e9117..3bf1f5e6c 100644
--- a/sdk/typescript/src/provider-profile.ts
+++ b/sdk/typescript/src/provider-profile.ts
@@ -190,7 +190,7 @@ export async function legacyWorkerUsesScanProvider(
});
}
-async function withCodexPreflightLock<T>(
+export async function withCodexPreflightLock<T>(
env: Record<string, string> | undefined,
signal: AbortSignal | undefined,
operation: () => Promise<T>,
diff --git a/sdk/typescript/tests-ts/api-deep-scan-advisory-routing.test.ts b/sdk/typescript/tests-ts/api-deep-scan-advisory-routing.test.ts
new file mode 100644
index 000000000..4009bd8be
--- /dev/null
+++ b/sdk/typescript/tests-ts/api-deep-scan-advisory-routing.test.ts
@@ -0,0 +1,239 @@
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { afterEach, expect, mock, test } from "bun:test";
+import type { TurnOptions } from "@openai/codex-sdk";
+import { parse } from "smol-toml";
+import type { ScanAuthentication, ScanOptions } from "../src/api.js";
+import type { DirectDeepScanOptions } from "../src/deep-scan.js";
+import { TestClient } from "./support/api-client.js";
+import {
+ preparedRuntime,
+ scanRuntimeDependencies,
+} from "./support/api-events.js";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+
+const { temporaryDirectory, cleanup } = createApiTestFixtures();
+afterEach(cleanup);
+
+interface RoutingCase {
+ name: string;
+ route: "parent" | "direct";
+ environment?: Record<string, string>;
+ storedAuthMode?: string;
+ auth?: ScanOptions["auth"];
+ provider?: string;
+ commandAuth?: boolean;
+ authentication: ScanAuthentication;
+}
+
+const cases: RoutingCase[] = [
+ {
+ name: "ChatGPT with unrelated AWS credentials",
+ route: "parent",
+ environment: { AWS_PROFILE: "synthetic-unrelated-profile" },
+ storedAuthMode: "chatgpt",
+ authentication: {
+ method: "stored_credentials",
+ credentialType: "chatgpt",
+ verified: false,
+ },
+ },
+ {
+ name: "selected ChatGPT with an ambient API key",
+ route: "parent",
+ environment: { CODEX_API_KEY: "synthetic-unused-key" },
+ storedAuthMode: "chatgpt",
+ auth: "chatgpt",
+ authentication: {
+ method: "stored_credentials",
+ credentialType: "chatgpt",
+ verified: false,
+ },
+ },
+ {
+ name: "stored credentials without auth.json",
+ route: "parent",
+ authentication: { method: "stored_credentials", verified: false },
+ },
+ {
+ name: "unclassified stored credentials",
+ route: "parent",
+ storedAuthMode: "unknown",
+ authentication: { method: "stored_credentials", verified: false },
+ },
+ {
+ name: "command authentication with an ambient API key",
+ route: "parent",
+ environment: { CODEX_API_KEY: "synthetic-unused-key" },
+ commandAuth: true,
+ authentication: { method: "command", verified: false },
+ },
+ {
+ name: "selected API key with stored ChatGPT credentials",
+ route: "direct",
+ environment: { CODEX_API_KEY: "synthetic-selected-key" },
+ storedAuthMode: "chatgpt",
+ authentication: {
+ method: "api_key",
+ source: "CODEX_API_KEY",
+ verified: false,
+ },
+ },
+ ...["apikey", "api_key"].map((storedAuthMode): RoutingCase => ({
+ name: `stored ${storedAuthMode} credentials`,
+ route: "direct",
+ storedAuthMode,
+ authentication: {
+ method: "stored_credentials",
+ credentialType: "api_key",
+ verified: false,
+ },
+ })),
+ {
+ name: "selected Bedrock with stored ChatGPT credentials",
+ route: "direct",
+ provider: "amazon-bedrock",
+ storedAuthMode: "chatgpt",
+ authentication: {
+ method: "aws_credentials",
+ source: "default_credential_chain",
+ verified: false,
+ },
+ },
+ {
+ name: "selected Bedrock with command authentication",
+ route: "direct",
+ provider: "amazon-bedrock",
+ commandAuth: true,
+ authentication: { method: "command", verified: false },
+ },
+ {
+ name: "selected external provider API key",
+ route: "direct",
+ provider: "openrouter",
+ environment: { OPENROUTER_API_KEY: "synthetic-provider-key" },
+ storedAuthMode: "chatgpt",
+ authentication: {
+ method: "api_key",
+ source: "OPENROUTER_API_KEY",
+ verified: false,
+ },
+ },
+];
+
+test.each(cases)(
+ "Deep Scan preserves the advisory route for $name",
+ async (scenario) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ if (scenario.storedAuthMode !== undefined) {
+ await writeFile(
+ join(codexHome, "auth.json"),
+ JSON.stringify({ auth_mode: scenario.storedAuthMode }),
+ );
+ }
+ const environment = {
+ ...scenario.environment,
+ CODEX_HOME: codexHome,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ XDG_CACHE_HOME: join(root, "cache"),
+ };
+ const configPath = join(codexHome, "scan-runtime.toml");
+ const deepScanConfigPath = join(codexHome, "deep-scan.toml");
+ const modelProvider = scenario.provider ?? "openai";
+ const onAuthentication = mock();
+ const parentTurn = mock(async (prompt: string, options?: TurnOptions) => {
+ expect(prompt).toContain("start_codex_security_deep_scan");
+ expect(options?.cyberAccessProgram).toBe("daybreak_blue");
+ throw new Error("parent route reached");
+ });
+ const directRun = mock(async function* (options: DirectDeepScanOptions) {
+ expect(options.scanDir).toBe(scanDir);
+ expect(options.repository).toBe(repository);
+ throw new Error("direct route reached");
+ });
+ const client = new TestClient(
+ {
+ codexOverrides: {
+ model: "gpt-6.1-sol",
+ model_reasoning_effort: "high",
+ model_provider: modelProvider,
+ features: { api_key_cyber_access_programs: false },
+ ...(scenario.commandAuth
+ ? {
+ model_providers: {
+ [modelProvider]: { auth: { command: "synthetic-auth" } },
+ },
+ }
+ : {}),
+ },
+ },
+ {
+ ...scanRuntimeDependencies(codexHome, scanDir),
+ environment,
+ prepareRuntime: async () => ({
+ ...preparedRuntime(codexHome),
+ environment,
+ configPath,
+ deepScanConfigPath,
+ }),
+ // Exercise routing independently of the host's Bun capability fallback.
+ supportsDirectDeepScan: async () => true,
+ createCodex: (options) => {
+ expect(options.config).toMatchObject({
+ model: "gpt-6.1-sol",
+ model_reasoning_effort: "high",
+ model_provider: modelProvider,
+ features: { api_key_cyber_access_programs: false },
+ });
+ expect(options.env).toMatchObject({
+ XDG_CACHE_HOME: environment.XDG_CACHE_HOME,
+ CODEX_SECURITY_CONFIG_PATH: configPath,
+ CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH: deepScanConfigPath,
+ });
+ return {
+ startThread: (options) => {
+ expect(options.workingDirectory).toBe(scanDir);
+ return { id: null, runStreamed: parentTurn };
+ },
+ };
+ },
+ runDeepScan: directRun,
+ },
+ );
+ try {
+ await expect(
+ client.run(repository, {
+ mode: "deep",
+ auth: scenario.auth,
+ cyberAccessProgram: "daybreak_blue",
+ onAuthentication,
+ }),
+ ).rejects.toThrow(`${scenario.route} route reached`);
+ expect(onAuthentication).toHaveBeenCalledWith(scenario.authentication);
+ expect(parentTurn).toHaveBeenCalledTimes(
+ scenario.route === "parent" ? 1 : 0,
+ );
+ expect(directRun).toHaveBeenCalledTimes(
+ scenario.route === "direct" ? 1 : 0,
+ );
+ expect(parse(await readFile(configPath, "utf8"))).toMatchObject({
+ codex_security: { cyber_access_program: "daybreak_blue" },
+ features: { api_key_cyber_access_programs: false },
+ });
+ expect(parse(await readFile(deepScanConfigPath, "utf8"))).toMatchObject({
+ worker_runtime: {
+ model_provider: modelProvider,
+ features: { api_key_cyber_access_programs: false },
+ },
+ });
+ } finally {
+ await client.close();
+ }
+ },
+);
diff --git a/sdk/typescript/tests-ts/api-deep-scan-runtime-routing.test.ts b/sdk/typescript/tests-ts/api-deep-scan-runtime-routing.test.ts
new file mode 100644
index 000000000..b23873ad8
--- /dev/null
+++ b/sdk/typescript/tests-ts/api-deep-scan-runtime-routing.test.ts
@@ -0,0 +1,128 @@
+import { mkdir } from "node:fs/promises";
+import { join } from "node:path";
+import { afterEach, expect, mock, test } from "bun:test";
+import type { CodexOptions } from "@openai/codex-sdk";
+import type { DirectDeepScanOptions } from "../src/deep-scan.js";
+import { TestClient } from "./support/api-client.js";
+import {
+ preparedRuntime,
+ scanRuntimeDependencies,
+} from "./support/api-events.js";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+
+const { temporaryDirectory, cleanup } = createApiTestFixtures();
+afterEach(cleanup);
+
+test.each([
+ {
+ name: "inherited Node override",
+ dependencyNode: "configured runtime",
+ runtimeNode: "configured runtime",
+ route: "parent",
+ },
+ {
+ name: "Node override supplied by the prepared runtime",
+ dependencyNode: null,
+ runtimeNode: "selected runtime",
+ route: "parent",
+ },
+ {
+ name: "prepared Node override replacing the dependency value",
+ dependencyNode: "ambient runtime",
+ runtimeNode: "selected runtime",
+ route: "parent",
+ },
+ {
+ name: "dependency Node override absent from the prepared runtime",
+ dependencyNode: "unused runtime",
+ runtimeNode: null,
+ route: "direct",
+ },
+ {
+ name: "no Node override",
+ dependencyNode: null,
+ runtimeNode: null,
+ route: "direct",
+ },
+])("Deep Scan respects $name", async (scenario) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ const selectedNode =
+ scenario.runtimeNode === null
+ ? undefined
+ : join(root, scenario.runtimeNode, "node");
+ const runtimeEnvironment: Record<string, string> =
+ selectedNode === undefined ? {} : { CODEX_MCP_NODE_PATH: selectedNode };
+ const originalRuntimeEnvironment = { ...runtimeEnvironment };
+ const parentTurn = mock(async () => {
+ throw new Error("parent route reached");
+ });
+ const directRun = mock(async function* (options: DirectDeepScanOptions) {
+ expect(options.codexOptions.env?.["CODEX_MCP_NODE_PATH"]).toBe(
+ selectedNode,
+ );
+ throw new Error("direct route reached");
+ });
+ const createCodex = mock((options: CodexOptions) => {
+ expect(options.apiKey).toBe("synthetic-routing-key");
+ expect(options.env?.["CODEX_MCP_NODE_PATH"]).toBe(selectedNode);
+ expect(options.env?.["CODEX_SECURITY_SCAN_DIR"]).toBe(scanDir);
+ expect(options.config).toMatchObject({
+ model: "gpt-6.1-sol",
+ model_reasoning_effort: "high",
+ features: { shell_tool: false },
+ });
+ return {
+ startThread: () => ({ id: null, runStreamed: parentTurn }),
+ };
+ });
+ const client = new TestClient(
+ {
+ codexOverrides: {
+ model: "gpt-6.1-sol",
+ model_reasoning_effort: "high",
+ features: { shell_tool: false },
+ },
+ },
+ {
+ ...scanRuntimeDependencies(codexHome, scanDir),
+ environment: {
+ CODEX_API_KEY: "synthetic-routing-key",
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ ...(scenario.dependencyNode === null
+ ? {}
+ : {
+ CODEX_MCP_NODE_PATH: join(root, scenario.dependencyNode, "node"),
+ }),
+ },
+ prepareRuntime: async () => ({
+ ...preparedRuntime(codexHome),
+ environment: runtimeEnvironment,
+ }),
+ // Keep the host's Bun fallback and account advisory out of this check.
+ supportsDirectDeepScan: async () => true,
+ createCodex,
+ runDeepScan: directRun,
+ },
+ );
+ try {
+ await expect(client.run(repository, { mode: "deep" })).rejects.toThrow(
+ `${scenario.route} route reached`,
+ );
+ expect(createCodex).toHaveBeenCalledTimes(1);
+ expect(parentTurn).toHaveBeenCalledTimes(
+ scenario.route === "parent" ? 1 : 0,
+ );
+ expect(directRun).toHaveBeenCalledTimes(
+ scenario.route === "direct" ? 1 : 0,
+ );
+ expect(runtimeEnvironment).toEqual(originalRuntimeEnvironment);
+ } finally {
+ await client.close();
+ }
+});
diff --git a/sdk/typescript/tests-ts/api-direct-deep-scan.test.ts b/sdk/typescript/tests-ts/api-direct-deep-scan.test.ts
new file mode 100644
index 000000000..45b4512aa
--- /dev/null
+++ b/sdk/typescript/tests-ts/api-direct-deep-scan.test.ts
@@ -0,0 +1,241 @@
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { hash } from "node:crypto";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { delimiter, join } from "node:path";
+import { afterEach, expect, mock, test } from "bun:test";
+import { copyCompletedScan, PLUGIN_ROOT } from "./plugin-root.js";
+import { TestClient, mockWorkbench } from "./support/api-client.js";
+import {
+ completedEvents,
+ preparedRuntime,
+ scanRuntimeDependencies,
+} from "./support/api-events.js";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+
+const { temporaryDirectory, cleanup } = createApiTestFixtures();
+afterEach(cleanup);
+
+test.each([undefined, "Summarize the completed scan."])(
+ "Deep Scan uses the finalized report with post-scan prompt %p",
+ async (postScanPrompt) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ const finalReport =
+ "# Final scan report\n\nFinalized synthetic findings.\n";
+ const commands: string[] = [];
+ const parentTurn = mock(async () => {
+ throw new Error("A parent model turn must not execute the Deep Scan.");
+ });
+ const postScanTurn = mock(async () => ({
+ events: completedEvents("engine-session"),
+ }));
+ const resumeThread = mock((threadId: string) => ({
+ id: threadId,
+ runStreamed: postScanTurn,
+ }));
+ const started = mock();
+ const client = TestClient.withDependencies({
+ ...scanRuntimeDependencies(codexHome, scanDir),
+ supportsDirectDeepScan: async () => true,
+ environment: {
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ CODEX_API_KEY: "synthetic-direct-scan-key",
+ },
+ createCodex: () => ({
+ startThread: () => ({ id: null, runStreamed: parentTurn }),
+ resumeThread,
+ }),
+ runDeepScan: async function* (options) {
+ expect(options.scanId).toBe("scan_example_001");
+ expect(options.codexOptions.env).toMatchObject({
+ CODEX_SECURITY_SCAN_ID: options.scanId,
+ CODEX_SECURITY_SCAN_DIR: scanDir,
+ CODEX_SECURITY_REPOSITORY: repository,
+ });
+ await copyCompletedScan(root);
+ const coveragePath = join(scanDir, "coverage.json");
+ const coverage = JSON.parse(await readFile(coveragePath, "utf8"));
+ coverage.mode = "deep_repository";
+ const coverageBytes = JSON.stringify(coverage);
+ await writeFile(coveragePath, coverageBytes);
+ const manifestPath = join(scanDir, "scan-manifest.json");
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
+ const artifact = manifest.scan.artifacts.find(
+ (entry: { path: string }) => entry.path === "coverage.json",
+ );
+ artifact.sha256 = hash("sha256", coverageBytes);
+ await writeFile(manifestPath, JSON.stringify(manifest));
+ yield { type: "thread.started", thread_id: "engine-session" };
+ yield {
+ type: "turn.completed",
+ usage: {
+ input_tokens: 0,
+ cached_input_tokens: 0,
+ cache_write_input_tokens: 0,
+ output_tokens: 0,
+ },
+ };
+ },
+ runWorkbench: async (_options, args, input) => {
+ commands.push(args[0]!);
+ if (args[0] === "prepare-scan-completion") {
+ await writeFile(
+ join(scanDir, "report.md"),
+ "# Prepared scan report\n",
+ );
+ } else if (args[0] === "complete-scan") {
+ await writeFile(join(scanDir, "report.md"), finalReport);
+ }
+ return mockWorkbench(args, input);
+ },
+ });
+ try {
+ const result = await client.run(repository, {
+ mode: "deep",
+ postScanPrompt,
+ onScanStarted: started,
+ });
+ expect(result.threadId).toBe("engine-session");
+ expect(result.reportPath).toBe(join(scanDir, "report.md"));
+ expect(result.turnResult.finalResponse).toBe(finalReport);
+ expect(result.toJSON()["turn"]).toMatchObject({
+ finalResponse: finalReport,
+ });
+ expect(parentTurn).not.toHaveBeenCalled();
+ expect(resumeThread).toHaveBeenCalledTimes(postScanPrompt ? 1 : 0);
+ expect(postScanTurn).toHaveBeenCalledTimes(postScanPrompt ? 1 : 0);
+ if (postScanPrompt) {
+ expect(resumeThread).toHaveBeenCalledWith(
+ "engine-session",
+ expect.objectContaining({ workingDirectory: scanDir }),
+ );
+ expect(postScanTurn).toHaveBeenCalledWith(
+ postScanPrompt,
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ }
+ expect(started).toHaveBeenCalledTimes(1);
+ expect(
+ commands.filter((command) =>
+ [
+ "register-cli-scan",
+ "set-scan-thread",
+ "prepare-scan-completion",
+ "complete-scan",
+ ].includes(command),
+ ),
+ ).toEqual([
+ "register-cli-scan",
+ "set-scan-thread",
+ "prepare-scan-completion",
+ "complete-scan",
+ ]);
+ } finally {
+ await client.close();
+ }
+ },
+);
+
+test.each(["configured", "managed"] as const)(
+ "Bun Deep Scans retain the parent route and %s Node configuration",
+ async (selection) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ await mkdir(repository);
+ await mkdir(codexHome);
+ await mkdir(scanDir, { mode: 0o700 });
+ const inheritedTools = join(root, "operator-tools");
+ await mkdir(inheritedTools);
+ const runtimeEnvironment: Record<string, string> =
+ selection === "configured"
+ ? { CODEX_MCP_NODE_PATH: join(root, "managed-node") }
+ : { XDG_CACHE_HOME: join(root, "managed-cache") };
+ const environment = {
+ PATH: inheritedTools,
+ ...runtimeEnvironment,
+ CODEX_API_KEY: "synthetic-bun-scan-key",
+ };
+ const parentTurn = mock(async (prompt: string) => {
+ expect(prompt).toContain("start_codex_security_deep_scan");
+ throw new Error("parent route reached");
+ });
+ const client = new TestClient(
+ {
+ codexOverrides: {
+ model: "gpt-6.1-sol",
+ model_reasoning_effort: "high",
+ },
+ },
+ {
+ ...scanRuntimeDependencies(codexHome, scanDir),
+ environment: {
+ ...environment,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ },
+ prepareRuntime: async () => ({
+ ...preparedRuntime(codexHome),
+ environment,
+ }),
+ createCodex: (options) => {
+ expect(options.env).toMatchObject(runtimeEnvironment);
+ expect(options.env?.["PATH"]?.split(delimiter)).toContain(
+ inheritedTools,
+ );
+ expect(options.config).toMatchObject({
+ model: "gpt-6.1-sol",
+ model_reasoning_effort: "high",
+ });
+ return {
+ startThread: (options) => {
+ expect(options.workingDirectory).toBe(scanDir);
+ return { id: null, runStreamed: parentTurn };
+ },
+ };
+ },
+ runDeepScan: async function* () {
+ throw new Error("unexpected direct engine");
+ },
+ },
+ );
+ try {
+ await expect(
+ client.run(repository, {
+ mode: "deep",
+ }),
+ ).rejects.toThrow("parent route reached");
+ expect(parentTurn).toHaveBeenCalledTimes(1);
+ } finally {
+ await client.close();
+ }
+ },
+);
+
+test("Node retains the direct Deep Scan capability", async () => {
+ const root = await temporaryDirectory();
+ const source = new URL("../src/deep-scan.ts", import.meta.url);
+ const built = await Bun.build({
+ entrypoints: [fileURLToPath(source)],
+ target: "node",
+ format: "esm",
+ define: { "import.meta.url": JSON.stringify(source.href) },
+ });
+ expect(built.success).toBe(true);
+ const module = join(root, "deep-scan.mjs");
+ await writeFile(module, await built.outputs[0]!.text());
+ await promisify(execFile)("node", [
+ "--input-type=module",
+ "--eval",
+ `import assert from "node:assert/strict";
+ const { supportsDirectDeepScan } = await import(${JSON.stringify(pathToFileURL(module).href)});
+ assert.equal(await supportsDirectDeepScan(${JSON.stringify(PLUGIN_ROOT)}), true);`,
+ ]);
+});
diff --git a/sdk/typescript/tests-ts/direct-deep-scan.test.ts b/sdk/typescript/tests-ts/direct-deep-scan.test.ts
new file mode 100644
index 000000000..2302b8422
--- /dev/null
+++ b/sdk/typescript/tests-ts/direct-deep-scan.test.ts
@@ -0,0 +1,276 @@
+import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { afterEach, expect, test } from "bun:test";
+import { runDeepScan } from "../src/deep-scan.js";
+import { ScanCostTracker } from "../src/cost.js";
+import { PLUGIN_ROOT } from "./plugin-root.js";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+import { writeSession } from "./support/usage-rollout.js";
+
+const { temporaryDirectory, cleanup } = createApiTestFixtures();
+afterEach(cleanup);
+
+async function fixture() {
+ const root = await temporaryDirectory();
+ const pluginRoot = join(root, "plugin");
+ await mkdir(join(pluginRoot, "mcp"), { recursive: true });
+ await mkdir(join(pluginRoot, "scripts"));
+ await mkdir(join(root, "codex-home"), { mode: 0o700 });
+ await copyFile(
+ join(PLUGIN_ROOT, "scripts", "codex_profile.mjs"),
+ join(pluginRoot, "scripts", "codex_profile.mjs"),
+ );
+ await writeFile(
+ join(pluginRoot, "mcp", "permission-profile-preflight.mjs"),
+ `
+import { writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+let initializing = false;
+export async function prepareCliDeepScanSession(options) {
+ // Reproduce the native SQLite cold-start conflict while initialization does I/O.
+ if (initializing) throw new Error('Concurrent native SQLite initialization');
+ initializing = true;
+ try {
+ await writeFile(join(options.env.CODEX_HOME, 'initialized'), 'ready');
+ return { threadId: options.env.SYNTHETIC_THREAD_ID,
+ model: 'synthetic-model', reasoningEffort: 'high',
+ permissionProfile: { configOverrides: options.configOverrides, commandArgs: options.commandArgs } };
+ } finally { initializing = false; }
+}
+`,
+ );
+ await writeFile(
+ join(pluginRoot, "mcp", "server.mjs"),
+ `
+import { writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { createInterface } from 'node:readline';
+const lines = createInterface({input: process.stdin});
+const request = JSON.parse((await lines[Symbol.asyncIterator]().next()).value);
+writeFileSync(process.env.SYNTHETIC_RECEIPT, JSON.stringify({
+ request, argv: process.argv.slice(2), key: process.env.CODEX_API_KEY,
+ awsProfile: process.env.AWS_PROFILE, snapshot: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,
+}));
+if (process.env.SYNTHETIC_WAIT === '1') {
+ lines.once('close', () => { writeFileSync(process.env.SYNTHETIC_RECEIPT + '.stopped', 'stopped'); process.exit(0); });
+ setInterval(() => {}, 1000);
+} else {
+ process.stdout.write(JSON.stringify({ scanId: request.scanId,
+ manifestPath: join(process.env.CODEX_SECURITY_SCAN_DIR, 'scan-manifest.json') }) + '\\n');
+ lines.close();
+ process.stdin.destroy();
+}
+`,
+ );
+ return { root, pluginRoot };
+}
+
+test("isolates direct engine credentials and runtime snapshots across concurrent scans", async () => {
+ const { root, pluginRoot } = await fixture();
+ const events = await Promise.all(
+ ["first", "second"].map(async (name) => {
+ const scanDir = join(root, name);
+ const receipt = join(root, `${name}.json`);
+ await mkdir(scanDir);
+ const environment = {
+ PATH: process.env["PATH"]!,
+ CODEX_HOME: join(root, "codex-home"),
+ SYNTHETIC_RECEIPT: receipt,
+ SYNTHETIC_THREAD_ID: `thread-${name}`,
+ CODEX_SECURITY_SCAN_DIR: scanDir,
+ CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH: join(
+ scanDir,
+ "private-snapshot.toml",
+ ),
+ AWS_PROFILE: `profile-${name}`,
+ };
+ const before = { ...environment };
+ const collected = [];
+ for await (const event of runDeepScan({
+ preflightCommand: {
+ command: "/synthetic/codex",
+ args: ["--config", `model_provider="provider_${name}"`],
+ },
+ pluginRoot,
+ repository: root,
+ scanDir,
+ scanId: `scan-${name}`,
+ prompt: "Synthetic audit request.",
+ signal: new AbortController().signal,
+ codexOptions: {
+ codexPathOverride: "/synthetic/codex",
+ nativeProfile: `provider_${name}`,
+ apiKey: `synthetic-key-${name}`,
+ env: environment,
+ config: { model: "synthetic-model" },
+ configOverrides: ['permissions.scan.filesystem={":root"="read"}'],
+ },
+ }))
+ collected.push(event);
+ const saved = JSON.parse(await readFile(receipt, "utf8"));
+ expect(saved).toMatchObject({
+ key: `synthetic-key-${name}`,
+ awsProfile: `profile-${name}`,
+ snapshot: environment.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,
+ argv: ["--deep-scan-engine"],
+ request: {
+ scanId: `scan-${name}`,
+ threadId: `thread-${name}`,
+ permissionProfile: {
+ commandArgs: ["--config", `model_provider="provider_${name}"`],
+ configOverrides: [
+ 'model="synthetic-model"',
+ 'permissions.scan.filesystem={":root"="read"}',
+ "features.plugins=false",
+ ],
+ },
+ },
+ });
+ expect(environment).toEqual(before);
+ return collected;
+ }),
+ );
+ for (const run of events)
+ expect(run.map((event) => event.type)).toEqual([
+ "thread.started",
+ "turn.completed",
+ ]);
+});
+
+test("preserves complete worker usage and cost after direct engine completion", async () => {
+ const { root, pluginRoot } = await fixture();
+ const codexHome = join(root, "codex-home");
+ const scanDir = join(root, "scan");
+ await mkdir(scanDir);
+ await writeSession(
+ codexHome,
+ "discovery-session",
+ {
+ input_tokens: 1_000,
+ cached_input_tokens: 200,
+ cache_write_input_tokens: 100,
+ output_tokens: 100,
+ },
+ {
+ cwd: join(
+ scanDir,
+ "artifacts",
+ "deep_discovery",
+ "workers",
+ "1",
+ "output",
+ ),
+ timestamp: "2026-07-26T12:00:01.000Z",
+ },
+ );
+ await writeSession(
+ codexHome,
+ "reducer-session",
+ {
+ input_tokens: 500,
+ cached_input_tokens: 50,
+ cache_write_input_tokens: 40,
+ output_tokens: 60,
+ },
+ {
+ cwd: join(scanDir, "artifacts"),
+ timestamp: "2026-07-26T12:00:02.000Z",
+ },
+ );
+ await writeFile(
+ join(codexHome, "sessions", "owner.jsonl"),
+ JSON.stringify({
+ type: "session_meta",
+ payload: {
+ id: "engine-session",
+ cwd: scanDir,
+ timestamp: "2026-07-26T12:00:00.000Z",
+ },
+ }) + "\n",
+ );
+ const events = runDeepScan({
+ preflightCommand: { command: "/synthetic/codex" },
+ pluginRoot,
+ repository: root,
+ scanDir,
+ scanId: "usage-scan",
+ prompt: "Synthetic audit.",
+ signal: new AbortController().signal,
+ codexOptions: {
+ env: {
+ PATH: process.env["PATH"]!,
+ CODEX_HOME: codexHome,
+ CODEX_SECURITY_SCAN_DIR: scanDir,
+ SYNTHETIC_RECEIPT: join(root, "engine.json"),
+ SYNTHETIC_THREAD_ID: "engine-session",
+ },
+ },
+ });
+ expect((await events.next()).value).toMatchObject({
+ type: "thread.started",
+ thread_id: "engine-session",
+ });
+ const tracker = new ScanCostTracker({
+ codexHome,
+ scanDirectory: scanDir,
+ model: "gpt-6.1-sol",
+ });
+ tracker.start("engine-session");
+ const running = await tracker.refresh();
+ const completed = (await events.next()).value;
+ expect(completed?.type).toBe("turn.completed");
+ const final = await tracker.stop(completed?.["usage"]);
+ expect(running.usage).toEqual({
+ input_tokens: 1_500,
+ cached_input_tokens: 250,
+ cache_write_input_tokens: 140,
+ output_tokens: 160,
+ reasoning_output_tokens: 0,
+ total_tokens: 1_660,
+ });
+ expect(running.cost).not.toBeNull();
+ expect(final).toEqual(running);
+ expect(final.cost?.cacheWriteInputTokensReported).toBeUndefined();
+ expect((await events.next()).done).toBe(true);
+});
+
+test("waits for the direct engine to stop when the scan is canceled", async () => {
+ const { root, pluginRoot } = await fixture();
+ const receipt = join(root, "engine.json");
+ const controller = new AbortController();
+ const events = runDeepScan({
+ preflightCommand: { command: "/synthetic/codex" },
+ pluginRoot,
+ repository: root,
+ scanDir: root,
+ scanId: "canceled-scan",
+ prompt: "Synthetic audit.",
+ signal: controller.signal,
+ codexOptions: {
+ codexPathOverride: "/synthetic/codex",
+ env: {
+ PATH: process.env["PATH"]!,
+ CODEX_HOME: join(root, "codex-home"),
+ SYNTHETIC_RECEIPT: receipt,
+ SYNTHETIC_THREAD_ID: "cancel-session",
+ SYNTHETIC_WAIT: "1",
+ },
+ },
+ });
+ expect((await events.next()).value).toMatchObject({ type: "thread.started" });
+ const running = events.next();
+ const outcome = running.then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+ try {
+ while (!(await readFile(receipt).catch(() => undefined)))
+ await Bun.sleep(10);
+ controller.abort();
+ expect(await outcome).toBeInstanceOf(Error);
+ expect(await readFile(receipt + ".stopped", "utf8")).toBe("stopped");
+ } finally {
+ controller.abort();
+ await outcome;
+ }
+});
diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.ts
index 072f5b7ab..fd49b32b7 100644
--- a/sdk/typescript/tests-ts/scan-resume.test.ts
+++ b/sdk/typescript/tests-ts/scan-resume.test.ts
@@ -353,8 +353,26 @@ test.each([
},
);
-test("CLI resumes the owning Codex thread and preserves running state on a transport failure", async () => {
+test("CLI resumes through native execution with current permissions and preserves interrupted state", async () => {
const f = await interruptedScan();
+ const originalHome = join(f.root, "original-codex-home");
+ await appendFile(
+ f.sessionPath,
+ JSON.stringify({
+ type: "turn_context",
+ payload: {
+ permission_profile: {
+ type: "managed",
+ file_system: {
+ type: "restricted",
+ entries: [
+ { path: { type: "path", path: originalHome }, access: "deny" },
+ ],
+ },
+ },
+ },
+ }) + "\n",
+ );
const before = await f.command([
"get-deep-scan",
"--scan-id",
@@ -371,14 +389,41 @@ test("CLI resumes the owning Codex thread and preserves running state on a trans
createSecurity: (config) =>
new TestClient(config, {
environment: f.environment,
- prepareRuntime: async () => preparedRuntime(f.codexHome),
+ prepareRuntime: async () => ({
+ ...preparedRuntime(f.codexHome),
+ deepScanConfigDirectory: join(f.codexHome, "worker-config"),
+ deepScanConfigPath: join(
+ f.codexHome,
+ "worker-config",
+ "deep-scan-config.toml",
+ ),
+ }),
resolvePluginPython: async () => f.python,
runWorkbench,
+ runDeepScan: async function* () {
+ throw new Error("Resumed scans must refresh native permissions.");
+ },
createCodex: (options) => ({
startThread: () => fail("Resume must not create a new thread."),
resumeThread(threadId, threadOptions) {
resumedThread = threadId;
expect(threadOptions.workingDirectory).toBe(f.scanDir);
+ expect(threadOptions.approvalPolicy).toBe("never");
+ expect(options.config).toMatchObject({
+ model: f.recipe.config["model"],
+ default_permissions: "codex_security_scan",
+ });
+ const permissions = parseToml(
+ options.configOverrides!.join("\n"),
+ ) as {
+ permissions: {
+ codex_security_scan: { filesystem: Record<string, unknown> };
+ };
+ };
+ const filesystem =
+ permissions.permissions.codex_security_scan.filesystem;
+ expect(filesystem[f.codexHome]).toEqual({ ".": "deny" });
+ expect(filesystem[originalHome]).toBeUndefined();
expect(options.env).toMatchObject({
CODEX_SECURITY_SCAN_ID: f.scanId,
CODEX_SECURITY_SCAN_DIR: f.scanDir,
diff --git a/sdk/typescript/tests-ts/support/api-client.ts b/sdk/typescript/tests-ts/support/api-client.ts
index 5545eac82..1d78e1d4d 100644
--- a/sdk/typescript/tests-ts/support/api-client.ts
+++ b/sdk/typescript/tests-ts/support/api-client.ts
@@ -1,8 +1,61 @@
import { CodexSecurity } from "../../src/api.js";
import type { JsonObject } from "../../src/config.js";
import { throwing } from "./errors.js";
+import { readFile } from "node:fs/promises";
+import { parse } from "smol-toml";
+import type { TurnOptions } from "@openai/codex-sdk";
type ClientArguments = ConstructorParameters<typeof CodexSecurity>;
+type Dependencies = NonNullable<ClientArguments[1]>;
+
+/** Reuse a test's synthetic events at both scan execution boundaries. */
+export function withSyntheticScanEvents<T extends Partial<Dependencies>>(
+ dependencies: T,
+): T {
+ const createCodex = dependencies.createCodex;
+ if (createCodex === undefined) return dependencies;
+ type Client = Awaited<ReturnType<Dependencies["createCodex"]>>;
+ let thread: ReturnType<Client["startThread"]> | undefined;
+ const runDeepScan: NonNullable<Dependencies["runDeepScan"]> =
+ async function* (options) {
+ if (!thread) throw new Error("The synthetic scan session is missing.");
+ const configPath =
+ options.codexOptions.env?.["CODEX_SECURITY_CONFIG_PATH"];
+ const config = configPath
+ ? parse(await readFile(configPath, "utf8"))
+ : {};
+ const security = config["codex_security"] as
+ | { cyber_access_program?: TurnOptions["cyberAccessProgram"] }
+ | undefined;
+ yield* (
+ await thread.runStreamed(options.prompt, {
+ signal: options.signal,
+ cyberAccessProgram: security?.cyber_access_program,
+ })
+ ).events;
+ };
+ return {
+ ...dependencies,
+ createCodex: async (
+ options: Parameters<Dependencies["createCodex"]>[0],
+ ) => {
+ const client = await createCodex(options);
+ return {
+ startThread: (options: Parameters<Client["startThread"]>[0]) =>
+ (thread = client.startThread(options)),
+ ...(client.resumeThread === undefined
+ ? {}
+ : {
+ resumeThread: (
+ id: string,
+ options: Parameters<Client["startThread"]>[0],
+ ) => (thread = client.resumeThread!(id, options)),
+ }),
+ };
+ },
+ runDeepScan: dependencies.runDeepScan ?? runDeepScan,
+ };
+}
export const TEST_SNAPSHOT_DIGEST = `codex-security-snapshot/v1:sha256:${"a".repeat(64)}`;
@@ -70,7 +123,7 @@ export class TestClient extends CodexSecurity {
) {
super(
config,
- {
+ withSyntheticScanEvents({
createCodex: throwing("Unexpected Codex invocation in test"),
environment: {},
probeCodexSandbox: async () => {},
@@ -80,7 +133,7 @@ export class TestClient extends CodexSecurity {
runWorkbench: async (_options, args, input) =>
mockWorkbench(args, input),
...dependencies,
- },
+ }),
{ surface: "sdk" },
);
}
diff --git a/sdk/typescript/tests-ts/support/internal-security.ts b/sdk/typescript/tests-ts/support/internal-security.ts
index c0b69f669..976b66c3a 100644
--- a/sdk/typescript/tests-ts/support/internal-security.ts
+++ b/sdk/typescript/tests-ts/support/internal-security.ts
@@ -1,6 +1,21 @@
import { CodexSecurity } from "../../src/index.js";
+import { withSyntheticScanEvents } from "./api-client.js";
-export const InternalSecurity = CodexSecurity as unknown as new (
+type Arguments = ConstructorParameters<typeof CodexSecurity>;
+
+class InternalTestSecurity extends CodexSecurity {
+ constructor(...[config, dependencies, options]: Arguments) {
+ super(
+ config,
+ dependencies === undefined
+ ? undefined
+ : withSyntheticScanEvents(dependencies),
+ options,
+ );
+ }
+}
+
+export const InternalSecurity = InternalTestSecurity as unknown as new (
config: Record<string, unknown>,
dependencies: Record<string, unknown>,
runtimeOptions?: { surface: "cli" | "sdk" },