Datasets:
File size: 17,672 Bytes
e60bf9b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | diff --git a/CUA-KiCad/gym_codex/cradle_agent.py b/CUA-KiCad/gym_codex/cradle_agent.py
new file mode 100644
index 0000000..5b3e990
--- /dev/null
+++ b/CUA-KiCad/gym_codex/cradle_agent.py
@@ -0,0 +1,195 @@
+"""A Cradle-style arm: the direct arm plus Cradle's screenshot-based episodic memory.
+
+Cradle (Tan et al., 2024; BAAI-Agents/Cradle) keeps, for computer control, an episodic
+memory of recent screenshots, the actions taken between them and its own reflections on
+them, plus a running history summary. It rebuilds that memory with four model calls per
+action (information gathering, self-reflection, task inference, action planning) and labels
+every screenshot with SAM set-of-marks. Run as released on KiCad, through the same model
+channel, it took ~155 s and ~51k input tokens per action (pilot, 11-07): four sequential
+calls plus a ~47 s SAM pass. That cannot finish 25 tasks.
+
+This arm keeps the memory and folds the four calls into ONE reply per step:
+ - Reflection (Cradle's self-reflection): did the last batch do what was intended,
+ judged from the screenshots before it and the current one;
+ - History summary (task inference): the model rewrites the running summary each step;
+ - Subtask (task inference): what it is working on now;
+ - Reason + the action batch (action planning).
+The harness stores every step as an episode -- the screenshot, the batch, the reflection
+written about it on the next step, the subtask -- and pushes into each call:
+ - the current screenshot plus the screenshots before the last 2 batches (Cradle's
+ `self_reflection_image_num = 2`), each labelled with its step and the batch that followed;
+ - the last RECENT episodes as text (subtask, batch, reflection);
+ - the latest history summary.
+No full action log (the direct arm's memory) is sent: the summary and the recent episodes
+are the only record of older steps, as in Cradle.
+
+Everything else is the direct arm's: the system prompt and action contract
+(gym_codex/actions.py), the reply's json block, the codex channel (CodexClient, no tools).
+Departures from Cradle: one call per step instead of four; no SAM set-of-marks (the model
+gives coordinates, as every other arm); the KiCad action set instead of Cradle's Chrome
+skills (which have no drag or scroll).
+
+Screenshots are attached as image_url data URIs in the message (CodexClient._flatten),
+not through `images=` -- that path only takes PIL images and drops raw PNG bytes.
+"""
+from __future__ import annotations
+
+import base64
+import json
+import logging
+import re
+from pathlib import Path
+
+from gym_codex.actions import last_json_block, parse_batch
+from gym_codex.codex_gui_agent import DESKTOP_NOTES, SYSTEM_PROMPT
+from prolong_search.codex_client import CodexClient
+
+logger = logging.getLogger("gym_codex.cradle")
+
+_DIRECT_FORMAT = "Reply format: first think briefly in plain text (1-3 sentences), then give EXACTLY ONE fenced json block:"
+_CRADLE_FORMAT = """Reply format: first write these four sections, each starting on its own line with its label, then give EXACTLY ONE fenced json block:
+Reflection: did your LAST action batch do what you intended? Compare the screenshot taken before it with the current one. If it failed or did something else, say what happened and why. (On the first step: "none".)
+History summary: your updated summary of the whole task so far -- what is done, what is in progress, what went wrong and what you learned about this application. It REPLACES the previous summary and is the only record you will have of steps older than the last few, so keep everything you still need (at most ~200 words).
+Subtask: the subtask you are working on now, in one sentence.
+Reason: 1-3 sentences on why the next batch."""
+
+_SECTION = re.compile(
+ r"^[ \t>*#_]*(Reflection|History[ _]summary|Subtask|Reason)[ \t*_]*:[ \t]*(.*?)"
+ r"(?=^[ \t>*#_]*(?:Reflection|History[ _]summary|Subtask|Reason)[ \t*_]*:|^```|\Z)",
+ re.I | re.M | re.S)
+
+
+def _sections(reply: str) -> dict[str, str]:
+ out: dict[str, str] = {}
+ for name, body in _SECTION.findall(reply or ""):
+ key = name.lower().replace(" ", "_")
+ out.setdefault(key, body.strip().lstrip("*_ \t").strip()) # "**Label:** text"
+ return out
+
+
+def _data_uri(png: bytes) -> dict:
+ return {"type": "image_url",
+ "image_url": {"url": "data:image/png;base64," + base64.b64encode(png).decode()}}
+
+
+class CradleEpisodicAgent:
+ """Screenshot in, action batch out, with Cradle's screenshot episodic memory.
+
+ The same `predict / add_feedback / reset / audit` surface as CodexGuiAgent, so
+ run_eval drives it unchanged.
+ """
+
+ REFLECTION_IMAGES = 2 # Cradle's self_reflection_image_num
+ RECENT = 5 # episodes shown as text
+ SUMMARY_CHARS = 2400
+
+ def __init__(self, model: str, effort: str, env_id: str | None, transcript_dir: str,
+ episodic_dir: str, timeout: int = 600, base_url: str | None = None) -> None:
+ notes = DESKTOP_NOTES.get(env_id or "", "")
+ prompt = SYSTEM_PROMPT.replace("{desktop_notes}", notes)
+ assert _DIRECT_FORMAT in prompt
+ self.system_prompt = prompt.replace(_DIRECT_FORMAT, _CRADLE_FORMAT)
+ self.client = CodexClient(model_name=model, reasoning_effort=effort,
+ transcript_dir=transcript_dir, max_images=None,
+ timeout=timeout, base_url=base_url)
+ self.dir = Path(episodic_dir)
+ (self.dir / "screens").mkdir(parents=True, exist_ok=True)
+ self.episodes: list[dict] = [] # one per step: screen, batch, subtask, reflection
+ self.summary = ""
+ self.summary_step: int | None = None
+ self._pending_feedback: str | None = None
+ self._call_seq = 0
+ self.stats = {"steps": 0, "images_attached": 0, "summary_updates": 0,
+ "summary_missing": 0, "reflections": 0, "reflection_missing": 0,
+ "subtask_missing": 0, "unparsed_batches": 0}
+
+ def reset(self) -> None:
+ self.episodes, self.summary, self.summary_step = [], "", None
+ self._pending_feedback = None
+
+ def add_feedback(self, msg: str) -> None:
+ msg = msg.strip()
+ if msg:
+ self._pending_feedback = (f"{self._pending_feedback} | {msg}"
+ if self._pending_feedback else msg)[:1500]
+
+ # -- one step ----------------------------------------------------------------------
+
+ def _user_message(self, instruction: str, png: bytes, step_idx: int, max_steps: int) -> list[dict]:
+ lines = [f"TASK: {instruction}", f"STEP: {step_idx + 1} of at most {max_steps}"]
+ if self.summary:
+ lines += ["", f"HISTORY SUMMARY (you wrote it at step {self.summary_step}):", self.summary]
+ recent = self.episodes[-self.RECENT:]
+ if recent:
+ lines += ["", "RECENT STEPS (oldest first; the reflection on each was written on the step after it):"]
+ for e in recent:
+ lines.append(f" step {e['step']}: subtask: {e.get('subtask') or '-'}")
+ lines.append(f" actions: {e['batch']}")
+ if e.get("reflection"):
+ lines.append(f" reflection: {e['reflection']}")
+ else:
+ lines += ["", "This is the first step; the screenshot shows the initial state."]
+ if self._pending_feedback:
+ lines += ["", f"FEEDBACK ON YOUR LAST REPLY: {self._pending_feedback}"]
+ self._pending_feedback = None
+ content: list[dict] = []
+ past = [e for e in self.episodes if e.get("screen")][-self.REFLECTION_IMAGES:]
+ if past:
+ lines += ["", "SCREENSHOTS, oldest first:"]
+ for e in past:
+ lines.append(f" - before step {e['step']}'s actions ({e['batch'][:160]})")
+ lines.append(" - the CURRENT screen (last image)")
+ lines += ["", "What next?"]
+ content.append({"type": "text", "text": "\n".join(lines)})
+ for e in past:
+ content.append(_data_uri(Path(e["screen"]).read_bytes()))
+ content.append(_data_uri(png))
+ self.stats["images_attached"] += len(past) + 1
+ return [{"role": "system", "content": self.system_prompt},
+ {"role": "user", "content": content}]
+
+ def predict(self, instruction: str, screenshot_png: bytes,
+ step_idx: int, max_steps: int) -> tuple[str, list[dict], bool]:
+ messages = self._user_message(instruction, screenshot_png, step_idx, max_steps)
+ reply = self.client.generate_text(messages)
+ self.stats["steps"] += 1
+ sec = _sections(reply)
+ # the reflection is about the previous episode
+ if self.episodes:
+ if sec.get("reflection"):
+ self.episodes[-1]["reflection"] = sec["reflection"][:800]
+ self.stats["reflections"] += 1
+ else:
+ self.stats["reflection_missing"] += 1
+ if sec.get("history_summary"):
+ self.summary = sec["history_summary"][: self.SUMMARY_CHARS]
+ self.summary_step = step_idx + 1
+ self.stats["summary_updates"] += 1
+ else:
+ self.stats["summary_missing"] += 1
+ if not sec.get("subtask"):
+ self.stats["subtask_missing"] += 1
+ pb = parse_batch(last_json_block(reply), self._tool_call)
+ if pb.feedback:
+ self._pending_feedback = pb.feedback
+ if not pb.calls:
+ self.stats["unparsed_batches"] += 1
+ screen = None
+ if screenshot_png:
+ screen = self.dir / "screens" / f"step_{step_idx + 1:03d}.png"
+ screen.write_bytes(screenshot_png)
+ ep = {"step": step_idx + 1, "screen": str(screen) if screen else None,
+ "batch": pb.log_line, "subtask": (sec.get("subtask") or "")[:300]}
+ self.episodes.append(ep)
+ with open(self.dir / "episodes.jsonl", "a") as f:
+ f.write(json.dumps({**ep, "summary": self.summary, "reflection_on_prev": sec.get("reflection")}) + "\n")
+ return reply, pb.calls, pb.done
+
+ def _tool_call(self, name: str, args: dict) -> dict:
+ self._call_seq += 1
+ return {"id": f"call_{self._call_seq:04d}", "type": "function",
+ "function": {"name": name, "arguments": args}}
+
+ def audit(self) -> dict:
+ return {"arm": "cradle", **self.stats, "episodes": len(self.episodes),
+ "summary_chars": len(self.summary)}
diff --git a/CUA-KiCad/gym_codex/run_eval.py b/CUA-KiCad/gym_codex/run_eval.py
index 9d12109..674a79f 100644
--- a/CUA-KiCad/gym_codex/run_eval.py
+++ b/CUA-KiCad/gym_codex/run_eval.py
@@ -169,6 +169,15 @@ def _make_agent(args, task_dir: Path):
transcript_dir=str(task_dir / "codex"),
timeout=args.codex_timeout or 360,
base_url=args.codex_base_url, **_cli_kw(args))
+ if args.agent == "cradle":
+ # Cradle-style (gym_codex/cradle_agent.py): the direct arm plus Cradle's screenshot
+ # episodic memory (recent screenshots, reflections, a running history summary).
+ from gym_codex.cradle_agent import CradleEpisodicAgent
+ return CradleEpisodicAgent(model=args.model, effort=args.effort, env_id=args.env_id,
+ transcript_dir=str(task_dir / "codex"),
+ episodic_dir=str(task_dir / "episodic"),
+ timeout=args.codex_timeout or 600,
+ base_url=args.codex_base_url)
kw = dict(workspace=task_dir / "workspace", model=args.model, effort=args.effort,
max_steps=args.max_steps, transcript_dir=task_dir / "codex",
session_turns=args.session_turns, base_url=args.codex_base_url)
@@ -465,7 +474,7 @@ async def main() -> int:
help="step budget; default = the benchmark's standard "
"(kicad 200, workflows 100, else 30)")
p.add_argument("--concurrency", type=int, default=3)
- p.add_argument("--agent", choices=("direct", "prolong-logonly", "vista", "mfm", "mfm-carry"),
+ p.add_argument("--agent", choices=("direct", "prolong-logonly", "vista", "mfm", "mfm-carry", "cradle"),
default="direct",
help="memory arm: direct (no persistent memory), prolong-logonly "
"(PRO-LONG: an append-only log is the only memory), vista "
@@ -476,7 +485,9 @@ async def main() -> int:
"multi-batch plan queue), mfm-carry (MFM: the same, with the "
"finished tasks' records and a persistent notes/ carried into "
"each task's workspace under <out>/carry; tasks run in order at "
- "concurrency 1). The options of the two MFM arms are "
+ "concurrency 1), cradle (the direct arm plus Cradle's screenshot episodic memory: the "
+ "screenshots before the last 2 batches, recent reflections, a running "
+ "history summary; gym_codex/cradle_agent.py). The options of the two MFM arms are "
"gym_codex.memory_agents.ARMS")
abl = p.add_argument_group(
"ablations of the MFM arms",
@@ -534,6 +545,8 @@ async def main() -> int:
args.max_steps = _DEFAULT_BUDGETS.get(args.env_id, _FALLBACK_BUDGET)
if _cli_error(args):
p.error(_cli_error(args))
+ if args.agent == "cradle" and getattr(args, "cli", "codex") != "codex":
+ p.error("--agent cradle runs on the codex channel only")
if _ablation_kw(args) and args.agent not in ("mfm", "mfm-carry"):
p.error("--no-history-images/--flat-retrieval/--no-consolidation are ablations of "
"the mfm arms")
diff --git a/CUA-KiCad/scripts/run_kicad_arm.sh b/CUA-KiCad/scripts/run_kicad_arm.sh
index 331cc74..dae20a2 100755
--- a/CUA-KiCad/scripts/run_kicad_arm.sh
+++ b/CUA-KiCad/scripts/run_kicad_arm.sh
@@ -24,7 +24,8 @@ export CODEX_EVAL_HOME=$WORK/codex-eval-home
export CODEX_SANDBOX_INNER_PYTHON=$(command -v python3)
unset CODEX_HOME
# The memory arms run codex inside the bubblewrap sandbox; the direct arm runs it bare.
-if [ "$AGENT" != direct ]; then
+# The Cradle-style arm has no tools either (one reply per step) and runs bare too.
+if [ "$AGENT" != direct ] && [ "$AGENT" != cradle ]; then
export CODEX_BIN=$KICAD/prolong_search/codex_sandbox.sh
fi
CLI_ARGS=()
diff --git a/CUA-KiCad/slurm/kicad_arm.sbatch b/CUA-KiCad/slurm/kicad_arm.sbatch
new file mode 100644
index 0000000..80b667d
--- /dev/null
+++ b/CUA-KiCad/slurm/kicad_arm.sbatch
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# One KiCad run through the release launcher (scripts/run_kicad_arm.sh) as a batch job,
+# from this worktree's CUA-KiCad/ and mfm/.
+#
+# sbatch slurm/kicad_arm.sbatch <agent> <model> <effort> <out-dir> [run_eval args...]
+#
+# Environment (passed by the submitter; nothing here names a user):
+# WORK the launcher's work dir: shim/docker, codex-node-0.153/, codex-eval-home/, cua-lite/
+# IMAGE_TAR the desktop image as an oci archive, loaded into the node-local podman
+# store so the launcher does not pull 7.6 GB from the registry
+#SBATCH -p sapphire
+#SBATCH -c 12
+#SBATCH --mem=32G
+#SBATCH -t 2-20:00:00
+#SBATCH -o slurm/logs/%x-%j.out
+#SBATCH -e slurm/logs/%x-%j.err
+set -uo pipefail
+AGENT=${1:?agent}; MODEL=${2:?model}; EFFORT=${3:?effort}; OUT=${4:?out dir}; shift 4
+KICAD="$SLURM_SUBMIT_DIR"; MFM_DIR="$(cd "$KICAD/.." && pwd)"
+echo "=== job $SLURM_JOB_ID on $(hostname -s) | $(date -Is) | agent=$AGENT model=$MODEL/$EFFORT out=$OUT extra=[$*]"
+
+python3 -c 'import sys, PIL; assert sys.version_info >= (3, 8)' \
+ || { echo "FATAL: python3 on PATH must be >= 3.8 with PIL (tools/zoom.py, the sandbox proxy)"; exit 1; }
+command -v bwrap >/dev/null || { echo "FATAL: bwrap not on PATH"; exit 1; }
+[ -f "${WORK:?}/codex-eval-home/auth.json" ] || { echo "FATAL: no $WORK/codex-eval-home/auth.json"; exit 1; }
+
+# The same node-local store the launcher derives from the job id.
+PODROOT=${TMPDIR:-/tmp}/$USER-podman-$SLURM_JOB_ID
+mkdir -p "$PODROOT/root" "$PODROOT/run"
+export PODMAN_ROOT=$PODROOT/root PODMAN_RUNROOT=$PODROOT/run PODMAN_NETWORK=slirp4netns PODMAN_SHM_SIZE=2g
+export PATH="$WORK/shim:$PATH"
+docker info >/dev/null 2>&1 || { echo "FATAL: podman not functional"; exit 1; }
+# The overlay layers belong to sub-uids: only the rootless user namespace can remove them.
+cleanup() { docker ps -aq 2>/dev/null | xargs -r docker rm -f >/dev/null 2>&1
+ podman --root "$PODMAN_ROOT" --runroot "$PODMAN_RUNROOT" unshare rm -rf "$PODROOT" 2>/dev/null
+ rm -rf "$PODROOT" 2>/dev/null; }
+trap cleanup EXIT
+docker load -i "${IMAGE_TAR:?}" >/dev/null || exit 1
+docker image exists trycua/cua-xfce:latest || docker tag docker.io/trycua/cua-xfce:latest trycua/cua-xfce:latest
+unset HF_HUB_OFFLINE
+
+mkdir -p "$OUT"
+git -C "$MFM_DIR" rev-parse HEAD > "$OUT/code.commit"
+git -C "$MFM_DIR" diff HEAD > "$OUT/code.patch"
+echo "--- codex: $("$WORK/codex-node-0.153/bin/codex" --version 2>/dev/null | tail -1)"
+t0=$SECONDS
+"$KICAD/scripts/run_kicad_arm.sh" "$AGENT" "$MODEL" "$EFFORT" "$OUT" "$@"
+rc=$?
+echo "=== run_eval rc=$rc in $((SECONDS-t0))s | $(date -Is) ==="
+cat "$OUT/summary.json" 2>/dev/null
+exit $rc
|