Skip to content

amElnagdy/delegate-skills / skills/codex-delegate

codex-delegate

Verified

Delegate a coding task to the OpenAI Codex CLI as a background implementer, then review its diff and land it yourself. Use this whenever the user wants to hand implementation work to Codex — phrasings like "have Codex do X", "delegate this to Codex", "run it through Codex", or "use Codex to implement/fix/refactor" — or to run a queue of coding tasks through Codex while staying the reviewer. Prefer it over a one-shot Codex forwarder (such as the codex-rescue agent) when the user will review the diff and commit it themselves. DO NOT USE for tasks small enough to do inline, or when the user wants the code written directly without delegating.

scripts/relay.mjs

View on GitHub
#!/usr/bin/env node
/**
 * delegate-skills · codex-delegate · relay.mjs
 *
 * Dispatch a self-contained brief to the OpenAI Codex CLI (`codex exec`),
 * capture the run, and write a structured result the orchestrating agent can
 * review. The orchestrator runs this one command and reads the result JSON —
 * every Codex-specific mechanic lives in here, which keeps the skill
 * orchestrator-agnostic. Verified on Claude Code; other shell-capable agents
 * (OpenCode, Cursor, …) are designed-for but not yet verified.
 *
 * Trust posture: relay.mjs itself makes no network calls, reads or writes no
 * credentials, and sends no telemetry; it has no dependencies (Node built-ins
 * only). It shells out only to `codex` and `git`. The `codex` process it
 * launches does authenticate — exactly as you do at the terminal. Read this
 * file before you run it.
 *
 * It deliberately does NOT commit. Whether Codex's sandbox can write `.git`
 * varies by Codex version, OS, and execution path, so committing is always the
 * orchestrator's job — after it reviews the diff and re-runs the project gates.
 *
 * Usage:
 *   node relay.mjs --brief <file> [options]
 *   cat brief.txt | node relay.mjs [options]
 *
 * Options:
 *   --brief <file>          Path to the brief. If omitted, the brief is read from stdin.
 *   --cd <dir>              Working root for Codex (default: current directory).
 *   --lane <name>           Fleet lane from delegate-setup config (dials apply; explicit flags win).
 *   --model <name>          Codex model (default: Codex's own configured default).
 *   --effort <level>        Reasoning effort, passed to Codex as
 *                           `-c model_reasoning_effort=<level>` (default: Codex's
 *                           own configured default).
 *   --subagent-model <name> Default model for subagents Codex spawns during the run,
 *                           passed as `-c agents.default_subagent_model=<name>`.
 *   --subagent-effort <level>
 *                           Default reasoning effort for those subagents, passed as
 *                           `-c agents.default_subagent_reasoning_effort=<level>`.
 *                           Without either, subagents follow Codex's own config. A model
 *                           TOML reads as a number (e.g. 5.5) fails at startup; an
 *                           unknown model or unsupported effort fails only the spawn, so
 *                           the run can still exit 0. Pass them again on every resume:
 *                           Codex does not carry them over.
 *   --web-search <mode>     Codex's web search mode, passed as `-c web_search=<mode>`
 *                           (Codex's modes: disabled | cached | indexed | live; default:
 *                           Codex's own configured default). Search is a hosted tool, so
 *                           it works under every sandbox, read-only included. Pass it
 *                           again on every resume: Codex does not carry it over.
 *   --network-access        Allow network access inside the workspace-write sandbox, passed
 *                           to Codex as `-c sandbox_workspace_write.network_access=true`.
 *                           Pass it again on every resume, with the sandbox named by
 *                           --sandbox or a fleet lane: Codex does not carry it over.
 *                           Rejected with a read-only sandbox, which Codex keeps offline.
 *   --sandbox <mode>        read-only | workspace-write | danger-full-access
 *                           (default: workspace-write).
 *   --read-only             Shortcut for --sandbox read-only (review/diagnosis, no edits).
 *   --resume-last           Continue the most recent Codex session; send only the delta brief.
 *                           An explicit --sandbox/--read-only override applies to the resumed turn.
 *   --session <id>          Continue a specific Codex session by thread id (from a prior
 *                           result.json). Safer than --resume-last when other Codex runs
 *                           may have happened since - "last" is global, not per-repo.
 *                           Mutually exclusive with --resume-last.
 *   --clean-env             Launch Codex and its version preflight with only runtime basics.
 *                           Changes inherited variables only; does not protect files or other
 *                           same-user secrets.
 *   --ignore-user-config    Do not load Codex user config. Authentication still uses CODEX_HOME;
 *                           useful for isolated reviews that must not start ambient MCP servers.
 *   --no-project-doc        Do not load project AGENTS.md docs, passed as
 *                           `-c project_doc_max_bytes=0`. Codex's user-level instructions
 *                           in CODEX_HOME still load. Pass it again on every resume: Codex
 *                           does not carry it over.
 *   --keep-env <name>       Keep one additional variable under --clean-env (repeatable).
 *                           Required for environment-backed auth and other stripped variables.
 *   --skip-git-repo-check   Allow running outside a git repository.
 *   --timeout <dur>         Relay-side watchdog (default: off). Durations use h/m/s
 *                           strings like 30m or 2h. On expiry the codex child is killed
 *                           and result.json gets status "timeout". Codex has no timeout
 *                           flag of its own, so the watchdog is relay-only.
 *   --out-dir <dir>         Where to write run artifacts (default: a fresh dir under
 *                           the system temp dir, so the repo under review stays clean).
 *   -h, --help              Show this help.
 *
 * Result: written to <out-dir>/result.json and summarized on stdout —
 *   status, exitCode, signal, codexVersion, threadId (for a later resume), finalMessage
 *   (Codex's own report), touchedFiles (git porcelain, null if git can't report), stderrTail on a
 *   run that did not succeed, and the paths to events.jsonl, final.txt and stderr.txt. stderr.txt
 *   holds the complete stderr stream; stderrTail is up to 20 nonblank lines from its final
 *   64 KiB, with a partial first line marked as truncated.
 *
 * Exit codes: a pre-run usage error (bad/missing args, empty brief) exits 2
 * before any run and writes no result file; a missing `codex` binary exits 127;
 * otherwise the exit code mirrors Codex's own (0 success, non-zero failure).
 * If the child dies on a signal, the exit code is 128 plus the signal number and
 * `result.json` records the signal.
 * Once the brief validates, `result.json` is written on every outcome —
 * completed, failed, timeout (the --timeout watchdog fired), aborted (the relay
 * itself was killed and forwarded the kill to codex), or codex_unavailable. An
 * orchestrator that polls for the file must therefore also treat a non-zero exit
 * with no file as a usage error.
 *
 * Windows: a sandboxed run (read-only or workspace-write) gets a PATH with every
 * `WindowsApps` entry removed, for the preflight and the dispatch alike. The Microsoft
 * Store installs apps — including PowerShell 7 — under a folder whose ACLs deny
 * execution to the restricted token Codex's sandbox runs commands with, and Codex
 * prefers a `pwsh` found on PATH, so a Store `pwsh` makes every sandboxed command
 * fail with 0xC0070005. Without those entries Codex falls back to System32
 * powershell.exe. `--sandbox danger-full-access` runs without the restricted token
 * and gets PATH unchanged.
 */

import {spawn, execSync, execFileSync, spawnSync } from "node:child_process";
import { mkdirSync, writeFileSync, renameSync, readFileSync, existsSync, appendFileSync, openSync, fstatSync, readSync, closeSync } from "node:fs";
import {join, resolve, basename, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { constants, tmpdir } from "node:os";
import { StringDecoder } from "node:string_decoder";

const VERSION_PROBE_TIMEOUT_MS = 10_000;
const MAX_TIMER_MS = 2_147_483_647;
const MAX_STDERR_TAIL_BYTES = 64 * 1024;
const SANDBOX_MODES = new Set(["read-only", "workspace-write", "danger-full-access"]);
const SAFE_SESSION = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
const SAFE_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
// Model reaches cmd.exe on win32 (shell:true for the codex.cmd shim) — same shell-safe
// family as grok/pi. Keep in lockstep with delegate-setup MODEL_TOKEN.shellSafe.
const SAFE_MODEL = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
// Effort and web search modes are Codex-owned enums that vary by version; the relay
// checks only for a bare token, which also keeps them inert in cmd.exe on win32.
const BARE_TOKEN = /^[a-z][a-z0-9-]*$/i;

const IMPLEMENTER_KEY = "codex";

function applyFleetLane(opts, flagged) {
  if (!opts.lane) return;
  const script = join(dirname(fileURLToPath(import.meta.url)), "../../delegate-setup/scripts/lane.mjs");
  if (!existsSync(script)) {
    fail("--lane requires the delegate-setup skill installed beside this relay");
  }
  const r = spawnSync(
    process.execPath,
    [script, "resolve", "--cwd", opts.cd, "--lane", opts.lane, "--implementer", IMPLEMENTER_KEY],
    { encoding: "utf8", env: process.env },
  );
  if (r.error) fail(`lane resolve failed: ${r.error.message}`);
  if (r.status !== 0) {
    fail((r.stderr || "lane resolve failed").trim().replace(/^lane\.mjs:\s*/, ""));
  }
  let resolved;
  try {
    const lines = (r.stdout || "").trim().split("\n").filter(Boolean);
    resolved = JSON.parse(lines[lines.length - 1]);
  } catch {
    fail("lane resolve returned invalid JSON");
  }
  opts.laneSource = resolved.source;
  for (const [field, value] of Object.entries(resolved.dials || {})) {
    if (flagged.has(field)) continue;
    if (field === "autonomy" && (flagged.has("autonomy") || flagged.has("sandbox") || flagged.has("readOnly"))) continue;
    if (field === "agent" && (flagged.has("agent") || flagged.has("readOnly"))) continue;
    if (field === "sandbox" && (flagged.has("sandbox") || flagged.has("readOnly"))) continue;
    if (field === "permissionMode" && (flagged.has("permissionMode") || flagged.has("readOnly"))) continue;
    if (field === "planOnly" && (flagged.has("planOnly") || flagged.has("readOnly"))) continue;
    if (field === "readOnly" && flagged.has("readOnly")) continue;
    if (field === "force" && flagged.has("force")) continue;
    opts[field] = value;
    if (field === "sandbox") opts.sandboxConfigured = true;
  }
}

function fail(message, code = 2) {
  process.stderr.write(`relay: ${message}\n`);
  process.exit(code);
}

function parseArgs(argv) {
  const flagged = new Set();
  const opts = {
    lane: null,
    laneSource: null,
    brief: null,
    cd: process.cwd(),
    model: null,
    effort: null,
    subagentModel: null,
    subagentEffort: null,
    webSearch: null,
    networkAccess: false,
    sandbox: "workspace-write",
    sandboxConfigured: false,
    resumeLast: false,
    session: null,
    cleanEnv: false,
    ignoreUserConfig: false,
    noProjectDoc: false,
    keepEnv: [],
    skipGitRepoCheck: false,
    timeout: null,
    outDir: null,
  };
  for (let i = 0; i < argv.length; i += 1) {
    const arg = argv[i];
    const next = () => {
      const value = argv[i + 1];
      if (value === undefined) fail(`${arg} requires a value`);
      i += 1;
      return value;
    };
    switch (arg) {
      case "-h":
      case "--help":
        process.stdout.write(headerComment());
        process.exit(0);
        break;
      case "--brief": opts.brief = next(); break;
      case "--cd": opts.cd = resolve(next()); break;
      case "--lane": opts.lane = next(); break;
      case "--model": opts.model = next(); flagged.add("model"); break;
      case "--effort": opts.effort = next(); flagged.add("effort"); break;
      case "--subagent-model": opts.subagentModel = next(); break;
      case "--subagent-effort": opts.subagentEffort = next(); break;
      case "--web-search": opts.webSearch = next(); break;
      case "--network-access": opts.networkAccess = true; break;
      case "--sandbox": opts.sandbox = next(); opts.sandboxConfigured = true; flagged.add("sandbox"); break;
      case "--read-only": opts.sandbox = "read-only"; opts.sandboxConfigured = true; flagged.add("sandbox"); flagged.add("readOnly"); break;
      case "--resume-last": opts.resumeLast = true; break;
      case "--session": opts.session = next(); break;
      case "--clean-env": opts.cleanEnv = true; break;
      case "--ignore-user-config": opts.ignoreUserConfig = true; break;
      case "--no-project-doc": opts.noProjectDoc = true; break;
      case "--keep-env": opts.keepEnv.push(next()); break;
      case "--skip-git-repo-check": opts.skipGitRepoCheck = true; break;
      case "--timeout": opts.timeout = next(); flagged.add("timeout"); break;
      case "--out-dir": opts.outDir = resolve(next()); break;
      default:
        fail(`unknown option: ${arg}`);
    }
  }
  applyFleetLane(opts, flagged);
  if (!SANDBOX_MODES.has(opts.sandbox)) {
    fail(`invalid --sandbox "${opts.sandbox}" (expected: ${[...SANDBOX_MODES].join(", ")})`);
  }
  // Codex ignores the workspace-write network key under read-only and the run stays
  // offline without a word, so refuse the pair rather than record access that never happened.
  if (opts.networkAccess && opts.sandbox === "read-only") {
    fail("--network-access cannot be combined with a read-only sandbox: Codex keeps read-only offline");
  }
  // An unqualified resume runs under Codex's configured sandbox, which may be read-only
  // and drop the override without a word; require the sandbox named so the record holds.
  if (opts.networkAccess && (opts.session || opts.resumeLast) && !opts.sandboxConfigured) {
    fail("--network-access on a resumed run needs the sandbox named by --sandbox (e.g. --sandbox workspace-write) or a fleet lane");
  }
  if (opts.effort !== null && !BARE_TOKEN.test(opts.effort)) {
    fail(`invalid --effort "${opts.effort}" (expected a non-empty bare token)`);
  }
  if (opts.webSearch !== null && !BARE_TOKEN.test(opts.webSearch)) {
    fail(`invalid --web-search "${opts.webSearch}" (expected a non-empty bare token)`);
  }
  if (opts.model !== null && !SAFE_MODEL.test(opts.model)) {
    fail("--model contains unsupported characters (allowed: letters, digits, . _ : / -)");
  }
  if (opts.subagentModel !== null && !SAFE_MODEL.test(opts.subagentModel)) {
    fail("--subagent-model contains unsupported characters (allowed: letters, digits, . _ : / -)");
  }
  if (opts.subagentEffort !== null && !BARE_TOKEN.test(opts.subagentEffort)) {
    fail(`invalid --subagent-effort "${opts.subagentEffort}" (expected a non-empty bare token)`);
  }
  if (opts.keepEnv.length && !opts.cleanEnv) {
    fail("--keep-env requires --clean-env");
  }
  const invalidEnvName = opts.keepEnv.find((name) => !SAFE_ENV_NAME.test(name));
  if (invalidEnvName) {
    fail(`invalid --keep-env "${invalidEnvName}" (expected an environment variable name)`);
  }
  const missingEnvName = opts.keepEnv.find((name) => process.env[name] === undefined);
  if (missingEnvName) {
    fail(`--keep-env "${missingEnvName}" is not set`);
  }
  // The watchdog is relay-only (codex has no timeout flag), so a malformed
  // --timeout must fail loudly here - a silent no-watchdog fallback would be wrong.
  if (opts.timeout !== null && parseDuration(opts.timeout) === null) {
    fail(`--timeout "${opts.timeout}" is invalid or too long; use a positive h/m/s duration no longer than about 24 days`);
  }
  if (opts.session !== null && opts.resumeLast) {
    fail("--session and --resume-last are mutually exclusive; pass only one");
  }
  // This value reaches cmd.exe on win32 (shell:true for the codex.cmd shim), so
  // accept only the same shell-safe session token shape used by sibling relays.
  if (opts.session !== null && !SAFE_SESSION.test(opts.session)) {
    fail("--session must be a shell-safe thread id (letters, digits, . _ : -)");
  }
  return opts;
}

function parseDuration(duration) {
  const match = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(duration);
  if (!match || (!match[1] && !match[2] && !match[3])) return null;
  try {
    const seconds =
      BigInt(match[1] || 0) * 3600n +
      BigInt(match[2] || 0) * 60n +
      BigInt(match[3] || 0);
    const milliseconds = seconds * 1000n;
    if (milliseconds <= 0n || milliseconds > BigInt(MAX_TIMER_MS)) return null;
    return Number(milliseconds);
  } catch {
    return null;
  }
}

function killChild(child, signal = "SIGTERM") {
  if (!child || !child.pid) return;
  if (process.platform === "win32") {
    if (signal !== "SIGTERM") return;
    try {
      execFileSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], {
        stdio: ["ignore", "ignore", "inherit"],
      });
    } catch {
      // The process tree already exited.
    }
    return;
  }
  try {
    process.kill(-child.pid, signal);
  } catch {
    try {
      child.kill(signal);
    } catch {
      // The process group already exited.
    }
  }
}

function headerComment() {
  // The leading block comment doubles as --help text.
  const src = readFileSync(new URL(import.meta.url), "utf8");
  const match = src.match(/\/\*\*([\s\S]*?)\*\//);
  if (!match) return "relay.mjs — dispatch a brief to codex exec\n";
  return match[1].replace(/^\s*\* ?/gm, "").trim() + "\n";
}

function readBrief(opts) {
  if (opts.brief) {
    if (!existsSync(opts.brief)) fail(`brief file not found: ${opts.brief}`);
    return readFileSync(opts.brief, "utf8");
  }
  // No --brief: read from stdin (fd 0). Empty stdin is an error.
  if (process.stdin.isTTY) {
    fail("no --brief given and stdin is a TTY; pass --brief <file> or pipe the brief on stdin");
  }
  let stdin = "";
  try {
    stdin = readFileSync(0, "utf8");
  } catch {
    stdin = "";
  }
  return stdin;
}

function versionProbeTimeout(opts) {
  // The watchdog is only armed once codex is running, so the preflight needs a bound of
  // its own: a `codex --version` that never returns would wedge the relay here, before
  // any result.json exists, and --timeout could not reach it.
  const timeoutMs = opts.timeout === null ? null : parseDuration(opts.timeout);
  return timeoutMs === null ? VERSION_PROBE_TIMEOUT_MS : Math.min(timeoutMs, VERSION_PROBE_TIMEOUT_MS);
}

function codexEnv(opts) {
  const env = opts.cleanEnv ? cleanEnvironment(opts) : { ...process.env };
  if (process.platform === "win32" && opts.sandbox !== "danger-full-access") removeWindowsAppsFromPath(env);
  return env;
}

function cleanEnvironment(opts) {
  const keep = ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "LC_CTYPE", "TERM",
    "TMPDIR", "CODEX_HOME", "SystemRoot", "SystemDrive", "USERPROFILE", "APPDATA", "LOCALAPPDATA",
    "TEMP", "TMP", "PATHEXT", "COMSPEC", ...opts.keepEnv];
  return Object.fromEntries(keep.filter((key) => process.env[key] !== undefined).map((key) => [key, process.env[key]]));
}

// Both Store roots: "C:\Program Files\WindowsApps\<package>" and the per-user alias
// folder "%LOCALAPPDATA%\Microsoft\WindowsApps" (a symlink into the same protected tree).
const WINDOWS_APPS_PATH_ENTRY = /(^|[\\/])WindowsApps([\\/]|$)/i;

function removeWindowsAppsFromPath(env) {
  // process.env is case-insensitive on win32, but a spread copy keeps the original key
  // casing ("Path"), and a caller-built env may carry both spellings — rewrite every one.
  for (const key of Object.keys(env)) {
    if (key.toUpperCase() !== "PATH") continue;
    env[key] = env[key].split(";").filter((entry) => !WINDOWS_APPS_PATH_ENTRY.test(entry)).join(";");
  }
}

function codexVersion(probeTimeoutMs, env) {
  try {
    // On Windows, npm installs `codex` as a .cmd shim; Node's CreateProcess only
    // auto-appends .exe, never .cmd, so launching it needs shell:true there or it
    // ENOENTs on a working install. POSIX is unaffected. (git installs a real
    // git.exe and must NOT get this flag — see gitTouchedFiles.)
    const options = {
      encoding: "utf8",
      shell: process.platform === "win32",
      timeout: probeTimeoutMs,
      killSignal: "SIGKILL",
      env,
    };
    const version = (process.platform === "win32"
      ? execSync("codex --version", options)
      : execFileSync("codex", ["--version"], options)).trim();
    return { version: version || "unknown", error: null };
  } catch (error) {
    if (error?.code === "ENOENT") return { version: null, error: null };
    // shell:true routes a missing binary through cmd.exe, which reports it as a non-zero
    // exit rather than ENOENT; that is still "not installed", not a broken install.
    if (process.platform === "win32" &&
        /not recognized as an internal or external command/i.test(String(error?.stderr || ""))) {
      return { version: null, error: null };
    }
    // Anything else — a hung probe we killed, or a real non-zero exit — means codex is
    // installed but not usable. Reporting that as "unavailable" would send the caller
    // off to reinstall a binary that is already there.
    return { version: null, error };
  }
}

function gitTouchedFiles(cwd) {
  try {
    const output = execFileSync("git", ["status", "--porcelain"], {
      cwd,
      encoding: "utf8",
      timeout: 10_000,
      killSignal: "SIGKILL",
      stdio: ["ignore", "pipe", "ignore"],
      maxBuffer: 64 * 1024 * 1024,
    });
    return output.split("\n").map((line) => line.trimEnd()).filter(Boolean);
  } catch {
    return null;
  }
}

function timestamp() {
  // Local script (not a workflow): Date is available and fine here.
  return new Date().toISOString().replace(/[:.]/g, "-");
}

function buildArgv(opts, finalPath) {
  const argv = ["exec"];
  if (opts.ignoreUserConfig) argv.push("--ignore-user-config");
  const resuming = Boolean(opts.session || opts.resumeLast);
  // Codex accepts shared exec options before the resume subcommand. Reapply only
  // an explicitly selected sandbox; otherwise leave the active Codex config alone.
  if (resuming && opts.sandboxConfigured) argv.push("-s", opts.sandbox);
  if (opts.session) argv.push("resume", opts.session);
  else if (opts.resumeLast) argv.push("resume", "--last");
  // ponytail: shell:true on win32 (needed for the codex.cmd shim) doesn't quote
  // args, so a temp path with spaces (C:\Users\First Last\...) splits and the
  // trailing "-" misparses (issue #3). Quote the only spaceable arg in argv.
  // Ceiling: if quoting proves too blunt, drop shell:true and resolve the shim.
  const outPath = process.platform === "win32" ? `"${finalPath}"` : finalPath;
  argv.push("--json", "-o", outPath);
  if (!resuming) {
    argv.push("-s", opts.sandbox);
  }
  if (opts.model) argv.push("-m", opts.model);
  // `-c` is accepted by the resume subcommand, so the effort, subagent, web search, network and
  // project-doc overrides apply to fresh and resumed runs alike. Keep every `-c` after `resume`: once one
  // follows it, Codex drops any placed before it.
  if (opts.effort !== null) argv.push("-c", `model_reasoning_effort=${opts.effort}`);
  if (opts.subagentModel !== null) argv.push("-c", `agents.default_subagent_model=${opts.subagentModel}`);
  if (opts.subagentEffort !== null) argv.push("-c", `agents.default_subagent_reasoning_effort=${opts.subagentEffort}`);
  if (opts.webSearch !== null) argv.push("-c", `web_search=${opts.webSearch}`);
  if (opts.networkAccess) argv.push("-c", "sandbox_workspace_write.network_access=true");
  if (opts.noProjectDoc) argv.push("-c", "project_doc_max_bytes=0");
  if (opts.skipGitRepoCheck) argv.push("--skip-git-repo-check");
  argv.push("-"); // read the prompt from stdin
  return argv;
}

function extractThreadId(event) {
  return (
    event.thread_id ??
    event.threadId ??
    (event.thread && (event.thread.thread_id ?? event.thread.id)) ??
    null
  );
}

function recordEventLine(eventsPath, line) {
  // Append one stdout line to the event log and pull a thread id from it when the
  // line is a JSON event. Non-JSON progress lines (and a newline-less final line)
  // are preserved in events.jsonl regardless; they just carry no thread id.
  appendFileSync(eventsPath, `${line}\n`, "utf8");
  try {
    return extractThreadId(JSON.parse(line));
  } catch {
    return null;
  }
}

function prepareRunDir(opts, brief) {
  const startedAt = new Date().toISOString();
  // Default the run dir to system temp so the repo under review stays pristine —
  // the touched-files report must show only Codex's edits, not relay's artifacts.
  const outDir = opts.outDir || join(tmpdir(), "delegate-relay", `${basename(opts.cd) || "repo"}-${timestamp()}`);
  mkdirSync(outDir, { recursive: true });
  const run = {
    startedAt,
    eventsPath: join(outDir, "events.jsonl"),
    finalPath: join(outDir, "final.txt"),
    briefPath: join(outDir, "brief.txt"),
    stderrPath: join(outDir, "stderr.txt"),
    resultPath: join(outDir, "result.json"),
  };
  writeFileSync(run.briefPath, brief, "utf8");
  writeFileSync(run.eventsPath, "", "utf8");
  writeFileSync(run.stderrPath, "", "utf8");
  return run;
}

function makeResultWriter(opts, version, run) {
  // Returns writeResult(extra): merges the per-outcome fields onto the run's
  // standing metadata, persists result.json, and returns the object it just
  // wrote so the caller can hand it straight to printSummary.
  return (extra) => {
    const resuming = Boolean(opts.resumeLast || opts.session);
    const result = {
      schema: "delegate-relay.result.v1",
      lane: opts.lane,
      laneSource: opts.laneSource,
      workdir: opts.cd,
      sandbox: !resuming || opts.sandboxConfigured ? opts.sandbox : "(Codex config on resume)",
      model: opts.model,
      effort: opts.effort,
      subagentModel: opts.subagentModel,
      subagentEffort: opts.subagentEffort,
      webSearch: opts.webSearch,
      networkAccess: opts.networkAccess,
      resumeLast: opts.resumeLast,
      session: opts.session,
      cleanEnv: opts.cleanEnv,
      ignoreUserConfig: opts.ignoreUserConfig,
      noProjectDoc: opts.noProjectDoc,
      keepEnv: opts.keepEnv,
      codexVersion: version,
      startedAt: run.startedAt,
      finishedAt: new Date().toISOString(),
      briefPath: run.briefPath,
      eventsPath: run.eventsPath,
      finalPath: existsSync(run.finalPath) ? run.finalPath : null,
      stderrPath: run.stderrPath,
      ...extra,
    };
    // Publish atomically so a polling orchestrator never reads a half-written file
    // (same idiom as claude-delegate's writeJsonAtomic and qoder-delegate).
    const temporary = `${run.resultPath}.${process.pid}.tmp`;
    writeFileSync(temporary, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    renameSync(temporary, run.resultPath);
    return result;
  };
}

function reportUnavailable(writeResult, resultPath) {
  const result = writeResult({ status: "codex_unavailable", exitCode: 127, signal: null, threadId: null, finalMessage: "", touchedFiles: null });
  printSummary(result, resultPath);
  process.stderr.write("relay: `codex` not found on PATH. Install it (npm i -g @openai/codex) and run `codex login`.\n");
  process.exit(127);
}

// ponytail: bound the summary to the final 64 KiB; read stderrPath for longer diagnostics.
// Reading the whole log here can exhaust memory before publishing a failure or forwarding an abort.
function stderrTail(stderrPath) {
  let fd;
  try {
    fd = openSync(stderrPath, "r");
    const size = fstatSync(fd).size;
    const start = Math.max(0, size - MAX_STDERR_TAIL_BYTES);
    const readStart = Math.max(0, start - 1);
    const buffer = Buffer.alloc(size - readStart);
    let bytesRead = 0;
    while (bytesRead < buffer.length) {
      const count = readSync(fd, buffer, bytesRead, buffer.length - bytesRead, readStart + bytesRead);
      if (count === 0) break;
      bytesRead += count;
    }
    let offset = start - readStart;
    // The preceding byte distinguishes a cut line from a line starting at the window boundary.
    const partialLine = offset > 0 && buffer[0] !== 0x0a;
    while (partialLine && offset < bytesRead && (buffer[offset] & 0xc0) === 0x80) offset += 1;
    const lines = buffer.subarray(offset, bytesRead).toString("utf8")
      .split(/\r?\n/)
      .map((line) => line.trimEnd());
    if (partialLine && lines[0]?.trim()) lines[0] = `[truncated; read stderrPath] ${lines[0]}`;
    return lines.filter((line) => line.trim()).slice(-20);
  } catch {
    // A missing or unreadable diagnostic must not prevent the run result from being published.
    return [];
  } finally {
    if (fd !== undefined) closeSync(fd);
  }
}

function reportVersionFailure(opts, writeResult, run, error, probeTimeoutMs) {
  const timedOut = error?.code === "ETIMEDOUT";
  const stderr = String(error?.stderr || "").trim();
  if (stderr) writeFileSync(run.stderrPath, `${stderr}\n`, "utf8");
  const message = timedOut
    ? `codex --version preflight timed out after ${probeTimeoutMs}ms; Codex was not dispatched`
    : `codex --version preflight failed${Number.isInteger(error?.status) ? ` with exit ${error.status}` : ""}; Codex was not dispatched`;
  const result = writeResult({
    status: timedOut ? "timeout" : "failed",
    exitCode: timedOut ? 124 : Number.isInteger(error?.status) ? error.status : 1,
    signal: null,
    threadId: null,
    finalMessage: "",
    touchedFiles: gitTouchedFiles(opts.cd),
    stderrTail: stderrTail(run.stderrPath),
    error: message,
  });
  printSummary(result, run.resultPath);
  process.stderr.write(`relay: ${message}\n`);
  process.exit(result.exitCode);
}

function spawnShellLaunch(binary, argv, options, useShell) {
  if (!useShell) return spawn(binary, argv, options);
  // Node 24 warns when shell:true is paired with an args array. The args here
  // are already token-validated or quoted for cmd.exe, so serialize them once.
  return spawn([binary, ...argv].join(" "), { ...options, shell: true });
}

function dispatchToCodex(opts, brief, run, writeResult, env) {
  const argv = buildArgv(opts, run.finalPath);
  // shell:true on Windows so the codex.cmd shim resolves (see codexVersion). Safe:
  // the brief is fed via child.stdin below — never argv — and argv holds only
  // sandbox enums, model names (including subagents), pattern-checked efforts
  // and web search modes, the fixed network and project-doc overrides, and file paths.
  // detached on POSIX: the child leads a new process group so killChild can fell the whole tree
  const child = spawnShellLaunch("codex", argv, { cwd: opts.cd, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", env }, process.platform === "win32");

  let threadId = null;
  let stdoutBuf = "";

  // Decode across chunk boundaries: a multibyte UTF-8 character split between
  // two data events would otherwise decode as U+FFFD and corrupt the report.
  const stdoutDecoder = new StringDecoder("utf8");

  child.stdout.on("data", (chunk) => {
    stdoutBuf += stdoutDecoder.write(chunk);
    let nl;
    while ((nl = stdoutBuf.indexOf("\n")) !== -1) {
      const line = stdoutBuf.slice(0, nl);
      stdoutBuf = stdoutBuf.slice(nl + 1);
      if (!line.trim()) continue;
      const tid = recordEventLine(run.eventsPath, line);
      if (tid) threadId = tid;
    }
  });

  child.stderr.on("data", (chunk) => {
    process.stderr.write(chunk); // surface Codex progress live for the orchestrator
    appendFileSync(run.stderrPath, chunk);
  });

  let settled = false;
  let watchdogFired = false;
  let watchdogTimer = null;
  let sigkillTimer = null;
  const timeoutMs = opts.timeout === null ? null : parseDuration(opts.timeout);
  if (timeoutMs !== null) {
    watchdogTimer = setTimeout(() => {
      watchdogFired = true;
      child.once("exit", () => {
        child.stdout.destroy();
        child.stderr.destroy();
      });
      killChild(child);
      sigkillTimer = setTimeout(() => {
        if (!settled) killChild(child, "SIGKILL");
      }, 10_000);
    }, timeoutMs);
  }

  const clearWatchdog = () => {
    if (watchdogTimer) clearTimeout(watchdogTimer);
    if (sigkillTimer) clearTimeout(sigkillTimer);
  };

  // The relay's own death must still produce a result: without this, a kill from the
  // orchestrator's side (its command timeout, a stopped task, a closed terminal) writes
  // no result.json and leaves the codex child running or dying mid-edit with nothing
  // recording why. SIGTERM/SIGHUP registration is a no-op on Windows; SIGINT works there.
  for (const sig of ["SIGTERM", "SIGINT", "SIGHUP"]) {
    process.on(sig, () => {
      if (settled) return;
      settled = true;
      clearWatchdog();
      const finalMessage = existsSync(run.finalPath) ? readFileSync(run.finalPath, "utf8").trim() : "";
      const abortedFields = {
        status: "aborted",
        exitCode: 128 + (constants.signals[sig] || 15),
        signal: sig,
        threadId,
        finalMessage,
        touchedFiles: gitTouchedFiles(opts.cd),
        stderrTail: stderrTail(run.stderrPath),
        error: `the relay was killed by ${sig}; codex was terminated with it — inspect the working tree before re-dispatching`,
      };
      const result = writeResult(abortedFields);
      printSummary(result, run.resultPath);
      killChild(child);
      setTimeout(() => {
        killChild(child, "SIGKILL");
        // the child may flush files during the grace window; refresh the snapshot so the
        // artifact matches the tree the orchestrator will actually find
        writeResult({ ...abortedFields, touchedFiles: gitTouchedFiles(opts.cd) });
        process.exit(result.exitCode);
      }, 2000);
    });
  }

  // A grandchild that outlives codex and inherited the pipes keeps stdout/stderr open, so
  // "close" never fires and the relay waits forever, writing no result. Once codex itself is
  // gone the pipes hold nothing we still need — finalMessage is read from the -o file, and the
  // stderr log is appended synchronously as it arrives — so drop them after a short drain
  // grace and let "close" run. This is the normal-exit twin of the stream teardown the
  // watchdog already does on the timeout path.
  child.once("exit", () => {
    // The implementer already exited. Leaving the watchdog armed lets a drain that
    // overlaps the remaining budget fire, set watchdogFired, and report timeout.
    if (!watchdogFired) clearWatchdog();
    const drain = setTimeout(() => {
      if (settled) return;
      child.stdout.destroy();
      child.stderr.destroy();
    }, 500);
    if (typeof drain.unref === "function") drain.unref();
  });

  child.on("error", (err) => {
    if (settled) return;
    settled = true;
    clearWatchdog();
    const result = writeResult({ status: "failed", exitCode: 1, signal: null, threadId, finalMessage: "", touchedFiles: gitTouchedFiles(opts.cd), error: String(err && err.message ? err.message : err) });
    printSummary(result, run.resultPath);
    process.exit(1);
  });

  child.on("close", (code, signal) => {
    if (settled) return;
    settled = true;
    clearWatchdog();
    // a descendant that ignored SIGTERM must not outlive the timeout report: once the
    // parent is down, sweep the group (no-op where taskkill already felled the tree)
    if (watchdogFired) killChild(child, "SIGKILL");
    if (stdoutBuf.trim()) {
      const tid = recordEventLine(run.eventsPath, stdoutBuf);
      if (tid) threadId = tid;
    }
    const finalMessage = existsSync(run.finalPath) ? readFileSync(run.finalPath, "utf8").trim() : "";
    // A timed-out run is never a success even if codex handles SIGTERM by exiting 0 -
    // orchestrators key off status and the relay exit code.
    const succeeded = code === 0 && !watchdogFired;
    const mapped = code ?? (constants.signals[signal] ? 128 + constants.signals[signal] : 1);
    const result = writeResult({
      status: succeeded ? "completed" : watchdogFired ? "timeout" : "failed",
      exitCode: succeeded ? 0 : mapped === 0 ? 1 : mapped,
      signal: signal ?? null,
      threadId,
      finalMessage,
      touchedFiles: gitTouchedFiles(opts.cd),
      ...(succeeded ? {} : { stderrTail: stderrTail(run.stderrPath) }),
      ...(watchdogFired ? { error: `codex did not finish within --timeout ${opts.timeout}; killed by the relay watchdog` } : {}),
    });
    printSummary(result, run.resultPath);
    process.exit(result.exitCode);
  });

  // If the child failed to launch, writing to its stdin can emit a stray 'error'
  // on the pipe; the 'error' handler above owns that outcome, so swallow it here.
  child.stdin.on("error", () => {});
  child.stdin.write(brief);
  child.stdin.end();
}

function main() {
  const opts = parseArgs(process.argv.slice(2));
  const brief = readBrief(opts);
  if (!brief.trim()) fail("empty brief (pass --brief <file> or pipe the brief on stdin)");

  // Prepare the run dir before probing, so a preflight that times out or fails still has
  // somewhere to publish result.json rather than exiting silently.
  const run = prepareRunDir(opts, brief);
  const probeTimeoutMs = versionProbeTimeout(opts);
  const env = codexEnv(opts);
  const probe = codexVersion(probeTimeoutMs, env);
  const writeResult = makeResultWriter(opts, probe.version, run);

  if (!probe.version && !probe.error) {
    reportUnavailable(writeResult, run.resultPath);
    return;
  }
  if (probe.error) {
    reportVersionFailure(opts, writeResult, run, probe.error, probeTimeoutMs);
    return;
  }

  dispatchToCodex(opts, brief, run, writeResult, env);
}

function printSummary(result, resultPath) {
  const lines = [];
  lines.push("");
  lines.push(`relay: ${result.status} (exit ${result.exitCode}${result.signal ? `, killed by ${result.signal}` : ""})  ·  codex ${result.codexVersion ?? "?"}`);
  if (result.signal === "SIGKILL" && result.status === "failed") lines.push("hint: the host killed the process (commonly the OOM killer or a supervisor timeout) — this is not a codex error; check host memory and re-dispatch, or split the task into smaller briefs.");
  if (result.signal === "SIGTERM" && result.status === "failed") lines.push("hint: something outside the relay terminated codex (a supervisor, the session ending, or a manual kill) — when the relay itself does the killing it reports status \"timeout\" or \"aborted\" instead; inspect the working tree before re-dispatching.");
  if (result.resumeLast) lines.push("mode: resumed most recent session");
  if (result.session) lines.push(`mode: resumed session ${result.session}`);
  if (result.threadId) lines.push(`thread id (resume with: --session ${result.threadId}): ${result.threadId}`);
  const touched = result.touchedFiles;
  if (touched === null) {
    lines.push("touched files: git unavailable — inspect the working tree directly");
  } else {
    lines.push(`touched files: ${touched.length}`);
    for (const file of touched.slice(0, 40)) lines.push(`  ${file}`);
    if (touched.length > 40) lines.push(`  … and ${touched.length - 40} more`);
  }
  if (result.stderrTail && result.stderrTail.length) {
    lines.push("last stderr:");
    for (const line of result.stderrTail.slice(-8)) lines.push(`  ${line}`);
  }
  lines.push("");
  lines.push("--- codex final report ---");
  lines.push(result.finalMessage || "(no final message captured)");
  lines.push("--- end report ---");
  lines.push("");
  lines.push(`result: ${resultPath}`);
  lines.push("relay does not commit. Review the diff, re-run the project gates yourself, then commit from the orchestrator.");
  process.stdout.write(`${lines.join("\n")}\n`);
}

main();
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 469kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall