M plugins/gitea/.claude-plugin/plugin.json M plugins/gitea/.codex-plugin/plugin.json M plugins/gitea/README.md M plugins/gitea/skills/gitea/SKILL.md M plugins/gitea/skills/gitea/scripts/fetch_ticket.py M plugins/gitea/skills/gitea/scripts/start_ticket.py A plugins/spire/UPGRADES.md A plugins/spire/agents/designer.md M plugins/spire/agents/planner.md A plugins/spire/providers/README.md A plugins/spire/providers/hosts/claude-desktop/spawning.md A plugins/spire/providers/hosts/t3-code/spawning.md A plugins/spire/providers/runtimes/codex/spawning.md M plugins/spire/skills/gremlins/grm/call.py M plugins/spire/skills/gremlins/grm/cli.py A plugins/spire/skills/gremlins/grm/codex.py A plugins/spire/skills/gremlins/grm/errors.py A plugins/spire/skills/gremlins/grm/harness.py M plugins/spire/skills/gremlins/grm/launch.py A plugins/spire/skills/gremlins/grm/scrub.py M plugins/spire/skills/gremlins/grm/stream.py A plugins/spire/skills/gremlins/grm/title.py A plugins/spire/skills/gremlins/tests/_pin.py M plugins/spire/skills/gremlins/tests/fake_claude.py A plugins/spire/skills/gremlins/tests/fake_codex.py M plugins/spire/skills/gremlins/tests/test_cli.py A plugins/spire/skills/gremlins/tests/test_cli_codex.py A plugins/spire/skills/gremlins/tests/test_codex.py A plugins/spire/skills/gremlins/tests/test_harness.py A plugins/spire/skills/gremlins/tests/test_scrub.py A plugins/spire/skills/gremlins/tests/test_title.py A plugins/spire/skills/igor/references/upgrades.md A plugins/spire/skills/igor/tests/test_upgrade_notes.py A plugins/spire/skills/igor/upgrade-notes.sh R plugins/spire/skills/implementation/references/spawning-claude-code.md -> plugins/spire/providers/runtimes/claude-code/spawning.md M plugins/spire/skills/project/SKILL.md
276 lines
12 KiB
Python
276 lines
12 KiB
Python
"""The Codex adapter (design §3.1, §4): `codex exec` argv and fingerprint, init checks, the model
|
|
and effort check against `<codex_home>/models_cache.json`, the rollout reader (base context) and
|
|
the `CODEX_HOME` write preflight. Imports neither `harness` nor `cli`."""
|
|
import glob
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
from grm import launch, scrub, stream
|
|
from grm.errors import Refusal
|
|
|
|
MODEL_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
|
|
EFFORTS = ("none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra", "persistent")
|
|
SANDBOX = "workspace-write"
|
|
NETWORK_CONFIG = "sandbox_workspace_write.network_access=true"
|
|
CODEX_NOMINAL_TTL_S = 600
|
|
COMMIT_LINE = (" You cannot commit here (`.git` is read-only in your sandbox); list the paths you "
|
|
"changed on the note's Commits line.")
|
|
STALE_CACHE_REMEDY = ("pick a slug listed in models_cache.json; if the cache is stale, run `codex` "
|
|
"once to refresh it")
|
|
MISSING_HOME_REMEDY = ("check CODEX_HOME (a typo, or a home never used); run `codex` once to create it "
|
|
"and log in")
|
|
PREFLIGHT_REMEDY = ("run G escalated, or start the caller with --add-dir %s "
|
|
"-c sandbox_workspace_write.network_access=true")
|
|
|
|
|
|
def codex_home(environ=None) -> str:
|
|
"""`CODEX_HOME`, else `~/.codex`, made absolute. Used at `init` only; later calls use the
|
|
fingerprint's `codex_home`."""
|
|
if environ is None:
|
|
environ = os.environ
|
|
return os.path.abspath(os.path.expanduser(environ.get("CODEX_HOME") or "~/.codex"))
|
|
|
|
|
|
def _cached_models(home: str) -> dict | None:
|
|
"""{slug: [efforts]} from `<home>/models_cache.json`; None when it is missing, unparsable or
|
|
has no `models[].slug` list. Only `slug` and `supported_reasoning_levels[].effort` are read."""
|
|
try:
|
|
with open(os.path.join(home, "models_cache.json"), "rb") as f:
|
|
data = json.loads(f.read().decode("utf-8"))
|
|
except (OSError, ValueError):
|
|
return None
|
|
models = data.get("models") if isinstance(data, dict) else None
|
|
if not isinstance(models, list):
|
|
return None
|
|
out = {}
|
|
for m in models:
|
|
if isinstance(m, dict) and isinstance(m.get("slug"), str):
|
|
levels = m.get("supported_reasoning_levels") or []
|
|
out[m["slug"]] = [lv["effort"] for lv in levels
|
|
if isinstance(lv, dict) and isinstance(lv.get("effort"), str)]
|
|
return out or None
|
|
|
|
|
|
def rollout_path(home: str, thread_id: str) -> str | None:
|
|
"""`<home>/sessions/*/*/*/rollout-*-<thread_id>.jsonl`; with more than one match the newest
|
|
mtime wins; None when there is none."""
|
|
pattern = os.path.join(glob.escape(home), "sessions", "*", "*", "*",
|
|
"rollout-*-%s.jsonl" % glob.escape(thread_id))
|
|
best = None
|
|
for p in glob.glob(pattern):
|
|
try:
|
|
m = os.path.getmtime(p)
|
|
except OSError:
|
|
continue
|
|
if best is None or m > best[0]:
|
|
best = (m, p)
|
|
return best[1] if best else None
|
|
|
|
|
|
def _rollout_context(path: str) -> int | None:
|
|
"""The last `event_msg`/`token_count` `info.last_token_usage.input_tokens`, or None. Lines
|
|
without `token_count` are not decoded; of the others only `type` and that record are read."""
|
|
try:
|
|
with open(path, "rb") as f:
|
|
data = f.read()
|
|
except OSError:
|
|
return None
|
|
last = None
|
|
for ln in data.splitlines():
|
|
if b"token_count" not in ln:
|
|
continue
|
|
try:
|
|
ev = json.loads(ln.decode("utf-8", "replace"))
|
|
except ValueError:
|
|
continue
|
|
if not isinstance(ev, dict) or ev.get("type") != "event_msg":
|
|
continue
|
|
payload = ev.get("payload")
|
|
if not isinstance(payload, dict) or payload.get("type") != "token_count":
|
|
continue
|
|
info = payload.get("info") # null before the first usage
|
|
ltu = info.get("last_token_usage") if isinstance(info, dict) else None
|
|
n = ltu.get("input_tokens") if isinstance(ltu, dict) else None
|
|
if isinstance(n, int) and not isinstance(n, bool):
|
|
last = n
|
|
return last
|
|
|
|
|
|
def _inside(path: str, root: str) -> bool:
|
|
p, r = os.path.realpath(path), os.path.realpath(root)
|
|
return p == r or p.startswith(r.rstrip("\\/") + os.sep)
|
|
|
|
|
|
def _argv(fp: dict) -> list[str]:
|
|
"""The fingerprinted command line (design §4.1); its order must never change (cache hit).
|
|
Non-global flags (`-s`, `-C`, `--add-dir`) sit before any subcommand."""
|
|
a = [fp["binary"], "exec", "--json"]
|
|
if fp["ignore_user_config"]:
|
|
a.append("--ignore-user-config")
|
|
a += ["-s", fp["sandbox"], "-C", fp["cwd"]]
|
|
for d in fp["add_dirs"]:
|
|
a += ["--add-dir", d]
|
|
a += ["-m", fp["model"]]
|
|
for c in fp["config"]:
|
|
a += ["-c", c]
|
|
if fp["network"]:
|
|
a += ["-c", NETWORK_CONFIG]
|
|
return a
|
|
|
|
|
|
class CodexAdapter:
|
|
name = binary_name = "codex"
|
|
preassigns_session_id = False # the id comes from `thread.started`
|
|
commit_line = COMMIT_LINE
|
|
|
|
def resolve_binary(self, explicit):
|
|
path = explicit or shutil.which("codex")
|
|
return os.path.abspath(path) if path else None
|
|
|
|
def binary_version(self, path):
|
|
"""Last token of `<path> --version` (`codex-cli 0.172.0` -> `0.172.0`), or None."""
|
|
try:
|
|
r = subprocess.run([path, "--version"], stdin=subprocess.DEVNULL, capture_output=True,
|
|
timeout=60)
|
|
except (OSError, subprocess.SubprocessError):
|
|
return None
|
|
toks = r.stdout.decode("utf-8", "replace").split()
|
|
return toks[-1] if r.returncode == 0 and toks else None
|
|
|
|
def check_init(self, *, cwd, agent, network):
|
|
if agent:
|
|
raise Refusal("Codex has no main-thread agent", agent=agent)
|
|
try:
|
|
r = subprocess.run(["git", "--no-optional-locks", "rev-parse", "--show-toplevel"], cwd=cwd,
|
|
stdin=subprocess.DEVNULL, capture_output=True, timeout=60)
|
|
ok = r.returncode == 0 and r.stdout.strip()
|
|
except (OSError, subprocess.SubprocessError):
|
|
ok = False
|
|
if not ok:
|
|
raise Refusal("Codex runs need a git repository", cwd=cwd,
|
|
detail="codex exec refuses a cwd outside a git repository")
|
|
|
|
def check_model(self, model, effort):
|
|
"""Design §4.2: a slug, not a Claude id; with a readable cache the slug must be listed and
|
|
the effort must be one of its levels; without one, only the effort enum is checked."""
|
|
if (model or "").startswith("claude-") or not MODEL_RE.match(model or ""):
|
|
raise Refusal("model must be a Codex model slug", model=model)
|
|
cached = _cached_models(codex_home())
|
|
if cached is not None:
|
|
if model not in cached:
|
|
raise Refusal("unknown model", model=model, models=sorted(cached),
|
|
remedy=STALE_CACHE_REMEDY)
|
|
if cached[model]:
|
|
if effort not in cached[model]:
|
|
raise Refusal("unknown effort", effort=effort, efforts=list(cached[model]), model=model)
|
|
return
|
|
if effort not in EFFORTS:
|
|
raise Refusal("unknown effort", effort=effort, efforts=list(EFFORTS))
|
|
|
|
def build_fingerprint(self, *, binary, model, effort, cwd, agent, network, state, preamble_path,
|
|
mcp_config, env_pass):
|
|
"""Design §4.1 plus `env_pass` and `network`; `fp_hash` over the final dict. `mcp_config`
|
|
and `agent` are not used on Codex (`check_init` refuses an agent)."""
|
|
if not os.path.isdir(cwd):
|
|
raise ValueError("cwd is not a directory: %s" % cwd)
|
|
if not os.path.isfile(preamble_path):
|
|
raise ValueError("preamble not found: %s" % preamble_path)
|
|
if not binary or not os.path.isfile(binary):
|
|
raise ValueError("codex binary not found: %s" % binary)
|
|
cwd, state, preamble_path = os.path.abspath(cwd), os.path.abspath(state), os.path.abspath(preamble_path)
|
|
fp = {
|
|
"harness": self.name,
|
|
"binary": os.path.abspath(binary),
|
|
"binary_version": self.binary_version(binary),
|
|
"model": model,
|
|
"effort": effort,
|
|
"sandbox": SANDBOX,
|
|
"network": bool(network),
|
|
"add_dirs": [] if _inside(state, cwd) else [state],
|
|
"cwd": cwd,
|
|
"ignore_user_config": True,
|
|
"config": ['model_reasoning_effort="%s"' % effort, 'web_search="disabled"',
|
|
"agents.enabled=false"],
|
|
"ephemeral_forks": True,
|
|
"codex_home": codex_home(),
|
|
"preamble": {"path": preamble_path, "sha256": launch._sha256_file(preamble_path),
|
|
"placement": "train_prompt"},
|
|
"env_pass": sorted(env_pass or []),
|
|
}
|
|
return {"fingerprint": fp, "argv": _argv(fp),
|
|
"fp_hash": launch._sha256_bytes(launch.canonical_json(fp).encode("utf-8"))}
|
|
|
|
def preflight(self, fp):
|
|
"""Design §6.3: a nested `codex exec` must write `CODEX_HOME`. Create and remove one file
|
|
under `<codex_home>/tmp/` (`tmp/` made if missing; a missing home is refused, never
|
|
created). `init` passes its inputs, not the final fingerprint, so `codex_home` falls back
|
|
to the env, as `build_fingerprint` does."""
|
|
home = fp.get("codex_home") or codex_home()
|
|
if not os.path.isdir(home):
|
|
raise Refusal("codex_home_missing", codex_home=home, remedy=MISSING_HOME_REMEDY)
|
|
tmp = os.path.join(home, "tmp")
|
|
try:
|
|
if not os.path.isdir(tmp):
|
|
os.mkdir(tmp)
|
|
fd, probe = tempfile.mkstemp(prefix=".spire-preflight-", dir=tmp)
|
|
os.close(fd)
|
|
os.remove(probe)
|
|
except OSError as e:
|
|
raise Refusal("codex_home_not_writable", codex_home=home,
|
|
detail="%s: %s" % (type(e).__name__, e.strerror or "write failed"),
|
|
remedy=PREFLIGHT_REMEDY % home)
|
|
|
|
# per-call tails: the title is not in any Codex argv (it is line 1 of the train prompt)
|
|
def train_argv(self, run, sid, title):
|
|
return list(run["argv"]) + ["-"]
|
|
|
|
def fork_argv(self, run, base_sid, sid, title):
|
|
return list(run["argv"]) + ["--ephemeral", "fork", base_sid, "-"]
|
|
|
|
def resume_argv(self, run, base_sid, title):
|
|
return list(run["argv"]) + ["resume", base_sid, "-"]
|
|
|
|
def train_prompt(self, state, title, rendered):
|
|
"""No system-prompt file on Codex: the frozen preamble heads the train turn (design §4.3)."""
|
|
preamble = (Path(state) / "preamble.md").read_text(encoding="utf-8")
|
|
return title + "\n\n" + preamble + "\n\n---\n\n" + rendered
|
|
|
|
def env(self, fp, environ=None):
|
|
return scrub.env_for("codex", fp, environ)
|
|
|
|
def infer_ttl(self, tokens, prev):
|
|
return prev or CODEX_NOMINAL_TTL_S
|
|
|
|
def new_stream(self, fp):
|
|
return stream.CodexStreamState(fp["model"])
|
|
|
|
def usage(self, ss, before_mu, cost_before):
|
|
return stream.codex_usage(ss.result, before_mu, cost_before)
|
|
|
|
def cache_verdict(self, ss, u, base_ctx):
|
|
"""None when the call produced no usage (a failed turn), as on Claude; else the turn-delta
|
|
estimate."""
|
|
if not u or not isinstance((ss.result or {}).get("usage"), dict):
|
|
return None
|
|
return stream.codex_cache_verdict(u["tokens"], base_ctx)
|
|
|
|
def context_tokens(self, fp, ss):
|
|
"""(base context tokens, warnings) after a persisted call (train, rebase): the last
|
|
`token_count` `last_token_usage.input_tokens` of the thread's rollout (cached tokens are
|
|
part of it). 0 with a warning when none is found; `hit` is then never reported."""
|
|
tid = ss.session_id
|
|
if not tid:
|
|
return 0, ["no thread id: base context unknown (0); spawns cannot report cache: hit"]
|
|
path = rollout_path(fp.get("codex_home") or codex_home(), tid)
|
|
n = _rollout_context(path) if path else None
|
|
if n is None:
|
|
what = "no rollout found" if path is None else "no token_count record in the rollout"
|
|
return 0, ["%s for thread %s: base context unknown (0); spawns cannot report cache: hit"
|
|
% (what, tid)]
|
|
return n, []
|