401 lines
16 KiB
TypeScript
401 lines
16 KiB
TypeScript
#!/usr/bin/env bun
|
|
/**
|
|
* claude-codex — compatibility adapter for Codex CLI's non-interactive mode.
|
|
*
|
|
* Satellite callers already speak one internal CLI shape and consume Claude
|
|
* `stream-json` records. This wrapper accepts that shape, invokes
|
|
* `codex exec --json`, and emits the normalised records downstream already
|
|
* understands. It deliberately preserves one important runner invariant: a
|
|
* clean Codex exit without a required STATUS/ASSESSMENT is a format failure,
|
|
* not an infrastructure retry.
|
|
*/
|
|
import { spawn, type Subprocess } from "bun";
|
|
import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
import { homedir, tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { randomUUID } from "node:crypto";
|
|
import {
|
|
AGENT_SESSION_FILE_ENV,
|
|
mappedAgentSessionIdFromEnv,
|
|
recordAgentSessionIdFromEnv,
|
|
} from "../shared/src/agent_session";
|
|
|
|
type ParsedArgs = {
|
|
prompt: string;
|
|
addDirs: string[];
|
|
sessionUuid: string | null;
|
|
resumeUuid: string | null;
|
|
appendSys: string | null;
|
|
model: string | null;
|
|
readOnly: boolean;
|
|
};
|
|
|
|
type Usage = {
|
|
input_tokens: number;
|
|
output_tokens: number;
|
|
cache_read_input_tokens: number;
|
|
cache_creation_input_tokens: number;
|
|
thinking_tokens: number;
|
|
};
|
|
|
|
const CODEX_BIN = process.env.CODEX_BIN || "codex";
|
|
function configuredCodexModel(): string {
|
|
const explicit = process.env.STREAMLINE_CODEX_MODEL?.trim();
|
|
if (explicit) return explicit;
|
|
const codexHome = process.env.CODEX_HOME?.trim() || path.join(homedir(), ".codex");
|
|
try {
|
|
const config = readFileSync(path.join(codexHome, "config.toml"), "utf8");
|
|
const match = config.match(/^\s*model\s*=\s*["']([^"']+)["']/m);
|
|
return match?.[1]?.trim() || "";
|
|
} catch {
|
|
return "";
|
|
}
|
|
}
|
|
const CODEX_MODEL = configuredCodexModel();
|
|
const BRIDGE_DIR = process.env.CODEX_BRIDGE_DIR || path.join(homedir(), ".codex-agent-bridge");
|
|
const DEBUG = process.env.CLAUDE_CODEX_DEBUG === "1";
|
|
|
|
function dbg(message: string): void {
|
|
if (DEBUG) process.stderr.write(`[claude-codex] ${message}\n`);
|
|
}
|
|
|
|
function parseArgs(argv: string[]): ParsedArgs {
|
|
const addDirs: string[] = [];
|
|
let prompt: string | null = null;
|
|
let sessionUuid: string | null = null;
|
|
let resumeUuid: string | null = null;
|
|
let appendSys: string | null = null;
|
|
let model: string | null = null;
|
|
let readOnly = false;
|
|
|
|
const DROP_WITH_VALUE = new Set([
|
|
"--output-format", "--input-format", "--fallback-model", "--max-budget-usd", "--json-schema", "--settings",
|
|
]);
|
|
const DROP_BARE = new Set([
|
|
"--verbose", "--print", "--include-partial-messages", "--replay-user-messages", "--no-session-persistence",
|
|
"--dangerously-skip-permissions",
|
|
]);
|
|
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const arg = argv[i]!;
|
|
if (arg === "-p" || arg === "--print") {
|
|
const next = argv[i + 1];
|
|
if (next !== undefined && !next.startsWith("-")) { prompt = next; i++; }
|
|
continue;
|
|
}
|
|
if (arg === "--add-dir") { const dir = argv[++i]; if (dir) addDirs.push(dir); continue; }
|
|
if (arg === "--session-id") { sessionUuid = argv[++i] ?? null; continue; }
|
|
if (arg === "--resume") { resumeUuid = argv[++i] ?? null; continue; }
|
|
if (arg === "--append-system-prompt") { appendSys = argv[++i] ?? null; continue; }
|
|
if (arg === "--model") { model = argv[++i] ?? null; continue; }
|
|
if (arg === "--remote-control") { i++; continue; }
|
|
if (arg === "--streamline-read-only") { readOnly = true; continue; }
|
|
if (DROP_BARE.has(arg)) continue;
|
|
if (DROP_WITH_VALUE.has(arg)) { i++; continue; }
|
|
if (DROP_WITH_VALUE.has(arg.split("=")[0]!)) continue;
|
|
if (!arg.startsWith("-") && prompt === null) { prompt = arg; continue; }
|
|
dbg(`dropping unrecognised internal arg: ${arg}`);
|
|
}
|
|
if (prompt === null) throw new Error("claude-codex: no prompt found in args");
|
|
return { prompt, addDirs, sessionUuid, resumeUuid, appendSys, model, readOnly };
|
|
}
|
|
|
|
function bridgePath(uuid: string): string {
|
|
return path.join(BRIDGE_DIR, `${uuid}.thread`);
|
|
}
|
|
|
|
function readThreadId(uuid: string): string | null {
|
|
const managed = mappedAgentSessionIdFromEnv("codex", uuid);
|
|
if (managed) return managed;
|
|
try {
|
|
const value = readFileSync(bridgePath(uuid), "utf8").trim();
|
|
return value || null;
|
|
} catch { return null; }
|
|
}
|
|
|
|
function writeThreadId(uuid: string, threadId: string): void {
|
|
recordAgentSessionIdFromEnv("codex", threadId);
|
|
try {
|
|
mkdirSync(BRIDGE_DIR, { recursive: true });
|
|
writeFileSync(bridgePath(uuid), threadId, "utf8");
|
|
} catch (err) {
|
|
dbg(`could not persist Codex thread mapping: ${(err as Error).message}`);
|
|
}
|
|
}
|
|
|
|
function normaliseSandbox(value: string | undefined, readOnly: boolean): "read-only" | "workspace-write" | "danger-full-access" {
|
|
if (readOnly) return "read-only";
|
|
if (value === "read-only" || value === "workspace-write" || value === "danger-full-access") return value;
|
|
if (value) dbg(`invalid STREAMLINE_CODEX_SANDBOX=${value}; using workspace-write`);
|
|
return "workspace-write";
|
|
}
|
|
|
|
function clip(value: string, max = 8_000): string {
|
|
return value.length <= max ? value : `${value.slice(0, max)}\n…(truncated)`;
|
|
}
|
|
|
|
function stringValue(value: unknown): string {
|
|
if (typeof value === "string") return value;
|
|
if (value === null || value === undefined) return "";
|
|
try { return JSON.stringify(value); } catch { return String(value); }
|
|
}
|
|
|
|
function toolName(type: string): string {
|
|
const names: Record<string, string> = {
|
|
command_execution: "Bash",
|
|
file_change: "Edit",
|
|
mcp_tool_call: "MCP",
|
|
web_search: "WebSearch",
|
|
error: "CodexError",
|
|
};
|
|
return names[type] || (type ? type[0]!.toUpperCase() + type.slice(1) : "tool");
|
|
}
|
|
|
|
function mapUsage(raw: unknown): Usage {
|
|
const usage = raw && typeof raw === "object" ? raw as Record<string, unknown> : {};
|
|
const num = (key: string) => typeof usage[key] === "number" ? usage[key] as number : 0;
|
|
const tokenDetail = (value: unknown) => typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
const outputDetails = usage.output_tokens_details && typeof usage.output_tokens_details === "object"
|
|
? usage.output_tokens_details as Record<string, unknown>
|
|
: {};
|
|
return {
|
|
input_tokens: num("input_tokens"),
|
|
output_tokens: num("output_tokens"),
|
|
cache_read_input_tokens: num("cached_input_tokens"),
|
|
cache_creation_input_tokens: num("cache_write_input_tokens"),
|
|
thinking_tokens: tokenDetail(
|
|
usage.thinking_tokens
|
|
?? outputDetails.thinking_tokens
|
|
?? usage.reasoning_output_tokens
|
|
?? usage.reasoning_tokens
|
|
?? outputDetails.reasoning_tokens,
|
|
),
|
|
};
|
|
}
|
|
|
|
const AUTOMODE_SYSPROMPT = [
|
|
"本会话运行在无人值守的自动化流水线中,没有任何人类在观看或会作出回应。",
|
|
"绝对禁止等待用户回复;遇到需要选择的情况,直接采用你推荐的可行方案并继续执行。",
|
|
"自主推进任务至完成,并按提示词要求写出全部报告、证据和终端状态。",
|
|
].join("\n");
|
|
|
|
export async function runClaudeCodex(argv: string[]): Promise<void> {
|
|
let parsed: ParsedArgs;
|
|
try {
|
|
parsed = parseArgs(argv);
|
|
} catch (err) {
|
|
process.stderr.write(`${(err as Error).message}\n`);
|
|
process.exit(2);
|
|
}
|
|
|
|
const isManagedRun = Boolean(process.env[AGENT_SESSION_FILE_ENV]?.trim());
|
|
const isAsking = !isManagedRun && !!(parsed.sessionUuid || parsed.resumeUuid);
|
|
const wrapperSessionId = parsed.resumeUuid || parsed.sessionUuid || randomUUID();
|
|
const bridgeKey = parsed.resumeUuid || parsed.sessionUuid;
|
|
const resumeThreadId = parsed.resumeUuid ? readThreadId(parsed.resumeUuid) : null;
|
|
const finalMessagePath = path.join(tmpdir(), `streamline-codex-${randomUUID()}.last-message`);
|
|
const sandbox = normaliseSandbox(process.env.STREAMLINE_CODEX_SANDBOX, parsed.readOnly);
|
|
const startedAt = Date.now();
|
|
|
|
let emittedInit = false;
|
|
let emittedText = "";
|
|
let finalised = false;
|
|
let lastError = "";
|
|
let turnUsage: Usage = {
|
|
input_tokens: 0,
|
|
output_tokens: 0,
|
|
cache_read_input_tokens: 0,
|
|
cache_creation_input_tokens: 0,
|
|
thinking_tokens: 0,
|
|
};
|
|
let fatalEvent = false;
|
|
const pendingTools = new Map<string, string>();
|
|
let child: Subprocess<"ignore", "pipe", "pipe"> | null = null;
|
|
|
|
const emit = (value: Record<string, unknown>) => process.stdout.write(`${JSON.stringify(value)}\n`);
|
|
const emitInit = () => {
|
|
if (emittedInit) return;
|
|
emittedInit = true;
|
|
emit({
|
|
type: "system", subtype: "init", cwd: process.cwd(), session_id: wrapperSessionId,
|
|
tools: [], model: parsed.model || CODEX_MODEL || "", permissionMode: sandbox,
|
|
apiKeySource: "none", mcp_servers: [], slash_commands: [], codex_exec: true,
|
|
});
|
|
};
|
|
const emitText = (text: string) => {
|
|
if (!text.trim()) return;
|
|
emitInit();
|
|
emittedText += (emittedText ? "\n" : "") + text;
|
|
emit({
|
|
type: "assistant",
|
|
message: { role: "assistant", content: [{ type: "text", text }] },
|
|
session_id: wrapperSessionId, parent_tool_use_id: null, uuid: randomUUID(),
|
|
});
|
|
};
|
|
const emitThinking = (text: string) => {
|
|
if (!text.trim()) return;
|
|
emitInit();
|
|
emit({
|
|
type: "assistant",
|
|
message: { role: "assistant", content: [{ type: "thinking", thinking: text }] },
|
|
session_id: wrapperSessionId, parent_tool_use_id: null, uuid: randomUUID(),
|
|
});
|
|
};
|
|
const startTool = (item: Record<string, unknown>) => {
|
|
const type = typeof item.type === "string" ? item.type : "tool";
|
|
if (["agent_message", "reasoning"].includes(type)) return;
|
|
const id = typeof item.id === "string" ? item.id : randomUUID();
|
|
if (pendingTools.has(id)) return;
|
|
const input = item.command ?? item.arguments ?? item.input ?? item;
|
|
pendingTools.set(id, toolName(type));
|
|
emitInit();
|
|
emit({
|
|
type: "assistant",
|
|
message: { role: "assistant", content: [{ type: "tool_use", id, name: toolName(type), input }] },
|
|
session_id: wrapperSessionId, parent_tool_use_id: null, uuid: randomUUID(),
|
|
});
|
|
};
|
|
const finishTool = (item: Record<string, unknown>) => {
|
|
const type = typeof item.type === "string" ? item.type : "tool";
|
|
if (["agent_message", "reasoning"].includes(type)) return;
|
|
const id = typeof item.id === "string" ? item.id : randomUUID();
|
|
startTool({ ...item, id });
|
|
const name = pendingTools.get(id) || toolName(type);
|
|
pendingTools.delete(id);
|
|
const output = clip(stringValue(item.aggregated_output ?? item.output ?? item.message ?? item.error ?? item));
|
|
const exitCode = item.exit_code;
|
|
const isError = typeof exitCode === "number" ? exitCode !== 0 : type === "error";
|
|
emit({
|
|
type: "user",
|
|
message: { role: "user", content: [{ type: "tool_result", tool_use_id: id, content: output, is_error: isError }] },
|
|
session_id: wrapperSessionId, parent_tool_use_id: null, uuid: randomUUID(),
|
|
});
|
|
if (type === "error") lastError = output;
|
|
void name;
|
|
};
|
|
const finalize = (subtype: string, isError: boolean, result: string) => {
|
|
if (finalised) return;
|
|
finalised = true;
|
|
emitInit();
|
|
emit({
|
|
type: "result", subtype, is_error: isError, result,
|
|
session_id: wrapperSessionId, duration_ms: Date.now() - startedAt,
|
|
total_cost_usd: 0, usage: turnUsage,
|
|
});
|
|
};
|
|
|
|
const promptParts: string[] = [];
|
|
if (!isAsking) promptParts.push(AUTOMODE_SYSPROMPT);
|
|
if (parsed.appendSys) promptParts.push(parsed.appendSys);
|
|
promptParts.push(parsed.prompt);
|
|
const prompt = promptParts.join("\n\n");
|
|
const model = parsed.model || CODEX_MODEL;
|
|
const common = ["--json", "--output-last-message", finalMessagePath, "--skip-git-repo-check"];
|
|
if (model) common.push("--model", model);
|
|
let codexArgs: string[];
|
|
if (resumeThreadId) {
|
|
// Current Codex releases persist the initial session's sandbox/add-dir
|
|
// policy; `exec resume` intentionally exposes a narrower flag surface.
|
|
codexArgs = ["exec", "resume", ...common, resumeThreadId, prompt];
|
|
} else {
|
|
codexArgs = ["exec", ...common, "--color", "never", "--sandbox", sandbox];
|
|
for (const dir of parsed.addDirs) codexArgs.push("--add-dir", dir);
|
|
if (!bridgeKey) codexArgs.push("--ephemeral");
|
|
codexArgs.push(prompt);
|
|
}
|
|
|
|
const consumeEvent = (event: Record<string, unknown>) => {
|
|
const type = typeof event.type === "string" ? event.type : "";
|
|
if (type === "thread.started") {
|
|
const threadId = typeof event.thread_id === "string" ? event.thread_id : "";
|
|
if (threadId && bridgeKey) writeThreadId(bridgeKey, threadId);
|
|
emitInit();
|
|
return;
|
|
}
|
|
if (type === "turn.started") { emitInit(); return; }
|
|
const item = event.item && typeof event.item === "object" ? event.item as Record<string, unknown> : null;
|
|
if (type === "item.started" && item) { startTool(item); return; }
|
|
if (type === "item.completed" && item) {
|
|
const itemType = typeof item.type === "string" ? item.type : "";
|
|
if (itemType === "agent_message") emitText(stringValue(item.text));
|
|
else if (itemType === "reasoning") emitThinking(stringValue(item.text ?? item.summary));
|
|
// Codex emits non-fatal CLI/config diagnostics as `item.error` too. They
|
|
// can precede a perfectly successful turn, so don't render them as a
|
|
// failed tool call; retain the text for a genuinely failing terminal run.
|
|
else if (itemType === "error") {
|
|
lastError = clip(stringValue(item.message ?? item.error ?? item), 2_000);
|
|
dbg(`non-terminal Codex diagnostic: ${lastError}`);
|
|
}
|
|
else finishTool(item);
|
|
return;
|
|
}
|
|
if (type === "turn.completed") { turnUsage = mapUsage(event.usage); return; }
|
|
if (type === "turn.failed" || type === "error") {
|
|
lastError = stringValue(event.error ?? event.message ?? event);
|
|
fatalEvent = true;
|
|
return;
|
|
}
|
|
dbg(`unhandled Codex event: ${type || "unknown"}`);
|
|
};
|
|
|
|
for (const signal of ["SIGINT", "SIGTERM"] as const) {
|
|
process.on(signal, () => {
|
|
lastError = `Codex wrapper received ${signal}`;
|
|
fatalEvent = true;
|
|
try { child?.kill(); } catch { /* already exited */ }
|
|
finalize("error_during_execution", true, lastError);
|
|
process.exit(143);
|
|
});
|
|
}
|
|
|
|
try {
|
|
dbg(`spawning ${CODEX_BIN} ${codexArgs.slice(0, -1).join(" ")} [prompt ${prompt.length} chars]`);
|
|
child = spawn({ cmd: [CODEX_BIN, ...codexArgs], cwd: process.cwd(), stdin: "ignore", stdout: "pipe", stderr: "pipe" });
|
|
const stdoutTask = (async () => {
|
|
const decoder = new TextDecoder();
|
|
let buffer = "";
|
|
for await (const chunk of child!.stdout) {
|
|
buffer += decoder.decode(chunk, { stream: true });
|
|
let newline: number;
|
|
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
const line = buffer.slice(0, newline).trim();
|
|
buffer = buffer.slice(newline + 1);
|
|
if (!line || !line.startsWith("{")) continue;
|
|
try { consumeEvent(JSON.parse(line) as Record<string, unknown>); }
|
|
catch (err) { dbg(`could not decode Codex event: ${(err as Error).message}`); }
|
|
}
|
|
}
|
|
const line = buffer.trim();
|
|
if (line.startsWith("{")) {
|
|
try { consumeEvent(JSON.parse(line) as Record<string, unknown>); }
|
|
catch (err) { dbg(`could not decode trailing Codex event: ${(err as Error).message}`); }
|
|
}
|
|
})();
|
|
const stderrTask = (async () => {
|
|
const decoder = new TextDecoder();
|
|
let stderr = "";
|
|
for await (const chunk of child!.stderr) stderr += decoder.decode(chunk, { stream: true });
|
|
if (stderr.trim()) dbg(`codex stderr: ${clip(stderr.trim(), 1_000)}`);
|
|
return stderr;
|
|
})();
|
|
const exitCode = await child.exited;
|
|
const [, stderr] = await Promise.all([stdoutTask, stderrTask]);
|
|
let finalMessage = "";
|
|
try { finalMessage = readFileSync(finalMessagePath, "utf8").trim(); } catch { /* no final message */ }
|
|
if (finalMessage && !emittedText.includes(finalMessage)) emitText(finalMessage);
|
|
if (exitCode !== 0 && !lastError) lastError = clip(stderr.trim() || `codex exited ${exitCode}`, 2_000);
|
|
const failed = exitCode !== 0 || fatalEvent;
|
|
finalize(failed ? "error_during_execution" : "success", failed, finalMessage || lastError || emittedText || "");
|
|
process.exit(failed ? (exitCode || 1) : 0);
|
|
} catch (err) {
|
|
lastError = (err as Error).message;
|
|
fatalEvent = true;
|
|
finalize("error_during_execution", true, lastError);
|
|
process.exit(1);
|
|
} finally {
|
|
try { unlinkSync(finalMessagePath); } catch { /* best effort */ }
|
|
}
|
|
}
|
|
|
|
if (import.meta.main) await runClaudeCodex(process.argv.slice(2));
|