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(workbench): share command argument encoding (#1577)

Michael D'Angelo46ce481b25cd
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 7ec16ce32..7a428fc2f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -23,8 +23,9 @@ run `node plugins/codex-security/mcp-app/scripts/generate-artifact-schemas.mjs`.
The MCP `typecheck` command checks that the generated resources are current.
`pnpm --dir sdk/typescript run generate:models` also copies shared finding
-normalization from the plugin source into the SDK. Edit the plugin helper, then
-regenerate its SDK copy. `pnpm --dir sdk/typescript run types` checks freshness.
+normalization and workbench argument encoding from the plugin source into the
+SDK. Edit the plugin helper, then regenerate its SDK copy.
+`pnpm --dir sdk/typescript run types` checks freshness.
Model-based evaluations live in [`evals/`](evals/README.md), outside the plugin
source. Deterministic triage checks and the MCP reducer IPC regression remain
diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.ts
index ac3f080cb..d818cd561 100644
--- a/plugins/codex-security/mcp-app/server.ts
+++ b/plugins/codex-security/mcp-app/server.ts
@@ -1,3 +1,4 @@
+import { workbenchArgs } from "./src/workbench-arguments.js";
import {
readingAnnotations,
writingAnnotations,
@@ -826,11 +827,9 @@ export function createCodexSecurityServer(): McpServer {
_meta: appMeta,
},
async ({ targetPath }) => {
- const target = await runWorkbench([
- "inspect-target",
- "--target-path",
- targetPath,
- ]);
+ const target = await runWorkbench(
+ workbenchArgs("inspect-target", { targetPath }),
+ );
return scanActionResult(
{ target },
"Validated the local Codex Security target.",
@@ -1083,7 +1082,7 @@ export function createCodexSecurityServer(): McpServer {
},
);
if (workspace === undefined && canceledLocally) {
- workspace = (await runWorkbench(["get-scan", "--scan-id", scanId]))[
+ workspace = (await runWorkbench(workbenchArgs("get-scan", { scanId })))[
"workspace"
] as JsonObject;
}
@@ -1144,7 +1143,7 @@ export function createCodexSecurityServer(): McpServer {
},
async ({ scanId }) =>
scanActionResult(
- await runWorkbench(["recover-scan-results", "--scan-id", scanId]),
+ await runWorkbench(workbenchArgs("recover-scan-results", { scanId })),
"Recovered retained Codex Security scan results.",
),
);
@@ -1387,7 +1386,7 @@ export function createCodexSecurityServer(): McpServer {
_meta: appMeta,
},
async ({ scanId, userContext }) => {
- const current = await runWorkbench(["get-scan", "--scan-id", scanId]);
+ const current = await runWorkbench(workbenchArgs("get-scan", { scanId }));
const workspace = isJsonObject(current.workspace)
? current.workspace
: undefined;
@@ -1431,7 +1430,7 @@ export function createCodexSecurityServer(): McpServer {
extra,
) => {
const modelSettings = codexModelSettingsFromExtra(extra);
- const current = await runWorkbench(["get-scan", "--scan-id", scanId]);
+ const current = await runWorkbench(workbenchArgs("get-scan", { scanId }));
const scan = isJsonObject(current.scan) ? current.scan : undefined;
const progress =
scan && isJsonObject(scan.progress) ? scan.progress : undefined;
@@ -1612,15 +1611,13 @@ export function createCodexSecurityServer(): McpServer {
},
async ({ occurrenceId, requestId, actionToken }) =>
scanActionResult(
- await runWorkbench([
- "request-finding-remediation",
- "--occurrence-id",
- occurrenceId,
- "--request-id",
- requestId,
- "--action-token",
- actionToken,
- ]),
+ await runWorkbench(
+ workbenchArgs("request-finding-remediation", {
+ occurrenceId,
+ requestId,
+ actionToken,
+ }),
+ ),
"Queued the local Codex Security finding remediation request.",
),
);
@@ -1637,19 +1634,15 @@ export function createCodexSecurityServer(): McpServer {
},
async ({ occurrenceId, requestId, expectedVersion, action, actionToken }) =>
scanActionResult(
- await runWorkbench([
- "request-finding-remediation-action",
- "--occurrence-id",
- occurrenceId,
- "--request-id",
- requestId,
- "--expected-version",
- String(expectedVersion),
- "--action",
- action,
- "--action-token",
- actionToken,
- ]),
+ await runWorkbench(
+ workbenchArgs("request-finding-remediation-action", {
+ occurrenceId,
+ requestId,
+ expectedVersion: String(expectedVersion),
+ action,
+ actionToken,
+ }),
+ ),
`Queued the local Codex Security finding remediation ${action} request.`,
),
);
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/store.ts b/plugins/codex-security/mcp-app/src/deep-scan/store.ts
index 24699d879..583665b07 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/store.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/store.ts
@@ -1,3 +1,4 @@
+import { workbenchArgs } from "../workbench-arguments.js";
import { availableParallelism } from "node:os";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
@@ -135,28 +136,19 @@ export class WorkbenchDeepScanStore {
}): Promise<DeepScanRunState> {
const userContext = input.userContext;
const result = await this.enqueueWrite(
- [
- "begin-deep-scan",
- "--thread-id",
- input.threadId,
- ...(input.scanId ? ["--scan-id", input.scanId] : []),
- ...(input.targetPath ? ["--target-path", input.targetPath] : []),
- ...(input.scope ? ["--scope", input.scope] : []),
- ...(userContext ? ["--user-context-stdin"] : []),
- ...(input.handoffClaimToken
- ? ["--claim-token", input.handoffClaimToken]
- : []),
- ...(input.model ? ["--model", input.model] : []),
- ...(input.reasoningEffort
- ? ["--reasoning-effort", input.reasoningEffort]
- : []),
- "--scan-root",
- input.scanRoot,
- "--available-parallelism",
- String(availableParallelism()),
- "--workflow-version",
- WORKFLOW_VERSION,
- ],
+ workbenchArgs("begin-deep-scan", {
+ threadId: input.threadId,
+ scanId: input.scanId || undefined,
+ targetPath: input.targetPath || undefined,
+ scope: input.scope || undefined,
+ userContextStdin: Boolean(userContext),
+ claimToken: input.handoffClaimToken || undefined,
+ model: input.model || undefined,
+ reasoningEffort: input.reasoningEffort || undefined,
+ scanRoot: input.scanRoot,
+ availableParallelism: availableParallelism(),
+ workflowVersion: WORKFLOW_VERSION,
+ }),
false,
userContext,
);
@@ -172,13 +164,9 @@ export class WorkbenchDeepScanStore {
async get(scanId: string, threadId: string): Promise<DeepScanRunState> {
const run = parseDeepScan(
- await this.runWorkbench([
- "get-deep-scan",
- "--scan-id",
- scanId,
- "--thread-id",
- threadId,
- ]),
+ await this.runWorkbench(
+ workbenchArgs("get-deep-scan", { scanId, threadId }),
+ ),
);
const generation =
this.coordinatorLeases.get(scanId)?.run.coordinatorGeneration;
@@ -196,17 +184,14 @@ export class WorkbenchDeepScanStore {
async claimCoordinator(
input: DeepScanCoordinatorLeaseInput,
): Promise<DeepScanCoordinatorClaim> {
- const result = await this.enqueueWrite([
- "claim-deep-scan-coordinator",
- "--scan-id",
- input.scanId,
- "--thread-id",
- input.threadId,
- ...this.coordinatorLeaseArgs(input.scanId),
- ...(input.handoffClaimToken
- ? ["--claim-token", input.handoffClaimToken]
- : []),
- ]);
+ const result = await this.enqueueWrite(
+ workbenchArgs("claim-deep-scan-coordinator", {
+ scanId: input.scanId,
+ threadId: input.threadId,
+ coordinatorGeneration: this.coordinatorGeneration(input.scanId),
+ claimToken: input.handoffClaimToken || undefined,
+ }),
+ );
const run = parseDeepScan(result);
const disposition = result.coordinatorDisposition;
if (
@@ -265,26 +250,18 @@ export class WorkbenchDeepScanStore {
): Promise<PersistedDeepScanWorker> {
const result = await this.enqueueWrite(
[
- "upsert-deep-scan-worker",
- "--scan-id",
- update.scanId,
- "--worker-id",
- update.id,
- "--kind",
- update.kind,
- "--status",
- update.status,
- "--prompt-path",
- update.promptPath,
- "--artifact-dir",
- update.artifactDir,
- "--attempt",
- String(update.attempt),
- ...this.coordinatorLeaseArgs(update.scanId),
- ...(update.resultManifestPath
- ? ["--result-manifest-path", update.resultManifestPath]
- : []),
- ...(update.threadId ? ["--sdk-thread-id", update.threadId] : []),
+ ...workbenchArgs("upsert-deep-scan-worker", {
+ scanId: update.scanId,
+ workerId: update.id,
+ kind: update.kind,
+ status: update.status,
+ promptPath: update.promptPath,
+ artifactDir: update.artifactDir,
+ attempt: update.attempt,
+ coordinatorGeneration: this.coordinatorGeneration(update.scanId),
+ resultManifestPath: update.resultManifestPath || undefined,
+ sdkThreadId: update.threadId || undefined,
+ }),
...(update.error ? [`--error-message=${update.error}`] : []),
...(update.replaceableFailureKind
? ["--replaceable-failure-kind", update.replaceableFailureKind]
@@ -313,22 +290,14 @@ export class WorkbenchDeepScanStore {
artifactDir: string;
}): Promise<void> {
await this.enqueueWrite(
- [
- "claim-deep-scan-dedup",
- "--scan-id",
- input.scanId,
- "--worker-id",
- input.id,
- "--prompt-path",
- input.promptPath,
- "--artifact-dir",
- input.artifactDir,
- ...this.coordinatorLeaseArgs(input.scanId),
- ...input.workerIds.flatMap((workerId) => [
- "--input-worker-id",
- workerId,
- ]),
- ],
+ workbenchArgs("claim-deep-scan-dedup", {
+ scanId: input.scanId,
+ workerId: input.id,
+ promptPath: input.promptPath,
+ artifactDir: input.artifactDir,
+ coordinatorGeneration: this.coordinatorGeneration(input.scanId),
+ inputWorkerId: input.workerIds,
+ }),
true,
);
}
@@ -336,21 +305,14 @@ export class WorkbenchDeepScanStore {
async commitDedup(commit: DedupCommit): Promise<DeepScanRunState> {
return parseDeepScan(
await this.enqueueWrite(
- [
- "commit-deep-scan-dedup",
- "--scan-id",
- commit.scanId,
- "--worker-id",
- commit.id,
- ...this.coordinatorLeaseArgs(commit.scanId),
- "--result-manifest-path",
- commit.resultManifestPath,
- ...(commit.candidateLedgerPath
- ? ["--candidate-ledger-path", commit.candidateLedgerPath]
- : []),
- "--new-findings-count",
- String(commit.newFindings),
- ],
+ workbenchArgs("commit-deep-scan-dedup", {
+ scanId: commit.scanId,
+ workerId: commit.id,
+ coordinatorGeneration: this.coordinatorGeneration(commit.scanId),
+ resultManifestPath: commit.resultManifestPath,
+ candidateLedgerPath: commit.candidateLedgerPath || undefined,
+ newFindingsCount: commit.newFindings,
+ }),
true,
),
);
@@ -365,23 +327,14 @@ export class WorkbenchDeepScanStore {
}): Promise<DeepScanRunState> {
return parseDeepScan(
await this.enqueueWrite(
- [
- "finish-deep-scan",
- "--scan-id",
- input.scanId,
- ...this.coordinatorLeaseArgs(input.scanId),
- "--terminal-reason",
- input.reason,
- "--manifest-path",
- input.manifestPath,
- ...(input.stagedManifestPath
- ? ["--staged-manifest-path", input.stagedManifestPath]
- : []),
- ...input.omittedWorkerIds.flatMap((workerId) => [
- "--omitted-worker-id",
- workerId,
- ]),
- ],
+ workbenchArgs("finish-deep-scan", {
+ scanId: input.scanId,
+ coordinatorGeneration: this.coordinatorGeneration(input.scanId),
+ terminalReason: input.reason,
+ manifestPath: input.manifestPath,
+ stagedManifestPath: input.stagedManifestPath || undefined,
+ omittedWorkerId: input.omittedWorkerIds,
+ }),
true,
),
);
@@ -396,10 +349,10 @@ export class WorkbenchDeepScanStore {
): Promise<DeepScanRunState> {
return parseDeepScan(
await this.enqueueWrite([
- "fail-deep-scan",
- "--scan-id",
- scanId,
- ...this.coordinatorLeaseArgs(scanId),
+ ...workbenchArgs("fail-deep-scan", {
+ scanId,
+ coordinatorGeneration: this.coordinatorGeneration(scanId),
+ }),
`--message=${message}`,
...(manifestPath ? ["--manifest-path", manifestPath] : []),
...(stagedManifestPath
@@ -418,12 +371,13 @@ export class WorkbenchDeepScanStore {
return parseDeepScan(
await this.enqueueWrite(
[
- "record-deep-scan-publication-failure",
- "--scan-id",
- scanId,
- ...(coordinatorGeneration === undefined
- ? this.coordinatorLeaseArgs(scanId)
- : ["--coordinator-generation", String(coordinatorGeneration)]),
+ ...workbenchArgs("record-deep-scan-publication-failure", {
+ scanId,
+ coordinatorGeneration:
+ coordinatorGeneration === undefined
+ ? this.coordinatorGeneration(scanId)
+ : coordinatorGeneration,
+ }),
`--message=${message}`,
],
true,
@@ -439,25 +393,21 @@ export class WorkbenchDeepScanStore {
reviewItemsTotal?: number;
reviewItemsCompleted?: number;
}): Promise<void> {
- await this.enqueueWrite([
- "update-progress",
- "--scan-id",
- input.scanId,
- ...this.coordinatorLeaseArgs(input.scanId),
- ...(input.handoffClaimToken
- ? ["--claim-token", input.handoffClaimToken]
- : []),
- ...(input.phase ? ["--phase", input.phase] : []),
- ...(input.deepReviewPass === undefined
- ? []
- : ["--deep-review-pass", String(input.deepReviewPass)]),
- ...(input.reviewItemsTotal === undefined
- ? []
- : ["--review-items-total", String(input.reviewItemsTotal)]),
- ...(input.reviewItemsCompleted === undefined
- ? []
- : ["--review-items-completed", String(input.reviewItemsCompleted)]),
- ]);
+ await this.enqueueWrite(
+ workbenchArgs("update-progress", {
+ scanId: input.scanId,
+ coordinatorGeneration: this.coordinatorGeneration(input.scanId),
+ claimToken: input.handoffClaimToken || undefined,
+ phase: input.phase || undefined,
+ deepReviewPass: input.deepReviewPass,
+ reviewItemsTotal: input.reviewItemsTotal,
+ reviewItemsCompleted: input.reviewItemsCompleted,
+ }),
+ );
+ }
+
+ private coordinatorGeneration(scanId: string): number | undefined {
+ return this.coordinatorLeases.get(scanId)?.run.coordinatorGeneration;
}
/**
@@ -470,8 +420,7 @@ export class WorkbenchDeepScanStore {
* state before or after each mutation.
*/
coordinatorLeaseArgs(scanId: string): string[] {
- const generation =
- this.coordinatorLeases.get(scanId)?.run.coordinatorGeneration;
+ const generation = this.coordinatorGeneration(scanId);
return generation === undefined
? []
: ["--coordinator-generation", String(generation)];
diff --git a/plugins/codex-security/mcp-app/src/server/handoff-tools.ts b/plugins/codex-security/mcp-app/src/server/handoff-tools.ts
index 1e41ca01c..f5d6f945d 100644
--- a/plugins/codex-security/mcp-app/src/server/handoff-tools.ts
+++ b/plugins/codex-security/mcp-app/src/server/handoff-tools.ts
@@ -1,3 +1,4 @@
+import { workbenchArgs } from "../workbench-arguments.js";
import { writingAnnotations } from "./tool-annotations.js";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
@@ -86,16 +87,12 @@ export function registerScanHandoffTools(
_meta: appMeta,
},
async (input: z.infer<typeof inputSchema>) => {
- const arguments_ = [
- command,
- "--scan-id",
- input.scanId,
- "--claim-token",
- input.claimToken,
- ];
- if ("takeOverStale" in input && input.takeOverStale)
- arguments_.push("--take-over-stale");
- if ("threadId" in input) arguments_.push("--thread-id", input.threadId);
+ const arguments_ = workbenchArgs(command, {
+ scanId: input.scanId,
+ claimToken: input.claimToken,
+ takeOverStale: "takeOverStale" in input && input.takeOverStale,
+ threadId: "threadId" in input ? input.threadId : undefined,
+ });
return workspaceResult(
(await runWorkbench(arguments_)) as HandoffWorkspaceState,
);
diff --git a/plugins/codex-security/mcp-app/src/workbench-arguments.ts b/plugins/codex-security/mcp-app/src/workbench-arguments.ts
new file mode 100644
index 000000000..d4e14276c
--- /dev/null
+++ b/plugins/codex-security/mcp-app/src/workbench-arguments.ts
@@ -0,0 +1,20 @@
+export type WorkbenchFields = Record<
+ string,
+ string | number | boolean | readonly string[] | undefined
+>;
+
+export function workbenchArgs(
+ command: string,
+ fields: WorkbenchFields,
+): string[] {
+ const args = [command];
+ for (const [name, value] of Object.entries(fields)) {
+ if (value === undefined || value === false) continue;
+ const flag = `--${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;
+ (Array.isArray(value) ? value : [value]).forEach((item) => {
+ args.push(flag);
+ if (item !== true) args.push(String(item));
+ });
+ }
+ return args;
+}
diff --git a/sdk/typescript/scripts/generate-models.cjs b/sdk/typescript/scripts/generate-models.cjs
index 0411b4ff1..60d04a8e1 100644
--- a/sdk/typescript/scripts/generate-models.cjs
+++ b/sdk/typescript/scripts/generate-models.cjs
@@ -88,17 +88,19 @@ async function generate() {
}
generate().then((models) => {
- const shared = ["finding-normalization"].map((name) => [
- `${name}.ts`,
- `/* Generated from plugin ${name}.ts. Run \`pnpm generate:models\`. */\n` +
- readFileSync(
- join(
- packageRoot,
- `../../plugins/codex-security/mcp-app/src/${name}.ts`,
+ const shared = ["finding-normalization", "workbench-arguments"].map(
+ (name) => [
+ `${name}.ts`,
+ `/* Generated from plugin ${name}.ts. Run \`pnpm generate:models\`. */\n` +
+ readFileSync(
+ join(
+ packageRoot,
+ `../../plugins/codex-security/mcp-app/src/${name}.ts`,
+ ),
+ "utf8",
),
- "utf8",
- ),
- ]);
+ ],
+ );
for (const [name, content] of [["models.ts", models], ...shared]) {
const output = join(packageRoot, "src", name);
if (process.argv.includes("--check")) {
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 9e0834b83..e9f85a496 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -73,6 +73,7 @@ const distModules = [
"deduplication/deduplication",
"finding-retrieval",
"finding-normalization",
+ "workbench-arguments",
"finding-workflow",
"findings-client",
"findings-errors",
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index db01e4975..b1accdb32 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -1,4 +1,5 @@
/// <reference lib="esnext.disposable" preserve="true" />
+import { workbenchArgs } from "./workbench-arguments.js";
import { isSafeNonNegativeInteger as safeInteger } from "./value.js";
import {
@@ -1651,13 +1652,10 @@ export class CodexSecurity {
}
await workbench(
{ ...activeScan.options, signal: budgetSignal },
- [
- "set-scan-cost-limit",
- "--scan-id",
- activeScan.id,
- "--max-cost-usd",
- String(next),
- ],
+ workbenchArgs("set-scan-cost-limit", {
+ scanId: activeScan.id,
+ maxCostUsd: String(next),
+ }),
);
if (budgetSignal.aborted) return;
maxCostUsd = next;
@@ -1724,20 +1722,13 @@ export class CodexSecurity {
])
: await workbench(
workbenchOptions,
- [
- "register-cli-scan",
- "--repository",
- repo,
- "--scan-dir",
+ workbenchArgs("register-cli-scan", {
+ repository: repo,
scanDir,
- "--registration-json-stdin",
- ...(options.archiveExisting === true
- ? ["--archive-existing"]
- : []),
- ...(options.parentScanId === undefined
- ? []
- : ["--parent-scan-id", options.parentScanId]),
- ],
+ registrationJsonStdin: true,
+ archiveExisting: options.archiveExisting === true,
+ parentScanId: options.parentScanId,
+ }),
JSON.stringify({
recipe,
userContext: options.scanPrompt,
@@ -1888,7 +1879,7 @@ export class CodexSecurity {
...workbenchOptions,
signal: AbortSignal.any([signal, progressSignal]),
},
- ["get-scan", "--scan-id", scanId],
+ workbenchArgs("get-scan", { scanId }),
),
onProgress: (progress) =>
notifyObserver(options, "onDeepProgress")(progress),
@@ -2129,13 +2120,10 @@ export class CodexSecurity {
if (budgetRecovery !== null) budgetRecovery.threadId = threadId;
tracker.start(threadId);
try {
- await workbench(workbenchOptions, [
- "set-scan-thread",
- "--scan-id",
- scanId,
- "--thread-id",
- threadId,
- ]);
+ await workbench(
+ workbenchOptions,
+ workbenchArgs("set-scan-thread", { scanId, threadId }),
+ );
} catch (error) {
notifyObserver(
options,
@@ -2217,17 +2205,15 @@ export class CodexSecurity {
completionCost = snapshot.cost;
let preparation: JsonObject;
try {
- preparation = await workbench(workbenchOptions, [
- "prepare-scan-completion",
- "--scan-id",
- scanId,
- ]);
+ preparation = await workbench(
+ workbenchOptions,
+ workbenchArgs("prepare-scan-completion", { scanId }),
+ );
} catch (error) {
- const saved = await workbench(workbenchOptions, [
- "get-scan",
- "--scan-id",
- scanId,
- ]).catch(() => null);
+ const saved = await workbench(
+ workbenchOptions,
+ workbenchArgs("get-scan", { scanId }),
+ ).catch(() => null);
const savedScan = isRecord(saved) ? saved["scan"] : undefined;
const progress = isRecord(savedScan)
? savedScan["progress"]
@@ -3391,18 +3377,13 @@ export class CodexSecurity {
throwIfAborted(signal, scanDir);
const registration = await workbench(
workbenchOptions,
- [
- "register-cli-scan",
- "--repository",
- local.repository,
- "--scan-dir",
+ workbenchArgs("register-cli-scan", {
+ repository: local.repository,
scanDir,
- "--registration-json-stdin",
- ...(options.archiveExisting ? ["--archive-existing"] : []),
- ...(options.parentScanId === undefined
- ? []
- : ["--parent-scan-id", options.parentScanId]),
- ],
+ registrationJsonStdin: true,
+ archiveExisting: Boolean(options.archiveExisting),
+ parentScanId: options.parentScanId,
+ }),
JSON.stringify({
recipe: {
...scanRecipe({
@@ -3470,11 +3451,10 @@ export class CodexSecurity {
output_tokens: 0,
};
const cost = estimateScanCost(model, usage);
- await workbench(workbenchOptions, [
- "prepare-scan-completion",
- "--scan-id",
- scanId,
- ]);
+ await workbench(
+ workbenchOptions,
+ workbenchArgs("prepare-scan-completion", { scanId }),
+ );
const completion = await workbench(workbenchOptions, [
"complete-scan",
"--scan-id",
diff --git a/sdk/typescript/src/artifact-export.ts b/sdk/typescript/src/artifact-export.ts
index fb0b97919..3925b33ea 100644
--- a/sdk/typescript/src/artifact-export.ts
+++ b/sdk/typescript/src/artifact-export.ts
@@ -1,3 +1,4 @@
+import { workbenchArgs } from "./workbench-arguments.js";
import { spawn } from "node:child_process";
import { lstat, realpath } from "node:fs/promises";
import { basename, dirname, join, relative, resolve } from "node:path";
@@ -309,16 +310,14 @@ export async function resolveSavedArtifactDirectory(
): Promise<string> {
// Reuse the workbench's recorded digest and scan binding checks without
// requiring a writable saved-scan directory for stdout or external exports.
- const context = await workbench([
- "export-findings",
- "--scan-id",
- scanId,
- "--artifact",
- artifact,
- "--format",
- format,
- "--validate-only",
- ]);
+ const context = await workbench(
+ workbenchArgs("export-findings", {
+ scanId,
+ artifact,
+ format,
+ validateOnly: true,
+ }),
+ );
const scan = context["scan"] as JsonObject | undefined;
if (typeof scan?.["scanDir"] !== "string")
throw new CodexSecurityError(
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 1e16daa96..9d0b90c00 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -1,4 +1,5 @@
#!/usr/bin/env node
+import { workbenchArgs } from "./workbench-arguments.js";
import { listenForAbort } from "./cli-signals.js";
import { isNonEmptyString, parseJson } from "./value.js";
@@ -1819,14 +1820,11 @@ export async function main(
pythonPath?: string,
): Promise<SavedScan[] | undefined> => {
const result = await history(
- [
- "list-scans",
- "--repository",
- dependencies.currentDirectory(),
- ...(status === "complete" ? ["--status", "complete"] : []),
- "--limit",
- String(count),
- ],
+ workbenchArgs("list-scans", {
+ repository: dependencies.currentDirectory(),
+ status: status === "complete" ? "complete" : undefined,
+ limit: String(count),
+ }),
(value) => {
if ((value["scans"] as SavedScan[]).length < count) {
const kind = status === "complete" ? "completed" : "saved";
@@ -1898,14 +1896,11 @@ export async function main(
runMatching(async (options) => {
const { matchingCached, matchingInputs, ...comparison } =
await dependencies.runWorkbench(
- [
- "compare-scans",
- "--before-scan-id",
- beforeId,
- "--after-scan-id",
- afterId,
- "--include-matching-inputs",
- ],
+ workbenchArgs("compare-scans", {
+ beforeScanId: beforeId,
+ afterScanId: afterId,
+ includeMatchingInputs: true,
+ }),
undefined,
options.signal,
);
@@ -1914,14 +1909,11 @@ export async function main(
const matching = await dependencies.matchFindings(input, options);
options.signal?.throwIfAborted();
return await dependencies.runWorkbench(
- [
- "save-scan-comparison",
- "--before-scan-id",
- beforeId,
- "--after-scan-id",
- afterId,
- "--matches-json-stdin",
- ],
+ workbenchArgs("save-scan-comparison", {
+ beforeScanId: beforeId,
+ afterScanId: afterId,
+ matchesJsonStdin: true,
+ }),
JSON.stringify(matching),
options.signal,
);
@@ -2111,11 +2103,12 @@ export async function main(
? undefined
: resolveCliPath(directory, args.repository ?? directory);
return presentHistory(
- await history([
- "list-scans",
- ...(repository === undefined ? [] : ["--repository", repository]),
- ...(scanRoot === undefined ? [] : ["--scan-root", scanRoot]),
- ]),
+ await history(
+ workbenchArgs("list-scans", {
+ repository,
+ scanRoot,
+ }),
+ ),
"list",
format,
{
@@ -2276,11 +2269,9 @@ export async function main(
async run({ args, error: incurError, format, options }) {
let scanArguments: ScanArguments;
try {
- const saved = await dependencies.runWorkbench([
- "get-cli-scan-resume",
- "--scan-id",
- args.scanId,
- ]);
+ const saved = await dependencies.runWorkbench(
+ workbenchArgs("get-cli-scan-resume", { scanId: args.scanId }),
+ );
if (
typeof saved["scanId"] !== "string" ||
typeof saved["scanDir"] !== "string"
@@ -2392,11 +2383,9 @@ export async function main(
let scanArguments: ScanArguments;
try {
const { recipe, scanId: resolvedScanId } =
- await dependencies.runWorkbench([
- "get-scan-recipe",
- "--scan-id",
- scanId,
- ]);
+ await dependencies.runWorkbench(
+ workbenchArgs("get-scan-recipe", { scanId }),
+ );
const parentScanId = resolvedScanId as string;
if (
isJsonObject(recipe) &&
@@ -2862,11 +2851,9 @@ export async function main(
`Interactive scan selection requires a terminal. Select a saved scan: codex-security publish scan --scan SCAN_ID --to ${options.to}${options.to === "linear" ? " --linear-team TEAM_ID" : ""}.`,
);
}
- const saved = await scanDependencies.runWorkbench([
- "list-scans",
- "--status",
- "complete",
- ]);
+ const saved = await scanDependencies.runWorkbench(
+ workbenchArgs("list-scans", { status: "complete" }),
+ );
const listedScans = saved["scans"];
if (!Array.isArray(listedScans)) {
throw new CodexSecurityError(
@@ -4620,7 +4607,7 @@ export async function main(
? {
recoverScan: async (scanDir, prompts) => {
const history = await dependencies.runWorkbench(
- ["list-scans", "--scan-root", scanDir],
+ workbenchArgs("list-scans", { scanRoot: scanDir }),
undefined,
controller.signal,
);
@@ -4646,12 +4633,10 @@ export async function main(
if (status !== "running" || scan["mode"] !== "deep")
return undefined;
const saved = await dependencies.runWorkbench(
- [
- "get-cli-scan-resume",
- "--scan-id",
- scan.scanId,
- "--allow-unavailable",
- ],
+ workbenchArgs("get-cli-scan-resume", {
+ scanId: scan.scanId,
+ allowUnavailable: true,
+ }),
undefined,
controller.signal,
);
@@ -5685,11 +5670,11 @@ export async function main(
async run({ args, options }) {
let scanId = args.scanId;
if (scanId === undefined) {
- const value = await history([
- "list-scans",
- "--repository",
- dependencies.currentDirectory(),
- ]);
+ const value = await history(
+ workbenchArgs("list-scans", {
+ repository: dependencies.currentDirectory(),
+ }),
+ );
const scans = value["scans"] as {
scanId: string;
startedAt: string;
@@ -6513,12 +6498,10 @@ async function matchAllScans(
options: ScanComparisonOptions = {},
): Promise<JsonObject> {
const result = (await dependencies.runWorkbench(
- [
- "list-unmatched-scan-pairs",
- "--repository",
- dependencies.currentDirectory(),
- ...(force ? ["--force"] : []),
- ],
+ workbenchArgs("list-unmatched-scan-pairs", {
+ repository: dependencies.currentDirectory(),
+ force: Boolean(force),
+ }),
undefined,
options.signal,
)) as MatchingPlan;
@@ -6561,14 +6544,11 @@ async function matchAllScans(
for (const { scanId, comparison } of comparisons) {
options.signal?.throwIfAborted();
await dependencies.runWorkbench(
- [
- "save-scan-comparison",
- "--before-scan-id",
- scanId,
- "--after-scan-id",
+ workbenchArgs("save-scan-comparison", {
+ beforeScanId: scanId,
afterScanId,
- "--matches-json-stdin",
- ],
+ matchesJsonStdin: true,
+ }),
JSON.stringify(comparison),
options.signal,
);
@@ -6650,13 +6630,9 @@ async function selectSavedFindings(
let scanId = requestedScanId;
if (scanId === "latest") {
const repository = resolve(dependencies.currentDirectory());
- const history = await dependencies.runWorkbench([
- "list-scans",
- "--repository",
- repository,
- "--status",
- "complete",
- ]);
+ const history = await dependencies.runWorkbench(
+ workbenchArgs("list-scans", { repository, status: "complete" }),
+ );
const latest = (history["scans"] as { scanId?: string }[] | undefined)?.[0]
?.scanId;
if (typeof latest !== "string") {
@@ -9301,13 +9277,12 @@ async function readDeepScanStop(
nextStep: "To scan further, rerun with a higher --max-cost.",
};
}
- const response = await runWorkbench([
- "get-deep-scan",
- "--scan-id",
- result.manifest.scan.id,
- "--thread-id",
- result.threadId,
- ]);
+ const response = await runWorkbench(
+ workbenchArgs("get-deep-scan", {
+ scanId: result.manifest.scan.id,
+ threadId: result.threadId,
+ }),
+ );
const state = response["deepScan"] as
| {
terminalReason: string;
diff --git a/sdk/typescript/src/import-scan.ts b/sdk/typescript/src/import-scan.ts
index 611fca277..b14125c04 100644
--- a/sdk/typescript/src/import-scan.ts
+++ b/sdk/typescript/src/import-scan.ts
@@ -1,3 +1,4 @@
+import { workbenchArgs } from "./workbench-arguments.js";
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import {
@@ -203,18 +204,13 @@ export async function importScan(
signal?.throwIfAborted();
const registration = await workbench(
workbenchOptions,
- [
- "register-cli-scan",
- "--repository",
+ workbenchArgs("register-cli-scan", {
repository,
- "--scan-dir",
scanDir,
- "--registration-json-stdin",
- ...(options.archiveExisting ? ["--archive-existing"] : []),
- ...(options.parentScanId === undefined
- ? []
- : ["--parent-scan-id", options.parentScanId]),
- ],
+ registrationJsonStdin: true,
+ archiveExisting: Boolean(options.archiveExisting),
+ parentScanId: options.parentScanId,
+ }),
JSON.stringify({
recipe: {
repository,
@@ -292,11 +288,10 @@ export async function importScan(
{ flag: "wx", signal },
);
}
- await workbench(workbenchOptions, [
- "prepare-scan-completion",
- "--scan-id",
- scanId,
- ]);
+ await workbench(
+ workbenchOptions,
+ workbenchArgs("prepare-scan-completion", { scanId }),
+ );
// Finalization normally recovers partial output. An import must retain every supplied row.
const contract = await loadContract(scanDir, {
pluginRoot,
diff --git a/sdk/typescript/src/saved-scan.ts b/sdk/typescript/src/saved-scan.ts
index 655b8d0cb..1253e342c 100644
--- a/sdk/typescript/src/saved-scan.ts
+++ b/sdk/typescript/src/saved-scan.ts
@@ -1,3 +1,4 @@
+import { workbenchArgs } from "./workbench-arguments.js";
import { isNonEmptyString } from "./value.js";
import { lstat } from "node:fs/promises";
import { resolve } from "node:path";
@@ -44,13 +45,12 @@ export async function resolveCompletedScan(
): Promise<SavedScan> {
let scanId = requestedId;
if (scanId === "latest") {
- const history = await dependencies.runWorkbench([
- "list-scans",
- "--repository",
- resolve(dependencies.currentDirectory()),
- "--status",
- "complete",
- ]);
+ const history = await dependencies.runWorkbench(
+ workbenchArgs("list-scans", {
+ repository: resolve(dependencies.currentDirectory()),
+ status: "complete",
+ }),
+ );
const scans = history["scans"];
const latest = Array.isArray(scans) ? scans[0] : undefined;
if (!isJsonObject(latest) || typeof latest["scanId"] !== "string") {
@@ -60,11 +60,9 @@ export async function resolveCompletedScan(
}
scanId = latest["scanId"];
}
- const context = await dependencies.runWorkbench([
- "get-scan",
- "--scan-id",
- scanId,
- ]);
+ const context = await dependencies.runWorkbench(
+ workbenchArgs("get-scan", { scanId }),
+ );
const scan = context["scan"];
if (!isJsonObject(scan) || typeof scan["scanId"] !== "string") {
throw new CodexSecurityError(`Could not read saved scan ${scanId}.`);
diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.ts
index 45306f0ea..43769ea6a 100644
--- a/sdk/typescript/src/scan-comparison.ts
+++ b/sdk/typescript/src/scan-comparison.ts
@@ -1,3 +1,4 @@
+import { workbenchArgs } from "./workbench-arguments.js";
import { existsSync } from "node:fs";
import { isRecord } from "./record.js";
import { notify } from "./value.js";
@@ -816,14 +817,11 @@ export async function matchCompletedScan(
for (const { scanId, projected } of comparisons) {
options.signal?.throwIfAborted();
await options.workbench(
- [
- "save-scan-comparison",
- "--before-scan-id",
- scanId,
- "--after-scan-id",
- options.scanId,
- "--matches-json-stdin",
- ],
+ workbenchArgs("save-scan-comparison", {
+ beforeScanId: scanId,
+ afterScanId: options.scanId,
+ matchesJsonStdin: true,
+ }),
JSON.stringify(projected),
);
}
diff --git a/sdk/typescript/src/security-policy.ts b/sdk/typescript/src/security-policy.ts
index 43a049f3b..06607a6cf 100644
--- a/sdk/typescript/src/security-policy.ts
+++ b/sdk/typescript/src/security-policy.ts
@@ -1,3 +1,4 @@
+import { workbenchArgs } from "./workbench-arguments.js";
import { execFile } from "node:child_process";
import { randomUUID } from "node:crypto";
import { sha256Text as digest } from "./contract.js";
@@ -690,13 +691,11 @@ export async function resolveSecurityPolicyGuidance(
process.execPath,
[
join(pluginRoot, "mcp", "helpers.mjs"),
- "resolve-security-md",
- "--repo",
- target.repository,
- "--scope",
- dirname(target.targetPath),
- "--out",
- "-",
+ ...workbenchArgs("resolve-security-md", {
+ repo: target.repository,
+ scope: dirname(target.targetPath),
+ out: "-",
+ }),
],
{ encoding: "utf8", maxBuffer: Infinity, env: environment, signal },
);
diff --git a/sdk/typescript/src/workbench-arguments.ts b/sdk/typescript/src/workbench-arguments.ts
new file mode 100644
index 000000000..914be7cb6
--- /dev/null
+++ b/sdk/typescript/src/workbench-arguments.ts
@@ -0,0 +1,21 @@
+/* Generated from plugin workbench-arguments.ts. Run `pnpm generate:models`. */
+export type WorkbenchFields = Record<
+ string,
+ string | number | boolean | readonly string[] | undefined
+>;
+
+export function workbenchArgs(
+ command: string,
+ fields: WorkbenchFields,
+): string[] {
+ const args = [command];
+ for (const [name, value] of Object.entries(fields)) {
+ if (value === undefined || value === false) continue;
+ const flag = `--${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;
+ (Array.isArray(value) ? value : [value]).forEach((item) => {
+ args.push(flag);
+ if (item !== true) args.push(String(item));
+ });
+ }
+ return args;
+}
diff --git a/sdk/typescript/tests-ts/workbench-arguments.test.ts b/sdk/typescript/tests-ts/workbench-arguments.test.ts
new file mode 100644
index 000000000..ea4f31022
--- /dev/null
+++ b/sdk/typescript/tests-ts/workbench-arguments.test.ts
@@ -0,0 +1,35 @@
+import { expect, test } from "bun:test";
+import { workbenchArgs } from "../src/workbench-arguments.js";
+
+test("workbench arguments preserve field order, values, and repeated flags", () => {
+ expect(
+ workbenchArgs("fixture-command", {
+ scanId: "scan-example",
+ registrationJsonStdin: true,
+ archiveExisting: false,
+ parentScanId: undefined,
+ offset: 0,
+ name: "",
+ query: "--query\nUTF-8 λ\0",
+ inputWorkerId: ["worker-2", "worker-1", "worker-2"],
+ omittedWorkerId: [],
+ }),
+ ).toEqual([
+ "fixture-command",
+ "--scan-id",
+ "scan-example",
+ "--registration-json-stdin",
+ "--offset",
+ "0",
+ "--name",
+ "",
+ "--query",
+ "--query\nUTF-8 λ\0",
+ "--input-worker-id",
+ "worker-2",
+ "--input-worker-id",
+ "worker-1",
+ "--input-worker-id",
+ "worker-2",
+ ]);
+});