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

feat(cli): inspect saved scan and worker logs (#349)

ianw-oai7b2896c62bec
diff --git a/README.md b/README.md
index 3b39ddfcd..e1751a950 100644
--- a/README.md
+++ b/README.md
@@ -84,6 +84,9 @@ npx @openai/codex-security scan . --verbose
`LOG_LEVEL=debug` is its fallback. JSON results remain on stdout, and
credentials and provider identifiers remain redacted.
+Use `npx @openai/codex-security scans logs SCAN_ID` to inspect saved session
+events from a scan and its workers.
+
## TypeScript SDK
```ts
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 1fe6764ee..8de54fbdc 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -218,6 +218,7 @@ npx @openai/codex-security bulk-scan repositories.csv --output-dir /path/outside
npx @openai/codex-security scans list /path/to/repository
npx @openai/codex-security scans list --scan-root /path/outside/repository/results
npx @openai/codex-security scans show SCAN_ID
+npx @openai/codex-security scans logs SCAN_ID
npx @openai/codex-security scans rerun SCAN_ID
npx @openai/codex-security scans match PREVIOUS_SCAN_ID CURRENT_SCAN_ID
npx @openai/codex-security scans match --all
@@ -508,6 +509,9 @@ whose artifacts are under a particular root. `scans show SCAN_ID` includes the
scan configuration, results, coverage, and artifact locations. Add
`--show-linked-findings` to include finding links from previous scans.
+`scans logs SCAN_ID` shows complete session events from the scan and its
+workers, which can include source code and credentials.
+
Every scan history command accepts a full scan ID or a unique prefix of at
least eight characters.
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
index 48f17e248..fe4d7c767 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
@@ -147,6 +147,10 @@ def parse_args(description: str) -> argparse.Namespace:
register_cli_scan.add_argument("--archive-existing", action="store_true")
register_cli_scan.add_argument("--archived-scan-dir")
+ set_scan_thread = subparsers.add_parser("set-scan-thread")
+ set_scan_thread.add_argument("--scan-id", required=True)
+ set_scan_thread.add_argument("--thread-id", required=True)
+
get_scan_recipe = subparsers.add_parser("get-scan-recipe")
get_scan_recipe.add_argument("--scan-id", required=True)
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
index b7c7395f6..3cb96bb58 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
@@ -1432,6 +1432,16 @@ def register_cli_scan(connection: sqlite3.Connection, args: argparse.Namespace)
}
+def set_scan_thread(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:
+ scan = require_scan(connection, args.scan_id)
+ with connection:
+ connection.execute(
+ "UPDATE scans SET continuation_thread_id = ?, updated_at = ? WHERE id = ?",
+ (args.thread_id, now(), scan["id"]),
+ )
+ return {"scanId": scan["id"], "threadId": args.thread_id}
+
+
def parse_scan_recipe(value: str, repository: Path) -> dict[str, Any]:
if len(value.encode("utf-8")) > SCAN_RECIPE_MAX_BYTES:
raise SystemExit("Scan launch recipe must be no larger than 256 KiB.")
@@ -3354,6 +3364,8 @@ def main() -> None:
)
elif args.command == "register-cli-scan":
result = register_cli_scan(connection, args)
+ elif args.command == "set-scan-thread":
+ result = set_scan_thread(connection, args)
elif args.command == "get-scan-recipe":
result = get_scan_recipe(connection, args)
elif args.command == "compare-scans":
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index c4a04a578..baca687e1 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -158,6 +158,7 @@ const distFiles = new Set(
"scan-comparison",
"scan-dashboard",
"scan-history-renderer",
+ "scan-logs",
"targets",
"trusted-executable",
"version",
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index e90b42a03..0df4d1a42 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -996,7 +996,25 @@ export class CodexSecurity {
authentication,
workbenchValidated: true,
model,
- onThreadStarted: (threadId) => tracker.start(threadId),
+ onThreadStarted: async (threadId) => {
+ tracker.start(threadId);
+ try {
+ await workbench(workbenchOptions, [
+ "set-scan-thread",
+ "--scan-id",
+ scanId,
+ "--thread-id",
+ threadId,
+ ]);
+ } catch (error) {
+ notifyObserver(
+ "onWarning",
+ options.onWarning,
+ options.onObserverError,
+ `Could not save scan session: ${redactedErrorMessage(error)}`,
+ );
+ }
+ },
onFinalize: async (usage) => {
const snapshot = await tracker.stop(usage).catch((error: unknown) => {
if (options.maxCostUsd !== undefined) throw error;
@@ -1727,7 +1745,7 @@ interface ScanEventRunOptions {
model?: string;
expectedFilesTotal?: number;
onFinalize?: (usage: unknown) => Promise<unknown>;
- onThreadStarted?: (threadId: string) => void;
+ onThreadStarted?: (threadId: string) => Promise<void> | void;
onScanStarted?: () => void;
onTrustedAccessStatus?: (status: ScanTrustedAccessStatus) => void;
onReconnect?: (
@@ -1812,7 +1830,7 @@ export async function runScanEvents(
const startedThreadId = event["thread_id"];
if (typeof startedThreadId === "string") {
threadId = startedThreadId;
- options.onThreadStarted?.(startedThreadId);
+ await options.onThreadStarted?.(startedThreadId);
}
if (!scanStarted) {
scanStarted = true;
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 1a2a3f4a1..00f1024be 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -89,6 +89,7 @@ import {
matchScanFindings,
type ScanComparisonInput,
} from "./scan-comparison.js";
+import { readScanLogs } from "./scan-logs.js";
import {
renderScanHistory,
type HistoryCommand,
@@ -896,6 +897,39 @@ export async function main(
);
},
})
+ .command("logs", {
+ description: "Show saved activity for a scan and its workers.",
+ mcp: false,
+ args: z.object({
+ scanId: z
+ .string()
+ .min(1)
+ .describe("Saved scan identifier or unique prefix."),
+ }),
+ output: z.record(z.string(), z.unknown()).optional(),
+ async run({ args }) {
+ return await history(
+ ["get-scan", "--scan-id", args.scanId],
+ async (value) => {
+ const scan = value["scan"] as {
+ scanId: string;
+ continuationThreadId?: string;
+ };
+ const threadId = scan.continuationThreadId;
+ if (!threadId) {
+ throw new CodexSecurityError(
+ `No session is associated with scan ${scan.scanId}.`,
+ );
+ }
+ return (await readScanLogs({
+ scanId: scan.scanId,
+ threadId,
+ codexHome: codexSecurityCredentialHome(dependencies.environment),
+ })) as unknown as JsonObject;
+ },
+ );
+ },
+ })
.command("rerun", {
description: "Rerun a saved scan with its original configuration.",
destructive: true,
diff --git a/sdk/typescript/src/cost.ts b/sdk/typescript/src/cost.ts
index 31c2c611b..805e50771 100644
--- a/sdk/typescript/src/cost.ts
+++ b/sdk/typescript/src/cost.ts
@@ -311,7 +311,7 @@ export class ScanCostTracker {
}
}
-async function* sessionFiles(directory: string): AsyncGenerator<string> {
+export async function* sessionFiles(directory: string): AsyncGenerator<string> {
let entries;
try {
entries = await readdir(directory, { withFileTypes: true });
diff --git a/sdk/typescript/src/scan-logs.ts b/sdk/typescript/src/scan-logs.ts
new file mode 100644
index 000000000..51673c1eb
--- /dev/null
+++ b/sdk/typescript/src/scan-logs.ts
@@ -0,0 +1,111 @@
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { sessionFiles } from "./cost.js";
+import { CodexSecurityError } from "./errors.js";
+
+interface ScanLogOptions {
+ scanId: string;
+ threadId: string;
+ codexHome: string;
+}
+
+interface SessionLog {
+ threadId: string;
+ parentThreadId: string | null;
+ startedAt: number | null;
+ path: string;
+ events: Record<string, unknown>[];
+}
+
+export async function readScanLogs(options: ScanLogOptions) {
+ const logs = new Map<string, SessionLog>();
+ for await (const path of sessionFiles(join(options.codexHome, "sessions"))) {
+ const events = (await readFile(path, "utf8"))
+ .split("\n")
+ .filter((line) => line.trim() !== "")
+ .flatMap((line) => {
+ try {
+ const event: unknown = JSON.parse(line);
+ return isRecord(event) ? [event] : [];
+ } catch {
+ return [];
+ }
+ });
+ const first = events[0];
+ if (first?.["type"] !== "session_meta" || !isRecord(first["payload"])) {
+ continue;
+ }
+ const metadata = first["payload"];
+ const threadId = metadata["id"];
+ if (typeof threadId !== "string") continue;
+ const source = metadata["source"];
+ const subagent = isRecord(source) ? source["subagent"] : undefined;
+ const spawn = isRecord(subagent) ? subagent["thread_spawn"] : undefined;
+ const parent =
+ metadata["parent_thread_id"] ??
+ (isRecord(spawn) ? spawn["parent_thread_id"] : undefined);
+ logs.set(threadId, {
+ threadId,
+ parentThreadId: typeof parent === "string" ? parent : null,
+ startedAt:
+ typeof metadata["timestamp"] === "string"
+ ? Math.floor(Date.parse(metadata["timestamp"]) / 1_000)
+ : null,
+ path,
+ events,
+ });
+ }
+
+ const root = logs.get(options.threadId);
+ if (root === undefined) {
+ throw new CodexSecurityError(
+ `No saved session logs are available for scan ${options.scanId}.`,
+ );
+ }
+
+ const sessions = [root];
+ for (const parent of sessions) {
+ for (const session of logs.values()) {
+ if (session.parentThreadId === parent.threadId) sessions.push(session);
+ }
+ }
+ const events: Record<string, unknown>[] = [];
+ for (const session of sessions) {
+ let replaying = false;
+ for (const event of session.events) {
+ const payload = event["payload"];
+ if (event["type"] === "session_meta" && isRecord(payload)) {
+ replaying = payload["id"] !== session.threadId;
+ }
+ if (replaying) {
+ if (
+ event["type"] !== "event_msg" ||
+ !isRecord(payload) ||
+ payload["type"] !== "task_started" ||
+ typeof payload["started_at"] !== "number" ||
+ session.startedAt === null ||
+ payload["started_at"] < session.startedAt
+ ) {
+ continue;
+ }
+ replaying = false;
+ }
+ events.push({ threadId: session.threadId, event });
+ }
+ }
+
+ return {
+ scanId: options.scanId,
+ threadId: root.threadId,
+ sessions: sessions.map(({ threadId, parentThreadId, path }) => ({
+ threadId,
+ parentThreadId,
+ path,
+ })),
+ events,
+ };
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 8991361fc..9df4a129e 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -1940,11 +1940,18 @@ describe("CodexSecurity orchestration", () => {
"scan_example_001",
]);
expect(commands[2]).toEqual([
- "prepare-scan-completion",
+ "set-scan-thread",
"--scan-id",
"scan_example_001",
+ "--thread-id",
+ "thread-1",
]);
expect(commands[3]).toEqual([
+ "prepare-scan-completion",
+ "--scan-id",
+ "scan_example_001",
+ ]);
+ expect(commands[4]).toEqual([
"complete-scan",
"--scan-id",
"scan_example_001",
@@ -2308,6 +2315,7 @@ describe("CodexSecurity orchestration", () => {
expect(commands).toEqual([
"register-cli-scan",
"get-scan-feedback",
+ "set-scan-thread",
"prepare-scan-completion",
"fail-scan",
]);
@@ -2820,6 +2828,7 @@ describe("CodexSecurity orchestration", () => {
expect(commands.map((command) => command[0])).toEqual([
"register-cli-scan",
"get-scan-feedback",
+ "set-scan-thread",
"prepare-scan-completion",
"complete-scan",
]);
@@ -3033,6 +3042,13 @@ describe("CodexSecurity orchestration", () => {
"scan_example_001",
]);
expect(commands[2]).toEqual([
+ "set-scan-thread",
+ "--scan-id",
+ "scan_example_001",
+ "--thread-id",
+ "scan-thread",
+ ]);
+ expect(commands[3]).toEqual([
"fail-scan",
"--scan-id",
"scan_example_001",
@@ -3108,6 +3124,7 @@ describe("CodexSecurity orchestration", () => {
expect(commands.map(([command]) => command)).toEqual([
"register-cli-scan",
"get-scan-feedback",
+ "set-scan-thread",
"prepare-scan-completion",
"complete-scan",
]);
@@ -3346,6 +3363,7 @@ describe("CodexSecurity orchestration", () => {
id: null,
async runStreamed() {
async function* failingEvents(): AsyncGenerator<ThreadEvent> {
+ yield { type: "thread.started", thread_id: "failed-thread" };
yield {
type: "error",
message: `${SYNTHETIC_CREDENTIALS} ${quotedCredential}`,
@@ -3373,6 +3391,7 @@ describe("CodexSecurity orchestration", () => {
["get-scan", "--scan-id", scanId],
);
expect(context["scan"]).toMatchObject({
+ continuationThreadId: "failed-thread",
progress: { status: "failed" },
failureMessage: redactedFailure,
});
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index aea574ba7..f83a7c560 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -1,4 +1,6 @@
-import { resolve } from "node:path";
+import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
import { describe, expect, test } from "bun:test";
import type { CodexSecurityConfig, JsonObject } from "../src/index.js";
import { DiffTarget } from "../src/index.js";
@@ -171,6 +173,87 @@ describe("CLI workbench", () => {
}
});
+ test("shows saved scan activity without starting Codex", async () => {
+ const state = await realpath(
+ await mkdtemp(join(tmpdir(), "codex-security-cli-logs-")),
+ );
+ try {
+ const sessions = join(state, "codex-home", "sessions", "2026", "08");
+ await mkdir(sessions, { recursive: true });
+ await writeFile(
+ join(sessions, "rollout-thread-1.jsonl"),
+ [
+ {
+ type: "session_meta",
+ payload: { id: "thread-1" },
+ },
+ {
+ type: "response_item",
+ payload: {
+ type: "function_call",
+ call_id: "call-1",
+ name: "exec_command",
+ arguments: JSON.stringify({
+ cmd: "OPENAI_API_KEY=sk-proj-SYNTHETIC_KEY_123 pytest",
+ }),
+ },
+ },
+ ]
+ .map((event) => JSON.stringify(event))
+ .join("\n"),
+ );
+
+ const calls: Array<readonly string[]> = [];
+ const stdout = capture();
+ const deps = dependencies({
+ environment: { CODEX_SECURITY_STATE_DIR: state },
+ onWorkbench: (args) => {
+ calls.push(args);
+ return {
+ scan: {
+ scanId: "scan-1",
+ continuationThreadId: "thread-1",
+ },
+ };
+ },
+ });
+ deps.createSecurity = () => {
+ throw new Error("logs must not initialize Codex");
+ };
+ expect(
+ await main(
+ ["scans", "logs", "scan-1", "--json"],
+ stdout.stream,
+ capture().stream,
+ deps,
+ ),
+ ).toBe(0);
+ expect(calls).toEqual([["get-scan", "--scan-id", "scan-1"]]);
+ expect(stdout.text()).toContain("SYNTHETIC_KEY");
+ } finally {
+ await rm(state, { recursive: true, force: true });
+ }
+ });
+
+ test("explains when a saved scan has no associated session", async () => {
+ const stderr = capture();
+ expect(
+ await main(
+ ["scans", "logs", "scan-1"],
+ capture().stream,
+ stderr.stream,
+ dependencies({
+ onWorkbench: () => ({
+ scan: { scanId: "scan-1", targetPath: "/repo" },
+ }),
+ }),
+ ),
+ ).toBe(2);
+ expect(stderr.text()).toContain(
+ "No session is associated with scan scan-1.",
+ );
+ });
+
test("matches findings before matching or comparing scans", async () => {
const before = [{ occurrenceId: "before" }];
const after = [{ occurrenceId: "after" }];
diff --git a/sdk/typescript/tests-ts/scan-logs.test.ts b/sdk/typescript/tests-ts/scan-logs.test.ts
new file mode 100644
index 000000000..c6a1ae680
--- /dev/null
+++ b/sdk/typescript/tests-ts/scan-logs.test.ts
@@ -0,0 +1,204 @@
+import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, test } from "bun:test";
+import { readScanLogs } from "../src/scan-logs.js";
+
+const directories: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ directories
+ .splice(0)
+ .map((directory) => rm(directory, { recursive: true, force: true })),
+ );
+});
+
+async function writeSession(
+ home: string,
+ threadId: string,
+ events: Record<string, unknown>[],
+ parentThreadId?: string,
+ startedAt?: string,
+): Promise<void> {
+ const directory = join(home, "sessions", "2026", "08", "11");
+ await mkdir(directory, { recursive: true });
+ await writeFile(
+ join(directory, `rollout-${threadId}.jsonl`),
+ [
+ {
+ type: "session_meta",
+ payload: {
+ id: threadId,
+ ...(startedAt === undefined ? {} : { timestamp: startedAt }),
+ ...(parentThreadId === undefined
+ ? {}
+ : {
+ source: {
+ subagent: {
+ thread_spawn: { parent_thread_id: parentThreadId },
+ },
+ },
+ }),
+ },
+ },
+ ...events,
+ ]
+ .map((event) => JSON.stringify(event))
+ .join("\n"),
+ );
+}
+
+async function temporaryHome(): Promise<string> {
+ const directory = await realpath(
+ await mkdtemp(join(tmpdir(), "codex-security-scan-logs-")),
+ );
+ directories.push(directory);
+ return directory;
+}
+
+function commandEvent(command: string, id: string, timestamp?: string) {
+ return {
+ type: "response_item",
+ ...(timestamp === undefined ? {} : { timestamp }),
+ payload: {
+ type: "function_call",
+ call_id: id,
+ name: "exec_command",
+ arguments: JSON.stringify({ cmd: command }),
+ },
+ };
+}
+
+describe("saved scan logs", () => {
+ test("returns complete parent and worker events without unrelated sessions", async () => {
+ const home = await temporaryHome();
+ await writeSession(home, "parent", [
+ commandEvent(
+ "OPENAI_API_KEY=sk-proj-SYNTHETIC_KEY_123 rg authorization /repo/src/auth.ts",
+ "call-parent",
+ "2026-08-11T12:00:00.000Z",
+ ),
+ ]);
+ await writeSession(
+ home,
+ "worker",
+ [
+ commandEvent(
+ "python3 -m pytest /repo/tests",
+ "call-worker",
+ "2026-08-11T12:00:01.000Z",
+ ),
+ {
+ type: "response_item",
+ payload: {
+ type: "function_call_output",
+ call_id: "call-worker",
+ status: "failed",
+ output: "private command output",
+ },
+ },
+ ],
+ "parent",
+ );
+ await writeSession(home, "unrelated", [
+ {
+ type: "event_msg",
+ payload: { type: "agent_message", message: "private unrelated scan" },
+ },
+ ]);
+
+ const result = await readScanLogs({
+ scanId: "scan-1",
+ threadId: "parent",
+ codexHome: home,
+ });
+
+ expect(result.sessions.map(({ threadId }) => threadId).sort()).toEqual([
+ "parent",
+ "worker",
+ ]);
+ expect(result.events.map(({ threadId }) => threadId)).toEqual([
+ "parent",
+ "parent",
+ "worker",
+ "worker",
+ "worker",
+ ]);
+ expect(result.events.at(-1)).toMatchObject({
+ threadId: "worker",
+ event: {
+ type: "response_item",
+ payload: { status: "failed", output: "private command output" },
+ },
+ });
+ expect(JSON.stringify(result)).toContain("SYNTHETIC_KEY");
+ expect(JSON.stringify(result)).toContain("private command output");
+ expect(JSON.stringify(result)).not.toContain("private unrelated scan");
+ });
+
+ test("excludes inherited parent history from worker logs", async () => {
+ const home = await temporaryHome();
+ await writeSession(home, "parent", []);
+ const startedAt = "2026-08-11T12:02:00.000Z";
+ await writeSession(
+ home,
+ "worker",
+ [
+ {
+ type: "session_meta",
+ payload: { id: "parent", timestamp: "2026-08-11T12:00:00.000Z" },
+ },
+ {
+ type: "event_msg",
+ payload: {
+ type: "task_started",
+ started_at: Date.parse("2026-08-11T12:00:00.000Z") / 1_000,
+ },
+ },
+ {
+ type: "event_msg",
+ payload: {
+ type: "agent_message",
+ message: "PRIVATE PRE-SCAN CONVERSATION",
+ },
+ },
+ {
+ type: "event_msg",
+ payload: {
+ type: "task_started",
+ started_at: Date.parse(startedAt) / 1_000,
+ },
+ },
+ {
+ type: "event_msg",
+ payload: {
+ type: "agent_message",
+ message: "Reviewing authorization",
+ },
+ },
+ ],
+ "parent",
+ startedAt,
+ );
+
+ const result = await readScanLogs({
+ scanId: "scan-1",
+ threadId: "parent",
+ codexHome: home,
+ });
+ expect(JSON.stringify(result)).toContain("Reviewing authorization");
+ expect(JSON.stringify(result)).not.toContain("PRIVATE PRE-SCAN");
+ });
+
+ test("reports when the saved scan session is missing", async () => {
+ const home = await temporaryHome();
+ await expect(
+ readScanLogs({
+ scanId: "scan-1",
+ threadId: "missing",
+ codexHome: home,
+ }),
+ ).rejects.toThrow("No saved session logs are available for scan scan-1.");
+ });
+});