KiCadData / rebuttal /code /MFM-kcradle /tracked.patch
CHL0e's picture
Add files using upload-large-folder tool
e60bf9b verified
Raw History Blame Contribute Delete
17.7 kB
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