Add Codex launch arguments setting (#2892)

Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: root <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-07-20 11:04:03 +02:00
1 parent 33f1cb4224
commit 40c0ab0883
17 files changed
+414 -16

No files matched your search

@@ -279,6 +279,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
NodeAssert.deepStrictEqual(validationRuntimeFactory.factory.mock.calls[0]?.[0], {
binaryPath: "codex",
cwd: process.cwd(),
launchArgs: "",
model: "gpt-5.3-codex",
providerInstanceId: ProviderInstanceId.make("codex"),
serviceTier: "priority",
@@ -359,6 +360,69 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
}),
);
it.effect("passes configured launch args into the session runtime", () => {
const runtimeFactory = makeRuntimeFactory();
const layer = Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = decodeCodexSettings({ launchArgs: "--strict-config --enable foo" });
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: runtimeFactory.factory,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("sess-launch-args"),
runtimeMode: "full-access",
});
const runtime = runtimeFactory.lastRuntime;
NodeAssert.ok(runtime);
NodeAssert.equal(runtime.options.launchArgs, "--strict-config --enable foo");
}).pipe(Effect.provide(layer));
});
it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for the session runtime", () => {
const runtimeFactory = makeRuntimeFactory();
const layer = Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = decodeCodexSettings({ launchArgs: "--enable settings-feature" });
return yield* makeCodexAdapter(codexConfig, {
environment: { T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --enable env-feature " },
makeRuntime: runtimeFactory.factory,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
return Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("sess-launch-args-env"),
runtimeMode: "full-access",
});
const runtime = runtimeFactory.lastRuntime;
NodeAssert.ok(runtime);
NodeAssert.equal(runtime.options.launchArgs, "--strict-config --enable env-feature");
}).pipe(Effect.provide(layer));
});
it.effect("maps codex model options for the adapter's bound custom instance id", () => {
const customInstanceId = ProviderInstanceId.make("codex_personal");
const customRuntimeFactory = makeRuntimeFactory();
@@ -61,6 +61,7 @@ import {
type CodexSessionRuntimeShape,
} from "./CodexSessionRuntime.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
const isCodexAppServerProcessExitedError = Schema.is(CodexErrors.CodexAppServerProcessExitedError);
const isCodexAppServerTransportError = Schema.is(CodexErrors.CodexAppServerTransportError);
const isCodexSessionRuntimeThreadIdMissingError = Schema.is(
@@ -1399,6 +1400,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
providerInstanceId: boundInstanceId,
cwd: input.cwd ?? process.cwd(),
binaryPath: codexConfig.binaryPath,
launchArgs: resolveCodexLaunchArgs(codexConfig.launchArgs, options?.environment),
...(options?.environment ? { environment: options.environment } : {}),
...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),
...(isCodexResumeCursorSchema(input.resumeCursor)
@@ -26,6 +26,7 @@ import { ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
import {
AUTH_PROBE_TIMEOUT_MS,
buildServerProvider,
@@ -289,6 +290,7 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly launchArgs?: string;
readonly cwd: string;
readonly customModels?: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
@@ -303,10 +305,14 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
...input.environment,
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
};
const spawnCommand = yield* resolveSpawnCommand(input.binaryPath, ["app-server"], {
env: environment,
extendEnv: true,
});
const spawnCommand = yield* resolveSpawnCommand(
input.binaryPath,
codexAppServerArgs(input.launchArgs),
{
env: environment,
extendEnv: true,
},
);
const child = yield* spawner
.spawn(
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
@@ -465,6 +471,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
probe: (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly launchArgs?: string;
readonly cwd: string;
readonly customModels: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
@@ -503,6 +510,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
const probeResult = yield* probe({
binaryPath: codexSettings.binaryPath,
homePath: codexSettings.homePath,
launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),
cwd: process.cwd(),
customModels: codexSettings.customModels,
environment: resolvedEnvironment,
@@ -13,6 +13,7 @@ import {
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts";
import {
buildTurnStartParams,
hasConfiguredMcpServer,
@@ -289,6 +290,33 @@ describe("hasConfiguredMcpServer", () => {
});
});
describe("codexSessionAppServerArgs", () => {
it("keeps the app-server subcommand when explicit args are provided", () => {
NodeAssert.deepStrictEqual(codexSessionAppServerArgs(["-c", "model=gpt-5"], undefined), [
"app-server",
"-c",
"model=gpt-5",
]);
});
it("keeps launch args when explicit app-server args are provided", () => {
NodeAssert.deepStrictEqual(
codexSessionAppServerArgs(
["-c", "mcp_servers.t3-code.url=http://127.0.0.1/mcp"],
"--strict-config --enable foo",
),
[
"app-server",
"--strict-config",
"--enable",
"foo",
"-c",
"mcp_servers.t3-code.url=http://127.0.0.1/mcp",
],
);
});
});
describe("isRecoverableThreadResumeError", () => {
it("matches missing thread errors", () => {
NodeAssert.equal(
@@ -36,6 +36,7 @@ import * as CodexRpc from "effect-codex-app-server/rpc";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
import { buildCodexInitializeParams } from "./CodexProvider.ts";
import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { buildCodexDeveloperInstructions } from "../CodexDeveloperInstructions.ts";
const decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse);
@@ -97,6 +98,7 @@ export interface CodexSessionRuntimeOptions {
readonly providerInstanceId?: ProviderInstanceId;
readonly binaryPath: string;
readonly homePath?: string;
readonly launchArgs?: string;
readonly environment?: NodeJS.ProcessEnv;
readonly cwd: string;
readonly runtimeMode: RuntimeMode;
@@ -717,11 +719,11 @@ export const makeCodexSessionRuntime = (
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
};
const extendEnv = options.environment === undefined;
const spawnCommand = yield* resolveSpawnCommand(
options.binaryPath,
["app-server", ...(options.appServerArgs ?? [])],
{ env, extendEnv },
);
const appServerArgs = codexSessionAppServerArgs(options.appServerArgs, options.launchArgs);
const spawnCommand = yield* resolveSpawnCommand(options.binaryPath, appServerArgs, {
env,
extendEnv,
});
const child = yield* spawner
.spawn(
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
@@ -61,6 +61,7 @@ const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
binaryPath: "codex",
homePath: "",
shadowHomePath: "",
launchArgs: "",
customModels: [],
...overrides,
});
@@ -55,6 +55,7 @@ const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTING
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
const disabledCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({
enabled: false,
});
@@ -348,6 +349,21 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
}),
);
it.effect("passes configured launch args to the Codex provider probe", () =>
Effect.gen(function* () {
let observedLaunchArgs: string | undefined;
const settings = decodeCodexSettings({ launchArgs: "--strict-config --enable foo" });
const status = yield* checkCodexProviderStatus(settings, (input) => {
observedLaunchArgs = input.launchArgs;
return Effect.succeed(makeCodexProbeSnapshot());
});
assert.strictEqual(status.status, "ready");
assert.strictEqual(observedLaunchArgs, "--strict-config --enable foo");
}),
);
it.effect("returns unauthenticated when app-server requires OpenAI auth", () =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>
@@ -0,0 +1,59 @@
import * as NodeAssert from "node:assert/strict";
import { describe, it } from "vite-plus/test";
import {
codexAppServerArgs,
codexExecLaunchArgs,
resolveCodexLaunchArgs,
} from "./codexLaunchArgs.ts";
describe("resolveCodexLaunchArgs", () => {
it("uses T3CODE_CODEX_LAUNCH_ARGS before configured settings", () => {
NodeAssert.equal(
resolveCodexLaunchArgs(" --strict-config ", { T3CODE_CODEX_LAUNCH_ARGS: "--enable foo" }),
"--enable foo",
);
});
it("uses configured settings when T3CODE_CODEX_LAUNCH_ARGS is empty", () => {
NodeAssert.equal(
resolveCodexLaunchArgs(" --strict-config ", { T3CODE_CODEX_LAUNCH_ARGS: " " }),
"--strict-config",
);
});
it("ignores whitespace-only environment values", () => {
NodeAssert.equal(resolveCodexLaunchArgs("", { T3CODE_CODEX_LAUNCH_ARGS: " " }), "");
});
});
describe("codexAppServerArgs", () => {
it("returns the app-server command for empty launch args", () => {
NodeAssert.deepStrictEqual(codexAppServerArgs(""), ["app-server"]);
});
it("appends parsed launch args after app-server", () => {
NodeAssert.deepStrictEqual(codexAppServerArgs("--strict-config --enable foo"), [
"app-server",
"--strict-config",
"--enable",
"foo",
]);
});
});
describe("codexExecLaunchArgs", () => {
it("keeps shared codex flags and omits app-server-only flags", () => {
NodeAssert.deepStrictEqual(
codexExecLaunchArgs('--strict-config --enable foo --listen off --config model="gpt 5"'),
["--strict-config", "--enable", "foo", "--config", "model=gpt 5"],
);
});
it("does not pair value-taking flags with adjacent flags", () => {
NodeAssert.deepStrictEqual(codexExecLaunchArgs("--config --strict-config --enable --disable"), [
"--strict-config",
]);
});
});
@@ -0,0 +1,48 @@
import { tokenizeCliArgs } from "@t3tools/shared/cliArgs";
export const T3CODE_CODEX_LAUNCH_ARGS_ENV = "T3CODE_CODEX_LAUNCH_ARGS";
export const resolveCodexLaunchArgs = (
launchArgs?: string,
environment: NodeJS.ProcessEnv = process.env,
) => environment[T3CODE_CODEX_LAUNCH_ARGS_ENV]?.trim() || launchArgs?.trim() || "";
export const codexLaunchArgv = (launchArgs?: string): ReadonlyArray<string> =>
tokenizeCliArgs(launchArgs);
export const codexAppServerArgs = (launchArgs?: string) => [
"app-server",
...codexLaunchArgv(launchArgs),
];
export const codexExecLaunchArgs = (launchArgs?: string) => {
const args = codexLaunchArgv(launchArgs);
const execArgs: Array<string> = [];
for (let index = 0; index < args.length; index++) {
const arg = args[index];
if (arg === undefined) continue;
if (arg === "--strict-config" || arg.startsWith("--config=") || arg.startsWith("-c=")) {
execArgs.push(arg);
} else if (arg === "--config" || arg === "-c" || arg === "--enable" || arg === "--disable") {
const value = args[index + 1];
if (value !== undefined && !value.startsWith("-")) {
execArgs.push(arg, value);
index++;
}
} else if (arg.startsWith("--enable=") || arg.startsWith("--disable=")) {
execArgs.push(arg);
}
}
return execArgs;
};
export const codexSessionAppServerArgs = (
appServerArgs: ReadonlyArray<string> | undefined,
launchArgs: string | undefined,
) => {
const launchAppServerArgs = codexAppServerArgs(launchArgs);
return appServerArgs ? [...launchAppServerArgs, ...appServerArgs] : launchAppServerArgs;
};
+2
View File
@@ -179,6 +179,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
binaryPath: "/opt/homebrew/bin/codex",
homePath: "/Users/julius/.codex",
shadowHomePath: "",
launchArgs: "",
customModels: [],
});
assert.deepEqual(next.providers.claudeAgent, {
@@ -420,6 +421,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
binaryPath: "/opt/homebrew/bin/codex",
homePath: "",
shadowHomePath: "",
launchArgs: "",
customModels: [],
});
assert.deepEqual(next.providers.claudeAgent, {
@@ -35,6 +35,8 @@ function makeFakeCodexBinary(
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
requireArg?: string;
forbidArg?: string;
stdinMustContain?: string;
stdinMustNotContain?: string;
},
@@ -50,6 +52,7 @@ function makeFakeCodexBinary(
codexPath,
[
"#!/bin/sh",
'original_args="$*"',
'output_path=""',
'seen_image="0"',
'seen_service_tier=""',
@@ -87,6 +90,22 @@ function makeFakeCodexBinary(
" shift",
"done",
'stdin_content="$(cat)"',
...(input.requireArg !== undefined
? [
`case " $original_args " in *" ${input.requireArg} "*) ;; *)`,
` printf "%s\\n" "missing arg: ${input.requireArg}" >&2`,
` exit 8`,
"esac",
]
: []),
...(input.forbidArg !== undefined
? [
`case " $original_args " in *" ${input.forbidArg} "*)`,
` printf "%s\\n" "forbidden arg: ${input.forbidArg}" >&2`,
` exit 9`,
"esac",
]
: []),
...(input.requireImage
? [
'if [ "$seen_image" != "1" ]; then',
@@ -166,8 +185,12 @@ function withFakeCodexEnv<A, E, R>(
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
requireArg?: string;
forbidArg?: string;
stdinMustContain?: string;
stdinMustNotContain?: string;
launchArgs?: string;
environment?: NodeJS.ProcessEnv;
},
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
) {
@@ -175,8 +198,8 @@ function withFakeCodexEnv<A, E, R>(
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const config = decodeCodexSettings({ binaryPath: codexPath });
const textGeneration = yield* makeCodexTextGeneration(config);
const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs });
const textGeneration = yield* makeCodexTextGeneration(config, input.environment);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
}
@@ -237,6 +260,51 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
),
);
it.effect("passes exec-safe launch args into codex exec", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
}),
launchArgs: "--strict-config --listen off",
requireArg: "--strict-config",
forbidArg: "--listen",
},
(textGeneration) =>
textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
}),
),
);
it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for codex exec over settings", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
}),
launchArgs: "--enable settings-feature",
environment: { T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --listen off " },
requireArg: "--strict-config",
forbidArg: "settings-feature",
},
(textGeneration) =>
textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
}),
),
);
it.effect("defaults git text generation codex effort to low", () =>
withFakeCodexEnv(
{
@@ -14,6 +14,7 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import { expandHomePath } from "../pathExpansion.ts";
import { codexExecLaunchArgs, resolveCodexLaunchArgs } from "../provider/Layers/codexLaunchArgs.ts";
import { TextGenerationError } from "@t3tools/contracts";
import * as TextGeneration from "./TextGeneration.ts";
import {
@@ -174,6 +175,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
const launchArgs = resolveCodexLaunchArgs(codexConfig.launchArgs, resolvedEnvironment);
const reasoningEffort =
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
@@ -182,6 +184,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
codexConfig.binaryPath || "codex",
[
"exec",
...codexExecLaunchArgs(launchArgs),
"--ephemeral",
"--skip-git-repo-check",
"-s",
@@ -18,6 +18,7 @@ describe("ProviderSettingsForm helpers", () => {
"binaryPath",
"homePath",
"shadowHomePath",
"launchArgs",
]);
});
+4
View File
@@ -141,6 +141,7 @@ describe("ServerSettingsPatch string normalization", () => {
codex: {
binaryPath: " /opt/homebrew/bin/codex ",
homePath: " ~/.codex ",
launchArgs: " --strict-config --enable foo ",
},
},
providerInstances: {
@@ -157,6 +158,7 @@ describe("ServerSettingsPatch string normalization", () => {
expect(patch.observability?.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
expect(patch.providers?.codex?.binaryPath).toBe("/opt/homebrew/bin/codex");
expect(patch.providers?.codex?.homePath).toBe("~/.codex");
expect(patch.providers?.codex?.launchArgs).toBe("--strict-config --enable foo");
expect(patch.providerInstances?.[ProviderInstanceId.make("codex_personal")]?.driver).toBe(
"codex",
);
@@ -178,11 +180,13 @@ describe("ServerSettingsPatch string normalization", () => {
codex: {
...defaultSettings.providers.codex,
binaryPath: " /opt/homebrew/bin/codex ",
launchArgs: " --strict-config ",
},
},
});
expect(encoded.addProjectBaseDirectory).toBe("~/Development");
expect(encoded.providers?.codex?.binaryPath).toBe("/opt/homebrew/bin/codex");
expect(encoded.providers?.codex?.launchArgs).toBe("--strict-config");
});
});
+9 -1
View File
@@ -191,13 +191,20 @@ export const CodexSettings = makeProviderSettingsSchema(
},
}),
),
launchArgs: TrimmedString.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "Launch arguments",
description: "Additional CLI arguments passed to codex app-server on session start.",
}),
),
customModels: Schema.Array(Schema.String).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
},
{
order: ["binaryPath", "homePath", "shadowHomePath"],
order: ["binaryPath", "homePath", "shadowHomePath", "launchArgs"],
},
);
export type CodexSettings = typeof CodexSettings.Type;
@@ -469,6 +476,7 @@ const CodexSettingsPatch = Schema.Struct({
binaryPath: Schema.optionalKey(TrimmedString),
homePath: Schema.optionalKey(TrimmedString),
shadowHomePath: Schema.optionalKey(TrimmedString),
launchArgs: Schema.optionalKey(TrimmedString),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
+29 -1
View File
@@ -1,6 +1,27 @@
import { describe, expect, it } from "vite-plus/test";
import { parseCliArgs } from "./cliArgs.ts";
import { parseCliArgs, tokenizeCliArgs } from "./cliArgs.ts";
describe("tokenizeCliArgs", () => {
it("preserves quoted values and escaped spaces", () => {
expect(
tokenizeCliArgs(
String.raw`--config model="gpt 5" --enable foo\ bar --config=profile='work profile'`,
),
).toEqual(["--config", "model=gpt 5", "--enable", "foo bar", "--config=profile=work profile"]);
});
it("preserves literal backslashes in path values", () => {
expect(
tokenizeCliArgs(String.raw`--config cacheDir=C:\Users\me --config "quoted=C:\Users\me"`),
).toEqual([
"--config",
String.raw`cacheDir=C:\Users\me`,
"--config",
String.raw`quoted=C:\Users\me`,
]);
});
});
describe("parseCliArgs", () => {
it("returns empty result for empty string", () => {
@@ -57,6 +78,13 @@ describe("parseCliArgs", () => {
});
});
it("parses quoted --append-system-prompt with value and --chrome", () => {
expect(parseCliArgs(`--append-system-prompt "always think step by step" --chrome`)).toEqual({
flags: { "append-system-prompt": "always think step by step", chrome: null },
positionals: [],
});
});
it("parses --max-budget-usd with numeric value", () => {
expect(parseCliArgs("--chrome --max-budget-usd 5.00")).toEqual({
flags: { chrome: null, "max-budget-usd": "5.00" },
+59 -3
View File
@@ -7,10 +7,67 @@ export interface ParseCliArgsOptions {
readonly booleanFlags?: readonly string[];
}
export function tokenizeCliArgs(args?: string): ReadonlyArray<string> {
const input = args?.trim();
if (!input) return [];
const tokens: string[] = [];
let current = "";
let quote: "'" | '"' | undefined;
let quoted = false;
for (let index = 0; index < input.length; index++) {
const char = input[index];
if (char === undefined) continue;
if (quote) {
if (char === quote) {
quote = undefined;
quoted = true;
} else if (char === "\\" && quote === '"') {
const next = input[index + 1];
if (next !== undefined && ['"', "\\", "$", "`"].includes(next)) {
current += next;
index++;
} else {
current += char;
}
} else {
current += char;
}
continue;
}
if (char === "'" || char === '"') {
quote = char;
quoted = true;
} else if (/\s/.test(char)) {
if (current || quoted) {
tokens.push(current);
current = "";
quoted = false;
}
} else if (char === "\\") {
const next = input[index + 1];
if (next !== undefined && /\s/.test(next)) {
current += next;
index++;
} else {
current += char;
}
} else {
current += char;
}
}
if (current || quoted) tokens.push(current);
return tokens;
}
/**
* Parse CLI-style arguments into flags and positionals.
*
* Accepts a string (split by whitespace) or a pre-split argv array.
* Accepts a string (quote-aware tokenized) or a pre-split argv array.
* Supports `--key value`, `--key=value`, and `--flag` (boolean) syntax.
*
* parseCliArgs("")
@@ -32,8 +89,7 @@ export function parseCliArgs(
args: string | readonly string[],
options?: ParseCliArgsOptions,
): ParsedCliArgs {
const tokens =
typeof args === "string" ? args.trim().split(/\s+/).filter(Boolean) : Array.from(args);
const tokens = typeof args === "string" ? tokenizeCliArgs(args) : Array.from(args);
const booleanSet = options?.booleanFlags ? new Set(options.booleanFlags) : undefined;
const flags: Record<string, string | null> = {};