@openai/codex-security 0.1.26 → 0.1.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/README.md +398 -30
  2. package/_bundled_plugin/.mcp.json +1 -0
  3. package/_bundled_plugin/mcp/helpers.mjs +24 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  5. package/_bundled_plugin/mcp/native/COPYRIGHT-library.html +5556 -0
  6. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +5989 -0
  7. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  8. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  9. package/_bundled_plugin/mcp/native/licenses/Apache-2.0.txt +73 -0
  10. package/_bundled_plugin/mcp/native/licenses/BSD-2-Clause.txt +9 -0
  11. package/_bundled_plugin/mcp/native/licenses/MIT.txt +9 -0
  12. package/_bundled_plugin/mcp/native/licenses/Unicode-3.0.txt +39 -0
  13. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  14. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  15. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  16. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  17. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  18. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  19. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  20. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  21. package/_bundled_plugin/references/config-preflight.md +2 -0
  22. package/_bundled_plugin/references/core-scan.md +1 -1
  23. package/_bundled_plugin/references/scan-contract.md +35 -35
  24. package/_bundled_plugin/references/security-guidance.md +7 -1
  25. package/_bundled_plugin/scripts/generate_in_scope_files.py +2 -2
  26. package/_bundled_plugin/scripts/generate_rank_input.py +8 -1
  27. package/_bundled_plugin/scripts/launch_codex_security_mcp +6 -0
  28. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +43 -9
  29. package/_bundled_plugin/scripts/rank_preview.py +4 -1
  30. package/_bundled_plugin/scripts/workbench_cli.py +4 -0
  31. package/_bundled_plugin/scripts/workbench_db.py +33 -29
  32. package/_bundled_plugin/scripts/workbench_scan_history.py +117 -2
  33. package/_bundled_plugin/scripts/workbench_validation.py +4 -0
  34. package/_bundled_plugin/skills/define-security-policy/SKILL.md +3 -3
  35. package/dist/api.d.ts +7 -1
  36. package/dist/api.d.ts.map +1 -1
  37. package/dist/api.js +481 -60
  38. package/dist/api.js.map +1 -1
  39. package/dist/auth.js +10 -0
  40. package/dist/auth.js.map +1 -1
  41. package/dist/cli.d.ts +18 -2
  42. package/dist/cli.d.ts.map +1 -1
  43. package/dist/cli.js +962 -276
  44. package/dist/cli.js.map +1 -1
  45. package/dist/cloud-publish.d.ts.map +1 -1
  46. package/dist/cloud-publish.js +2 -207
  47. package/dist/cloud-publish.js.map +1 -1
  48. package/dist/component-plan.d.ts.map +1 -1
  49. package/dist/component-plan.js +116 -32
  50. package/dist/component-plan.js.map +1 -1
  51. package/dist/config.d.ts +1 -0
  52. package/dist/config.d.ts.map +1 -1
  53. package/dist/config.js +17 -2
  54. package/dist/config.js.map +1 -1
  55. package/dist/contract.d.ts +5 -10
  56. package/dist/contract.d.ts.map +1 -1
  57. package/dist/contract.js.map +1 -1
  58. package/dist/cost-model.d.ts +16 -0
  59. package/dist/cost-model.d.ts.map +1 -1
  60. package/dist/cost-model.js +57 -3
  61. package/dist/cost-model.js.map +1 -1
  62. package/dist/cost.d.ts.map +1 -1
  63. package/dist/cost.js +18 -3
  64. package/dist/cost.js.map +1 -1
  65. package/dist/custom-validation-prompt.js +1 -1
  66. package/dist/custom-validation-prompt.js.map +1 -1
  67. package/dist/deduplication/codex-review.d.ts +6 -1
  68. package/dist/deduplication/codex-review.d.ts.map +1 -1
  69. package/dist/deduplication/codex-review.js +72 -17
  70. package/dist/deduplication/codex-review.js.map +1 -1
  71. package/dist/deduplication/deduplication.d.ts +2 -0
  72. package/dist/deduplication/deduplication.d.ts.map +1 -1
  73. package/dist/deduplication/deduplication.js +99 -26
  74. package/dist/deduplication/deduplication.js.map +1 -1
  75. package/dist/deduplication/retry.d.ts +3 -0
  76. package/dist/deduplication/retry.d.ts.map +1 -0
  77. package/dist/deduplication/retry.js +15 -0
  78. package/dist/deduplication/retry.js.map +1 -0
  79. package/dist/deduplication/scan.d.ts +2 -0
  80. package/dist/deduplication/scan.d.ts.map +1 -1
  81. package/dist/deduplication/scan.js +4 -2
  82. package/dist/deduplication/scan.js.map +1 -1
  83. package/dist/feedback.d.ts +20 -0
  84. package/dist/feedback.d.ts.map +1 -0
  85. package/dist/feedback.js +121 -0
  86. package/dist/feedback.js.map +1 -0
  87. package/dist/findings-client.d.ts +7 -1
  88. package/dist/findings-client.d.ts.map +1 -1
  89. package/dist/findings-client.js +55 -10
  90. package/dist/findings-client.js.map +1 -1
  91. package/dist/findings-import.d.ts +44 -0
  92. package/dist/findings-import.d.ts.map +1 -0
  93. package/dist/findings-import.js +302 -0
  94. package/dist/findings-import.js.map +1 -0
  95. package/dist/import-scan.d.ts +27 -0
  96. package/dist/import-scan.d.ts.map +1 -0
  97. package/dist/import-scan.js +236 -0
  98. package/dist/import-scan.js.map +1 -0
  99. package/dist/index.d.ts +2 -0
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +1 -0
  102. package/dist/index.js.map +1 -1
  103. package/dist/knowledge-base.d.ts +1 -1
  104. package/dist/knowledge-base.d.ts.map +1 -1
  105. package/dist/knowledge-base.js +2 -2
  106. package/dist/knowledge-base.js.map +1 -1
  107. package/dist/multiscan.d.ts +2 -0
  108. package/dist/multiscan.d.ts.map +1 -1
  109. package/dist/multiscan.js +144 -52
  110. package/dist/multiscan.js.map +1 -1
  111. package/dist/publication-events.d.ts.map +1 -1
  112. package/dist/publication-events.js +7 -2
  113. package/dist/publication-events.js.map +1 -1
  114. package/dist/runtime.d.ts +5 -1
  115. package/dist/runtime.d.ts.map +1 -1
  116. package/dist/runtime.js +8 -2
  117. package/dist/runtime.js.map +1 -1
  118. package/dist/scan-dashboard.d.ts.map +1 -1
  119. package/dist/scan-dashboard.js +19 -6
  120. package/dist/scan-dashboard.js.map +1 -1
  121. package/dist/scan-logs.d.ts +29 -0
  122. package/dist/scan-logs.d.ts.map +1 -1
  123. package/dist/scan-logs.js +36 -5
  124. package/dist/scan-logs.js.map +1 -1
  125. package/dist/security-policy-cli.d.ts +39 -0
  126. package/dist/security-policy-cli.d.ts.map +1 -0
  127. package/dist/security-policy-cli.js +193 -0
  128. package/dist/security-policy-cli.js.map +1 -0
  129. package/dist/security-policy.d.ts +80 -0
  130. package/dist/security-policy.d.ts.map +1 -0
  131. package/dist/security-policy.js +672 -0
  132. package/dist/security-policy.js.map +1 -0
  133. package/dist/targets.d.ts +8 -1
  134. package/dist/targets.d.ts.map +1 -1
  135. package/dist/targets.js +243 -14
  136. package/dist/targets.js.map +1 -1
  137. package/package.json +8 -4
  138. package/_bundled_plugin/scripts/resolve_security_md.py +0 -158
package/dist/cli.js CHANGED
@@ -13,32 +13,38 @@ import { fileURLToPath, pathToFileURL } from "node:url";
13
13
  import { promisify, stripVTControlCharacters } from "node:util";
14
14
  import { Cli, z } from "incur";
15
15
  import { parse as parseToml } from "smol-toml";
16
- import { classifyConnectionFailure, createSecurityInternal, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, } from "./api.js";
17
- import { accountStatus } from "./auth.js";
16
+ import { classifyConnectionFailure, createSecurityInternal, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, runtimeScanAuthentication, selectedScanEnvironment, } from "./api.js";
17
+ import { accountStatus, CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, configuredCodexHome, readCodexHomeConfig, } from "./auth.js";
18
+ import { loadContract } from "./contract.js";
18
19
  import { publishScanToCustom } from "./custom-publish.js";
20
+ import { DEFAULT_DEDUPE_CONCURRENCY } from "./deduplication/deduplication.js";
19
21
  import { deduplicateScanInternal } from "./deduplication/scan.js";
20
22
  import { classifyScanSeverityInternal, classifyScanDirectorySeverityInternal, } from "./classify-scan-severity.js";
21
23
  import { resolveCompletedScan, resolveWorkflowScan, } from "./saved-scan.js";
22
24
  import { publishFindingsCsvToCloud, publishScanToCloud, } from "./cloud-publish.js";
23
25
  import { createBulkScanDiscoveryDependencies, runBulkScanWizard, } from "./bulk-scan-discovery.js";
24
- import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanModelConfiguration, scanModelProvider, } from "./config.js";
26
+ import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, hasCommandAuth, inlineToml, modelProviderConfigOverride, resolveCommandAuthConfig, mergedCodexConfig, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
25
27
  import { formatUsd } from "./cost.js";
26
- import { CodexSecurityError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
28
+ import { formatScanCostTokens, formatTokenUsage } from "./cost-model.js";
29
+ import { CodexSecurityError, AuthenticationRequiredError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
27
30
  import { GITHUB_ALERT_STATES, importGitHubCodeScanningAlerts, } from "./github.js";
28
31
  import { importLinearIssues, isLinearIssueIdentifier, resolveLinearApiKey, } from "./linear.js";
29
32
  import { runMultiscan } from "./multiscan.js";
30
33
  import { componentPlanSchema } from "./component-plan.js";
31
34
  import { runComponentScans, } from "./component-scan.js";
32
35
  import { checkScanPublication, forceTerminatePublicationProcesses as terminatePublishers, publishScan, } from "./publish.js";
33
- import { bundledPluginRoot, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, executablePathForSpawn, expandHome, prepareCodexSecurityCredentialHome, pythonUtf8Environment, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
36
+ import { importScan } from "./import-scan.js";
37
+ import { bundledPluginRoot, acquireCodexSecurityCredentialHomeLock, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, executablePathForSpawn, expandHome, prepareCodexSecurityCredentialHome, pythonUtf8Environment, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
34
38
  import { comparisonFindingGroups, comparisonForScan, matchScanFindingsInternal, unionFindingGroups, } from "./scan-comparison.js";
35
39
  import { scanActivitiesFromEvent } from "./scan-activity.js";
36
40
  import { CODEX_SECURITY_THREAD_SOURCES, } from "./thread-source.js";
37
- import { readScanLogs } from "./scan-logs.js";
41
+ import { findScanSession, readSavedScanLogs, } from "./scan-logs.js";
42
+ import { sendFeedback } from "./feedback.js";
38
43
  import { renderScanHistory, } from "./scan-history-renderer.js";
39
44
  import { ScanDashboard } from "./scan-dashboard.js";
45
+ import { policyDisplayData, runPolicyCommand, } from "./security-policy-cli.js";
40
46
  import { scanPhaseLabel as scanPhase, } from "./worker-progress.js";
41
- import { abortable, DiffTarget, } from "./targets.js";
47
+ import { abortable, DiffTarget, enclosingGitWorktreeRoots, } from "./targets.js";
42
48
  import { resolveTrustedExecutable } from "./trusted-executable.js";
43
49
  import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
44
50
  const PROGRESS_REFRESH_MILLISECONDS = 1_000;
@@ -83,6 +89,7 @@ const EXPORT_DEFAULT_OUTPUTS = {
83
89
  const VALUE_OPTIONS = new Set([
84
90
  "--port",
85
91
  "--workflow-id",
92
+ "--concurrency",
86
93
  "--auth",
87
94
  "--safety-identifier",
88
95
  "--path",
@@ -820,144 +827,268 @@ const DEFAULT_DEPENDENCIES = {
820
827
  matchFindings: (input, options) => matchScanFindingsInternal(input, options, { surface: "cli" }),
821
828
  };
822
829
  export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env, input) {
823
- const configuredHome = process.platform === "win32"
824
- ? environmentValue(processEnvironment, "CODEX_HOME")
825
- : processEnvironment["CODEX_HOME"];
826
- const environment = { ...processEnvironment };
827
- for (const name of Object.keys(environment)) {
828
- if (name.toUpperCase() === "CODEX_HOME")
829
- delete environment[name];
830
- }
831
- if (configuredHome?.trim()) {
832
- environment["CODEX_HOME"] = resolve(expandHome(configuredHome, processEnvironment));
833
- }
834
- const invocation = spawn(executablePathForSpawn(command.command), [...args], {
835
- env: environment,
836
- cwd: output?.appServer?.directory ?? parse(process.execPath).root,
837
- stdio: output === undefined
838
- ? input === undefined
839
- ? "inherit"
840
- : ["pipe", "inherit", "inherit"]
841
- : [
842
- output.appServer !== undefined || input !== undefined
843
- ? "pipe"
844
- : "ignore",
845
- "pipe",
846
- "pipe",
847
- ],
848
- windowsHide: true,
849
- });
850
- if (input !== undefined) {
851
- invocation.stdin?.on("error", () => { });
852
- invocation.stdin?.end(input);
853
- }
854
- let requestedSignal = null;
855
- let forcedTermination;
856
- let forceStatusCompletion = null;
857
- let forceCaptureCompletion = null;
858
- let invocationStatus;
859
- const requestTermination = (signal) => {
860
- requestedSignal = signal;
861
- invocation.kill(signal);
862
- if (forcedTermination !== undefined)
863
- return;
864
- forcedTermination = setTimeout(() => {
865
- forcedTermination = undefined;
866
- if (invocation.exitCode === null && invocation.signalCode === null) {
867
- invocation.kill("SIGKILL");
868
- }
869
- forceCaptureCompletion?.();
870
- invocation.stdout?.destroy();
871
- invocation.stderr?.destroy();
872
- forceStatusCompletion?.();
873
- }, CHILD_TERMINATION_GRACE_MS);
874
- };
875
- const onInterrupt = () => {
876
- requestTermination("SIGINT");
877
- };
878
- const onTerminate = () => {
879
- requestTermination("SIGTERM");
880
- };
881
- process.on("SIGINT", onInterrupt);
882
- process.on("SIGTERM", onTerminate);
830
+ let releaseCredentialHome;
883
831
  try {
884
- let diagnostic = "";
885
- invocation.stderr?.on("data", (chunk) => {
886
- diagnostic = `${diagnostic}${chunk.toString("utf8")}`.slice(-64 * 1_024);
832
+ let apiKey;
833
+ let authentication = null;
834
+ let modelProvider;
835
+ // runSkill selects auth; other process callers supply their own environment.
836
+ if (output?.auth !== undefined) {
837
+ const config = output.modelProvider !== undefined
838
+ ? {
839
+ model_provider: output.modelProvider,
840
+ ...(output.providerConfiguration === undefined
841
+ ? {}
842
+ : {
843
+ model_providers: {
844
+ [output.modelProvider]: output.providerConfiguration,
845
+ },
846
+ }),
847
+ }
848
+ : output.appServer === undefined
849
+ ? {}
850
+ : await readCodexHomeConfig(processEnvironment);
851
+ const provider = scanModelProvider(config);
852
+ const providerConfiguration = typeof provider === "string"
853
+ ? config["model_providers"]?.[provider]
854
+ : undefined;
855
+ const requiresOpenAiAuth = provider === undefined ||
856
+ provider === "openai" ||
857
+ providerConfiguration?.["requires_openai_auth"] === true;
858
+ modelProvider = output.modelProvider;
859
+ let credentialConfig;
860
+ authentication = scanAuthentication(processEnvironment, output.auth, provider, hasCommandAuth(config));
861
+ if (authentication.method === "stored_credentials" &&
862
+ isExternalModelProvider(provider)) {
863
+ const externalProvider = EXTERNAL_CODEX_PROVIDERS[provider];
864
+ throw new AuthenticationRequiredError(`Set ${externalProvider.env_key} to run ${output.command} through ${externalProvider.name}.`);
865
+ }
866
+ let selected = selectedScanEnvironment(processEnvironment, authentication.method === "command" ? "chatgpt" : output.auth, provider);
867
+ if (authentication.method === "stored_credentials" &&
868
+ requiresOpenAiAuth) {
869
+ const directory = await realpath(output.directory ?? output.appServer?.directory ?? process.cwd());
870
+ const protectedRoots = [
871
+ directory,
872
+ ...(await enclosingGitWorktreeRoots(directory)),
873
+ ];
874
+ const codexHome = await prepareCodexSecurityCredentialHome(selected, (path) => requireOutputOutsideRepositories(protectedRoots, path, "runtime"));
875
+ releaseCredentialHome =
876
+ await acquireCodexSecurityCredentialHomeLock(codexHome);
877
+ let credentialsAvailable;
878
+ const ambientConfig = await readCodexHomeConfig(selected);
879
+ credentialConfig = await readCodexHomeConfig({
880
+ ...selected,
881
+ CODEX_HOME: codexHome,
882
+ });
883
+ // Let native Codex apply the ambient home's project-trust decisions.
884
+ for (const key of [
885
+ ...CODEX_AUTH_CONFIG_KEYS,
886
+ "projects",
887
+ "project_root_markers",
888
+ ]) {
889
+ const value = ambientConfig[key];
890
+ if (value === undefined)
891
+ delete credentialConfig[key];
892
+ else
893
+ credentialConfig[key] = value;
894
+ }
895
+ if (typeof provider === "string")
896
+ credentialConfig["model_provider"] = provider;
897
+ else
898
+ delete credentialConfig["model_provider"];
899
+ delete credentialConfig["profile"];
900
+ if (typeof provider !== "string" || providerConfiguration === undefined)
901
+ delete credentialConfig["model_providers"];
902
+ else
903
+ credentialConfig["model_providers"] = {
904
+ [provider]: providerConfiguration,
905
+ };
906
+ await writeCodexConfig(join(codexHome, "config.toml"), credentialConfig);
907
+ credentialsAvailable = await initialCredentialsAvailable(selected, configuredCodexHome(selected), codexHome);
908
+ selected = {
909
+ ...selected,
910
+ CODEX_HOME: codexHome,
911
+ CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(selected),
912
+ };
913
+ if (!credentialsAvailable &&
914
+ !(await accountStatus(command, selected)).authenticated) {
915
+ throw new AuthenticationRequiredError(NO_CREDENTIALS_MESSAGE);
916
+ }
917
+ authentication = await runtimeScanAuthentication(selected, codexHome, output.auth, provider);
918
+ }
919
+ else if (authentication.method === "api_key" && requiresOpenAiAuth) {
920
+ apiKey = environmentValue(selected, authentication.source)?.trim();
921
+ // Match the SDK's key selection for native and nested plugin workers.
922
+ selected = {
923
+ ...selectedScanEnvironment(selected, "chatgpt"),
924
+ CODEX_API_KEY: apiKey,
925
+ };
926
+ if (output.appServer !== undefined) {
927
+ args = [
928
+ ...args,
929
+ "--config",
930
+ 'cli_auth_credentials_store="ephemeral"',
931
+ ];
932
+ }
933
+ }
934
+ if (output.appServer === undefined) {
935
+ const authConfig = credentialConfig ?? (await readCodexHomeConfig(selected));
936
+ args = [
937
+ ...args,
938
+ ...CODEX_AUTH_CONFIG_KEYS.flatMap((key) => authConfig[key] === undefined
939
+ ? []
940
+ : ["--config", `${key}=${inlineToml(authConfig[key])}`]),
941
+ ];
942
+ }
943
+ if (output.appServer === undefined)
944
+ await releaseCredentialHome?.();
945
+ processEnvironment = selected;
946
+ }
947
+ const configuredHome = process.platform === "win32"
948
+ ? environmentValue(processEnvironment, "CODEX_HOME")
949
+ : processEnvironment["CODEX_HOME"];
950
+ const environment = { ...processEnvironment };
951
+ for (const name of Object.keys(environment)) {
952
+ if (name.toUpperCase() === "CODEX_HOME")
953
+ delete environment[name];
954
+ }
955
+ if (configuredHome?.trim()) {
956
+ environment["CODEX_HOME"] = resolve(expandHome(configuredHome, processEnvironment));
957
+ }
958
+ const invocation = spawn(executablePathForSpawn(command.command), [...args], {
959
+ env: environment,
960
+ cwd: output?.appServer?.directory ?? parse(process.execPath).root,
961
+ stdio: output === undefined
962
+ ? input === undefined
963
+ ? "inherit"
964
+ : ["pipe", "inherit", "inherit"]
965
+ : [
966
+ output.appServer !== undefined || input !== undefined
967
+ ? "pipe"
968
+ : "ignore",
969
+ "pipe",
970
+ "pipe",
971
+ ],
972
+ windowsHide: true,
887
973
  });
888
- const captured = output === undefined || invocation.stdout === null
889
- ? Promise.resolve(undefined)
890
- : Promise.race([
891
- readSkillCommandOutput(invocation.stdout, output.appServer === undefined
892
- ? undefined
893
- : {
894
- directory: output.appServer.directory,
895
- prompt: output.appServer.prompt,
896
- threadSource: output.appServer.threadSource,
897
- input: invocation.stdin,
898
- sandbox: output.appServer.sandbox,
899
- onEvent: output.appServer.onEvent,
974
+ if (input !== undefined) {
975
+ invocation.stdin?.on("error", () => { });
976
+ invocation.stdin?.end(input);
977
+ }
978
+ let requestedSignal = null;
979
+ let forcedTermination;
980
+ let forceStatusCompletion = null;
981
+ let forceCaptureCompletion = null;
982
+ let invocationStatus;
983
+ const requestTermination = (signal) => {
984
+ requestedSignal = signal;
985
+ invocation.kill(signal);
986
+ if (forcedTermination !== undefined)
987
+ return;
988
+ forcedTermination = setTimeout(() => {
989
+ forcedTermination = undefined;
990
+ if (invocation.exitCode === null && invocation.signalCode === null) {
991
+ invocation.kill("SIGKILL");
992
+ }
993
+ forceCaptureCompletion?.();
994
+ invocation.stdout?.destroy();
995
+ invocation.stderr?.destroy();
996
+ forceStatusCompletion?.();
997
+ }, CHILD_TERMINATION_GRACE_MS);
998
+ };
999
+ const onInterrupt = () => {
1000
+ requestTermination("SIGINT");
1001
+ };
1002
+ const onTerminate = () => {
1003
+ requestTermination("SIGTERM");
1004
+ };
1005
+ process.on("SIGINT", onInterrupt);
1006
+ process.on("SIGTERM", onTerminate);
1007
+ try {
1008
+ let diagnostic = "";
1009
+ invocation.stderr?.on("data", (chunk) => {
1010
+ diagnostic = `${diagnostic}${chunk.toString("utf8")}`.slice(-64 * 1_024);
1011
+ });
1012
+ const captured = output === undefined || invocation.stdout === null
1013
+ ? Promise.resolve(undefined)
1014
+ : Promise.race([
1015
+ readSkillCommandOutput(invocation.stdout, output.appServer === undefined
1016
+ ? undefined
1017
+ : {
1018
+ apiKey,
1019
+ modelProvider,
1020
+ onThreadStarted: releaseCredentialHome,
1021
+ directory: output.appServer.directory,
1022
+ prompt: output.appServer.prompt,
1023
+ threadSource: output.appServer.threadSource,
1024
+ input: invocation.stdin,
1025
+ sandbox: output.appServer.sandbox,
1026
+ onEvent: output.appServer.onEvent,
1027
+ }),
1028
+ new Promise((resolve) => {
1029
+ forceCaptureCompletion = () => resolve(undefined);
900
1030
  }),
901
- new Promise((resolve) => {
902
- forceCaptureCompletion = () => resolve(undefined);
903
- }),
904
- ]);
905
- invocationStatus = new Promise((resolve, reject) => {
906
- let completed = false;
907
- const complete = (code, signal) => {
908
- if (completed)
909
- return;
910
- completed = true;
911
- forceStatusCompletion = null;
912
- resolve(requestedSignal === "SIGINT" || signal === "SIGINT"
913
- ? 130
914
- : requestedSignal === "SIGTERM" || signal === "SIGTERM"
915
- ? 143
916
- : code ?? 1);
917
- };
918
- forceStatusCompletion = () => complete(null, null);
919
- invocation.once("error", (error) => {
920
- if (completed)
921
- return;
922
- completed = true;
923
- forceStatusCompletion = null;
924
- reject(error);
1031
+ ]);
1032
+ invocationStatus = new Promise((resolve, reject) => {
1033
+ let completed = false;
1034
+ const complete = (code, signal) => {
1035
+ if (completed)
1036
+ return;
1037
+ completed = true;
1038
+ forceStatusCompletion = null;
1039
+ resolve(requestedSignal === "SIGINT" || signal === "SIGINT"
1040
+ ? 130
1041
+ : requestedSignal === "SIGTERM" || signal === "SIGTERM"
1042
+ ? 143
1043
+ : code ?? 1);
1044
+ };
1045
+ forceStatusCompletion = () => complete(null, null);
1046
+ invocation.once("error", (error) => {
1047
+ if (completed)
1048
+ return;
1049
+ completed = true;
1050
+ forceStatusCompletion = null;
1051
+ reject(error);
1052
+ });
1053
+ invocation.once(output === undefined ? "exit" : "close", complete);
925
1054
  });
926
- invocation.once(output === undefined ? "exit" : "close", complete);
927
- });
928
- let [status, events] = await Promise.all([invocationStatus, captured]);
929
- if (status === 0 && output?.appServer !== undefined && events?.error) {
930
- status = 1;
931
- }
932
- if (output === undefined || status === 130 || status === 143)
933
- return status;
934
- if (status !== 0) {
935
- await writeCliOutput(output.stderr, `codex-security: ${skillCommandFailure(output.command, status, events?.error ?? diagnostic)}\n`);
1055
+ let [status, events] = await Promise.all([invocationStatus, captured]);
1056
+ if (status === 0 && output?.appServer !== undefined && events?.error) {
1057
+ status = 1;
1058
+ }
1059
+ if (output === undefined || status === 130 || status === 143)
1060
+ return status;
1061
+ if (status !== 0) {
1062
+ await writeCliOutput(output.stderr, `codex-security: ${skillCommandFailure(output.command, status, events?.error ?? diagnostic, authentication)}\n`);
1063
+ return status;
1064
+ }
1065
+ if ((output.appServer !== undefined && events?.completed !== true) ||
1066
+ events?.message === undefined ||
1067
+ events.message.trim().length === 0) {
1068
+ await writeCliOutput(output.stderr, `codex-security: Codex did not return a completed ${output.command} response.\n`);
1069
+ return 2;
1070
+ }
1071
+ await writeCliOutput(output.stdout, `${events.message.trimEnd()}\n`);
936
1072
  return status;
937
1073
  }
938
- if ((output.appServer !== undefined && events?.completed !== true) ||
939
- events?.message === undefined ||
940
- events.message.trim().length === 0) {
941
- await writeCliOutput(output.stderr, `codex-security: Codex did not return a completed ${output.command} response.\n`);
942
- return 2;
1074
+ catch (error) {
1075
+ invocation.stdout?.destroy();
1076
+ invocation.stderr?.destroy();
1077
+ requestTermination("SIGTERM");
1078
+ await invocationStatus?.catch(() => undefined);
1079
+ throw error;
1080
+ }
1081
+ finally {
1082
+ if (forcedTermination !== undefined)
1083
+ clearTimeout(forcedTermination);
1084
+ forceStatusCompletion = null;
1085
+ forceCaptureCompletion = null;
1086
+ process.off("SIGINT", onInterrupt);
1087
+ process.off("SIGTERM", onTerminate);
943
1088
  }
944
- await writeCliOutput(output.stdout, `${events.message.trimEnd()}\n`);
945
- return status;
946
- }
947
- catch (error) {
948
- invocation.stdout?.destroy();
949
- invocation.stderr?.destroy();
950
- requestTermination("SIGTERM");
951
- await invocationStatus?.catch(() => undefined);
952
- throw error;
953
1089
  }
954
1090
  finally {
955
- if (forcedTermination !== undefined)
956
- clearTimeout(forcedTermination);
957
- forceStatusCompletion = null;
958
- forceCaptureCompletion = null;
959
- process.off("SIGINT", onInterrupt);
960
- process.off("SIGTERM", onTerminate);
1091
+ await releaseCredentialHome?.();
961
1092
  }
962
1093
  }
963
1094
  async function writeCliOutput(output, value) {
@@ -1015,10 +1146,11 @@ export function exportEnvironment(environment = process.env) {
1015
1146
  .map((key) => [key, environment[key]])));
1016
1147
  }
1017
1148
  export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
1018
- argv = defaultListCommand(argv);
1149
+ argv = normalizeScanImportArguments(defaultListCommand(argv));
1150
+ const policyFullOutput = argv[cliCommandIndex(argv)] === "policy" && argv.includes("--full-output");
1019
1151
  const positionals = [];
1020
1152
  const argumentError = validateCliArguments(argv, positionals);
1021
- if (argumentError !== undefined) {
1153
+ if (argumentError !== undefined && !policyFullOutput) {
1022
1154
  errorOutput.write(`codex-security: ${argumentError}\n`);
1023
1155
  return 2;
1024
1156
  }
@@ -1045,6 +1177,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1045
1177
  let frameworkOutput = "";
1046
1178
  let renderedHistory;
1047
1179
  let renderedPublication;
1180
+ let renderedPolicy;
1181
+ const runImport = (options) => runScanImport(options, errorOutput, dependencies);
1048
1182
  const history = async (args, select = (value) => value) => {
1049
1183
  try {
1050
1184
  return await select(await dependencies.runWorkbench(args));
@@ -1320,26 +1454,62 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1320
1454
  const scanId = args.scanId ?? (await latestScans(1, "any"))?.[0]?.scanId;
1321
1455
  if (scanId === undefined)
1322
1456
  return;
1323
- return await history(["get-scan", "--scan-id", scanId], async (value) => {
1324
- const scan = value["scan"];
1325
- const threadId = scan.continuationThreadId;
1326
- if (!threadId) {
1327
- throw new CodexSecurityError(`No session is associated with scan ${scan.scanId}.`);
1457
+ return await history(["get-scan", "--scan-id", scanId], async (value) => (await readSavedScanLogs(value["scan"], codexSecurityCredentialHome(dependencies.environment))));
1458
+ },
1459
+ })
1460
+ .command("resume", {
1461
+ description: "Resume an interrupted Deep Scan in its original session.",
1462
+ mcp: false,
1463
+ args: z.object({
1464
+ scanId: z.string().min(1).describe("Interrupted Deep Scan identifier."),
1465
+ }),
1466
+ options: z.object({
1467
+ verbose: z
1468
+ .boolean()
1469
+ .default(false)
1470
+ .describe("Print scan diagnostics to stderr."),
1471
+ }),
1472
+ output: z.record(z.string(), z.unknown()).optional(),
1473
+ async run({ args, error: incurError, options }) {
1474
+ let scanArguments;
1475
+ try {
1476
+ const saved = await dependencies.runWorkbench([
1477
+ "get-cli-scan-resume",
1478
+ "--scan-id",
1479
+ args.scanId,
1480
+ ]);
1481
+ if (typeof saved["scanId"] !== "string" ||
1482
+ typeof saved["scanDir"] !== "string") {
1483
+ throw new CodexSecurityError("The workbench returned invalid scan resume context.");
1328
1484
  }
1329
- return (await readScanLogs({
1330
- scanId: scan.scanId,
1331
- threadId,
1332
- codexHome: codexSecurityCredentialHome(dependencies.environment),
1333
- scanDirectory: scan.mode === "deep" ? scan.scanDir : undefined,
1334
- completedAt: scan.progress?.status === "running"
1335
- ? null
1336
- : scan.progress?.status === "complete" ||
1337
- scan.progress?.status === "failed" ||
1338
- scan.progress?.status === "canceled"
1339
- ? scan.progress.updatedAt ?? ""
1340
- : "",
1341
- }));
1342
- });
1485
+ scanArguments = scanArgumentsFromRecipe(saved["recipe"], saved["scanId"]);
1486
+ scanArguments.resumeScanId = saved["scanId"];
1487
+ scanArguments.outputDir = saved["scanDir"];
1488
+ scanArguments.parentScanId = undefined;
1489
+ // Resume uses the installed engine with the saved recipe and checkpoints.
1490
+ scanArguments.expectedPluginVersion = undefined;
1491
+ scanArguments.verbose = options.verbose;
1492
+ }
1493
+ catch (error) {
1494
+ const message = errorMessage(error);
1495
+ errorOutput.write(`codex-security: ${message}\n`);
1496
+ exitCode = 2;
1497
+ return incurError({
1498
+ code: "SCAN_RESUME_UNAVAILABLE",
1499
+ message,
1500
+ exitCode,
1501
+ });
1502
+ }
1503
+ const outcome = await runScan(scanArguments, errorOutput, dependencies);
1504
+ exitCode = outcome.exitCode;
1505
+ if (outcome.error !== undefined) {
1506
+ return incurError({
1507
+ code: "SCAN_FAILED",
1508
+ message: outcome.error,
1509
+ exitCode,
1510
+ });
1511
+ }
1512
+ return outcome.data;
1343
1513
  },
1344
1514
  })
1345
1515
  .command("rerun", {
@@ -1374,6 +1544,36 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1374
1544
  "--scan-id",
1375
1545
  scanId,
1376
1546
  ]);
1547
+ if (recipe !== undefined &&
1548
+ isJsonObject(recipe) &&
1549
+ recipe["import"] !== undefined &&
1550
+ isJsonObject(recipe["import"])) {
1551
+ if (options.validationPromptFile !== undefined) {
1552
+ throw new CodexSecurityError("--validation-prompt-file is not supported when rerunning an imported scan; imports do not perform security analysis.");
1553
+ }
1554
+ const imported = recipe["import"];
1555
+ const sourcePath = imported["sourcePath"];
1556
+ const format = imported["format"];
1557
+ if (typeof sourcePath !== "string" ||
1558
+ sourcePath.length === 0 ||
1559
+ (format !== "csv" && format !== "json")) {
1560
+ throw new CodexSecurityError("The saved scan recipe contains invalid import settings.");
1561
+ }
1562
+ const outcome = await runImport({
1563
+ sourcePath,
1564
+ format,
1565
+ parentScanId: scanId,
1566
+ });
1567
+ exitCode = outcome.exitCode;
1568
+ if (outcome.error !== undefined) {
1569
+ return incurError({
1570
+ code: "SCAN_IMPORT_FAILED",
1571
+ message: outcome.error,
1572
+ exitCode,
1573
+ });
1574
+ }
1575
+ return outcome.data;
1576
+ }
1377
1577
  scanArguments = scanArgumentsFromRecipe(recipe, scanId, options.validationPromptFile);
1378
1578
  scanArguments.verbose = options.verbose;
1379
1579
  }
@@ -2051,15 +2251,171 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2051
2251
  },
2052
2252
  });
2053
2253
  const cli = Cli.create("codex-security", {
2054
- description: "Run, import, validate, patch, verify fixes, export, and publish Codex Security findings.",
2254
+ description: "Draft security policies; run, import, validate, patch, verify fixes, export, and publish Codex Security findings.",
2055
2255
  version: VERSION,
2056
2256
  mcp: {
2057
2257
  command: "npx --yes @openai/codex-security --mcp",
2058
2258
  instructions: "Use info for read-only SDK metadata. Scans and other state-changing commands are CLI-only because the MCP transport cannot cancel active commands.",
2059
2259
  },
2260
+ })
2261
+ .command("policy", {
2262
+ description: "Draft SECURITY.md guidance for future scans and owner review.",
2263
+ destructive: true,
2264
+ mcp: false,
2265
+ args: z.object({
2266
+ repository: z
2267
+ .string()
2268
+ .optional()
2269
+ .describe("Repository or component directory (default: current directory)."),
2270
+ }),
2271
+ options: z.object({
2272
+ path: optionValue("--path")
2273
+ .optional()
2274
+ .describe("Generate SECURITY.md for this repository-relative component directory."),
2275
+ knowledgeBase: z
2276
+ .array(optionValue("--knowledge-base"))
2277
+ .default([])
2278
+ .describe("Add architecture or security-context files; repeat for multiple paths."),
2279
+ outputDir: optionValue("--output-dir")
2280
+ .optional()
2281
+ .describe("Private artifact directory outside the repository (default: Codex Security state)."),
2282
+ headless: z
2283
+ .boolean()
2284
+ .default(false)
2285
+ .describe("Skip owner questions and authentication prompts."),
2286
+ dryRun: z
2287
+ .boolean()
2288
+ .default(false)
2289
+ .describe("Validate local generation inputs without starting Codex."),
2290
+ auth: z
2291
+ .enum(["auto", "chatgpt", "api-key"])
2292
+ .default("auto")
2293
+ .describe("Select ChatGPT, API-key, or automatic authentication."),
2294
+ model: optionValue("--model")
2295
+ .optional()
2296
+ .describe(`Model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`),
2297
+ effort: effortOption(),
2298
+ provider: PROVIDER_OPTION.describe("Inference provider for policy generation."),
2299
+ maxCost: z
2300
+ .number()
2301
+ .positive()
2302
+ .optional()
2303
+ .describe("Stop when estimated total USD cost across all three stages exceeds AMOUNT."),
2304
+ pluginPath: optionValue("--plugin-path")
2305
+ .optional()
2306
+ .describe(PLUGIN_PATH_DESCRIPTION),
2307
+ python: optionValue("--python")
2308
+ .optional()
2309
+ .describe(PYTHON_PATH_DESCRIPTION),
2310
+ codex: z
2311
+ .array(optionValue("--codex"))
2312
+ .default([])
2313
+ .describe(CODEX_OVERRIDE_DESCRIPTION),
2314
+ }),
2315
+ examples: [
2316
+ { args: { repository: "." } },
2317
+ { args: { repository: "." }, options: { path: "services/api" } },
2318
+ ],
2319
+ hint: "Save a draft for review:\n" +
2320
+ " codex-security policy . --headless --output-dir /path/outside/repository/policy --json",
2321
+ output: z
2322
+ .union([z.record(z.string(), z.unknown()), z.string()])
2323
+ .optional(),
2324
+ async run({ args, error: incurError, options, format, formatExplicit }) {
2325
+ const outputOptions = argv.filter((argument) => OUTPUT_OPTION.test(argument));
2326
+ const explicitOutput = formatExplicit || outputOptions.length > 0;
2327
+ const transformOutput = outputOptions.some((argument) => !argument.startsWith("--format"));
2328
+ const filterOutput = outputOptions.some((argument) => argument.startsWith("--filter-output"));
2329
+ const fail = (message, failureExitCode) => {
2330
+ exitCode = failureExitCode;
2331
+ return incurError({
2332
+ code: "POLICY_FAILED",
2333
+ message,
2334
+ exitCode: failureExitCode,
2335
+ });
2336
+ };
2337
+ try {
2338
+ if (argumentError !== undefined)
2339
+ return fail(argumentError, 2);
2340
+ const directory = dependencies.currentDirectory();
2341
+ const outcome = await withTerminalErrorsHandled(errorOutput, () => runPolicyCommand({
2342
+ repository: resolveCliPath(directory, args.repository ?? "."),
2343
+ config: {
2344
+ pluginPath: options.pluginPath,
2345
+ pythonPath: options.python,
2346
+ codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
2347
+ },
2348
+ generation: {
2349
+ auth: options.auth,
2350
+ path: options.path,
2351
+ knowledgeBasePaths: options.knowledgeBase.map((path) => resolveCliPath(directory, path)),
2352
+ outputDir: options.outputDir === undefined
2353
+ ? undefined
2354
+ : resolveCliPath(directory, options.outputDir),
2355
+ maxCostUsd: options.maxCost,
2356
+ },
2357
+ headless: options.headless || explicitOutput,
2358
+ dryRun: options.dryRun,
2359
+ format,
2360
+ explicitOutput,
2361
+ }, {
2362
+ createSecurity: dependencies.createPolicySecurity ??
2363
+ ((config) => createSecurityInternal(config, { surface: "cli" })),
2364
+ chooseAuthentication: (config, auth, signal) => chooseInteractiveAuthentication({
2365
+ auth,
2366
+ provider: scanModelProvider({
2367
+ ...DEFAULT_CODEX_CONFIG,
2368
+ ...config.codexOverrides,
2369
+ }),
2370
+ command: "policy",
2371
+ signal,
2372
+ }, errorOutput, dependencies),
2373
+ prompt: dependencies.policyPrompt ??
2374
+ createBulkScanDiscoveryDependencies({
2375
+ output: errorOutput,
2376
+ now: dependencies.now,
2377
+ currentDirectory: dependencies.currentDirectory,
2378
+ }).prompt,
2379
+ environment: dependencies.environment,
2380
+ errorOutput,
2381
+ now: dependencies.now,
2382
+ addSignalListener: dependencies.addSignalListener,
2383
+ removeSignalListener: dependencies.removeSignalListener,
2384
+ forceExit: dependencies.forceExit,
2385
+ }));
2386
+ exitCode = outcome.exitCode;
2387
+ if (exitCode !== 0) {
2388
+ return fail(outcome.error ?? "Policy command failed.", exitCode);
2389
+ }
2390
+ if (format === "md" &&
2391
+ outcome.markdown !== undefined &&
2392
+ !filterOutput) {
2393
+ if (!transformOutput)
2394
+ renderedPolicy = outcome.markdown;
2395
+ return outcome.markdown;
2396
+ }
2397
+ return format === "toon" && !explicitOutput && !options.dryRun
2398
+ ? undefined
2399
+ : format === "toon"
2400
+ ? policyDisplayData(outcome.data)
2401
+ : outcome.data;
2402
+ }
2403
+ catch (error) {
2404
+ const message = safeErrorMessage(error);
2405
+ try {
2406
+ errorOutput.write(`codex-security: ${message}\n`);
2407
+ }
2408
+ catch { }
2409
+ return fail(message, 2);
2410
+ }
2411
+ },
2060
2412
  })
2061
2413
  .command("scan", {
2062
2414
  description: "Run a Codex Security scan.",
2415
+ hint: "Import existing findings without security analysis:\n" +
2416
+ " codex-security scan import --csv findings.csv\n" +
2417
+ " codex-security scan import --json findings.json\n" +
2418
+ "Use ./import to scan a repository named import.",
2063
2419
  destructive: true,
2064
2420
  mcp: false,
2065
2421
  args: z.object({
@@ -2429,6 +2785,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2429
2785
  destructive: true,
2430
2786
  mcp: false,
2431
2787
  options: z.object({
2788
+ concurrency: z
2789
+ .number()
2790
+ .int()
2791
+ .positive()
2792
+ .default(DEFAULT_DEDUPE_CONCURRENCY)
2793
+ .describe("Maximum concurrent dedupe jobs across Luna and Sol; use 1 for serial execution."),
2432
2794
  workflowId: optionValue("--workflow-id")
2433
2795
  .optional()
2434
2796
  .describe("Resume the named local findings workflow; reuses its saved scan."),
@@ -2468,6 +2830,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2468
2830
  throw new CodexSecurityError("Deduplication requires --scan or --workflow-id.");
2469
2831
  return await (dependencies.deduplicateScan ?? deduplicateScanInternal)(scanId, {
2470
2832
  findingsUrl: options.findingsUrl,
2833
+ concurrency: options.concurrency,
2471
2834
  ...(options.workflowId === undefined
2472
2835
  ? {}
2473
2836
  : { workflowId: options.workflowId }),
@@ -2720,6 +3083,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2720
3083
  .describe("CSV repository list; omit to discover repositories interactively."),
2721
3084
  }),
2722
3085
  options: z.object({
3086
+ recover: z
3087
+ .boolean()
3088
+ .default(false)
3089
+ .describe("Recover failed or interrupted attempts in an existing campaign, preserving their artifacts and checkouts."),
2723
3090
  outputDir: z
2724
3091
  .string()
2725
3092
  .min(1, "--output-dir must not be empty.")
@@ -2799,6 +3166,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2799
3166
  dependencies.addSignalListener("SIGTERM", onTerminate);
2800
3167
  try {
2801
3168
  const currentDirectory = dependencies.currentDirectory();
3169
+ if (options.recover && args.input === undefined) {
3170
+ throw new Error("Bulk recovery requires the original repository CSV and --output-dir.");
3171
+ }
2802
3172
  const prompts = await readPromptFiles(currentDirectory, options.scanPromptFile, options.postScanPromptFile, currentDirectory, options.validationPromptFile);
2803
3173
  let inputPath;
2804
3174
  let outputDir;
@@ -2844,6 +3214,76 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2844
3214
  codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
2845
3215
  },
2846
3216
  createSecurity: dependencies.createSecurity,
3217
+ ...(options.recover
3218
+ ? {
3219
+ recoverScan: async (scanDir) => {
3220
+ const history = await dependencies.runWorkbench(["list-scans", "--scan-root", scanDir], undefined, controller.signal);
3221
+ const scan = history["scans"].find((scan) => resolve(scan.scanDir) === scanDir);
3222
+ if (scan === undefined)
3223
+ return undefined;
3224
+ const status = scan["progress"]["status"];
3225
+ if (status === "complete") {
3226
+ const contract = await loadContract(scanDir, {
3227
+ pluginRoot: await bundledPluginRoot(),
3228
+ expectedScanId: scan.scanId,
3229
+ signal: controller.signal,
3230
+ });
3231
+ return {
3232
+ coverage: contract.coverage,
3233
+ cost: scan["cost"] ??
3234
+ null,
3235
+ };
3236
+ }
3237
+ if (status !== "running" || scan["mode"] !== "deep")
3238
+ return undefined;
3239
+ const saved = await dependencies.runWorkbench([
3240
+ "get-cli-scan-resume",
3241
+ "--scan-id",
3242
+ scan.scanId,
3243
+ "--allow-unavailable",
3244
+ ], undefined, controller.signal);
3245
+ if (typeof saved["unavailable"] === "string") {
3246
+ errorOutput.write(`codex-security: ${scan.scanId}: ${saved["unavailable"]} Preserving this attempt and starting a new one.\n`);
3247
+ return undefined;
3248
+ }
3249
+ const session = typeof saved["threadId"] === "string"
3250
+ ? await findScanSession(codexSecurityCredentialHome(dependencies.environment), saved["threadId"])
3251
+ : null;
3252
+ if (session?.workingDirectory !== scanDir) {
3253
+ errorOutput.write(`codex-security: ${scan.scanId}: Original session logs are unavailable. Preserving this attempt and starting a new one.\n`);
3254
+ return undefined;
3255
+ }
3256
+ const recipe = scanArgumentsFromRecipe(saved["recipe"], scan.scanId);
3257
+ const security = dependencies.createSecurity({
3258
+ pluginPath: options.pluginPath,
3259
+ pythonPath: options.python,
3260
+ codexOverrides: recipe.codexOverrides,
3261
+ });
3262
+ try {
3263
+ return await security.run(recipe.repository, {
3264
+ resumeScanId: scan.scanId,
3265
+ outputDir: scanDir,
3266
+ mode: recipe.mode,
3267
+ target: targetFromArguments(recipe),
3268
+ knowledgeBasePaths: recipe.knowledgeBasePaths,
3269
+ workers: recipe.workers,
3270
+ subagents: recipe.subagents,
3271
+ stopAfterNoNew: recipe.stopAfterNoNew,
3272
+ maxDiscoveryRuns: recipe.maxDiscoveryRuns,
3273
+ maxTimeHours: recipe.maxTimeHours,
3274
+ maxCostUsd: recipe.maxCostUsd,
3275
+ failureSeverity: recipe.failOnSeverity,
3276
+ safetyIdentifier: recipe.safetyIdentifier,
3277
+ postScanPrompt: recipe.postScanPrompt ?? prompts.postScanPrompt,
3278
+ signal: controller.signal,
3279
+ });
3280
+ }
3281
+ finally {
3282
+ await security.close();
3283
+ }
3284
+ },
3285
+ }
3286
+ : {}),
2847
3287
  signal: controller.signal,
2848
3288
  onProgress: ({ repository, status, attempt, error, warning }) => {
2849
3289
  const detail = error ?? warning;
@@ -2929,6 +3369,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2929
3369
  .describe("Finding text or a file containing findings."),
2930
3370
  }),
2931
3371
  options: z.object({
3372
+ auth: z
3373
+ .enum(SCAN_AUTH_MODES)
3374
+ .default("auto")
3375
+ .describe("Credential source: auto, chatgpt, or api-key."),
2932
3376
  effort: effortOption(),
2933
3377
  codex: z
2934
3378
  .array(optionValue("--codex"))
@@ -2937,7 +3381,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2937
3381
  }),
2938
3382
  async run({ options }) {
2939
3383
  try {
2940
- exitCode = await runSkill("validation", positionals, options.codex, options.effort, output, errorOutput, dependencies);
3384
+ exitCode = await runSkill("validation", positionals, options.codex, options.effort, output, errorOutput, dependencies, { auth: options.auth });
2941
3385
  }
2942
3386
  catch (error) {
2943
3387
  exitCode = 2;
@@ -2957,6 +3401,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2957
3401
  .describe("Finding text, a file, or a saved finding identifier."),
2958
3402
  }),
2959
3403
  options: z.object({
3404
+ auth: z
3405
+ .enum(SCAN_AUTH_MODES)
3406
+ .default("auto")
3407
+ .describe("Credential source: auto, chatgpt, or api-key."),
2960
3408
  effort: effortOption(),
2961
3409
  scan: optionValue("--scan")
2962
3410
  .optional()
@@ -3048,6 +3496,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3048
3496
  ...(selected === undefined
3049
3497
  ? {}
3050
3498
  : { findings: selected.findings }),
3499
+ auth: options.auth,
3051
3500
  verificationIds: identifiers,
3052
3501
  environment,
3053
3502
  onEvent: progress.observe.bind(progress),
@@ -3115,6 +3564,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3115
3564
  .describe("Issue text or a file containing issues."),
3116
3565
  }),
3117
3566
  options: z.object({
3567
+ auth: z
3568
+ .enum(SCAN_AUTH_MODES)
3569
+ .default("auto")
3570
+ .describe("Credential source: auto, chatgpt, or api-key."),
3118
3571
  effort: effortOption(),
3119
3572
  scan: optionValue("--scan")
3120
3573
  .optional()
@@ -3158,6 +3611,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3158
3611
  options.linearFilter !== undefined ||
3159
3612
  options.linearApiKey !== undefined ||
3160
3613
  options.effort !== undefined ||
3614
+ options.auth !== "auto" ||
3161
3615
  options.codex.length > 0) {
3162
3616
  throw new CodexSecurityError("--resume-pr cannot be combined with patch inputs or options.");
3163
3617
  }
@@ -3186,7 +3640,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3186
3640
  const patchRiskBase = options.assessPatchRisk
3187
3641
  ? await snapshotPatchTree(selected.repository, dependencies)
3188
3642
  : undefined;
3189
- const patches = await runFindingPatches(selected, options.codex, options.effort, errorOutput, dependencies);
3643
+ const patches = await runFindingPatches(selected, options.codex, options.effort, errorOutput, dependencies, { auth: options.auth });
3190
3644
  exitCode = patchExitCode(patches);
3191
3645
  let patchRisk;
3192
3646
  if (options.assessPatchRisk && exitCode === 0) {
@@ -3198,6 +3652,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3198
3652
  files,
3199
3653
  codexOverrides: options.codex,
3200
3654
  effort: options.effort,
3655
+ auth: options.auth,
3201
3656
  }, errorOutput, dependencies);
3202
3657
  }
3203
3658
  }
@@ -3246,16 +3701,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3246
3701
  if (options.createPr) {
3247
3702
  await requireCleanPatchPullRequestBase(repository, patchBase, dependencies);
3248
3703
  }
3249
- exitCode = await runSkill("fix-finding", [...positionals, ...imports], options.codex, options.effort, output, errorOutput, dependencies, { environment });
3704
+ exitCode = await runSkill("fix-finding", [...positionals, ...imports], options.codex, options.effort, output, errorOutput, dependencies, { environment, auth: options.auth });
3250
3705
  if (patchBase !== undefined && exitCode === 0) {
3251
3706
  const files = await changedPatchFiles(repository, patchBase, dependencies);
3252
3707
  const patchRisk = options.assessPatchRisk
3253
3708
  ? await runPatchRiskAssessment({
3254
3709
  repository,
3710
+ environment,
3255
3711
  base: patchBase,
3256
3712
  files,
3257
3713
  codexOverrides: options.codex,
3258
3714
  effort: options.effort,
3715
+ auth: options.auth,
3259
3716
  }, errorOutput, dependencies)
3260
3717
  : undefined;
3261
3718
  if (options.createPr) {
@@ -3393,6 +3850,70 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3393
3850
  exitCode = 1;
3394
3851
  }
3395
3852
  },
3853
+ })
3854
+ .command("feedback", {
3855
+ description: "Send feedback to OpenAI and return a feedback ID.",
3856
+ destructive: true,
3857
+ mcp: false,
3858
+ args: z.object({
3859
+ scanId: z
3860
+ .string()
3861
+ .min(1)
3862
+ .optional()
3863
+ .describe("Scan ID or unique prefix (default: most recently started scan in the current repository)."),
3864
+ }),
3865
+ options: z.object({
3866
+ reason: z.string().trim().min(1).describe("Describe the problem."),
3867
+ includeLogs: z
3868
+ .boolean()
3869
+ .default(false)
3870
+ .describe("Upload diagnostic logs, including scan and worker conversations and tool output. Defaults to off."),
3871
+ }),
3872
+ output: z.object({
3873
+ feedbackId: z.string(),
3874
+ scanId: z.string().nullable(),
3875
+ includedLogs: z.boolean(),
3876
+ }),
3877
+ async run({ args, options }) {
3878
+ let scanId = args.scanId;
3879
+ if (scanId === undefined) {
3880
+ const value = await history([
3881
+ "list-scans",
3882
+ "--repository",
3883
+ dependencies.currentDirectory(),
3884
+ ]);
3885
+ const scans = value["scans"];
3886
+ scanId = scans.toSorted((a, b) => b.startedAt.localeCompare(a.startedAt))[0]?.scanId;
3887
+ }
3888
+ const scan = scanId === undefined
3889
+ ? undefined
3890
+ : (await history(["get-scan", "--scan-id", scanId]))["scan"];
3891
+ const controller = new AbortController();
3892
+ const onInterrupt = () => controller.abort("SIGINT");
3893
+ const onTerminate = () => controller.abort("SIGTERM");
3894
+ dependencies.addSignalListener("SIGINT", onInterrupt);
3895
+ dependencies.addSignalListener("SIGTERM", onTerminate);
3896
+ try {
3897
+ return await (dependencies.sendFeedback ?? sendFeedback)({
3898
+ ...options,
3899
+ scan,
3900
+ environment: dependencies.environment,
3901
+ workingDirectory: dependencies.currentDirectory(),
3902
+ signal: controller.signal,
3903
+ });
3904
+ }
3905
+ catch (error) {
3906
+ if (controller.signal.aborted) {
3907
+ exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;
3908
+ errorOutput.write("codex-security: Feedback upload canceled.\n");
3909
+ }
3910
+ throw error;
3911
+ }
3912
+ finally {
3913
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
3914
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
3915
+ }
3916
+ },
3396
3917
  })
3397
3918
  .command("info", {
3398
3919
  description: "Show read-only SDK and bundled-plugin metadata.",
@@ -3430,6 +3951,73 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3430
3951
  };
3431
3952
  },
3432
3953
  });
3954
+ // Incur cannot mount a command with both a handler and subcommands.
3955
+ // Select the nested import route while preserving scan [repository].
3956
+ if (isScanImportCommand(argv)) {
3957
+ cli.command(Cli.create("scan", {
3958
+ description: "Run or import a saved scan.",
3959
+ }).command("import", {
3960
+ description: "Save CSV or JSON findings as a completed scan without security analysis.",
3961
+ destructive: true,
3962
+ mcp: false,
3963
+ options: z
3964
+ .object({
3965
+ csv: optionValue("--csv")
3966
+ .optional()
3967
+ .describe("Findings CSV in the codex-security export format."),
3968
+ json: optionValue("--json")
3969
+ .optional()
3970
+ .describe("Findings JSON document or object with a findings array."),
3971
+ outputDir: optionValue("--output-dir")
3972
+ .optional()
3973
+ .describe("Artifact directory (default: Codex Security state; CODEX_SECURITY_STATE_DIR)."),
3974
+ archiveExisting: z
3975
+ .boolean()
3976
+ .default(false)
3977
+ .describe("Archive existing results; requires --output-dir."),
3978
+ dryRun: z
3979
+ .boolean()
3980
+ .default(false)
3981
+ .describe("Validate the input without saving a scan."),
3982
+ })
3983
+ .refine((options) => Number(options.csv !== undefined) +
3984
+ Number(options.json !== undefined) ===
3985
+ 1, { message: "Provide exactly one of --csv FILE or --json FILE." })
3986
+ .refine((options) => !options.archiveExisting || options.outputDir !== undefined, { message: "--archive-existing requires --output-dir." }),
3987
+ examples: [
3988
+ { options: { csv: "findings.csv" } },
3989
+ { options: { json: "findings.json" } },
3990
+ ],
3991
+ hint: "Each input row is retained, including duplicates. --json selects the input file; use --format json for JSON output.",
3992
+ output: z.record(z.string(), z.unknown()).optional(),
3993
+ async run({ options, format, error: incurError }) {
3994
+ const directory = dependencies.currentDirectory();
3995
+ const outcome = await runImport({
3996
+ sourcePath: resolveCliPath(directory, options.csv ?? options.json),
3997
+ format: options.csv === undefined ? "json" : "csv",
3998
+ outputDir: options.outputDir === undefined
3999
+ ? undefined
4000
+ : resolveCliPath(directory, options.outputDir),
4001
+ archiveExisting: options.archiveExisting,
4002
+ dryRun: options.dryRun,
4003
+ });
4004
+ exitCode = outcome.exitCode;
4005
+ if (outcome.error !== undefined) {
4006
+ return incurError({
4007
+ code: "SCAN_IMPORT_FAILED",
4008
+ message: outcome.error,
4009
+ exitCode,
4010
+ });
4011
+ }
4012
+ if (!options.dryRun &&
4013
+ format === "toon" &&
4014
+ !argv.some((argument) => OUTPUT_OPTION.test(argument))) {
4015
+ return;
4016
+ }
4017
+ return outcome.data;
4018
+ },
4019
+ }));
4020
+ }
3433
4021
  let notice;
3434
4022
  try {
3435
4023
  await cli.serve(argv.flatMap((argument) => argument.startsWith("--format=")
@@ -3452,15 +4040,24 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3452
4040
  if (notice !== undefined)
3453
4041
  errorOutput.write(formatUpdateNotice(notice));
3454
4042
  if (frameworkExit !== undefined) {
3455
- if (exitCode !== 0)
3456
- return exitCode;
3457
- errorOutput.write(`codex-security: ${errorMessage(incurErrorMessage(frameworkOutput))}\n`);
3458
- return 2;
4043
+ if (policyFullOutput) {
4044
+ if (exitCode === 0)
4045
+ exitCode = 2;
4046
+ }
4047
+ else {
4048
+ if (exitCode !== 0)
4049
+ return exitCode;
4050
+ errorOutput.write(`codex-security: ${errorMessage(incurErrorMessage(frameworkOutput))}\n`);
4051
+ return 2;
4052
+ }
3459
4053
  }
3460
4054
  if (frameworkOutput.length === 0)
3461
4055
  return exitCode;
3462
4056
  try {
3463
- await writeCliOutput(output, renderedPublication ?? renderedHistory ?? frameworkOutput);
4057
+ await writeCliOutput(output, renderedPolicy ??
4058
+ renderedPublication ??
4059
+ renderedHistory ??
4060
+ frameworkOutput);
3464
4061
  return exitCode;
3465
4062
  }
3466
4063
  catch (error) {
@@ -3468,12 +4065,75 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3468
4065
  return 2;
3469
4066
  }
3470
4067
  }
3471
- function defaultListCommand(argv) {
3472
- const commandIndex = argv.findIndex((value, index) => {
4068
+ async function runScanImport(options, errorOutput, dependencies) {
4069
+ const controller = new AbortController();
4070
+ const onInterrupt = () => controller.abort("SIGINT");
4071
+ const onTerminate = () => controller.abort("SIGTERM");
4072
+ dependencies.addSignalListener("SIGINT", onInterrupt);
4073
+ dependencies.addSignalListener("SIGTERM", onTerminate);
4074
+ try {
4075
+ const result = await (dependencies.importScan ?? importScan)({ ...options, signal: controller.signal }, { environment: dependencies.environment });
4076
+ if ("dryRun" in result)
4077
+ return { exitCode: 0, data: { ...result } };
4078
+ try {
4079
+ errorOutput.write(`Imported ${result.findings.findings.length} findings as scan ${result.manifest.scan.id}.\n` +
4080
+ `Artifacts: ${result.scanDir}\n`);
4081
+ }
4082
+ catch { }
4083
+ return { exitCode: 0, data: result.toJSON() };
4084
+ }
4085
+ catch (error) {
4086
+ const signal = controller.signal.reason;
4087
+ const message = signal === "SIGINT" || signal === "SIGTERM"
4088
+ ? "Scan import canceled."
4089
+ : safeErrorMessage(error);
4090
+ errorOutput.write(`codex-security: ${message}\n`);
4091
+ return {
4092
+ exitCode: signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2,
4093
+ error: message,
4094
+ };
4095
+ }
4096
+ finally {
4097
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
4098
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
4099
+ }
4100
+ }
4101
+ function isScanImportCommand(argv) {
4102
+ const commandIndex = cliCommandIndex(argv);
4103
+ return argv[commandIndex] === "scan" && argv[commandIndex + 1] === "import";
4104
+ }
4105
+ function normalizeScanImportArguments(argv) {
4106
+ if (!isScanImportCommand(argv))
4107
+ return argv;
4108
+ const normalized = [];
4109
+ const subcommandIndex = cliCommandIndex(argv) + 1;
4110
+ for (let index = 0; index < argv.length; index += 1) {
4111
+ const argument = argv[index];
4112
+ const next = argv[index + 1];
4113
+ // Incur reserves bare --json for output, but parses --json=FILE normally.
4114
+ if (index > subcommandIndex &&
4115
+ argument === "--json" &&
4116
+ next !== undefined &&
4117
+ !next.startsWith("--") &&
4118
+ next !== "-h") {
4119
+ normalized.push(`--json=${next}`);
4120
+ index += 1;
4121
+ }
4122
+ else {
4123
+ normalized.push(argument);
4124
+ }
4125
+ }
4126
+ return normalized;
4127
+ }
4128
+ function cliCommandIndex(argv) {
4129
+ return argv.findIndex((value, index) => {
3473
4130
  if (value.startsWith("-"))
3474
4131
  return false;
3475
4132
  return index === 0 || !VALUE_OPTIONS.has(argv[index - 1]);
3476
4133
  });
4134
+ }
4135
+ function defaultListCommand(argv) {
4136
+ const commandIndex = cliCommandIndex(argv);
3477
4137
  if (commandIndex < 0 ||
3478
4138
  !["scans", "findings"].includes(argv[commandIndex]) ||
3479
4139
  argv.includes("--help") ||
@@ -3564,11 +4224,19 @@ function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
3564
4224
  Object.keys(deepScan.data).length > 0) {
3565
4225
  throw new CodexSecurityError("The saved scan recipe contains deep scan settings for a standard scan.");
3566
4226
  }
4227
+ const safetyIdentifier = recipe["safetyIdentifier"];
4228
+ const postScanPrompt = recipe["postScanPrompt"];
4229
+ if ((safetyIdentifier !== undefined && typeof safetyIdentifier !== "string") ||
4230
+ (postScanPrompt !== undefined && typeof postScanPrompt !== "string")) {
4231
+ throw new CodexSecurityError("The saved scan recipe contains invalid launch settings.");
4232
+ }
3567
4233
  return {
3568
4234
  repository,
3569
4235
  paths,
3570
4236
  knowledgeBasePaths,
3571
4237
  validationPromptFile,
4238
+ safetyIdentifier,
4239
+ postScanPrompt,
3572
4240
  diff: kind === "refs" ? reference : undefined,
3573
4241
  workingTree: kind === "working_tree",
3574
4242
  head: kind === "refs" ? head ?? "HEAD" : undefined,
@@ -3593,27 +4261,31 @@ function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
3593
4261
  function validateCliArguments(argv, positionals) {
3594
4262
  if (argv.includes("--help") || argv.includes("-h"))
3595
4263
  return undefined;
3596
- const commandIndex = argv.findIndex((value) => [
3597
- "scan",
3598
- "install-hook",
3599
- "bulk-scan",
3600
- "scan-components",
3601
- "scans",
3602
- "findings",
3603
- "export",
3604
- "publish",
3605
- "import",
3606
- "validate",
3607
- "verify-fix",
3608
- "patch",
3609
- "login",
3610
- "logout",
3611
- "serve",
3612
- "info",
3613
- ].includes(value));
3614
- if (commandIndex < 0)
3615
- return undefined;
4264
+ const commandIndex = cliCommandIndex(argv);
3616
4265
  const command = argv[commandIndex];
4266
+ if (command === undefined ||
4267
+ ![
4268
+ "scan",
4269
+ "policy",
4270
+ "install-hook",
4271
+ "bulk-scan",
4272
+ "scan-components",
4273
+ "scans",
4274
+ "findings",
4275
+ "export",
4276
+ "publish",
4277
+ "import",
4278
+ "validate",
4279
+ "verify-fix",
4280
+ "patch",
4281
+ "login",
4282
+ "logout",
4283
+ "serve",
4284
+ "feedback",
4285
+ "info",
4286
+ ].includes(command)) {
4287
+ return undefined;
4288
+ }
3617
4289
  const structuredOutput = argv.some((value, index) => value === "--json" ||
3618
4290
  ((value === "--format" ||
3619
4291
  value === "--format=json" ||
@@ -3644,7 +4316,9 @@ function validateCliArguments(argv, positionals) {
3644
4316
  return "Markdown output is not supported for scan results.";
3645
4317
  }
3646
4318
  }
3647
- const nestedCommand = command === "scans" ||
4319
+ const scanImport = isScanImportCommand(argv);
4320
+ const nestedCommand = scanImport ||
4321
+ command === "scans" ||
3648
4322
  command === "findings" ||
3649
4323
  command === "publish" ||
3650
4324
  command === "import";
@@ -3685,7 +4359,8 @@ function validateCliArguments(argv, positionals) {
3685
4359
  }
3686
4360
  const equals = value.indexOf("=");
3687
4361
  const option = equals < 0 ? value : value.slice(0, equals);
3688
- if (equals >= 0 || !VALUE_OPTIONS.has(option))
4362
+ if (equals >= 0 ||
4363
+ (!VALUE_OPTIONS.has(option) && !(scanImport && option === "--json")))
3689
4364
  continue;
3690
4365
  const next = argv[index + 1];
3691
4366
  if (next === undefined || next.startsWith("--") || next === "-h") {
@@ -3706,7 +4381,10 @@ function validateCliArguments(argv, positionals) {
3706
4381
  command !== "verify-fix" &&
3707
4382
  command !== "patch" &&
3708
4383
  positionals.length >
3709
- (command === "logout" || command === "info" || command === "serve"
4384
+ (scanImport ||
4385
+ command === "logout" ||
4386
+ command === "info" ||
4387
+ command === "serve"
3710
4388
  ? 0
3711
4389
  : subcommand === "compare" || subcommand === "match"
3712
4390
  ? 2
@@ -4174,6 +4852,8 @@ async function assessPatchRisk(request, stderr, dependencies) {
4174
4852
  };
4175
4853
  const status = await runSkill("assess-patch-risk", [], request.codexOverrides, request.effort, stdout, stderr, dependencies, {
4176
4854
  directory: request.repository,
4855
+ auth: request.auth,
4856
+ environment: request.environment,
4177
4857
  patchArtifact: {
4178
4858
  path: patchPath,
4179
4859
  repository: basename(resolve(request.repository)),
@@ -4411,10 +5091,14 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
4411
5091
  ...(options.provider === undefined
4412
5092
  ? []
4413
5093
  : ["--config", `model_provider=${JSON.stringify(options.provider)}`]),
4414
- ...Object.entries(options.providerConfiguration ?? {}).flatMap(([key, value]) => [
4415
- "--config",
4416
- `model_providers.${options.provider}.${key}=${JSON.stringify(value)}`,
4417
- ]),
5094
+ ...(options.provider === undefined ||
5095
+ options.providerConfiguration === undefined
5096
+ ? []
5097
+ : modelProviderConfigOverride(resolveCommandAuthConfig({
5098
+ model_providers: {
5099
+ [options.provider]: options.providerConfiguration,
5100
+ },
5101
+ }, configuredCodexHome(options.environment ?? dependencies.environment))).flatMap((value) => ["--config", value])),
4418
5102
  "--config",
4419
5103
  verify || assess
4420
5104
  ? 'approval_policy="on-request"'
@@ -4442,6 +5126,10 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
4442
5126
  ]),
4443
5127
  ], {
4444
5128
  command: verify ? "verify-fix" : patch || assess ? "patch" : "validate",
5129
+ auth: options.auth ?? "auto",
5130
+ directory,
5131
+ modelProvider: options.provider,
5132
+ providerConfiguration: options.providerConfiguration,
4445
5133
  stdout,
4446
5134
  stderr,
4447
5135
  ...(appServer
@@ -4457,7 +5145,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
4457
5145
  },
4458
5146
  }
4459
5147
  : {}),
4460
- }, options.environment, appServer ? undefined : prompt);
5148
+ }, options.environment ?? dependencies.environment, appServer ? undefined : prompt);
4461
5149
  }
4462
5150
  export async function readSkillCommandOutput(stream, appServer) {
4463
5151
  let message;
@@ -4479,6 +5167,9 @@ export async function readSkillCommandOutput(stream, appServer) {
4479
5167
  // Inherit the child process cwd and preserve the user's decision.
4480
5168
  params: {
4481
5169
  threadSource: appServer.threadSource,
5170
+ ...(appServer.modelProvider === undefined
5171
+ ? {}
5172
+ : { modelProvider: appServer.modelProvider }),
4482
5173
  approvalPolicy: appServer?.sandbox === "read-only" ? "on-request" : "never",
4483
5174
  sandbox: appServer?.sandbox ?? "workspace-write",
4484
5175
  ...(config === undefined ? {} : { config }),
@@ -4532,8 +5223,18 @@ export async function readSkillCommandOutput(stream, appServer) {
4532
5223
  error = value["error"].message;
4533
5224
  appServer.input.end();
4534
5225
  }
4535
- else if (value["id"] === 1) {
4536
- send({ method: "notifications/initialized" });
5226
+ else if (value["id"] === 1 || value["id"] === "login") {
5227
+ if (value["id"] === 1) {
5228
+ send({ method: "notifications/initialized" });
5229
+ if (appServer.apiKey !== undefined) {
5230
+ send({
5231
+ id: "login",
5232
+ method: "account/login/start",
5233
+ params: { type: "apiKey", apiKey: appServer.apiKey },
5234
+ });
5235
+ continue;
5236
+ }
5237
+ }
4537
5238
  if (appServer.sandbox === "read-only") {
4538
5239
  if (appServer.directory === undefined) {
4539
5240
  error =
@@ -4610,6 +5311,7 @@ export async function readSkillCommandOutput(stream, appServer) {
4610
5311
  });
4611
5312
  }
4612
5313
  else if (value["id"] === 2) {
5314
+ await appServer.onThreadStarted?.();
4613
5315
  threadId = value["result"].thread.id;
4614
5316
  send({
4615
5317
  id: 3,
@@ -4686,9 +5388,9 @@ export async function readSkillCommandOutput(stream, appServer) {
4686
5388
  ...(appServer === undefined ? {} : { completed }),
4687
5389
  };
4688
5390
  }
4689
- export function skillCommandFailure(command, status, detail) {
5391
+ export function skillCommandFailure(command, status, detail, authentication = null) {
4690
5392
  if (/401|invalid.api.key|token.expired|unauthori[sz]ed|authorizationrequired/iu.test(detail)) {
4691
- return "Authentication failed. Run codex-security login or check the configured API key.";
5393
+ return authenticationFailureMessage(authentication);
4692
5394
  }
4693
5395
  if (/403|model.not.found|model.*access|access.*model|permission/iu.test(detail)) {
4694
5396
  return "The selected model is unavailable for the current credentials.";
@@ -4918,7 +5620,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
4918
5620
  let preflight = null;
4919
5621
  let effectiveModel = DEFAULT_SCAN_MODEL_CONFIGURATION.model;
4920
5622
  let effectiveReasoningEffort = DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort;
4921
- let providerOptions = {};
5623
+ let providerOptions = { provider: "openai" };
5624
+ let auth = arguments_.auth;
4922
5625
  let patchAnalyticsOverride;
4923
5626
  let selectedAuthentication = null;
4924
5627
  let repository = "";
@@ -4949,23 +5652,27 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
4949
5652
  analytics["enabled"] !== undefined) {
4950
5653
  patchAnalyticsOverride = `analytics.enabled=${JSON.stringify(analytics["enabled"])}`;
4951
5654
  }
4952
- const auth = !arguments_.dryRun && !arguments_.mock && interactive
4953
- ? await chooseInteractiveAuthentication({
4954
- auth: arguments_.auth,
4955
- provider,
4956
- command: "scan",
4957
- signal: preparationAbortController.signal,
4958
- }, errorOutput, dependencies)
4959
- : arguments_.auth;
4960
- if (typeof provider === "string" && provider !== "openai") {
5655
+ auth =
5656
+ !arguments_.dryRun && !arguments_.mock && interactive
5657
+ ? await chooseInteractiveAuthentication({
5658
+ auth: arguments_.auth,
5659
+ provider,
5660
+ command: "scan",
5661
+ signal: preparationAbortController.signal,
5662
+ }, errorOutput, dependencies)
5663
+ : arguments_.auth;
5664
+ if (typeof provider === "string") {
4961
5665
  providerOptions = {
4962
5666
  provider,
4963
- providerConfiguration: effectiveConfiguration["model_providers"]?.[provider],
5667
+ providerConfiguration: effectiveConfiguration["model_providers"]?.[provider] ??
5668
+ (isExternalModelProvider(provider)
5669
+ ? EXTERNAL_CODEX_PROVIDERS[provider]
5670
+ : undefined),
4964
5671
  };
4965
5672
  }
4966
5673
  selectedAuthentication = arguments_.mock
4967
5674
  ? null
4968
- : scanAuthentication(dependencies.environment, auth, provider);
5675
+ : scanAuthentication(dependencies.environment, auth, provider, hasCommandAuth(effectiveConfiguration));
4969
5676
  diagnostic("scan.configuration", {
4970
5677
  cli_version: VERSION,
4971
5678
  bundled_plugin_version: BUNDLED_PLUGIN_VERSION,
@@ -5023,13 +5730,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5023
5730
  details.push(`Files: ${fileProgress.filesCompleted.toLocaleString("en-US")}/${fileProgress.filesTotal.toLocaleString("en-US")}`);
5024
5731
  }
5025
5732
  if (runningCost !== null) {
5026
- const tokens = formatTokenUsage({
5027
- input_tokens: runningCost.inputTokens,
5028
- cached_input_tokens: runningCost.cachedInputTokens,
5029
- output_tokens: runningCost.outputTokens,
5030
- });
5031
- if (tokens !== null)
5032
- details.push(`Tokens: ${tokens}`);
5733
+ details.push(`Tokens: ${formatScanCostTokens(runningCost)}`);
5033
5734
  details.push(`Cost: ${formatUsd(runningCost.estimatedUsd)}`);
5034
5735
  }
5035
5736
  return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;
@@ -5052,6 +5753,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5052
5753
  errorOutput.write("codex-security: Mock scan: generating synthetic findings; no security analysis or LLM calls.\n");
5053
5754
  }
5054
5755
  const options = {
5756
+ ...(arguments_.resumeScanId === undefined
5757
+ ? {}
5758
+ : { resumeScanId: arguments_.resumeScanId }),
5055
5759
  ...(arguments_.mock ? { mock: true } : {}),
5056
5760
  ...(arguments_.workflowId === undefined
5057
5761
  ? {}
@@ -5061,6 +5765,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5061
5765
  target,
5062
5766
  knowledgeBasePaths: arguments_.knowledgeBasePaths,
5063
5767
  ...prompts,
5768
+ postScanPrompt: arguments_.postScanPrompt ?? prompts.postScanPrompt,
5064
5769
  mode: arguments_.mode,
5065
5770
  workers: arguments_.workers,
5066
5771
  subagents: arguments_.subagents,
@@ -5094,12 +5799,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5094
5799
  }
5095
5800
  progress?.stopTimer();
5096
5801
  if (maxCostUsd === undefined) {
5097
- const tokens = formatTokenUsage({
5098
- input_tokens: cost.inputTokens,
5099
- cached_input_tokens: cost.cachedInputTokens,
5100
- output_tokens: cost.outputTokens,
5101
- });
5102
- progress?.stage(`${tokens === null ? "" : `Tokens: ${tokens}. `}Estimated cost: ${formatUsd(cost.estimatedUsd)} USD.`);
5802
+ progress?.stage(`Tokens: ${formatScanCostTokens(cost)}. Estimated cost: ${formatUsd(cost.estimatedUsd)} USD.`);
5103
5803
  }
5104
5804
  else {
5105
5805
  progress?.stage(`Estimated cost: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(maxCostUsd)} limit`);
@@ -5463,15 +6163,6 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5463
6163
  (patchSelection === null ||
5464
6164
  patchSelection.occurrenceIds.includes(finding.occurrenceId))),
5465
6165
  };
5466
- const environment = { ...dependencies.environment };
5467
- if (selectedAuthentication?.method === "stored_credentials") {
5468
- for (const name of Object.keys(environment)) {
5469
- if (["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase())) {
5470
- delete environment[name];
5471
- }
5472
- }
5473
- environment["CODEX_HOME"] = codexSecurityCredentialHome(dependencies.environment);
5474
- }
5475
6166
  try {
5476
6167
  patches = await runFindingPatches(selected, [
5477
6168
  `model=${JSON.stringify(effectiveModel)}`,
@@ -5481,7 +6172,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5481
6172
  ], effectiveReasoningEffort, errorOutput, dependencies, {
5482
6173
  ...providerOptions,
5483
6174
  safetyIdentifier: arguments_.safetyIdentifier,
5484
- environment,
6175
+ auth,
5485
6176
  findingInstructions: patchSelection?.instructions,
5486
6177
  });
5487
6178
  scanData = { ...scanData, patchSeverity: patchThreshold, patches };
@@ -5545,6 +6236,36 @@ function isLocalScanFailure(error) {
5545
6236
  typeof error.code === "string" &&
5546
6237
  LOCAL_SYSCALL_CODES.has(error.code));
5547
6238
  }
6239
+ function authenticationFailureMessage(authentication) {
6240
+ if (authentication?.method === "command") {
6241
+ return "Native Codex command authentication failed. Check the configured provider auth command.";
6242
+ }
6243
+ if (authentication?.method === "aws_credentials") {
6244
+ return (`Authentication failed using AWS credentials from ${authentication.source}. ` +
6245
+ "Check your Amazon Bedrock bearer token or AWS credential chain.");
6246
+ }
6247
+ if (authentication?.method === "stored_credentials" &&
6248
+ authentication.credentialType === "api_key") {
6249
+ return ("Authentication failed using a stored API key. " +
6250
+ "Sign in again with 'codex-security login --with-api-key' or provide a valid API key.");
6251
+ }
6252
+ if (authentication?.method === "api_key") {
6253
+ const openAiKey = authentication.source === "OPENAI_API_KEY" ||
6254
+ authentication.source === "CODEX_API_KEY";
6255
+ return (`Authentication failed using ${authentication.source}. ` +
6256
+ (openAiKey
6257
+ ? "Retry with '--auth chatgpt' or provide a valid API key."
6258
+ : `Provide a valid ${authentication.source} for the selected provider.`));
6259
+ }
6260
+ if (authentication?.method === "stored_credentials") {
6261
+ return authentication.credentialType === "chatgpt"
6262
+ ? "Authentication failed using stored ChatGPT credentials. " +
6263
+ "Sign in again with 'codex-security login' or provide a valid API key."
6264
+ : "Authentication failed using stored credentials. " +
6265
+ "Check 'codex-security login status' and refresh the stored login or provide a valid API key.";
6266
+ }
6267
+ return "Authentication failed. Check the selected provider's credentials and retry.";
6268
+ }
5548
6269
  function scanFailureMessage(error, authentication) {
5549
6270
  // A local failure keeps its own message. Classification matches bare words
5550
6271
  // such as "permission denied" anywhere in the text, so an EACCES from a
@@ -5568,18 +6289,7 @@ function scanFailureMessage(error, authentication) {
5568
6289
  }
5569
6290
  switch (classifyConnectionFailure(error)) {
5570
6291
  case "unauthorized":
5571
- if (authentication?.method === "command") {
5572
- return "Native Codex command authentication failed. Check the configured provider auth command.";
5573
- }
5574
- if (authentication?.method === "aws_credentials") {
5575
- return (`Authentication failed using AWS credentials from ${authentication.source}. ` +
5576
- "Check your Amazon Bedrock bearer token or AWS credential chain.");
5577
- }
5578
- return authentication?.method === "api_key"
5579
- ? `Authentication failed using ${authentication.source}. ` +
5580
- "Retry with '--auth chatgpt' or provide a valid API key."
5581
- : "Authentication failed using stored ChatGPT credentials. " +
5582
- "Sign in again with 'codex-security login' or provide a valid API key.";
6292
+ return authenticationFailureMessage(authentication);
5583
6293
  case "forbidden":
5584
6294
  if (authentication?.method === "command") {
5585
6295
  return "The configured Codex provider denied access. Check the command credentials and provider permissions.";
@@ -5713,34 +6423,15 @@ function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
5713
6423
  if (tokenSummary !== null) {
5714
6424
  errorOutput.write(` ${paint("TOKENS", 1)} ${tokenSummary}\n`);
5715
6425
  }
5716
- if (result.cost !== null) {
5717
- errorOutput.write(` ${paint("COST", 1)} ${formatUsd(result.cost.estimatedUsd)}\n`);
5718
- }
6426
+ const costSummary = result.cost === null
6427
+ ? "unavailable (model pricing or usage missing)"
6428
+ : `${formatUsd(result.cost.estimatedUsd)} (standard, short context)`;
6429
+ errorOutput.write(` ${paint("COST", 1)} ${costSummary}\n`);
5719
6430
  errorOutput.write(` ${paint("RESULTS", 1)} ${errorMessage(result.scanDir)}\n`);
5720
6431
  if (deepScanStop?.nextStep !== undefined) {
5721
6432
  errorOutput.write(`\n ${deepScanStop.nextStep}\n`);
5722
6433
  }
5723
6434
  }
5724
- function formatTokenUsage(usage) {
5725
- if (usage === null || typeof usage !== "object")
5726
- return null;
5727
- const values = usage;
5728
- return ([
5729
- ["input_tokens", "input"],
5730
- ["cached_input_tokens", "cached"],
5731
- ["output_tokens", "output"],
5732
- ]
5733
- .map(([key, label]) => {
5734
- const value = values[key];
5735
- return typeof value === "number" &&
5736
- Number.isSafeInteger(value) &&
5737
- value >= 0
5738
- ? `${value.toLocaleString("en-US")} ${label}`
5739
- : null;
5740
- })
5741
- .filter((value) => value !== null)
5742
- .join(", ") || null);
5743
- }
5744
6435
  function componentScanEventLine(componentName, event) {
5745
6436
  if (event.type === "progress") {
5746
6437
  const progress = event.value;
@@ -5749,12 +6440,7 @@ function componentScanEventLine(componentName, event) {
5749
6440
  if (event.type !== "cost")
5750
6441
  return null;
5751
6442
  const cost = event.value;
5752
- const tokens = formatTokenUsage({
5753
- input_tokens: cost.inputTokens,
5754
- cached_input_tokens: cost.cachedInputTokens,
5755
- output_tokens: cost.outputTokens,
5756
- });
5757
- return `codex-security: ${componentName} | ${tokens === null ? "" : `Tokens: ${tokens} | `}Cost: ${formatUsd(cost.estimatedUsd)}\n`;
6443
+ return `codex-security: ${componentName} | Tokens: ${formatScanCostTokens(cost)} | Cost: ${formatUsd(cost.estimatedUsd)}\n`;
5758
6444
  }
5759
6445
  function protectedRootErrorMessage(error) {
5760
6446
  const description = error.pathKind === "output"