mirror of
https://github.com/openai/codex-security.git
synced 2026-12-04 00:40:12 +08:00
feat(sdk): report runtime worker dispatch from spawn_agent
Emit onWorkerEvent dispatch and failed signals from live spawn_agent tool calls so CI guards can see the delegated-work boundary without relying on model-emitted status markers. Fixes #956
This commit is contained in:
committed by
Aditya-linux
parent
0676faa3eb
commit
33985eb0d9
+36
-18
@@ -383,35 +383,53 @@ reported window. An allowance can arrive before any token measurement. See
|
||||
controls, replay, and reporting definitions.
|
||||
|
||||
Follow scans with `onWorkerEvent` and `onReconnect`. `onWorkerEvent` reports
|
||||
persisted worker sessions discovered by the SDK's existing session tracker,
|
||||
independently of model-emitted status markers:
|
||||
two kinds of signal:
|
||||
|
||||
- `{ kind: "dispatch", phase, planned, started }` and `{ kind: "failed",
|
||||
phase, planned, started, reason }` come from live `spawn_agent` tool calls
|
||||
on the parent event stream. These fire when the runtime actually starts (or
|
||||
fails to start) a delegated worker, independently of model-emitted status
|
||||
markers. `started` is the number of spawn attempts observed so far in the
|
||||
run; `planned` is the same count when the scheduler has not advertised a
|
||||
larger target. The event is delivered in the same turn as the spawn item,
|
||||
before session-log polling. A completed scan that never emitted `dispatch`
|
||||
or `failed` started no `spawn_agent` call on that stream.
|
||||
- `{ kind: "observed", worker: number }` reports persisted worker sessions
|
||||
discovered by the SDK's existing session tracker.
|
||||
|
||||
```ts
|
||||
await security.run(repository, {
|
||||
onWorkerEvent(event) {
|
||||
console.log(`Worker ${event.worker} observed`);
|
||||
if (event.kind === "dispatch") {
|
||||
console.log(
|
||||
`Delegated ${event.phase}: ${event.started}/${event.planned}`,
|
||||
);
|
||||
} else if (event.kind === "failed") {
|
||||
console.log(`Worker start failed: ${event.reason}`);
|
||||
} else {
|
||||
console.log(`Worker ${event.worker} observed`);
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
The callback contains only `{ kind: "observed", worker: number }`. The scan-local
|
||||
worker number matches `onActivity` and `onSessionEvent`; no prompts, raw thread
|
||||
IDs, or session contents are exposed. Each session is reported once per run,
|
||||
including nested workers and scan-associated validation or Deep Scan sessions.
|
||||
On resume, already persisted workers can be reported again. Observation ends
|
||||
with scan cost tracking, before `postScanPrompt`.
|
||||
The scan-local worker number on `observed` events matches `onActivity` and
|
||||
`onSessionEvent`; no prompts, raw thread IDs, or session contents are exposed.
|
||||
Each session is reported once per run, including nested workers and
|
||||
scan-associated validation or Deep Scan sessions. On resume, already persisted
|
||||
workers can be reported again. Session observation ends with scan cost
|
||||
tracking, before `postScanPrompt`.
|
||||
|
||||
This works with the bundled Codex version. Persistence and polling can delay
|
||||
notification, and missing notifications do not prove that delegation was skipped.
|
||||
An observed session does not establish that a worker just started or that file
|
||||
review has begun. The callback does not report failed spawn attempts, phase names,
|
||||
or planned counts, and cannot act as a pre-dispatch gate. Use `maxCostUsd` or
|
||||
`signal` for cancellation. Observer failures go to `onObserverError` without
|
||||
stopping the scan.
|
||||
Persistence and polling can delay `observed` notifications, and a missing
|
||||
`observed` event does not prove that delegation was skipped. An observed
|
||||
session does not establish that a worker just started or that file review has
|
||||
begun. Use the `dispatch` and `failed` events for that boundary. Use
|
||||
`maxCostUsd` or `signal` for cancellation. Observer failures go to
|
||||
`onObserverError` without stopping the scan.
|
||||
|
||||
`onWorkerStatus` reports **best-effort** phase dispatch counts from model-emitted
|
||||
text markers. A missing dispatch status does not mean delegation was skipped.
|
||||
For retired progress hooks, see [older progress integrations](#older-progress-integrations).
|
||||
text markers. A missing `onWorkerStatus` dispatch does not mean delegation was
|
||||
skipped. For retired progress hooks, see [older progress integrations](#older-progress-integrations).
|
||||
|
||||
`onSessionEvent` receives saved events with thread IDs and worker numbers and can
|
||||
contain source code or credentials. Deep scans additionally expose durable
|
||||
|
||||
@@ -143,8 +143,14 @@ const options: ScanOptions = {
|
||||
progress.filesCompleted satisfies number;
|
||||
},
|
||||
onWorkerEvent(event: ScanWorkerEvent) {
|
||||
event.kind satisfies "observed";
|
||||
event.worker satisfies number;
|
||||
if (event.kind === "observed") {
|
||||
event.worker satisfies number;
|
||||
} else {
|
||||
event.phase satisfies
|
||||
"file_review" | "ranking" | "validation" | "attack_path";
|
||||
event.started satisfies number;
|
||||
event.planned satisfies number;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -231,6 +231,7 @@ import {
|
||||
matchScanFindingsInternal,
|
||||
} from "./scan-comparison.js";
|
||||
import {
|
||||
createWorkerDispatchMonitor,
|
||||
scanProgressUpdatesFromEvent,
|
||||
scanPhaseSchema,
|
||||
workerStatusFromEvent,
|
||||
@@ -453,11 +454,15 @@ export interface ScanOptions extends ScanSettings {
|
||||
/** Best-effort, model-reported phase dispatch counts. */
|
||||
onWorkerStatus?: (status: ScanWorkerStatus) => void;
|
||||
/**
|
||||
* Reports each persisted worker session once when discovered during this run.
|
||||
* Worker numbers match onActivity/onSessionEvent. Includes saved workers on
|
||||
* resume; observation ends before postScanPrompt. Persistence and polling can
|
||||
* delay delivery. Does not report failed spawns, phase, or planned counts and
|
||||
* cannot gate dispatch; use maxCostUsd or signal for cancellation.
|
||||
* Reports runtime worker dispatch and persisted worker sessions.
|
||||
* `kind: "dispatch"` and `kind: "failed"` come from live spawn_agent tool
|
||||
* calls at the delegated-work boundary (not model-emitted status markers).
|
||||
* `kind: "observed"` reports each persisted worker session once when
|
||||
* discovered during this run. Worker numbers on observed events match
|
||||
* onActivity/onSessionEvent. Observed sessions include saved workers on
|
||||
* resume; session observation ends before postScanPrompt. Persistence and
|
||||
* polling can delay `observed` events; they do not identify when file review
|
||||
* begins and cannot gate dispatch. Use maxCostUsd or signal for cancellation.
|
||||
*/
|
||||
onWorkerEvent?: (event: ScanWorkerEvent) => void;
|
||||
onWarning?: (warning: string, details?: ScanWarningDetails) => void;
|
||||
@@ -3862,6 +3867,7 @@ export class CodexSecurity {
|
||||
: (event) => tracker.recordParentItem(event),
|
||||
onProgress: reportProgress,
|
||||
onWorkerStatus: reportWorkerStatus,
|
||||
onWorkerEvent: options.onWorkerEvent,
|
||||
onWarning: options.onWarning,
|
||||
onObserverError: options.onObserverError,
|
||||
});
|
||||
@@ -6009,6 +6015,7 @@ interface ScanEventRunOptions extends Pick<ScanOptions, "onReconnect"> {
|
||||
onProgressItem?: (event: Readonly<Record<string, unknown>>) => void;
|
||||
onProgress?: (progress: ScanProgress, source: ParentProgressSource) => void;
|
||||
onWorkerStatus?: (status: ScanWorkerStatus) => void;
|
||||
onWorkerEvent?: (event: ScanWorkerEvent) => void;
|
||||
onWarning?: (warning: string) => void;
|
||||
onObserverError?: (observer: ScanObserverName, error: unknown) => void;
|
||||
}
|
||||
@@ -6021,6 +6028,7 @@ export async function runScanEvents(
|
||||
let tacStatusReported = false;
|
||||
try {
|
||||
options.signal.throwIfAborted();
|
||||
const workerDispatch = createWorkerDispatchMonitor();
|
||||
const turn = await readCodexTurn({
|
||||
thread: options.thread,
|
||||
events: options.events,
|
||||
@@ -6066,6 +6074,10 @@ export async function runScanEvents(
|
||||
if (workerStatus !== null) {
|
||||
notifyObserver(options, "onWorkerStatus")(workerStatus);
|
||||
}
|
||||
const workerEvent = workerDispatch.observe(event);
|
||||
if (workerEvent !== null) {
|
||||
notifyObserver(options, "onWorkerEvent")(workerEvent);
|
||||
}
|
||||
if (event.type === "thread.started") {
|
||||
const startedThreadId = event["thread_id"];
|
||||
if (typeof startedThreadId === "string") {
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
import {
|
||||
scanProgressUpdatesFromText,
|
||||
type ScanProgress,
|
||||
type ScanWorkerPhase,
|
||||
} from "./worker-progress.js";
|
||||
|
||||
export { estimateScanCost, formatUsd, type ScanCost } from "./cost-model.js";
|
||||
@@ -147,12 +148,31 @@ const rateLimitSnapshot = z.object({
|
||||
secondary: rateLimitWindow.nullish(),
|
||||
});
|
||||
|
||||
/** A persisted worker session discovered during this run. Contains no model text. */
|
||||
export interface ScanWorkerEvent {
|
||||
kind: "observed";
|
||||
/** Scan-local number shared with activity and session observers. */
|
||||
worker: number;
|
||||
}
|
||||
/**
|
||||
* Worker signals delivered through onWorkerEvent.
|
||||
* `observed` is a persisted session discovered during this run and contains no
|
||||
* model text. `dispatch` and `failed` are runtime spawn_agent boundaries from
|
||||
* the live event stream, distinct from late session observations.
|
||||
*/
|
||||
export type ScanWorkerEvent =
|
||||
| {
|
||||
kind: "observed";
|
||||
/** Scan-local number shared with activity and session observers. */
|
||||
worker: number;
|
||||
}
|
||||
| {
|
||||
kind: "dispatch";
|
||||
phase: ScanWorkerPhase;
|
||||
planned: number;
|
||||
started: number;
|
||||
}
|
||||
| {
|
||||
kind: "failed";
|
||||
phase: ScanWorkerPhase;
|
||||
planned: number;
|
||||
started: number;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
export interface ScanSessionEvent {
|
||||
threadId: string;
|
||||
|
||||
@@ -151,3 +151,113 @@ function dispatchStatus(
|
||||
);
|
||||
return parsed.success ? { kind: "dispatch", ...parsed.data } : null;
|
||||
}
|
||||
|
||||
/** Runtime dispatch counts derived from live spawn_agent tool calls. */
|
||||
export type ScanWorkerRuntimeEvent =
|
||||
| ({ kind: "dispatch" } & z.infer<typeof dispatchSchema>)
|
||||
| {
|
||||
kind: "failed";
|
||||
phase: ScanWorkerPhase;
|
||||
planned: number;
|
||||
started: number;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
const DEFAULT_SPAWN_PHASE = "file_review" satisfies ScanWorkerPhase;
|
||||
|
||||
/** Accumulate runtime worker starts from live Codex item events. */
|
||||
export function createWorkerDispatchMonitor(): {
|
||||
observe(
|
||||
event: Readonly<Record<string, unknown>>,
|
||||
): ScanWorkerRuntimeEvent | null;
|
||||
} {
|
||||
const startedIds = new Set<string>();
|
||||
const failedIds = new Set<string>();
|
||||
let started = 0;
|
||||
|
||||
const snapshot = (kind: "dispatch" | "failed", reason?: string) => {
|
||||
const event = {
|
||||
kind,
|
||||
phase: DEFAULT_SPAWN_PHASE,
|
||||
planned: started,
|
||||
started,
|
||||
...(kind === "failed"
|
||||
? { reason: reason ?? "Delegated worker failed to start." }
|
||||
: {}),
|
||||
};
|
||||
return event as ScanWorkerRuntimeEvent;
|
||||
};
|
||||
|
||||
return {
|
||||
observe(
|
||||
event: Readonly<Record<string, unknown>>,
|
||||
): ScanWorkerRuntimeEvent | null {
|
||||
const spawn = spawnAgentCallFromEvent(event);
|
||||
if (spawn === null) return null;
|
||||
if (spawn.status === "started") {
|
||||
if (startedIds.has(spawn.id)) return null;
|
||||
startedIds.add(spawn.id);
|
||||
started += 1;
|
||||
return snapshot("dispatch");
|
||||
}
|
||||
if (failedIds.has(spawn.id)) return null;
|
||||
failedIds.add(spawn.id);
|
||||
if (!startedIds.has(spawn.id)) {
|
||||
startedIds.add(spawn.id);
|
||||
started += 1;
|
||||
}
|
||||
return snapshot("failed", spawn.reason);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function spawnAgentCallFromEvent(
|
||||
event: Readonly<Record<string, unknown>>,
|
||||
): { id: string; status: "started" | "failed"; reason?: string } | null {
|
||||
if (
|
||||
(event["type"] !== "item.started" && event["type"] !== "item.completed") ||
|
||||
!isRecord(event["item"])
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const item = event["item"];
|
||||
if (
|
||||
typeof item["id"] !== "string" ||
|
||||
!isSpawnAgentTool(toolNameFromItem(item))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (event["type"] === "item.started") {
|
||||
return { id: item["id"], status: "started" };
|
||||
}
|
||||
if (item["status"] !== "failed") return null;
|
||||
return { id: item["id"], status: "failed", reason: spawnFailureReason(item) };
|
||||
}
|
||||
|
||||
function toolNameFromItem(
|
||||
item: Readonly<Record<string, unknown>>,
|
||||
): string | null {
|
||||
for (const value of [item["tool"], item["name"], item["function"]]) {
|
||||
if (typeof value === "string") return value;
|
||||
if (isRecord(value) && typeof value["name"] === "string")
|
||||
return value["name"];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isSpawnAgentTool(name: string | null): name is string {
|
||||
if (name === null || name === "") return false;
|
||||
const separator = name.lastIndexOf("__");
|
||||
const local = separator === -1 ? name : name.slice(separator + 2);
|
||||
return local === "spawn_agent";
|
||||
}
|
||||
|
||||
function spawnFailureReason(item: Readonly<Record<string, unknown>>): string {
|
||||
const error = item["error"];
|
||||
if (typeof error === "string" && error.trim() !== "") return error;
|
||||
if (isRecord(error) && typeof error["message"] === "string") {
|
||||
const message = error["message"].trim();
|
||||
if (message !== "") return message;
|
||||
}
|
||||
return "Delegated worker failed to start.";
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type ScanActivity,
|
||||
type ScanProgress,
|
||||
type ScanTrustedAccessStatus,
|
||||
type ScanWorkerEvent,
|
||||
type ScanWorkerStatus,
|
||||
} from "../src/index.js";
|
||||
import {
|
||||
@@ -838,6 +839,102 @@ describe("one-shot scan events", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("reports runtime dispatch from spawn_agent without a status marker", async () => {
|
||||
const scanDir = await copyCompletedScan(await temporaryDirectory());
|
||||
const events: ScanWorkerEvent[] = [];
|
||||
const statuses: ScanWorkerStatus[] = [];
|
||||
async function* spawnEvents(): AsyncGenerator<ThreadEvent> {
|
||||
yield {
|
||||
type: "item.started",
|
||||
item: {
|
||||
id: "spawn-1",
|
||||
type: "mcp_tool_call",
|
||||
server: "collaboration",
|
||||
tool: "spawn_agent",
|
||||
arguments: { message: "Review routes/login.ts" },
|
||||
status: "in_progress",
|
||||
},
|
||||
};
|
||||
yield {
|
||||
type: "item.started",
|
||||
item: {
|
||||
id: "spawn-2",
|
||||
type: "mcp_tool_call",
|
||||
server: "collaboration",
|
||||
tool: "multi_agent_v1__spawn_agent",
|
||||
arguments: { message: "Review routes/auth.ts" },
|
||||
status: "in_progress",
|
||||
},
|
||||
};
|
||||
yield {
|
||||
type: "item.completed",
|
||||
item: {
|
||||
id: "message-1",
|
||||
type: "agent_message",
|
||||
text: "Delegated two file reviews.",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
await expect(
|
||||
runEvents(scanDir, completedEvents("thread-1", spawnEvents()), {
|
||||
onWorkerEvent: (event) => events.push(event),
|
||||
onWorkerStatus: (status) => statuses.push(status),
|
||||
}),
|
||||
).resolves.toBeDefined();
|
||||
expect(events).toEqual([
|
||||
{ kind: "dispatch", phase: "file_review", planned: 1, started: 1 },
|
||||
{ kind: "dispatch", phase: "file_review", planned: 2, started: 2 },
|
||||
]);
|
||||
expect(statuses).toEqual([]);
|
||||
});
|
||||
|
||||
test("reports a failed spawn_agent start as a runtime worker event", async () => {
|
||||
const scanDir = await copyCompletedScan(await temporaryDirectory());
|
||||
const events: ScanWorkerEvent[] = [];
|
||||
async function* failedSpawn(): AsyncGenerator<ThreadEvent> {
|
||||
yield {
|
||||
type: "item.started",
|
||||
item: {
|
||||
id: "spawn-1",
|
||||
type: "mcp_tool_call",
|
||||
server: "collaboration",
|
||||
tool: "spawn_agent",
|
||||
arguments: { message: "Review routes/login.ts" },
|
||||
status: "in_progress",
|
||||
},
|
||||
};
|
||||
yield {
|
||||
type: "item.completed",
|
||||
item: {
|
||||
id: "spawn-1",
|
||||
type: "mcp_tool_call",
|
||||
server: "collaboration",
|
||||
tool: "spawn_agent",
|
||||
arguments: { message: "Review routes/login.ts" },
|
||||
status: "failed",
|
||||
error: { message: "capacity exhausted" },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
await expect(
|
||||
runEvents(scanDir, completedEvents("thread-1", failedSpawn()), {
|
||||
onWorkerEvent: (event) => events.push(event),
|
||||
}),
|
||||
).resolves.toBeDefined();
|
||||
expect(events).toEqual([
|
||||
{ kind: "dispatch", phase: "file_review", planned: 1, started: 1 },
|
||||
{
|
||||
kind: "failed",
|
||||
phase: "file_review",
|
||||
planned: 1,
|
||||
started: 1,
|
||||
reason: "capacity exhausted",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("forwards real file activity as commands start and complete", async () => {
|
||||
const scanDir = await copyCompletedScan(await temporaryDirectory());
|
||||
const activities: ScanActivity[] = [];
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
createWorkerDispatchMonitor,
|
||||
scanProgressUpdatesFromEvent,
|
||||
workerStatusFromEvent,
|
||||
} from "../src/worker-progress.js";
|
||||
@@ -306,3 +307,111 @@ describe("worker progress events", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function spawnEvent(
|
||||
type: "item.started" | "item.completed",
|
||||
id: string,
|
||||
options: { tool?: string; status?: string; error?: unknown } = {},
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
type,
|
||||
item: {
|
||||
id,
|
||||
type: "mcp_tool_call",
|
||||
tool: options.tool ?? "spawn_agent",
|
||||
arguments: { message: "Review routes/login.ts" },
|
||||
status:
|
||||
options.status ??
|
||||
(type === "item.started" ? "in_progress" : "completed"),
|
||||
...(options.error === undefined ? {} : { error: options.error }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("runtime worker dispatch monitor", () => {
|
||||
test("counts live spawn_agent starts without model status markers", () => {
|
||||
const monitor = createWorkerDispatchMonitor();
|
||||
expect(
|
||||
monitor.observe(
|
||||
messageEvent(
|
||||
'CODEX_SECURITY_WORKER_STATUS {"phase":"file_review","planned":6,"started":3}',
|
||||
),
|
||||
),
|
||||
).toBeNull();
|
||||
expect(monitor.observe(spawnEvent("item.started", "spawn-1"))).toEqual({
|
||||
kind: "dispatch",
|
||||
phase: "file_review",
|
||||
planned: 1,
|
||||
started: 1,
|
||||
});
|
||||
expect(
|
||||
monitor.observe(
|
||||
spawnEvent("item.started", "spawn-2", {
|
||||
tool: "multi_agent_v1__spawn_agent",
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
kind: "dispatch",
|
||||
phase: "file_review",
|
||||
planned: 2,
|
||||
started: 2,
|
||||
});
|
||||
expect(monitor.observe(spawnEvent("item.started", "spawn-1"))).toBeNull();
|
||||
expect(monitor.observe(spawnEvent("item.completed", "spawn-1"))).toBeNull();
|
||||
expect(
|
||||
monitor.observe(
|
||||
spawnEvent("item.started", "wait-1", { tool: "wait_agent" }),
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("reports a failed spawn and counts an unseen failed item as an attempt", () => {
|
||||
const monitor = createWorkerDispatchMonitor();
|
||||
expect(
|
||||
monitor.observe(
|
||||
spawnEvent("item.completed", "spawn-fail", {
|
||||
status: "failed",
|
||||
error: "capacity exhausted",
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
kind: "failed",
|
||||
phase: "file_review",
|
||||
planned: 1,
|
||||
started: 1,
|
||||
reason: "capacity exhausted",
|
||||
});
|
||||
expect(
|
||||
monitor.observe(
|
||||
spawnEvent("item.completed", "spawn-fail", {
|
||||
status: "failed",
|
||||
error: "capacity exhausted",
|
||||
}),
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("emits dispatch then failed when a started spawn later fails", () => {
|
||||
const monitor = createWorkerDispatchMonitor();
|
||||
expect(monitor.observe(spawnEvent("item.started", "spawn-1"))).toEqual({
|
||||
kind: "dispatch",
|
||||
phase: "file_review",
|
||||
planned: 1,
|
||||
started: 1,
|
||||
});
|
||||
expect(
|
||||
monitor.observe(
|
||||
spawnEvent("item.completed", "spawn-1", {
|
||||
status: "failed",
|
||||
error: { message: "thread spawn rejected" },
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
kind: "failed",
|
||||
phase: "file_review",
|
||||
planned: 1,
|
||||
started: 1,
|
||||
reason: "thread spawn rejected",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user