Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ export const DEFAULT_PLUGIN_CONFIG: PluginConfig = {
liveAccountSync: true,
liveAccountSyncDebounceMs: 250,
liveAccountSyncPollMs: 2_000,
codexCliSessionSupervisor: false,
sessionAffinity: true,
sessionAffinityTtlMs: 20 * 60_000,
sessionAffinityMaxEntries: 512,
Expand Down Expand Up @@ -857,6 +858,25 @@ export function getLiveAccountSyncPollMs(pluginConfig: PluginConfig): number {
);
}

/**
* Determines whether the CLI session supervisor wrapper is enabled.
*
* This accessor is synchronous, side-effect free, and safe for concurrent reads.
* It performs no filesystem I/O and does not expose token material.
*
* @param pluginConfig - The plugin configuration object used as the non-environment fallback
* @returns `true` when the session supervisor should wrap interactive Codex sessions
*/
export function getCodexCliSessionSupervisor(
pluginConfig: PluginConfig,
): boolean {
return resolveBooleanSetting(
"CODEX_AUTH_CLI_SESSION_SUPERVISOR",
pluginConfig.codexCliSessionSupervisor,
false,
);
}

/**
* Indicates whether session affinity is enabled.
*
Expand Down
31 changes: 31 additions & 0 deletions lib/quota-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,19 @@ export interface ProbeCodexQuotaOptions {
model?: string;
fallbackModels?: readonly string[];
timeoutMs?: number;
signal?: AbortSignal;
}

function createAbortError(message: string): Error {
const error = new Error(message);
error.name = "AbortError";
return error;
}

function throwIfQuotaProbeAborted(signal: AbortSignal | undefined): void {
if (signal?.aborted) {
throw createAbortError("Quota probe aborted");
}
}

/**
Expand All @@ -331,8 +344,11 @@ export async function fetchCodexQuotaSnapshot(
let lastError: Error | null = null;

for (const model of models) {
throwIfQuotaProbeAborted(options.signal);
try {
throwIfQuotaProbeAborted(options.signal);
const instructions = await getCodexInstructions(model);
throwIfQuotaProbeAborted(options.signal);
const probeBody: RequestBody = {
model,
stream: true,
Expand All @@ -356,6 +372,12 @@ export async function fetchCodexQuotaSnapshot(
headers.set("content-type", "application/json");

const controller = new AbortController();
const onAbort = () => controller.abort(options.signal?.reason);
if (options.signal?.aborted) {
controller.abort(options.signal.reason);
} else {
options.signal?.addEventListener("abort", onAbort, { once: true });
}
const timeout = setTimeout(() => controller.abort(), timeoutMs);
let response: Response;
try {
Expand All @@ -367,6 +389,7 @@ export async function fetchCodexQuotaSnapshot(
});
} finally {
clearTimeout(timeout);
options.signal?.removeEventListener("abort", onAbort);
}

const snapshotBase = parseQuotaSnapshotBase(response.headers, response.status);
Expand All @@ -390,6 +413,7 @@ export async function fetchCodexQuotaSnapshot(

const unsupportedInfo = getUnsupportedCodexModelInfo(errorBody);
if (unsupportedInfo.isUnsupported) {
throwIfQuotaProbeAborted(options.signal);
lastError = new Error(
unsupportedInfo.message ?? `Model '${model}' unsupported for this account`,
);
Expand All @@ -406,9 +430,16 @@ export async function fetchCodexQuotaSnapshot(
}
lastError = new Error("Codex response did not include quota headers");
} catch (error) {
if (options.signal?.aborted) {
throw error instanceof Error ? error : createAbortError("Quota probe aborted");
}
lastError = error instanceof Error ? error : new Error(String(error));
}
}

if (options.signal?.aborted) {
throw createAbortError("Quota probe aborted");
}

throw lastError ?? new Error("Failed to fetch quotas");
}
1 change: 1 addition & 0 deletions lib/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const PluginConfigSchema = z.object({
liveAccountSync: z.boolean().optional(),
liveAccountSyncDebounceMs: z.number().min(50).optional(),
liveAccountSyncPollMs: z.number().min(500).optional(),
codexCliSessionSupervisor: z.boolean().optional(),
sessionAffinity: z.boolean().optional(),
sessionAffinityTtlMs: z.number().min(1_000).optional(),
sessionAffinityMaxEntries: z.number().min(8).optional(),
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"test:model-matrix": "node scripts/test-model-matrix.js",
"test:model-matrix:smoke": "node scripts/test-model-matrix.js --smoke",
"test:model-matrix:report": "node scripts/test-model-matrix.js --smoke --report-json=.tmp/model-matrix-report.json",
"test:session-supervisor:smoke": "vitest run test/codex-supervisor.test.ts test/codex-bin-wrapper.test.ts test/plugin-config.test.ts test/quota-probe.test.ts",
"clean:repo": "node scripts/repo-hygiene.js clean --mode aggressive",
"clean:repo:check": "node scripts/repo-hygiene.js check",
"bench:edit-formats": "node scripts/benchmark-edit-formats.mjs --preset=codex-core",
Expand Down
91 changes: 91 additions & 0 deletions scripts/codex-routing.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const AUTH_SUBCOMMANDS = new Set([
"fix",
"doctor",
]);
const COMMAND_FLAGS_WITH_VALUE = new Set(["-c", "--config"]);
const HELP_OR_VERSION_FLAGS = new Set(["--help", "-h", "--version"]);

export function normalizeAuthAlias(args) {
if (args.length >= 2 && args[0] === "multi" && args[1] === "auth") {
Expand All @@ -32,4 +34,93 @@ export function shouldHandleMultiAuthAuth(args) {
return AUTH_SUBCOMMANDS.has(subcommand);
}

export function findPrimaryCodexCommand(args) {
let expectFlagValue = false;
let stopOptionParsing = false;

for (let index = 0; index < args.length; index += 1) {
const normalizedArg = `${args[index] ?? ""}`.trim().toLowerCase();
if (normalizedArg.length === 0) {
continue;
}
if (expectFlagValue) {
expectFlagValue = false;
continue;
}
if (!stopOptionParsing && normalizedArg === "--") {
stopOptionParsing = true;
continue;
}
if (!stopOptionParsing) {
if (COMMAND_FLAGS_WITH_VALUE.has(normalizedArg)) {
expectFlagValue = true;
continue;
}
if (normalizedArg.startsWith("--config=")) {
continue;
}
if (normalizedArg.startsWith("-")) {
continue;
}
}
return {
command: normalizedArg,
index,
};
}

return null;
}

export function hasTopLevelHelpOrVersionFlag(args) {
let expectFlagValue = false;

for (let index = 0; index < args.length; index += 1) {
const normalizedArg = `${args[index] ?? ""}`.trim().toLowerCase();
if (normalizedArg.length === 0) {
continue;
}
if (expectFlagValue) {
expectFlagValue = false;
continue;
}
if (normalizedArg === "--") {
return false;
}
if (HELP_OR_VERSION_FLAGS.has(normalizedArg)) {
return true;
}
if (COMMAND_FLAGS_WITH_VALUE.has(normalizedArg)) {
expectFlagValue = true;
continue;
}
if (normalizedArg.startsWith("--config=")) {
continue;
}
if (normalizedArg.startsWith("-")) {
continue;
}
return false;
}

return false;
}

export function splitCodexCommandArgs(args) {
const primaryCommand = findPrimaryCodexCommand(args);
if (!primaryCommand) {
return {
leadingArgs: [...args],
command: null,
trailingArgs: [],
};
}

return {
leadingArgs: args.slice(0, primaryCommand.index),
command: primaryCommand.command,
trailingArgs: args.slice(primaryCommand.index + 1),
};
}

export { AUTH_SUBCOMMANDS };
Loading