Skip to content
Merged
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
10 changes: 10 additions & 0 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -899,6 +899,16 @@ never read as alive. To stop a shift, `touch <slot>/STOP` (or comment `/stop` on
its issue); to remove the
watcher, `systemctl --user disable --now pyauto-orchestrator.timer`.

## Codex execution workers

A brief may explicitly select `worker-backend: codex`; omitted means Claude.
The adapter changes execution, observations, stop and accounting only, retaining
this conductor's scheduling and autonomy contracts. Codex workers use an
accounted fresh Opus session for the required pre-ship review; close-outs remain
Opus. The canonical keys live in Mind `batches/AGENTS.md`. Read
[Codex setup and first-run checks](../../../docs/codex_orchestrator.md) before
the first Codex shift. No live shift is authorized by selecting a backend.

## Running

```
Expand Down
14 changes: 12 additions & 2 deletions agents/conductors/batch/_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -1575,10 +1575,20 @@ def login_findings(top: dict, brief: dict | None) -> tuple[dict, list[str], list
shadow brief starts no worker and is not probed."""
if brief is None or _brief.is_shadow(brief):
return {"state": "skipped", "detail": "shadow shift", "expires_at": ""}, [], []
login = _login.probe()
if _brief.backend_of(brief) == "codex":
import _codex
login = _codex.probe()
# Even merge-cap: 0 requires the independent Opus pre-ship review.
if login["state"] == "ok":
review_login = _login.probe()
if review_login["state"] not in {"ok", "skipped"}:
return login, ["review login: independent Opus pre-ship review requires a verified Claude login"], []
else:
login = _login.probe()
errors, warnings = [], []
if login["state"] == "expired":
errors.append(f"login: {_login.EXPIRED_LINE} ({login['detail']})")
errors.append(f"login: {login['detail']}" if _brief.backend_of(brief) == "codex"
else f"login: {_login.EXPIRED_LINE} ({login['detail']})")
elif login["state"] == "unknown":
warnings.append(f"login: could not tell whether the CLI login holds "
f"({login['detail']})")
Expand Down
24 changes: 24 additions & 0 deletions agents/conductors/batch/_brief.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,29 @@ def effective(brief: dict, counters: dict | None) -> dict:
return out


def backend_of(brief: dict) -> str:
return brief.get("worker-backend", {}).get("value", "claude")


def backend_errors(brief: dict) -> list[str]:
backend = backend_of(brief)
if backend not in {"claude", "codex"}:
return ["brief.worker-backend: must be claude or codex"]
errors = []
if backend == "codex":
model = brief.get("codex-model", {}).get("value", "")
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", model):
errors.append("brief.codex-model: explicit Codex model id required")
if worker_mode_of(brief) not in {"auto", "dontAsk"}:
errors.append("brief.worker-mode: Codex supports auto or dontAsk; no acceptEdits equivalent")
effort = brief.get("codex-effort", {}).get("value", "medium")
if effort not in {"low", "medium", "high", "xhigh"}:
errors.append("brief.codex-effort: must be low, medium, high or xhigh")
elif any(k.startswith("codex-") for k in brief):
errors.append("brief.worker-backend: codex settings require worker-backend: codex")
return errors


def worker_mode_of(brief: dict) -> str:
return brief.get("worker-mode", {}).get("value") or DEFAULT_WORKER_MODE

Expand Down Expand Up @@ -350,6 +373,7 @@ def check(path: Path, mind: Path) -> dict:
if key in brief and _nonneg_int(brief[key]["value"]) is None:
errors.append(f"brief.{key}: not a whole number ({brief[key]['value']!r})")

errors.extend(backend_errors(brief))
if "worker-mode" in brief and brief["worker-mode"]["value"] not in WORKER_MODES:
errors.append(f"brief.worker-mode: {brief['worker-mode']['value']} — one of "
+ ", ".join(WORKER_MODES)
Expand Down
224 changes: 224 additions & 0 deletions agents/conductors/batch/_codex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
"""Codex CLI backend. Local Linux/WSL process records, never an API client.

Opaque codex:<uuid> identities route observations independently of a brief
which may subsequently change. Each runner owns one private session directory.
Unknown/corrupt state holds a lease; it is never evidence that a worker died.
"""
from __future__ import annotations

import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import uuid

PREFIX = "codex:"
ID_RE = re.compile(r"codex:([0-9a-f]{32})\Z")


def session_dir(agent_id: str, home: Path) -> Path:
match = ID_RE.fullmatch(agent_id)
if not match:
raise ValueError("invalid Codex worker identity")
return Path(home) / "codex-sessions" / match[1]


def write_json(path: Path, value: dict) -> None:
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(value), encoding="utf-8")
tmp.replace(path)


def read_record(agent_id: str, home: Path) -> dict | None:
try:
obj = json.loads((session_dir(agent_id, home) / "state.json").read_text())
if not isinstance(obj, dict) or obj.get("agent_id") != agent_id:
return None
if obj.get("state") not in {"starting", "working", "done", "error", "killed"}:
return None
for key in ("pid", "child_pid"):
if key in obj and (type(obj[key]) is not int or obj[key] <= 0):
return None
for key in ("identity", "child_identity"):
if key in obj and (not isinstance(obj[key], str) or not obj[key]):
return None
return obj
except (OSError, ValueError, TypeError):
return None


def process_identity(pid: int) -> str | None:
"""Linux start ticks + boot id prevent PID reuse across ticks/reboots."""
try:
stat = Path(f"/proc/{int(pid)}/stat").read_text().rsplit(")", 1)[1].split()
if stat[0] == "Z":
return None
boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
return f"{boot}:{stat[19]}"
except (OSError, ValueError, IndexError, TypeError):
return None


def state(agent_id: str, home: Path) -> str | None:
rec = read_record(agent_id, home)
if rec is None:
return None
if rec["state"] in {"done", "error", "killed"}:
return rec["state"]
if rec.get("pid") and rec.get("identity"):
if process_identity(rec["pid"]) == rec["identity"]:
return "working"
# A supervisor crash is not a worker crash while its child survives.
if not rec.get("child_pid") or not rec.get("child_identity"):
# Death between Popen and the child's identity write is ambiguous.
# Holding the lease is safer than starting a duplicate worker.
return None
if process_identity(rec["child_pid"]) == rec["child_identity"]:
return "working"
return "error"
# A launcher crash before the supervisor starts cannot silently free a slot.
return None


def usage(agent_id: str, home: Path) -> dict | None:
"""Completed-turn usage. Missing/partial events retain the reservation.

Codex input includes cached input: subtract it for the existing shift
budget's uncached-input + output convention; report cache reads separately.
"""
try:
totals = dict(input=0, output=0, cache_creation=0, cache_read=0, subagents=0)
found = False
for line in (session_dir(agent_id, home) / "events.jsonl").read_text().splitlines():
try:
event = json.loads(line)
except ValueError:
continue # an in-flight final line is normal
if not isinstance(event, dict) or event.get("type") != "turn.completed":
continue
u = event.get("usage")
if not isinstance(u, dict):
return None
fields = [u.get(k) for k in ("input_tokens", "output_tokens", "cached_input_tokens")]
if any(type(n) is not int or n < 0 for n in fields) or fields[2] > fields[0]:
return None
found = True
totals["input"] += fields[0] - fields[2]
totals["output"] += fields[1]
totals["cache_read"] += fields[2]
if not found:
return None
for request in session_dir(agent_id, home).glob("review-*.request.json"):
result = request.with_name(request.name.replace(".request.json", ".result.json"))
try:
raw = json.loads(result.read_text())["usage"]
fields = [raw.get(k) for k in ("input_tokens", "output_tokens",
"cache_creation_input_tokens", "cache_read_input_tokens")]
if any(type(n) is not int or n < 0 for n in fields):
return None
except (OSError, ValueError, KeyError, TypeError, AttributeError):
return None
totals["input"] += fields[0]
totals["output"] += fields[1]
totals["cache_creation"] += fields[2]
totals["cache_read"] += fields[3]
totals["subagents"] += sum(fields[:3])
totals["total"] = totals["input"] + totals["output"] + totals["cache_creation"]
return totals
except (OSError, ValueError):
return None


def probe(run=None) -> dict:
"""Require ChatGPT CLI auth, never accept an API-key billing fallback."""
run = run or subprocess.run
try:
res = run(["codex", "login", "status"], capture_output=True, text=True, timeout=30)
output = (res.stdout or "") + (res.stderr or "")
if res.returncode == 0 and "logged in using chatgpt" in output.lower():
return {"state": "ok", "detail": "Codex ChatGPT login", "backend": "codex", "expires_at": ""}
# Do not echo CLI output: some versions show a masked API key.
return {"state": "expired", "detail": "Codex ChatGPT login required; run codex login", "backend": "codex",
"expires_at": ""}
except (OSError, subprocess.SubprocessError):
return {"state": "expired", "detail": "Codex login could not be verified; run codex login status", "backend": "codex",
"expires_at": ""}


def command(model: str, effort: str, mode: str, cwd: Path, write_root: Path) -> list[str]:
if mode not in {"auto", "dontAsk"}:
raise ValueError("Codex worker-mode must be auto or dontAsk (acceptEdits has no equivalent)")
argv = ["codex", "exec", "--json", "--color", "never", "--model", model,
"-c", f"model_reasoning_effort={json.dumps(effort)}",
"-c", 'model_provider="openai"', "-c", 'forced_login_method="chatgpt"',
"-c", "features.multi_agent=false", "-c", "features.goals=false", # usage is for this worker only
"--sandbox", "workspace-write", "--cd", str(cwd),
"--add-dir", str(write_root), "--skip-git-repo-check"]
if mode == "auto":
argv.append("--approve-for-me")
else:
argv += ["-c", 'approval_policy="never"']
return argv + ["-"]


def launch(prompt: str, *, home: Path, cwd: Path, write_root: Path, model: str,
effort: str, mode: str, env: dict, scope=None, lease_path: Path | None = None) -> dict:
if not Path("/proc/self/stat").exists():
raise ValueError("Codex shift workers currently require Linux/WSL process identity")
agent_id = PREFIX + uuid.uuid4().hex
directory = session_dir(agent_id, home)
directory.mkdir(parents=True, mode=0o700)
argv = command(model, effort, mode, cwd, write_root)
argv[-1:-1] = ["--add-dir", str(home)]
(directory / "prompt.txt").write_text(prompt, encoding="utf-8")
write_json(directory / "request.json", {"argv": argv, "cwd": str(cwd)})
write_json(directory / "state.json", {"agent_id": agent_id, "state": "starting"})
identity = {"pid": 0, "agent_id": agent_id, "session_id": agent_id,
"backend": "codex", "model": model, "effort": effort, "mode": mode}
if lease_path is not None:
lease = json.loads(lease_path.read_text())
# Reserve identity before starting any process. A watcher killed after
# spawn can adopt this attempt instead of treating it as a dead stub.
write_json(lease_path, {**lease, **identity})
clean_env = dict(env)
clean_env["PYAUTO_CODEX_SESSION_DIR"] = str(directory)
for key in ("OPENAI_API_KEY", "CODEX_API_KEY", "OPENAI_BASE_URL"):
clean_env.pop(key, None)
# The runner and child retain the existing Mind commit guard environment.
runner = [sys.executable, str(Path(__file__).with_name("_codex_runner.py")), str(directory)]
if scope:
runner = scope(runner)
with (directory / "runner.log").open("ab") as log:
proc = subprocess.Popen(runner, cwd=cwd, env=clean_env, stdin=subprocess.DEVNULL,
stdout=log, stderr=log, start_new_session=True)
# Only the runner writes state; a late parent cannot overwrite completion.
# No retry after an ambiguous start: that would duplicate the worker.
try:
for _ in range(100):
rec = read_record(agent_id, home)
if rec and rec["state"] != "starting":
break
if proc.poll() is not None:
write_json(directory / "state.json", {"agent_id": agent_id, "state": "error",
"reason": "runner exited before handshake"})
break
time.sleep(0.02)
except OSError:
pass # Process exists: return the reserved identity, never permit a retry.
return identity


def stop(agent_id: str, home: Path) -> tuple[bool, str]:
rec = read_record(agent_id, home)
if not rec:
return False, "Codex session state unreadable; refusing to target an unverified process"
if rec["state"] in {"done", "error", "killed"}:
return True, ""
if not rec.get("pid") or process_identity(rec["pid"]) != rec.get("identity"):
return False, "Codex supervisor identity unavailable; inspect its local session record"
# Supervisor handles termination and escalation of its own child group.
(session_dir(agent_id, home) / "STOP").touch()
return True, ""
89 changes: 89 additions & 0 deletions agents/conductors/batch/_codex_review.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""Accounted independent Opus review for one Codex shift worker.

Invoked synchronously by the worker, never a timer or an autonomous close-out.
The reviewer gets the existing faculty contract and repository paths, not the
writer's conversation. All review attempts remain part of that worker's spend.
"""
from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
import subprocess
import uuid

from _codex import write_json

SCHEMA = {"type": "object", "properties": {
"verdict": {"type": "string", "enum": ["CLEAN", "FINDINGS", "BLOCKED"]},
"report": {"type": "string"}}, "required": ["verdict", "report"],
"additionalProperties": False}


def review(task: str, repos: list[Path], *, run=None) -> dict:
directory = os.environ.get("PYAUTO_CODEX_SESSION_DIR")
if os.environ.get("PYAUTO_SHIFT_WORKER") != "1" or not directory:
raise ValueError("review helper is only for a registered Codex shift worker")
directory = Path(directory)
state = json.loads((directory / "state.json").read_text())
if state.get("state") != "working" or state.get("agent_id") != "codex:" + directory.name:
raise ValueError("Codex worker session is not running")
repos = [p.resolve(strict=True) for p in repos]
session = str(uuid.uuid4())
prefix = directory / f"review-{session}"
# Create evidence before the call; a killed/incomplete reviewer is unknown
# spend, never silently zero. Each fresh attempt has a different identity.
write_json(prefix.with_suffix(".request.json"), {"session_id": session, "task": task,
"repos": list(map(str, repos))})
faculty = Path(__file__).resolve().parents[2] / "faculties" / "review" / "AGENTS.md"
brain = Path(__file__).resolve().parents[3]
prompt = (f"You are the independent review faculty for task {task}. "
f"Read {faculty}, then use {brain}/bin/pyauto-brain review --task {task} "
"to prepare its review surface (use explicit repo paths if needed). "
"Review both committed and uncommitted changes against origin/main in "
+ ", ".join(map(str, repos)) + ". "
"Follow the faculty's code-review and verify pass. Read the task's "
"Mind prompt and its Witness. Never edit source, fix findings, write "
"Mind state, commit, push, merge or contact anyone. Never delegate or "
"start another model. If evidence or permissions are insufficient, "
"return BLOCKED. Return the structured verdict and full findings/evidence; "
"CLEAN only when the faculty's requirements pass. This is ship leg 3, "
"not the close-out adversary or merge authority.")
argv = ["claude", "--print", "--model", "opus", "--effort", "medium",
"--session-id", session, "--permission-mode", "auto", "--max-turns", "40",
"--tools", "Read,Glob,Grep,Bash", "--output-format", "json",
"--json-schema", json.dumps(SCHEMA), "--add-dir", *map(str, repos)]
run = run or subprocess.run
try:
result = run(argv, input=prompt, text=True, capture_output=True, cwd=brain.parent,
timeout=1800)
payload = json.loads(result.stdout)
if not isinstance(payload, dict):
raise ValueError("review output is not an object")
write_json(prefix.with_suffix(".result.json"), payload)
verdict = payload.get("structured_output") or {}
if result.returncode or payload.get("is_error") or not isinstance(verdict, dict):
raise ValueError("review session failed")
if verdict.get("verdict") not in {"CLEAN", "FINDINGS", "BLOCKED"}:
raise ValueError("review returned no recognized verdict")
return {**verdict, "session_id": session, "evidence": str(prefix.with_suffix(".result.json"))}
except (OSError, ValueError, subprocess.SubprocessError) as exc:
return {"verdict": "BLOCKED", "report": str(exc), "session_id": session}


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--task", required=True)
parser.add_argument("--repo", type=Path, action="append", required=True)
args = parser.parse_args()
try:
result = review(args.task, args.repo)
except (ValueError, OSError) as exc:
result = {"verdict": "BLOCKED", "report": str(exc)}
print(json.dumps(result))
return 0 if result["verdict"] == "CLEAN" else 1


if __name__ == "__main__":
raise SystemExit(main())
Loading
Loading