graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
eval: SuperGrok wrappers for OpenCode, Pi, and exo
Rach6b2ba5fe0ad3
diff --git a/graff-evals/README.md b/graff-evals/README.mdindex fa467f2d..5b843a13 100644--- a/graff-evals/README.md+++ b/graff-evals/README.md@@ -39,6 +39,8 @@ CODEGRAFF_API_KEY=cg_sk_… ./run.py --suite swe --harness graff-dev,opencode-co./run.py --suite inhouse --harness graff-dev,grok,opencode --model grok-4.6 -j 1# live PRs (no SPEC.md). Smoke gates first: python3 verify_live_gates.py --only graff-195./run.py --suite live --harness graff-dev --reps 3 -j 1+# same SuperGrok seat, other harnesses (OpenCode / Pi / exo local-process):+./run.py --suite live --harness opencode,pi-xai,exo --reps 3 -j 1```## Run it@@ -109,8 +111,10 @@ grok-build's heap or a 4-tool catalog (ADR 0024). First keep:Add a harness by adding an entry; add a model by passing `--model`.-Same-model grok-4.6 series: `graff-dev`, `grok`, `opencode` (needs xAI-auth), `dsh-grok` (needs `dsh` + an xAI key dsh will accept; 0.1.1-rc.2+Same-model grok-4.6 series: `graff-dev`, `grok`, `opencode` / `pi-xai`+(SuperGrok JWT + `X-XAI-Token-Auth`), `exo` (exoharness CLI,+`--provider local-process`, no Docker; same header via a localhost+proxy), `dsh-grok` (needs `dsh` + an xAI key dsh will accept; 0.1.1-rc.2catalog has no grok-4.6 — use `dsh-xai` / grok-4.5 for a live dsh point).Mixed-model native defaults — `opencode-zen`, `dsh-deepseek` — are a**different comparison**; do not read them as grok-4.6 list-price points.diff --git a/graff-evals/exo-xai.sh b/graff-evals/exo-xai.shnew file mode 100755index 00000000..0970af41--- /dev/null+++ b/graff-evals/exo-xai.sh@@ -0,0 +1,117 @@+#!/bin/sh+# Drive https://github.com/exoharness/exo on graff's SuperGrok seat.+# local-process (no Docker). SuperGrok JWTs go through xai-header-proxy.py.+set -eu+root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)+evals="$root/graff-evals"+oauth="${GRAFF_XAI_OAUTH:-$HOME/.xai/credentials/graff-oauth.json}"++python3 "$evals/refresh-graff-oauth.py" || true++if [ -z "${XAI_API_KEY:-}" ] && [ -f "$oauth" ]; then+ XAI_API_KEY=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["access_token"])' "$oauth")+ export XAI_API_KEY+fi+if [ -z "${XAI_API_KEY:-}" ]; then+ echo "exo-xai: no XAI_API_KEY and no $oauth — run \`graff login xai\`" >&2+ exit 127+fi++MODEL="${EXO_MODEL:-grok-4.6}"+PROMPT=""+while [ $# -gt 0 ]; do+ case "$1" in+ --model)+ MODEL=$2+ shift 2+ ;;+ -*)+ echo "exo-xai: unknown flag $1" >&2+ exit 2+ ;;+ *)+ if [ -n "$PROMPT" ]; then+ echo "exo-xai: unexpected extra arg" >&2+ exit 2+ fi+ PROMPT=$1+ shift+ ;;+ esac+done+if [ -z "$PROMPT" ]; then+ echo "exo-xai: missing prompt" >&2+ exit 2+fi++if [ -n "${EXO_BIN:-}" ]; then+ EXO=$EXO_BIN+elif command -v exo >/dev/null 2>&1; then+ EXO=$(command -v exo)+elif [ -x "$HOME/.local/bin/exo" ]; then+ EXO=$HOME/.local/bin/exo+elif [ -x /tmp/exo/target/release/exo ]; then+ EXO=/tmp/exo/target/release/exo+else+ echo "exo-xai: exo not found (build https://github.com/exoharness/exo or set EXO_BIN)" >&2+ exit 127+fi++WORKDIR=$(pwd)+ROOTDIR="${EXO_ROOT:-$WORKDIR/.exo-eval}"+SLUG="${EXO_SLUG:-ev-$$}"+MOUNT="${EXO_MOUNT:-/home/exo/workspace}"+mkdir -p "$ROOTDIR"++proxy=$(python3 "$evals/xai-header-proxy.py" --ensure)+base="${proxy%/}/v1"++exo() {+ "$EXO" --root "$ROOTDIR" --secret-backend file "$@"+}++cleanup() {+ exo agent delete "$SLUG" >/dev/null 2>&1 || true+}+trap cleanup EXIT++exo secret set xai --value "$XAI_API_KEY" >/dev/null+exo model register "$MODEL" --model "$MODEL" --secret xai --base-url "$base" >/dev/null+exo agent create eval --slug "$SLUG" --model "$MODEL" \+ --provider local-process --networking enabled --sandbox-scope conversation >/dev/null+# Conversation-scoped sandboxes ignore agent mounts; mount the eval cwd+# on the conversation so default_workdir maps to the host sandbox.+exo conversation create "$SLUG" run --slug run --provider local-process >/dev/null+exo conversation mount add "$SLUG" run "$WORKDIR" "$MOUNT" --rw >/dev/null+# Host path is what local-process actually chdirs to after the mount map.+payload=$(printf 'The project directory is %s. Edit files there only. Do not write to / or /workspace unless that is this directory.\n\n%s' "$WORKDIR" "$PROMPT")+exo conversation send "$SLUG" run "$payload"++# Emit a graff-shaped usage line so run.py list$ can score SuperGrok traffic.+evfile="$ROOTDIR/events.json"+exo conversation events "$SLUG" run --limit 400 >"$evfile" 2>/dev/null || true+python3 -c '+import json, sys+try:+ data = json.load(open(sys.argv[1]))+except (OSError, json.JSONDecodeError):+ sys.exit(0)+events = data.get("events") if isinstance(data, dict) else data+if not isinstance(events, list):+ sys.exit(0)+calls = tin = cached = writes = tout = 0+for ev in events:+ blob = ev.get("data") if isinstance(ev, dict) else None+ if not isinstance(blob, dict):+ continue+ usage = blob.get("usage")+ if not isinstance(usage, dict):+ continue+ calls += 1+ tin += int(usage.get("prompt_tokens") or 0)+ cached += int(usage.get("prompt_cached_tokens") or 0)+ writes += int(usage.get("prompt_cache_creation_tokens") or 0)+ tout += int(usage.get("completion_tokens") or 0)+if calls:+ print(f"[usage] {calls} api call(s) · {tin} in ({cached} cached, {writes} cache writes) + {tout} out tokens", file=sys.stderr)+' "$evfile" || truediff --git a/graff-evals/harnesses.json b/graff-evals/harnesses.jsonindex 0665a4ae..31addc66 100644--- a/graff-evals/harnesses.json+++ b/graff-evals/harnesses.json@@ -166,13 +166,21 @@"note": "same SuperGrok seat as graff-dev. Wrapper reads graff-oauth.json into XAI_API_KEY. `pi` must be on PATH."},"opencode": {- "cmd": ["opencode", "run", "--format", "json", "--auto", "--pure", "--dir", "{sandbox}", "-m", "{model}", "{prompt}"],+ "cmd": ["{repo}/graff-evals/opencode-xai.sh", "--dir", "{sandbox}", "-m", "{model}", "{prompt}"],"answer": "opencode-json","usage": "opencode-json","capabilities": [],"model_prefix": "xai","default_model": "xai/grok-4.6",- "note": "OpenCode 1.18 headless. --dir is the eval sandbox (Popen cwd is not enough — OpenCode binds a project root). --pure skips plugins. SuperGrok via OpenCode xai auth."+ "note": "OpenCode 1.18 headless on SuperGrok. Wrapper maps graff-oauth.json → XAI_API_KEY and injects X-XAI-Token-Auth via opencode-xai.json. --dir is the eval sandbox. --pure skips plugins."+ },+ "exo": {+ "cmd": ["{repo}/graff-evals/exo-xai.sh", "--model", "{model}", "{prompt}"],+ "answer": "stdout",+ "usage": "graff-stderr",+ "capabilities": [],+ "default_model": "grok-4.6",+ "note": "exoharness/exo (https://github.com/exoharness/exo) on SuperGrok via local-process (no Docker). Wrapper refreshes graff-oauth, injects X-XAI-Token-Auth through xai-header-proxy.py, mounts the eval sandbox at /home/exo/workspace. Needs `exo` on PATH or EXO_BIN / /tmp/exo/target/release/exo."},"opencode-zen": {"cmd": ["opencode", "run", "--format", "json", "--auto", "--pure", "--dir", "{sandbox}", "-m", "{model}", "{prompt}"],diff --git a/graff-evals/opencode-xai.json b/graff-evals/opencode-xai.jsonnew file mode 100644index 00000000..5f160ea0--- /dev/null+++ b/graff-evals/opencode-xai.json@@ -0,0 +1,12 @@+{+ "$schema": "https://opencode.ai/config.json",+ "provider": {+ "xai": {+ "options": {+ "headers": {+ "X-XAI-Token-Auth": "xai-grok-cli"+ }+ }+ }+ }+}diff --git a/graff-evals/opencode-xai.sh b/graff-evals/opencode-xai.shnew file mode 100755index 00000000..172e40d5--- /dev/null+++ b/graff-evals/opencode-xai.sh@@ -0,0 +1,25 @@+#!/bin/sh+# OpenCode on SuperGrok: JWT needs X-XAI-Token-Auth (same flag graff/grok-build send).+set -e+root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)+oauth="${GRAFF_XAI_OAUTH:-$HOME/.xai/credentials/graff-oauth.json}"+python3 "$root/graff-evals/refresh-graff-oauth.py" || true+# OpenCode prefers auth.json over XAI_API_KEY; keep it in lockstep.+python3 "$root/graff-evals/seed-opencode-xai.py" >/dev/null+if [ -z "${XAI_API_KEY:-}" ] && [ -f "$oauth" ]; then+ XAI_API_KEY=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["access_token"])' "$oauth")+ export XAI_API_KEY+fi+if [ -z "${XAI_API_KEY:-}" ]; then+ echo "opencode-xai: no XAI_API_KEY and no $oauth — run \`graff login xai\`" >&2+ exit 127+fi+export PATH="${HOME}/.opencode/bin:${PATH}"+export OPENCODE_CONFIG="${OPENCODE_CONFIG:-$root/graff-evals/opencode-xai.json}"+export OPENCODE_DISABLE_AUTOUPDATE=1+export OPENCODE_DISABLE_DEFAULT_PLUGINS=1+if ! command -v opencode >/dev/null 2>&1; then+ echo "opencode-xai: opencode not found (https://opencode.ai/docs)" >&2+ exit 127+fi+exec opencode run --format json --auto --pure "$@"diff --git a/graff-evals/pi-xai.sh b/graff-evals/pi-xai.shindex 3d3e6aa0..b7824d77 100755--- a/graff-evals/pi-xai.sh+++ b/graff-evals/pi-xai.sh@@ -2,7 +2,11 @@# Drive Pi on graff's SuperGrok seat (same-login A/B as ADR 0024 grok-build).# Reads ~/.xai/credentials/graff-oauth.json unless XAI_API_KEY is already set.set -e+root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)oauth="${GRAFF_XAI_OAUTH:-$HOME/.xai/credentials/graff-oauth.json}"+python3 "$root/graff-evals/refresh-graff-oauth.py" || true+# auth.json wins over XAI_API_KEY; keep it in lockstep with graff-oauth.+python3 "$root/graff-evals/seed-pi-xai.py" >/dev/nullif [ -z "${XAI_API_KEY:-}" ] && [ -f "$oauth" ]; thenXAI_API_KEY=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["access_token"])' "$oauth")export XAI_API_KEY@@ -11,6 +15,33 @@ if [ -z "${XAI_API_KEY:-}" ]; thenecho "pi-xai: no XAI_API_KEY and no $oauth — run \`graff login xai\`" >&2exit 127fi+# SuperGrok JWTs need the same routing header graff sends (not a secret).+python3 -c '+import json, os+from pathlib import Path+p = Path.home() / ".pi" / "agent" / "models.json"+p.parent.mkdir(parents=True, exist_ok=True)+data = {}+if p.is_file():+ try:+ data = json.loads(p.read_text())+ except json.JSONDecodeError:+ data = {}+if not isinstance(data, dict):+ data = {}+prov = data.setdefault("providers", {})+xai = prov.setdefault("xai", {})+if not isinstance(xai, dict):+ xai = {}+ prov["xai"] = xai+xai.setdefault("baseUrl", "https://api.x.ai/v1")+xai.setdefault("apiKey", "XAI_API_KEY")+hdr = xai.setdefault("headers", {})+if isinstance(hdr, dict):+ hdr["X-XAI-Token-Auth"] = "xai-grok-cli"+xai.setdefault("models", [{"id": "grok-4.6", "name": "Grok 4.6", "reasoning": True, "input": ["text"], "contextWindow": 500000, "maxTokens": 16384}])+p.write_text(json.dumps(data, indent=2) + "\n")+'if [ -n "${PI:-}" ]; thenexec "$PI" "$@"fidiff --git a/graff-evals/refresh-graff-oauth.py b/graff-evals/refresh-graff-oauth.pynew file mode 100755index 00000000..248d898c--- /dev/null+++ b/graff-evals/refresh-graff-oauth.py@@ -0,0 +1,39 @@+#!/usr/bin/env python3+"""Refresh ~/.xai/credentials/graff-oauth.json if it expires within 30 minutes.++Reuses attach-dsh-xai-oauth.py so the refresh URL/client stay in one place.+Never prints the token.+"""+from __future__ import annotations++import importlib.util+import sys+import time+from pathlib import Path++HERE = Path(__file__).resolve().parent+MARGIN_S = 1800+++def main() -> int:+ path = HERE / "attach-dsh-xai-oauth.py"+ spec = importlib.util.spec_from_file_location("dsh_oauth", path)+ if spec is None or spec.loader is None:+ print("refresh-graff-oauth: cannot load attach-dsh-xai-oauth.py", file=sys.stderr)+ return 2+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ cred = mod._read_graff_oauth() or mod._read_grok_auth()+ if cred is None:+ print("refresh-graff-oauth: no SuperGrok OAuth — run `graff login xai`", file=sys.stderr)+ return 2+ exp = cred.get("expires_at") or 0+ if not exp or int(time.time()) >= int(exp) - MARGIN_S:+ cred = mod._refresh(cred)+ left = int(cred.get("expires_at") or 0) - int(time.time())+ print(f"refresh-graff-oauth: refreshed expires_in_s={left}", file=sys.stderr)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/graff-evals/seed-opencode-xai.py b/graff-evals/seed-opencode-xai.pynew file mode 100755index 00000000..998255d7--- /dev/null+++ b/graff-evals/seed-opencode-xai.py@@ -0,0 +1,48 @@+#!/usr/bin/env python3+"""Map graff's SuperGrok OAuth into OpenCode's auth.json.++OpenCode prefers ~/.local/share/opencode/auth.json over XAI_API_KEY, so a+stale stored JWT 403s even when the wrapper exported a fresh token.+Overwrites only the `xai` key. Does not print tokens.+"""+from __future__ import annotations++import json+import os+import stat+import sys+from pathlib import Path++GRAFF = Path.home() / ".xai/credentials/graff-oauth.json"+OC_AUTH = Path.home() / ".local/share/opencode/auth.json"+++def main() -> int:+ if not GRAFF.is_file():+ print(f"no SuperGrok OAuth at {GRAFF} — run `graff login xai`", file=sys.stderr)+ return 1+ src = json.loads(GRAFF.read_text())+ access = src.get("access_token") or ""+ if not access:+ print("graff-oauth.json has no access_token", file=sys.stderr)+ return 1+ OC_AUTH.parent.mkdir(parents=True, exist_ok=True)+ data = {}+ if OC_AUTH.is_file():+ try:+ data = json.loads(OC_AUTH.read_text())+ except json.JSONDecodeError:+ data = {}+ if not isinstance(data, dict):+ data = {}+ data["xai"] = {"type": "api", "key": access}+ tmp = OC_AUTH.with_suffix(".json.tmp")+ tmp.write_text(json.dumps(data, indent=2) + "\n")+ os.chmod(tmp, stat.S_IRUSR | stat.S_IWUSR)+ tmp.replace(OC_AUTH)+ print(f"wrote {OC_AUTH} (xai api from graff-oauth.json)", file=sys.stderr)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/graff-evals/xai-header-proxy.py b/graff-evals/xai-header-proxy.pynew file mode 100755index 00000000..3656985c--- /dev/null+++ b/graff-evals/xai-header-proxy.py@@ -0,0 +1,189 @@+#!/usr/bin/env python3+"""127.0.0.1 reverse proxy: inject X-XAI-Token-Auth onto https://api.x.ai.++SuperGrok JWTs 403 without that header (not a secret). Safe to add on metered+`xai-` keys too. Streaming is passed through byte-for-byte.+"""+from __future__ import annotations++import argparse+import http.client+import http.server+import os+import signal+import sys+import time+from pathlib import Path++UPSTREAM_HOST = "api.x.ai"+TOKEN_AUTH = "xai-grok-cli"+HOP = {+ "connection",+ "keep-alive",+ "proxy-authenticate",+ "proxy-authorization",+ "te",+ "trailers",+ "transfer-encoding",+ "upgrade",+ "host",+}+STATE_DIR = Path(os.environ.get("XAI_PROXY_DIR", "/tmp/xai-header-proxy"))+PID_PATH = STATE_DIR / "pid"+PORT_PATH = STATE_DIR / "port"+++class Handler(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, fmt: str, *args) -> None:+ sys.stderr.write("xai-header-proxy: " + (fmt % args) + "\n")++ def do_GET(self) -> None:+ self._forward()++ def do_POST(self) -> None:+ self._forward()++ def do_PUT(self) -> None:+ self._forward()++ def do_DELETE(self) -> None:+ self._forward()++ def do_PATCH(self) -> None:+ self._forward()++ def do_HEAD(self) -> None:+ self._forward()++ def _forward(self) -> None:+ if self.path in ("/health", "/"):+ body = b"ok\n"+ self.send_response(200)+ self.send_header("Content-Type", "text/plain")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ if self.command != "HEAD":+ self.wfile.write(body)+ return+ length = int(self.headers.get("Content-Length") or 0)+ body = self.rfile.read(length) if length else None+ hdrs = {}+ for key, value in self.headers.items():+ if key.lower() in HOP:+ continue+ hdrs[key] = value+ hdrs["Host"] = UPSTREAM_HOST+ hdrs["X-XAI-Token-Auth"] = TOKEN_AUTH+ conn = http.client.HTTPSConnection(UPSTREAM_HOST, timeout=600)+ try:+ conn.request(self.command, self.path, body=body, headers=hdrs)+ resp = conn.getresponse()+ self.send_response(resp.status, resp.reason)+ for key, value in resp.getheaders():+ if key.lower() in HOP or key.lower() == "content-length":+ continue+ self.send_header(key, value)+ self.send_header("Connection", "close")+ self.end_headers()+ if self.command != "HEAD":+ while True:+ chunk = resp.read(8192)+ if not chunk:+ break+ self.wfile.write(chunk)+ self.wfile.flush()+ finally:+ conn.close()+++def _alive(pid: int) -> bool:+ if pid <= 0:+ return False+ try:+ os.kill(pid, 0)+ except OSError:+ return False+ return True+++def _url(port: int) -> str:+ return f"http://127.0.0.1:{port}"+++def _read_running() -> str | None:+ try:+ pid = int(PID_PATH.read_text().strip())+ port = int(PORT_PATH.read_text().strip())+ except (OSError, ValueError):+ return None+ if not _alive(pid):+ return None+ try:+ conn = http.client.HTTPConnection("127.0.0.1", port, timeout=1)+ conn.request("GET", "/health")+ ok = conn.getresponse().status == 200+ conn.close()+ except OSError:+ return None+ return _url(port) if ok else None+++def _serve(port: int) -> None:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ httpd = http.server.ThreadingHTTPServer(("127.0.0.1", port), Handler)+ bound = httpd.server_address[1]+ PID_PATH.write_text(str(os.getpid()))+ PORT_PATH.write_text(str(bound))+ os.chmod(PID_PATH, 0o600)+ os.chmod(PORT_PATH, 0o600)++ def _stop(_signum, _frame):+ raise SystemExit(0)++ signal.signal(signal.SIGTERM, _stop)+ signal.signal(signal.SIGINT, _stop)+ httpd.serve_forever()+++def _spawn(port: int) -> str:+ child = os.fork()+ if child == 0:+ os.setsid()+ # Second fork so the proxy is not a session leader (classic daemon).+ if os.fork() != 0:+ os._exit(0)+ sys.stdin.close()+ _serve(port)+ os._exit(0)+ os.waitpid(child, 0)+ for _ in range(50):+ url = _read_running()+ if url:+ return url+ time.sleep(0.05)+ raise SystemExit("xai-header-proxy: failed to start")+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument("--ensure", action="store_true", help="start if needed; print base URL")+ ap.add_argument("--port", type=int, default=0, help="bind port (0 = ephemeral)")+ ap.add_argument("--foreground", action="store_true")+ args = ap.parse_args()+ if args.foreground:+ _serve(args.port)+ return 0+ url = _read_running()+ if url is None:+ url = _spawn(args.port)+ if args.ensure:+ sys.stdout.write(url + "\n")+ return 0+ print(url)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())