OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat: Add live scan session details (#403)
ianw-oaib88216a799d4
diff --git a/README.md b/README.mdindex 85a2f27b3..21d2e7ca4 100644--- a/README.md+++ b/README.md@@ -139,11 +139,13 @@ npx @openai/codex-security scan . --verbose`LOG_LEVEL=debug` is its fallback. JSON results remain on stdout.Verbose diagnostics may contain sensitive data. Review local logs before-sharing them. Saved failure summaries, bulk-scan receipts, and the interactive-dashboard omit messages that contain recognizable credentials.+sharing them. Saved failure summaries, bulk-scan receipts, and the normal+activity feed omit messages that contain recognizable credentials.Use `npx @openai/codex-security scans logs SCAN_ID` to inspect saved session-events from a scan and its workers.+events from a scan and its workers. Press `d` during a scan to inspect+unredacted details; `a`, `m`, and `1`–`9` select all, main, or worker+sessions. These events can contain credentials.## TypeScript SDKdiff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 31f27b5f3..298bfccac 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -92,9 +92,11 @@ Pass scan configuration to `security.run(repository, options)` orProgress and lifecycle callbacks are `onAuthentication`, `onCost`,`onOutputArchived`, `onOutputDirReady`, `onScanStarted`,-`onTrustedAccessStatus`, `onReconnect`, `onWorkerStatus`, `onWarning`, and-`onObserverError`. Preflight does not start the runtime, authenticate, resolve-Python, inspect the plugin, or run those scan-lifecycle callbacks.+`onTrustedAccessStatus`, `onReconnect`, `onSessionEvent`, `onWorkerStatus`,+`onWarning`, and `onObserverError`. `onSessionEvent` receives saved scan and+worker events with their thread IDs and worker numbers. Preflight does not start+the runtime, authenticate, resolve Python, inspect the plugin, or run those+scan-lifecycle callbacks.## Authentication@@ -500,9 +502,8 @@ Progress and summaries use stderr; structured scan results remain on stdout.Add `--verbose` or set `CODEX_SECURITY_LOG_LEVEL=debug` to printlifecycle, authentication, progress, and cost diagnostics to stderr.`LOG_LEVEL=debug` is used only when `CODEX_SECURITY_LOG_LEVEL` is unset.-Structured JSON results remain on stdout. Verbose diagnostics may contain-sensitive data; review local logs before sharing them. The interactive-dashboard omits activity containing recognizable credentials.+Structured JSON results remain on stdout. Review sensitive verbose logs before+sharing them. The normal activity feed hides credentials.Each scan records its model, tokens, and estimated cost in its JSON result,scan history, and bulk-scan receipt. Estimates use@@ -676,7 +677,9 @@ details include the configuration, results, coverage, and artifact locations. Ad`--show-linked-findings` to include finding links from previous scans.`scans logs` shows session events from the latest scan, including an active scan.-Pass `SCAN_ID` to select another scan. Logs can contain source code and credentials.+Pass `SCAN_ID` to select another scan. During a scan, press `d` for live details.+Filter with `a` for all sources, `m` for the main scan, or `1`–`9` for a worker.+Logs and live details can contain source code and credentials.Every scan history command accepts a full scan ID or a unique prefix of atleast eight characters.diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex a826fafbc..24bd0fac5 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -37,7 +37,12 @@ import {type JsonObject,writeCodexConfig,} from "./config.js";-import { estimateScanCost, ScanCostTracker, type ScanCost } from "./cost.js";+import {+ estimateScanCost,+ ScanCostTracker,+ type ScanCost,+ type ScanSessionEvent,+} from "./cost.js";import {loadContract,requireScanFile,@@ -189,6 +194,7 @@ export interface ScanOptions extends DeepScanOptions {details?: ScanReconnectDetails,) => void;onActivity?: (activity: ScanActivity) => void;+ onSessionEvent?: (event: ScanSessionEvent) => void;onProgress?: (progress: ScanProgress) => void;onWorkerStatus?: (status: ScanWorkerStatus) => void;onWarning?: (warning: string, details?: ScanWarningDetails) => void;@@ -246,6 +252,7 @@ type ScanObserverName =| "onTrustedAccessStatus"| "onReconnect"| "onActivity"+ | "onSessionEvent"| "onProgress"| "onWorkerStatus"| "onWarning";@@ -770,6 +777,16 @@ export class CodexSecurity {options.onObserverError,activity,),+ onSessionEvent:+ options.onSessionEvent === undefined+ ? undefined+ : (event) =>+ notifyObserver(+ "onSessionEvent",+ options.onSessionEvent,+ options.onObserverError,+ event,+ ),onProgress:options.onProgress === undefined ? undefined : reportProgress,onCost:diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex addcfb807..495cecd45 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -4099,6 +4099,10 @@ async function executeScan(dashboard.setStage("inspecting repository files");}},+ onSessionEvent:+ process.stdin.isTTY === true+ ? dashboard?.recordDetails.bind(dashboard)+ : undefined,onProgress: (update) => {const key = `${update.phase}:${update.filesCompleted}:${update.filesTotal}`;if (key === lastProgressUpdate) return;diff --git a/sdk/typescript/src/cost.ts b/sdk/typescript/src/cost.tsindex 5bb5c1061..764a1e759 100644--- a/sdk/typescript/src/cost.ts+++ b/sdk/typescript/src/cost.ts@@ -18,6 +18,13 @@ export interface ScanCost {estimatedUsd: number;}+export interface ScanSessionEvent {+ threadId: string;+ parentThreadId: string | null;+ worker?: number;+ event: Record<string, unknown>;+}+type ModelPricing = readonly [input: number,cachedInput: number,@@ -61,6 +68,7 @@ interface SessionUsage {prose: Set<string>;reasoning: SessionReasoning | null;reasoningCount: number;+ events?: Record<string, unknown>[];}interface ScanCostTrackerOptions {@@ -73,6 +81,7 @@ interface ScanCostTrackerOptions {onCost?: (cost: Readonly<ScanCost>) => void;onActivity?: (activity: ScanActivity) => void;onProgress?: (progress: ScanProgress) => void;+ onSessionEvent?: (event: ScanSessionEvent) => void;onError?: (error: unknown) => void;}@@ -91,6 +100,30 @@ const MODEL_PRICING_NANODOLLARS: Readonly<Record<string, ModelPricing>> = {const COST_POLL_INTERVAL_MS = 100;const SESSION_READ_SIZE = 64 * 1_024;+function createSessionUsage(): SessionUsage {+ return {+ offset: 0,+ pendingLine: [],+ pendingLineBytes: 0,+ unreadable: false,+ threadId: null,+ parentThreadId: null,+ workingDirectory: null,+ startedAt: null,+ inheritedUsage: null,+ replaying: false,+ usage: null,+ calls: new Map(),+ activities: [],+ progress: [],+ filesCompleted: 0,+ filesTotal: null,+ prose: new Set(),+ reasoning: null,+ reasoningCount: 0,+ };+}+export class ScanCostTracker {readonly #options: ScanCostTrackerOptions;readonly #sessions = new Map<string, SessionUsage>();@@ -121,7 +154,8 @@ export class ScanCostTracker {this.#options.maxCostUsd === undefined &&this.#options.onCost === undefined &&this.#options.onActivity === undefined &&- this.#options.onProgress === undefined+ this.#options.onProgress === undefined &&+ this.#options.onSessionEvent === undefined) {return;}@@ -180,27 +214,7 @@ export class ScanCostTracker {)) {let session = this.#sessions.get(path);if (session === undefined) {- session = {- offset: 0,- pendingLine: [],- pendingLineBytes: 0,- unreadable: false,- threadId: null,- parentThreadId: null,- workingDirectory: null,- startedAt: null,- inheritedUsage: null,- replaying: false,- usage: null,- calls: new Map(),- activities: [],- progress: [],- filesCompleted: 0,- filesTotal: null,- prose: new Set(),- reasoning: null,- reasoningCount: 0,- };+ session = createSessionUsage();this.#sessions.set(path, session);}try {@@ -263,15 +277,45 @@ export class ScanCostTracker {}let usage: ScanTokenUsage | null = null;- for (const session of this.#sessions.values()) {- if (session.threadId !== null && included.has(session.threadId)) {- if (session.threadId !== this.#threadId) {- this.#reportWorkerActivities(session);- this.#reportWorkerProgress(session);- }- if (session.usage !== null) {- usage = addTokenUsage(usage, session.usage);+ for (const [path, tracked] of this.#sessions) {+ const threadId = tracked.threadId;+ if (threadId === null || !included.has(threadId)) continue;+ let session = tracked;+ if (+ this.#options.onSessionEvent !== undefined &&+ session.events === undefined+ ) {+ // Replay only newly associated sessions, including their early events.+ session = createSessionUsage();+ session.events = [];+ await readSessionUsage(path, session, this.#options.repository);+ this.#sessions.set(path, session);+ }+ let worker: number | undefined;+ if (threadId !== this.#threadId) {+ worker = this.#workers.get(threadId) ?? this.#workers.size + 1;+ this.#workers.set(threadId, worker);+ }+ for (const event of session.events?.splice(0) ?? []) {+ this.#options.onSessionEvent?.({+ threadId,+ parentThreadId: session.parentThreadId,+ worker,+ event,+ });+ }+ if (worker !== undefined) {+ for (const activity of session.activities.splice(0)) {+ this.#options.onActivity?.({+ ...activity,+ id: `${threadId}:${activity.id}`,+ worker,+ });}+ this.#reportWorkerProgress(session);+ }+ if (session.usage !== null) {+ usage = addTokenUsage(usage, session.usage);}}if (usage === null) return;@@ -280,24 +324,6 @@ export class ScanCostTracker {this.#reportCost(cost);}- #reportWorkerActivities(session: SessionUsage): void {- if (this.#options.onActivity === undefined || session.threadId === null) {- return;- }- let worker = this.#workers.get(session.threadId);- if (worker === undefined) {- worker = this.#workers.size + 1;- this.#workers.set(session.threadId, worker);- }- for (const activity of session.activities.splice(0)) {- this.#options.onActivity({- ...activity,- id: `${session.threadId}:${activity.id}`,- worker,- });- }- }-#reportWorkerProgress(session: SessionUsage): void {if (this.#options.onProgress === undefined || session.threadId === null) {return;@@ -454,6 +480,7 @@ function readSessionEvent(if (event["type"] === "session_meta") {if (session.threadId !== null) {session.replaying = payload["id"] !== session.threadId;+ if (!session.replaying) session.events?.push(event);return;}if (typeof payload["id"] === "string") {@@ -472,6 +499,7 @@ function readSessionEvent(payload["parent_thread_id"] ??(isRecord(spawn) ? spawn["parent_thread_id"] : undefined);if (typeof parent === "string") session.parentThreadId = parent;+ session.events?.push(event);return;}if (session.replaying) {@@ -487,9 +515,11 @@ function readSessionEvent(payload["started_at"] >= session.startedAt) {session.replaying = false;+ session.events?.push(event);}return;}+ session.events?.push(event);if (event["type"] === "response_item") {session.progress.push(...sessionProgressUpdates(payload));if (repository === undefined) return;diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex f676f3ac2..609aa88d7 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -1,6 +1,6 @@export { CodexSecurity, createSecurity } from "./api.js";export { estimateScanCost } from "./cost.js";-export type { ScanCost } from "./cost.js";+export type { ScanCost, ScanSessionEvent } from "./cost.js";export type { ScanActivity, ScanActivityStatus } from "./scan-activity.js";export type {CodexSecurityMetadata,diff --git a/sdk/typescript/src/scan-dashboard.ts b/sdk/typescript/src/scan-dashboard.tsindex 2f6a8cf3e..11e15c25b 100644--- a/sdk/typescript/src/scan-dashboard.ts+++ b/sdk/typescript/src/scan-dashboard.ts@@ -2,7 +2,7 @@ import { basename, isAbsolute } from "node:path";import { pathToFileURL } from "node:url";import { stripVTControlCharacters } from "node:util";import type { ScanModelConfiguration } from "./config.js";-import { formatUsd, type ScanCost } from "./cost.js";+import { formatUsd, type ScanCost, type ScanSessionEvent } from "./cost.js";import type { ScanActivity } from "./scan-activity.js";import type { ScanMode } from "./targets.js";import type { ScanProgress } from "./worker-progress.js";@@ -66,6 +66,7 @@ interface DashboardActivityLine {kind: DashboardActivityKind | "path" | "code";links?: readonly DashboardActivityLink[];code?: readonly string[];+ bold?: readonly string[];}interface DashboardActivityLink {@@ -99,12 +100,22 @@ export class ScanDashboard {readonly #options: ScanDashboardOptions;readonly #startedAt: number;readonly #activities: TimedScanActivity[] = [];+ readonly #details: (ScanSessionEvent & { recordedAt: number })[] = [];+ #detailsCache: {+ width: number;+ source: "all" | "main" | number;+ count: number;+ lines: DashboardActivityLine[];+ summaries: Map<string, Set<string>>;+ } | null = null;#stage = "Preparing scan";#files: ScanProgress | null = null;#publicationProgress: { completed: number; total: number } | null = null;#cost: Readonly<ScanCost> | null = null;#timer: NodeJS.Timeout | null = null;#scrollOffset = 0;+ #view: "activity" | "details" = "activity";+ #source: "all" | "main" | number = "all";#inputWasRaw = false;#noteCount = 0;#observingStreamErrors = false;@@ -114,12 +125,25 @@ export class ScanDashboard {typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");let lines = 0;for (const key of input.match(- /[\u0003\u0004\u0015]|\u001B\[(?:[ABHF]|[1456]~)/gu,+ /[\u0003\u0004\u0015dam1-9]|\u001B\[(?:[ABHF]|[1456]~)/gu,) ?? []) {if (key === "\u0003") {if (lines !== 0) this.scroll(lines);this.#options.onInterrupt?.();lines = 0;+ } else if (/^[dam1-9]$/u.test(key)) {+ if (this.#options.presentation === "publication") continue;+ if (key !== "d" && this.#view !== "details") continue;+ if (lines !== 0) this.scroll(lines);+ if (key === "d") {+ this.#view = this.#view === "activity" ? "details" : "activity";+ } else {+ this.#source =+ key === "a" ? "all" : key === "m" ? "main" : Number(key);+ }+ this.#scrollOffset = 0;+ this.#refresh();+ lines = 0;} else if (key === "\u001B[A") {lines += 1;} else if (key === "\u001B[B") {@@ -280,6 +304,38 @@ export class ScanDashboard {this.#refresh();}+ public recordDetails(session: ScanSessionEvent): void {+ const previousRows =+ this.#view === "details" && this.#scrollOffset !== 0+ ? this.#activityLines(this.#width()).length+ : 0;+ const timestamp = session.event["timestamp"];+ const recordedAt =+ typeof timestamp === "string" ? Date.parse(timestamp) : NaN;+ const entry = {+ ...session,+ recordedAt: Number.isNaN(recordedAt)+ ? this.#options.clock.now()+ : recordedAt,+ };+ const index = this.#details.findLastIndex(+ (event) => event.recordedAt <= entry.recordedAt,+ );+ this.#details.splice(index + 1, 0, entry);+ if (index + 1 < (this.#detailsCache?.count ?? 0)) {+ this.#detailsCache = null;+ }+ if (this.#view === "details") {+ if (this.#scrollOffset !== 0) {+ this.#scrollOffset += Math.max(+ 0,+ this.#activityLines(this.#width()).length - previousRows,+ );+ }+ this.#refresh();+ }+ }+public scroll(lines: number): void {const maximum = Math.max(0,@@ -334,21 +390,27 @@ export class ScanDashboard {const activity = history.slice(first, first + activityRows);if (activity.length === 0) {activity.push({- text: ` [${formatLocalTime(this.#options.clock.now())}] · Waiting for ${publication ? "publication" : "scan"} activity…`,+ text: ` [${formatLocalTime(this.#options.clock.now())}] · Waiting for ${this.#view === "details" ? "session events" : publication ? "publication activity" : "scan activity"}…`,kind: "path",});}while (activity.length < activityRows) {activity.push({ text: "", kind: "path" });}- const scrollStatus =+ let scrollStatus =this.#scrollOffset === 0? "Ctrl+C to exit": `${formatCount(this.#scrollOffset)} ${this.#scrollOffset === 1 ? "line" : "lines"} above live · Ctrl+C to exit`;+ if (!publication && this.#options.input?.isTTY === true) {+ scrollStatus =+ this.#view === "details"+ ? `d activity · a/m/1-9 source · ${scrollStatus}`+ : `d details · ${scrollStatus}`;+ }const model = this.#options.model;const lines = [- ` CODEX SECURITY · ${publication ? "PUBLISH · " : ""}${basename(this.#options.repository)}${model === undefined ? "" : ` · ${model.model} (${model.reasoningEffort})`}`,+ ` CODEX SECURITY · ${publication ? "PUBLISH · " : ""}${basename(this.#options.repository)}${model === undefined ? "" : ` · ${model.model} (${model.reasoningEffort})`}${this.#view === "details" ? ` · DETAILS${this.#source === "all" ? "" : ` · ${typeof this.#source === "number" ? `worker ${this.#source}` : this.#source}`}` : ""}`,divider,...activity,divider,@@ -373,7 +435,9 @@ export class ScanDashboard {.map((line, index) => {const text = typeof line === "string" ? line : line.text;const clean = fitLine(- this.#options.sanitize?.(text) ?? text,+ typeof line !== "string" && this.#view === "details"+ ? text+ : this.#options.sanitize?.(text) ?? text,width,);const colored =@@ -385,6 +449,7 @@ export class ScanDashboard {? "title": undefined: line.kind,+ typeof line !== "string" && this.#view === "details",): clean;const formatted =@@ -392,7 +457,7 @@ export class ScanDashboard {? colored: linkActivity(this.#options.color === true- ? styleInlineCode(colored, line.code, line.kind)+ ? styleInlineCode(colored, line): colored,line.links,this.#options.sanitize,@@ -421,6 +486,96 @@ export class ScanDashboard {}#activityLines(width: number): DashboardActivityLine[] {+ if (this.#view === "details") {+ let cache = this.#detailsCache;+ if (+ cache === null ||+ cache.width !== width ||+ cache.source !== this.#source+ ) {+ this.#detailsCache = cache = {+ width,+ source: this.#source,+ count: 0,+ lines: [],+ summaries: new Map(),+ };+ }+ if (cache.count === this.#details.length) return cache.lines;+ const events = this.#details.slice(cache.count);+ cache.count = this.#details.length;+ for (const { threadId, worker, event, recordedAt } of events) {+ if (this.#source !== "all" && this.#source !== (worker ?? "main")) {+ continue;+ }+ let description = detailsDescription(event);+ if (description === undefined) continue;++ const payload = isRecord(event["payload"]) ? event["payload"] : {};+ const itemType = payload["type"];+ const prose =+ typeof itemType === "string" &&+ /^(?:message|agent_message|reasoning|agent_reasoning.*)$/u.test(+ itemType,+ );+ if (prose) {+ const seen = cache.summaries.get(threadId) ?? new Set<string>();+ cache.summaries.set(threadId, seen);+ if (itemType === "reasoning" && Array.isArray(payload["summary"])) {+ const summary = payload["summary"].filter(+ (part) => !isRecord(part) || !seen.has(String(part["text"])),+ );+ if (summary.length === 0) continue;+ for (const part of summary) {+ if (isRecord(part) && typeof part["text"] === "string") {+ seen.add(part["text"]);+ }+ }+ description = detailsDescription({+ ...event,+ payload: { ...payload, summary },+ });+ }+ if (description === undefined || seen.has(description)) continue;+ seen.add(description);+ if (itemType === "agent_reasoning") {+ seen.add(detailsText(payload["text"]));+ }+ } else {+ cache.summaries.delete(threadId);+ }++ const source = worker === undefined ? "main" : `worker ${worker}`;+ const prefix = ` [${formatLocalTime(recordedAt)}] ${source} · `;+ const code: string[] = [];+ const bold: string[] = [];+ if (prose) {+ description = description.replaceAll(+ /`([^`\r\n]+)`|\*\*([^*\r\n]+)\*\*/gu,+ (_match: string, inline: string, strong: string) => {+ const text = inline ?? strong;+ (inline === undefined ? bold : code).push(text);+ return text;+ },+ );+ }+ const paragraphs = description.split(/\r?\n/u);+ const lines =+ paragraphs.length === 1+ ? wrapActivity(prefix, description, width)+ : paragraphs.flatMap((line, index) =>+ wrapCode(+ index === 0 ? prefix : " ".repeat(prefix.length),+ line,+ width,+ ),+ );+ for (const text of lines) {+ cache.lines.push({ text, kind: "path", code, bold });+ }+ }+ return cache.lines;+ }const elapsed = Math.max(0,Math.floor((this.#options.clock.now() - this.#startedAt) / 1_000),@@ -504,15 +659,84 @@ export class ScanDashboard {}}-function styleInlineCode(- value: string,- code: readonly string[] | undefined,- kind: DashboardActivityLine["kind"],-): string {- for (const text of code ?? []) {+function detailsDescription(+ event: Record<string, unknown>,+): string | undefined {+ const type = typeof event["type"] === "string" ? event["type"] : "event";+ const payload = event["payload"];+ if (!isRecord(payload)) return type.replaceAll("_", " ");++ if (type === "session_meta") {+ const instructions = payload["base_instructions"];+ const text = isRecord(instructions) ? instructions["text"] : instructions;+ return typeof text === "string" ? `system: ${text}` : "session started";+ }+ if (type === "turn_context") {+ const details = [+ "model",+ "effort",+ "cwd",+ "summary",+ "developer_instructions",+ "user_instructions",+ ]+ .map((field) => payload[field])+ .filter((detail) => typeof detail === "string" && detail !== "");+ return `context${details.length === 0 ? "" : `: ${details.join(" · ")}`}`;+ }+ const itemType = typeof payload["type"] === "string" ? payload["type"] : type;+ if (itemType === "token_count") return undefined;+ if (itemType === "message" || itemType === "agent_message") {+ const role =+ typeof payload["role"] === "string" ? payload["role"] : "assistant";+ return `${role}: ${detailsText(payload["content"] ?? payload["message"])}`;+ }+ if (itemType === "reasoning" || itemType.startsWith("agent_reasoning")) {+ const text = detailsText(+ payload["summary"] ?? payload["text"] ?? payload["delta"],+ );+ return text.trim() === "" ? undefined : `reasoning: ${text}`;+ }+ if (itemType.endsWith("_call_output")) {+ return `result${payload["status"] === "failed" ? " failed" : ""}: ${detailsText(payload["output"])}`;+ }+ if (itemType.endsWith("_call")) {+ const name =+ typeof payload["name"] === "string" ? payload["name"] : "shell";+ const arguments_ = payload["arguments"] ?? payload["input"];+ const text =+ typeof arguments_ === "string"+ ? arguments_+ : arguments_ === undefined+ ? ""+ : JSON.stringify(arguments_);+ return `tool ${name}${text === "" ? "" : `: ${text}`}`;+ }+ return itemType.replaceAll("_", " ");+}++function detailsText(value: unknown): string {+ if (typeof value === "string") return value;+ if (!Array.isArray(value)) return "";+ return value+ .flatMap((item) =>+ isRecord(item) && typeof item["text"] === "string" ? [item["text"]] : [],+ )+ .join("\n");+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function styleInlineCode(value: string, line: DashboardActivityLine): string {+ for (const text of line.bold ?? []) {+ value = value.replace(text, `\u001B[1m${text}\u001B[22m`);+ }+ for (const text of line.code ?? []) {value = value.replace(text,- `\u001B[2m${text}\u001B[22m${kind === "message" ? "\u001B[1m" : ""}`,+ `\u001B[2m${text}\u001B[22m${line.kind === "message" ? "\u001B[1m" : ""}`,);}return value;@@ -625,7 +849,29 @@ function wrapCode(prefix: string, value: string, width: number): string[] {function styleLine(value: string,kind: DashboardActivityLine["kind"] | "title" | undefined,+ details = false,): string {+ if (details) {+ return value+ .replace(+ /^(\s*)(\[\d{2}:\d{2}:\d{2}\])(\s+)(main|worker \d+)/u,+ "$1\u001B[2m$2\u001B[22m$3\u001B[36m$4\u001B[39m",+ )+ .replace(+ /^(.*\u001B\[39m · )((reasoning|assistant|user|system|context|result(?: failed)?|tool(?: [^:]+)?):)/u,+ (_match: string, prefix: string, label: string, type: string) => {+ const color =+ type === "reasoning"+ ? "35"+ : type === "result"+ ? "32"+ : /^(?:result failed|system|context)$/u.test(type)+ ? "33"+ : "36";+ return `${prefix}\u001B[${color}m${label}\u001B[39m`;+ },+ );+ }if (kind === undefined) return value;const style = LINE_STYLES[kind];if (diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 37896482a..695a8e22a 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -33,6 +33,7 @@ import {ScanCostLimitExceededError,type ScanOptions,type ScanProgress,+ type ScanSessionEvent,ScanInterruptedError,} from "../src/index.js";import {@@ -2564,7 +2565,7 @@ describe("CodexSecurity orchestration", () => {await client.close();});- test("normalizes real worker review batches to the registered file total", async () => {+ test("normalizes worker progress while streaming related session events", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");const codexHome = join(root, "codex-home");@@ -2573,6 +2574,8 @@ describe("CodexSecurity orchestration", () => {await mkdir(codexHome);await mkdir(scanDir, { mode: 0o700 });const updates: ScanProgress[] = [];+ const sessionEvents: ScanSessionEvent[] = [];+ const observerErrors: ScanObserverName[] = [];const usage = { input_tokens: 100, output_tokens: 10 };const client = new TestClient({},@@ -2651,6 +2654,13 @@ describe("CodexSecurity orchestration", () => {const result = await client.run(repository, {onProgress: (progress) => updates.push(progress),+ onSessionEvent: (event) => {+ sessionEvents.push(event);+ if (sessionEvents.length === 1) {+ throw new Error("session observer exploded");+ }+ },+ onObserverError: (observer) => observerErrors.push(observer),});expect(result.threadId).toBe("thread-1");@@ -2660,6 +2670,15 @@ describe("CodexSecurity orchestration", () => {{ phase: "discovery", filesCompleted: 1_249, filesTotal: 1_258 },{ phase: "validation", filesCompleted: 1_249, filesTotal: 1_258 },]);+ expect(sessionEvents).toHaveLength(10);+ expect(+ new Set(+ sessionEvents.map(+ ({ threadId, parentThreadId }) => `${threadId}:${parentThreadId}`,+ ),+ ),+ ).toEqual(new Set(["thread-1:null", "worker-thread:thread-1"]));+ expect(observerErrors).toEqual(["onSessionEvent"]);await client.close();});diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex 1d923f15d..8d891cefb 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -1762,6 +1762,44 @@ describe("CLI", () => {}});+ test.each([false, true])(+ "subscribes to session details only with TTY stdin: %s",+ async (stdinTTY) => {+ const descriptor = Object.getOwnPropertyDescriptor(+ process.stdin,+ "isTTY",+ );+ const stderr = capture(true);+ let subscribed = false;+ try {+ Object.defineProperty(process.stdin, "isTTY", {+ configurable: true,+ value: stdinTTY,+ });+ const code = await main(+ ["scan", "."],+ capture().stream,+ stderr.stream,+ dependencies({+ onTurn: (_repository, options) => {+ subscribed =+ typeof (options as ScanOptions).onSessionEvent === "function";+ },+ }),+ );+ expect(code).toBe(0);+ expect(stderr.text()).toContain("CODEX SECURITY");+ expect(subscribed).toBe(stdinTTY);+ } finally {+ if (descriptor === undefined) {+ Reflect.deleteProperty(process.stdin, "isTTY");+ } else {+ Object.defineProperty(process.stdin, "isTTY", descriptor);+ }+ }+ },+ );+test("uses plain scan progress in headless, CI, and noninteractive terminals", async () => {for (const { options, environment, isTTY } of [{ options: ["--headless"], environment: {}, isTTY: true },diff --git a/sdk/typescript/tests-ts/cost.test.ts b/sdk/typescript/tests-ts/cost.test.tsindex 520efe90c..ce3fa8f4a 100644--- a/sdk/typescript/tests-ts/cost.test.ts+++ b/sdk/typescript/tests-ts/cost.test.ts@@ -10,7 +10,11 @@ import {import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, test } from "bun:test";-import { estimateScanCost, ScanCostTracker } from "../src/cost.js";+import {+ estimateScanCost,+ ScanCostTracker,+ type ScanSessionEvent,+} from "../src/cost.js";import type { ScanActivity } from "../src/scan-activity.js";import type { ScanProgress } from "../src/worker-progress.js";@@ -419,14 +423,14 @@ describe("live scan cost tracking", () => {test("counts the scan and delegated workers without including other scans", async () => {const home = await codexHome();- await writeSession(home, "scan-thread", {+ const parent = await writeSession(home, "scan-thread", {input_tokens: 1_000,cached_input_tokens: 100,cache_write_input_tokens: 200,output_tokens: 10,reasoning_output_tokens: 2,});- await writeSession(+ const worker = await writeSession(home,"worker-thread",{@@ -441,11 +445,24 @@ describe("live scan cost tracking", () => {input_tokens: 1_000_000,output_tokens: 1_000_000,});+ const events: ScanSessionEvent[] = [];const tracker = new ScanCostTracker({codexHome: home,model: "gpt-5.6-sol",+ onSessionEvent: (event) => events.push(event),});tracker.start("scan-thread");+ await waitFor(() => events.length === 4);+ await appendFile(+ parent,+ `${JSON.stringify({ type: "turn_context", payload: { instructions: "Check authorization" } })}\n`,+ );+ await appendSessionItem(worker, {+ type: "function_call",+ name: "spawn_agent",+ });+ await tracker.refresh();+ await tracker.refresh();expect(await tracker.stop()).toEqual({usage: {@@ -465,8 +482,105 @@ describe("live scan cost tracking", () => {estimatedUsd: 0.006275,},});+ expect(+ events.map(({ threadId, parentThreadId, event }) => [+ threadId,+ parentThreadId,+ event["type"],+ ]),+ ).toEqual(+ expect.arrayContaining([+ ["scan-thread", null, "session_meta"],+ ["scan-thread", null, "event_msg"],+ ["worker-thread", "scan-thread", "session_meta"],+ ["worker-thread", "scan-thread", "event_msg"],+ ["scan-thread", null, "turn_context"],+ ["worker-thread", "scan-thread", "response_item"],+ ]),+ );+ expect(events).toHaveLength(6);});+ test.each(["parent", "main"] as const)(+ "replays early worker events when the %s session arrives later",+ async (missing) => {+ const home = await codexHome();+ const scanDirectory = join(home, "scan");+ const usage = { input_tokens: 10, output_tokens: 1 };+ const writeMain = () =>+ writeSession(+ home,+ "scan-thread",+ usage,+ undefined,+ scanDirectory,+ "2026-07-26T12:00:00Z",+ );+ if (missing === "parent") await writeMain();+ const worker = await writeSession(+ home,+ "worker-thread",+ usage,+ missing === "parent" ? "parent-worker" : undefined,+ join(+ scanDirectory,+ "artifacts",+ "deep_discovery",+ "workers",+ "one",+ "output",+ ),+ "2026-07-26T12:01:00Z",+ );+ const message = (text: string) => ({+ type: "message",+ role: "assistant",+ content: [{ type: "output_text", text }],+ });+ await appendSessionItem(worker, message("Early worker output."));+ const unrelated = await writeSession(home, "unrelated-thread", usage);+ await appendSessionItem(unrelated, message("Unrelated output."));+ const events: ScanSessionEvent[] = [];+ const tracker = new ScanCostTracker({+ codexHome: home,+ scanDirectory: missing === "main" ? scanDirectory : undefined,+ model: "gpt-5.6-sol",+ onSessionEvent: (event) => events.push(event),+ });+ tracker.start("scan-thread");+ await tracker.refresh();+ expect(events.some((event) => event.threadId === "worker-thread")).toBe(+ false,+ );++ if (missing === "parent") {+ await writeSession(home, "parent-worker", usage, "scan-thread");+ } else {+ await writeMain();+ }+ await appendSessionItem(worker, message("Late worker output."));+ await tracker.refresh();+ await tracker.refresh();+ await tracker.stop();++ const workerEvents = events.filter(+ (event) => event.threadId === "worker-thread",+ );+ expect(workerEvents.map((event) => event.event)).toEqual([+ expect.objectContaining({ type: "session_meta" }),+ expect.objectContaining({ type: "event_msg" }),+ { type: "response_item", payload: message("Early worker output.") },+ { type: "response_item", payload: message("Late worker output.") },+ ]);+ expect(new Set(workerEvents.map((event) => event.worker))).toEqual(+ new Set([1]),+ );+ expect(+ events.some((event) => event.threadId === "unrelated-thread"),+ ).toBe(false);+ },+ );+test("counts independent Deep workers inside the scan directory only", async () => {const home = await codexHome();const scanDirectory = join(home, "scans", "current");@@ -544,10 +658,12 @@ describe("live scan cost tracking", () => {join(scanDirectory, "nested", "artifacts"),"2026-07-26T12:03:00Z",);+ const events: ScanSessionEvent[] = [];const tracker = new ScanCostTracker({codexHome: home,model: "gpt-5.6-sol",scanDirectory,+ onSessionEvent: (event) => events.push(event),});tracker.start("scan-thread");@@ -555,6 +671,21 @@ describe("live scan cost tracking", () => {input_tokens: 1_425,output_tokens: 14,});+ const labels = new Map(+ events.map(({ threadId, worker }) => [threadId, worker]),+ );+ expect(new Set(labels.keys())).toEqual(+ new Set([+ "scan-thread",+ "deep-worker",+ "deep-reducer",+ "deep-worker-child",+ ]),+ );+ expect(labels.get("scan-thread")).toBeUndefined();+ expect(+ [...labels.values()].filter((worker) => worker !== undefined).sort(),+ ).toEqual([1, 2, 3]);});test("ignores replayed parent history in forked worker sessions", async () => {@@ -675,6 +806,7 @@ describe("live scan cost tracking", () => {const activities: ScanActivity[] = [];const progress: ScanProgress[] = [];+ const events: ScanSessionEvent[] = [];const tracker = new ScanCostTracker({codexHome: home,model: "gpt-5.6-terra",@@ -682,6 +814,7 @@ describe("live scan cost tracking", () => {expectedFilesTotal: 8,onActivity: (activity) => activities.push(activity),onProgress: (update) => progress.push(update),+ onSessionEvent: (event) => events.push(event),});tracker.start("scan-thread");@@ -725,6 +858,13 @@ describe("live scan cost tracking", () => {expect(progress).toEqual([{ phase: "discovery", filesCompleted: 3, filesTotal: 8 },]);+ const workerEvents = events.filter(+ ({ threadId }) => threadId === "worker-thread",+ );+ expect(workerEvents).toHaveLength(6);+ expect(JSON.stringify(workerEvents)).not.toContain(+ "Inherited parent commentary.",+ );});test("forwards actions from this scan's delegated workers only", async () => {@@ -759,11 +899,13 @@ describe("live scan cost tracking", () => {}const activities: ScanActivity[] = [];+ const events: ScanSessionEvent[] = [];const tracker = new ScanCostTracker({codexHome: home,model: "gpt-5.6-sol",repository: "/code/juice-shop",onActivity: (activity) => activities.push(activity),+ onSessionEvent: (event) => events.push(event),});tracker.start("scan-thread");await tracker.stop();@@ -786,6 +928,14 @@ describe("live scan cost tracking", () => {worker: 1,},]);+ expect(+ new Map(events.map(({ threadId, worker }) => [threadId, worker])),+ ).toEqual(+ new Map([+ ["scan-thread", undefined],+ ["worker-thread", 1],+ ]),+ );});test("forwards genuine worker reasoning and transcript text", async () => {@@ -1513,9 +1663,11 @@ describe("live scan cost tracking", () => {input_tokens: 100,output_tokens: 10,});+ const events: ScanSessionEvent[] = [];const tracker = new ScanCostTracker({codexHome: home,model: "gpt-5.6-terra",+ onSessionEvent: (event) => events.push(event),});tracker.start("scan-thread");await tracker.refresh();@@ -1532,9 +1684,12 @@ describe("live scan cost tracking", () => {const padding = " ".repeat(128 * 1_024);await appendFile(path, `${padding}${event.slice(0, 40)}`);expect((await tracker.refresh()).cost?.inputTokens).toBe(100);+ expect(events).toHaveLength(2);await appendFile(path, `${event.slice(40)}\n`);expect((await tracker.stop()).cost?.inputTokens).toBe(250);+ expect(events).toHaveLength(3);+ expect(events.at(-1)?.event).toEqual(JSON.parse(event));});test("reads session events larger than 16 MiB", async () => {diff --git a/sdk/typescript/tests-ts/scan-dashboard.test.ts b/sdk/typescript/tests-ts/scan-dashboard.test.tsindex 012afc595..ffd48fe63 100644--- a/sdk/typescript/tests-ts/scan-dashboard.test.ts+++ b/sdk/typescript/tests-ts/scan-dashboard.test.ts@@ -42,11 +42,13 @@ class DashboardTestInput extends EventEmitter {describe("live scan dashboard", () => {test("renders publication progress without scan-only inventory and cost fields", () => {const stderr = capture(true);+ const input = new DashboardTestInput();const dashboard = new ScanDashboard({ ...stderr.stream, columns: 100, rows: 18 },{repository: "/synthetic/payments-api",presentation: "publication",+ input,color: false,clock: fakeClock(),},@@ -54,6 +56,7 @@ describe("live scan dashboard", () => {dashboard.setStage("Connecting to Linear");dashboard.start();+ input.emit("data", "d");let text = stripVTControlCharacters(stderr.text());expect(text).toContain("CODEX SECURITY · PUBLISH · payments-api");expect(text).toContain("Waiting for publication activity");@@ -61,6 +64,8 @@ describe("live scan dashboard", () => {expect(text).not.toContain("FILES");expect(text).not.toContain("TOKENS");expect(text).not.toContain("COST");+ expect(text).not.toContain("DETAILS");+ expect(text).not.toContain("d details");dashboard.setPublicationProgress(2, 5);dashboard.setStage("Publishing findings · 2/5");@@ -613,6 +618,227 @@ describe("live scan dashboard", () => {dashboard.stop();});+ test("shows unredacted, chronological session events and keeps the activity view safe", () => {+ const stderr = capture(true);+ const input = new DashboardTestInput();+ const dashboard = new ScanDashboard(+ { ...stderr.stream, columns: 140, rows: 24 },+ {+ repository: "/code/juice-shop",+ input,+ color: true,+ clock: fakeClock(),+ sanitize: (value) => value.replaceAll("synthetic-secret", "[redacted]"),+ },+ );++ dashboard.start();+ dashboard.record({+ id: "activity-1",+ kind: "command",+ status: "completed",+ description: "rg -n synthetic-secret routes/login.ts",+ paths: [],+ });+ for (const [seconds, type, payload] of [+ [+ 2,+ "turn_context",+ { model: "gpt-5.6-sol", developer_instructions: "Check boundaries." },+ ],+ [0, "session_meta", { base_instructions: { text: "Inspect safely." } }],+ [1, "message", { role: "user", content: [{ text: "Find bugs." }] }],+ [+ 3,+ "function_call",+ {+ name: "exec_command",+ arguments:+ "synthetic-secret `literal` **glob** \u001B[31mspoofed\u001B[0m\u0007",+ },+ ],+ [+ 4,+ "function_call_output",+ {+ output: [+ {+ text: "result\nfunction inspect() {\n if (input) {\n return input;\n }\n\n return null;\n}",+ },+ ],+ },+ ],+ [5, "agent_reasoning", { text: "Inspect **critical** `db.raw(input)`." }],+ [+ 5,+ "reasoning",+ {+ summary: [+ { text: "Inspect **critical** `db.raw(input)`." },+ { text: "New final detail." },+ ],+ encrypted_content: "never-display-encrypted-reasoning",+ },+ ],+ [6, "agent_message", { message: "Confirmed." }],+ [6, "message", { role: "assistant", content: [{ text: "Confirmed." }] }],+ [7, "token_count", {}],+ [8, "reasoning", { summary: [] }],+ [9, "agent_reasoning", { text: " " }],+ ] as [number, string, Record<string, unknown>][]) {+ dashboard.recordDetails({+ threadId: "scan-thread",+ parentThreadId: null,+ event: {+ type: ["session_meta", "turn_context"].includes(type)+ ? type+ : type.startsWith("agent_") || type === "token_count"+ ? "event_msg"+ : "response_item",+ payload: { type, ...payload },+ timestamp: new Date(STARTED_AT + seconds * 1_000).toISOString(),+ },+ });+ }++ let frame = lastFrame(stderr);+ expect(frame).toContain("rg -n [redacted] routes/login.ts");+ expect(frame).toContain("d details");++ input.emit("data", "d");+ frame = lastFrame(stderr);+ for (const line of [+ "main · system: Inspect safely.",+ "main · user: Find bugs.",+ "main · context: gpt-5.6-sol · Check boundaries.",+ "main · tool exec_command: synthetic-secret `literal` **glob** spoofed",+ "main · result: result",+ "main · reasoning: Inspect critical db.raw(input).",+ "main · reasoning: New final detail.",+ "main · assistant: Confirmed.",+ ]) {+ expect(frame).toContain(line);+ }+ expect(frame.indexOf("main · system:")).toBeLessThan(+ frame.indexOf("main · context:"),+ );+ const continuation = " ".repeat(" [09:41:04] main · ".length);+ expect(frame).toContain(`${continuation} if (input) {`);+ expect(frame).toContain(`\n${continuation}\n${continuation} return null;`);+ expect(frame).not.toContain("main · token count");+ expect(frame.match(/main · reasoning:/gu)).toHaveLength(2);+ expect(frame.match(/Inspect critical db\.raw\(input\)\./gu)).toHaveLength(+ 1,+ );+ expect(frame.match(/Confirmed\./gu)).toHaveLength(1);+ for (const sequence of [+ "\u001B[2m[09:41:05]\u001B[22m",+ "\u001B[36mmain\u001B[39m",+ "\u001B[35mreasoning:\u001B[39m",+ "\u001B[36mtool exec_command:\u001B[39m",+ "\u001B[32mresult:\u001B[39m",+ "\u001B[36massistant:\u001B[39m",+ "\u001B[1mcritical\u001B[22m",+ "\u001B[2mdb.raw(input)\u001B[22m",+ ]) {+ expect(stderr.text()).toContain(sequence);+ }+ expect(frame).toContain("TOKENS");+ expect(stderr.text()).not.toContain("never-display-encrypted-reasoning");+ expect(stderr.text()).not.toContain("\u001B[31m");+ expect(stderr.text()).not.toContain("\u0007");++ input.emit("data", "d");+ frame = lastFrame(stderr);+ expect(frame).toContain("rg -n [redacted] routes/login.ts");+ expect(frame).not.toContain("synthetic-secret");+ dashboard.stop();+ });++ test("filters workers and scrolls the details separately from scan activity", () => {+ const stderr = capture(true);+ const input = new DashboardTestInput();+ const dashboard = new ScanDashboard(+ { ...stderr.stream, columns: 120, rows: 14 },+ { repository: "/code/juice-shop", input, clock: fakeClock() },+ );+ let payloadReads = 0;+ const event = (threadId: string, text: string, worker?: number) => {+ dashboard.recordDetails({+ threadId,+ parentThreadId: null,+ worker,+ event: {+ type: "event_msg",+ get payload() {+ payloadReads += 1;+ return { type: "agent_message", message: text };+ },+ },+ });+ };++ dashboard.start();+ event("worker-one", "Worker one inspected routes.", 1);+ event("scan-thread", "Main scan started.");+ event("worker-two", "Independent worker inspected models.", 2);+ for (let index = 1; index <= 10; index += 1) {+ event("scan-thread", `trace ${index}`);+ }++ input.emit("data", "d");+ for (const [source, included, excluded] of [+ ["m", "trace 10", "Worker one"],+ ["1", "Worker one", "Independent worker"],+ ["2", "Independent worker", "Worker one"],+ ] as const) {+ input.emit("data", source);+ const frame = lastFrame(stderr);+ expect(frame).toContain(+ `DETAILS · ${source === "m" ? "main" : `worker ${source}`}`,+ );+ expect(frame).toContain(included);+ expect(frame).not.toContain(excluded);+ }++ input.emit("data", "a");+ input.emit("data", "\u001B[H");+ let frame = lastFrame(stderr);+ expect(frame).toContain("worker 1 · assistant: Worker one");+ expect(frame).toContain("main · assistant: Main scan started.");+ expect(frame).not.toContain("trace 10");+ expect(frame).toContain("above live");++ const readsBeforeScroll = payloadReads;+ input.emit("data", "\u001B[B");+ input.emit("data", "\u001B[A");+ expect(payloadReads).toBe(readsBeforeScroll);++ event("scan-thread", "live result\nsecond line");+ frame = lastFrame(stderr);+ expect(frame).toContain("Worker one inspected routes.");+ expect(frame).not.toContain("live result");+ expect(payloadReads).toBe(readsBeforeScroll + 3);++ dashboard.record({+ id: "background-activity",+ kind: "command",+ status: "completed",+ description: "Background activity must not move the details.",+ paths: [],+ });+ frame = lastFrame(stderr);+ expect(frame).toContain("Worker one inspected routes.");+ expect(frame).not.toContain("trace 10");++ input.emit("data", "d");+ frame = lastFrame(stderr);+ expect(frame).toContain("Background activity must not move the details.");+ expect(frame).not.toContain("above live");+ expect(stderr.text()).not.toMatch(/\u001B\[[\d;]*m/u);+ dashboard.stop();+ });+test("wraps real reasoning and assistant prose into chronological history", () => {const stderr = capture(true);const dashboard = new ScanDashboard(