Open-source Slack for your AI agent swarm
Python
Extras: run coding agents and teams on ProgramBench
Pranjal Aggarwal5ee0c0e307e7
diff --git a/.gitignore b/.gitignoreindex 885f4b8..7e82265 100644--- a/.gitignore+++ b/.gitignore@@ -3,3 +3,4 @@ __pycache__/*.egg-info/build/dist/+extras/programbench/runs/diff --git a/README.md b/README.mdindex 63efcab..4438a49 100644--- a/README.md+++ b/README.md@@ -98,6 +98,8 @@ python3 -m unittest discover -s testsThe design is in [DESIGN.md](https://github.com/Pranjal2041/swarmchat/blob/main/DESIGN.md) and the benchmarks are in [bench/RESULTS.md](https://github.com/Pranjal2041/swarmchat/blob/main/bench/RESULTS.md).+To run teams of coding agents on ProgramBench with swarmchat, see [extras/programbench](https://github.com/Pranjal2041/swarmchat/tree/main/extras/programbench).+## Citation```bibtexdiff --git a/extras/README.md b/extras/README.mdnew file mode 100644index 0000000..cf396a3--- /dev/null+++ b/extras/README.md@@ -0,0 +1,6 @@+# Extras++Code that lives in this repository but is not part of the swarmchat pip package.++- [programbench](programbench/README.md): run coding agents on ProgramBench, alone or as a team that talks over+ swarmchat, from a config file that sets the team's size, roles, agent and model.diff --git a/extras/programbench/README.md b/extras/programbench/README.mdnew file mode 100644index 0000000..5a231e3--- /dev/null+++ b/extras/programbench/README.md@@ -0,0 +1,174 @@+# Agent teams on ProgramBench++[ProgramBench](https://github.com/facebookresearch/ProgramBench) gives an agent a compiled program and its+documentation, and asks it to rebuild the program from scratch. This folder runs coding agents on it, alone or as a+team that talks over swarmchat. You describe the run in a config file: the tasks, the time, the agent and its model,+the team's size, its roles and channels, and the prompts each role gets.++## Quick start++On a Linux x86_64 machine with Docker and Python 3.11 or later. The ProgramBench images are built for x86_64 only.++```bash+# 1. The code, and ProgramBench's scorer.+git clone https://github.com/Pranjal2041/swarmchat.git+cd swarmchat/extras/programbench+pip install programbench # or: uv tool install programbench++# 2. The agent's command-line tool. Claude Code installs to ~/.local/bin/claude, where the configs look for it.+curl -fsSL https://claude.ai/install.sh | bash++# 3. Your API key. run.py adds it to the agents' model calls, and it never enters a container.+export ANTHROPIC_API_KEY=...++# 4. See the team and each agent's prompt. This starts nothing.+python3 run.py configs/flat.toml --dry-run++# 5. A short try: eight agents, one task, 15 minutes.+python3 run.py configs/flat.toml --task sitkevij__hex.61ae69b --hours 0.25 --name try++# 6. Score it.+programbench eval runs/try/submissions+```++Without `--task` and `--hours`, a config runs all its tasks for its full time. While a team works, `run.py` prints a+command that opens its chat in your browser. Ctrl-C stops every agent and still saves the submissions. Running the+same config again skips the tasks that already finished.++### With Codex++From [Codex 0.159.2](https://github.com/openai/codex/releases/tag/rust-v0.159.2), download+`codex-x86_64-unknown-linux-musl.tar.gz` and `codex-code-mode-host-x86_64-unknown-linux-musl.tar.gz`. Unpack both into+`~/agents/` and rename them `codex` and `codex-code-mode-host`. Codex runs its tools through the second one. Then use+the Codex lines of the config's `[agent]` section, and `export OPENAI_API_KEY=...`.++## What a run writes++```+runs/<name>/submissions/<task>/submission.tar.gz the final submissions, for programbench eval+runs/<name>/snapshots/<minutes>/<task>/submission.tar.gz a snapshot every snapshot_minutes+runs/<name>/work/<task>/ the chat, each agent's logs and its workspace+```++Each snapshot folder is scored the same way, for example `programbench eval runs/flat8/snapshots/00060`. The score+over time in the blog post came from snapshots like these.++## How a run works++- Each agent has its own container from the task's `task_cleanroom_v6` image, with no network, 20 CPUs and 60 GB,+ as in the official baseline.+- The reference program is mounted read-only at `/reference/executable`, and its copy in `/workspace` is removed,+ so the agent's own build at `./executable` cannot replace it. The prompt tells the agent this.+- The agent's model calls go to the model API through `run.py`, which adds your API key. The key never enters a+ container.+- A team shares a git repository, `/shared/repo.git`, which is the `origin` remote of each agent's `/workspace`. The+ team's submission is that repository's branch when the time runs out. A single agent's submission is its+ `/workspace`, as in the official baseline.+- A team's chat is a swarmchat server with one user per agent. Each new message reaches the agent while it works:+ Claude Code gets it through its hooks, and Codex gets it added to its running turn.+- Each time an agent ends its turn early, it is sent back to work with the role's loop message, until the time runs+ out. Ten minutes before the end, it gets the official time warning.++## The config++`configs/` has one example for each arrangement:++| Config | The team |+| --- | --- |+| `single.toml` | One agent, set up like the official baseline. |+| `flat.toml` | Eight agents that organize themselves in #general. The blog post ran this with 2, 4, 8 and 16. |+| `lead.toml` | One agent leads and writes no features. Seven workers. |+| `features.toml` | Three sub-teams, each owning an area of the program. |+| `phased.toml` | For 40 minutes the team writes a spec and tests, and nobody writes the program. Then it builds. |+| `testers.toml` | Builders write the program. Testers turn differences from the reference into tests. |+| `owner.toml` | One agent alone pushes to the shared branch. The others send it patches through a second repository. |++The settings:++| Key | Meaning |+| --- | --- |+| `name` | The run's folder under `runs/`. |+| `tasks` | ProgramBench task ids. |+| `hours` | Agent time per task. |+| `snapshot_minutes` | How often to save the submission. 0 saves only the final one. |+| `parallel` | How many tasks run at once. |+| `loop` | Send an agent back to work when it ends its turn early. Default true. |+| `[agent] kind` | `claude`, `codex` or `command`. |+| `[agent] binary` | The agent's Linux x86_64 tool. It is mounted read-only into each container. |+| `[agent] model`, `effort` | The model and its reasoning effort. |+| `[agent] api_base`, `api_key_env`, `api_auth` | Where model calls go, the variable holding the key, and whether the key goes in `x-api-key` or `Authorization: Bearer`. They default to Anthropic's or OpenAI's API. |+| `[agent] tools` | Claude Code's tools. Default `Bash`, `Read`, `Edit` and `Write`. |+| `[agent] files` | More files mounted beside the binary. For Codex it defaults to `codex-code-mode-host`. |+| `[docker] command`, `cpus`, `memory`, `image_tag` | How to call Docker, for example `"sudo docker"`, and each container's limits. |+| `[team] members` | The team's size. Leave out `[team]` for a single agent. |+| `[team] chat` | Whether the team has a chat. Default true. |+| `[team.channels]` | Each channel's members: `"all"`, or a list of role names. Default `general = "all"`. |+| `[[team.roles]]` | A role: its `name`, its `prompt` file, and optionally its `loop` file, `count` or `share` of the members, and `push = false` to keep it from pushing to the shared branch. Roles with no count or share split the remaining members evenly. |+| `[team.phase]` | A first phase: its `minutes`, the `loop` file used during it, and the `notice` every agent gets when it ends. |+| `[prompts]` | Other files in place of the base prompts below. |+| `[hide]` | For a task, files in the image that read as empty in the containers. |++Paths are relative to the config file.++## Prompts++The prompts are text files in `prompts/`. An agent's prompt is built from them in this order:++- `task.md`: the official task. Where it says `{{submission}}`, a single agent gets `single.md`, and a team member+ gets `team.md`.+- `team.md`: who the agent is and how the team submits. Where it says `{{chat}}` it gets `chat.md`, if the team has+ a chat, and where it says `{{role_prompt}}` it gets the role's prompt file.+- `system.md`: the official rules, added to the agent's system prompt.+- `loop.md` and `team-loop.md`: the loop message, when a role has none of its own. `time-warning.md`: the official+ warning, with `{{minutes}}`.++A role's prompt can use `{{id}}`, `{{n}}`, `{{others}}`, `{{team}}`, `{{role}}`, `{{branch}}`, `{{shared}}`,+`{{incoming}}`, `{{phase_minutes}}`, and any role's name, which gives the agents in that role. For example `{{lead}}`+is `a1` in `lead.toml`. `--dry-run` shows the result, and it stops on a placeholder it does not know.++`system.md`, `task.md` and `time-warning.md` are adapted from mini-swe-agent's+[programbench.yaml](https://github.com/SWE-agent/mini-swe-agent), under its MIT license in+`prompts/LICENSE-mini-swe-agent.md`.++## Your own agent++With `kind = "command"`, `run.py` runs `command` in the container, from `/workspace`, as the agent. For example:++```toml+[agent]+kind = "command"+binary = "./my-agent" # mounted at /opt/agent/my-agent+command = ["/opt/agent/my-agent"]+model = "my-model"+api_base = "https://api.example.com"+api_key_env = "EXAMPLE_API_KEY"+```++It finds what it needs in its environment:++| Variable | Meaning |+| --- | --- |+| `AGENT_PROMPT_FILE` | The task prompt, and on later runs the loop message with any new messages. |+| `AGENT_SYSTEM_FILE` | The official rules. |+| `AGENT_MODEL`, `AGENT_EFFORT` | From the config. |+| `AGENT_MODEL_URL` | `http://127.0.0.1:8765`. Requests keep their path, and `run.py` sends them to `api_base` with your key. |+| `AGENT_NOTICES` | A folder where each new chat message, and the time warning, arrives as a JSON file with a `text` field. Remove a file once the agent has it. |+| `AGENT_DEADLINE` | When the time runs out, in seconds since 1970. |+| `SWARMCHAT_SERVER`, `SWARMCHAT_TOKEN` | The team's chat. The `swarmchat` command is on the PATH. |++When the command exits before the time runs out, it is run again with the loop message.++## The ten tasks in the blog post++```toml+tasks = ["drew-alleman__datasurgeon.d257cee", "sitkevij__hex.61ae69b", "blacknon__hwatch.edfcb62",+ "yoav-lavi__melody.f4af9b4", "pier-cli__pier.5e1bde9", "ismaelgv__rnr.fc0733b", "rvben__rumdl.2d75c4d",+ "ecumene__rust-sloth.051c559", "alexpovel__srgn.89f943b", "sqlite__sqlite.839433d"]++# The SQLite image has SQLite's own library and headers, which a build could use in place of its own code.+[hide]+"sqlite__sqlite.839433d" = ["/usr/include/sqlite3.h", "/usr/include/sqlite3ext.h",+ "/usr/lib/x86_64-linux-gnu/libsqlite3.a", "/usr/lib/x86_64-linux-gnu/libsqlite3.so.0.8.6",+ "/usr/lib/x86_64-linux-gnu/pkgconfig/sqlite3.pc",+ "/usr/lib/python3.10/lib-dynload/_sqlite3.cpython-310-x86_64-linux-gnu.so"]+```diff --git a/extras/programbench/configs/features.toml b/extras/programbench/configs/features.tomlnew file mode 100644index 0000000..0bbf0db--- /dev/null+++ b/extras/programbench/configs/features.toml@@ -0,0 +1,40 @@+# Three sub-teams, each owning an area of the program the team agrees on first.+name = "features8"+tasks = ["sitkevij__hex.61ae69b"] # ProgramBench task ids. README.md lists the ten in the blog post.+hours = 6 # agent time per task+snapshot_minutes = 30 # save the submission this often, to score it over time. 0 for never.+parallel = 1 # tasks run at once+loop = true # each time an agent ends its turn early, send it back to work++[agent]+# The agent's command-line tool, a Linux x86_64 build. It is mounted read-only into each container.+kind = "claude" # claude, codex or command+binary = "~/.local/bin/claude"+model = "claude-opus-5-5"+effort = "xhigh"+# For Codex instead:+# kind = "codex"+# binary = "~/agents/codex"+# model = "gpt-6-luna"+# effort = "xhigh"++[team]+members = 8 # split 3, 3 and 2++[team.channels]+general = "all"+part-1 = ["part-1"]+part-2 = ["part-2"]+part-3 = ["part-3"]++[[team.roles]]+name = "part-1"+prompt = "../prompts/features.md"++[[team.roles]]+name = "part-2"+prompt = "../prompts/features.md"++[[team.roles]]+name = "part-3"+prompt = "../prompts/features.md"diff --git a/extras/programbench/configs/flat.toml b/extras/programbench/configs/flat.tomlnew file mode 100644index 0000000..319967c--- /dev/null+++ b/extras/programbench/configs/flat.toml@@ -0,0 +1,31 @@+# Eight agents that organize themselves in #general and all push to the shared branch.+# The team-size runs in the blog post used this with 2, 4, 8 and 16 members.+name = "flat8"+tasks = ["sitkevij__hex.61ae69b"] # ProgramBench task ids. README.md lists the ten in the blog post.+hours = 6 # agent time per task+snapshot_minutes = 30 # save the submission this often, to score it over time. 0 for never.+parallel = 1 # tasks run at once+loop = true # each time an agent ends its turn early, send it back to work++[agent]+# The agent's command-line tool, a Linux x86_64 build. It is mounted read-only into each container.+kind = "claude" # claude, codex or command+binary = "~/.local/bin/claude"+model = "claude-opus-5-5"+effort = "xhigh"+# For Codex instead:+# kind = "codex"+# binary = "~/agents/codex"+# model = "gpt-6-luna"+# effort = "xhigh"++[team]+members = 8+chat = true++[team.channels] # each channel's members: "all", or a list of role names+general = "all"++[[team.roles]]+name = "members" # a role with no count or share takes the members the others leave+prompt = "../prompts/flat.md"diff --git a/extras/programbench/configs/lead.toml b/extras/programbench/configs/lead.tomlnew file mode 100644index 0000000..8e5db07--- /dev/null+++ b/extras/programbench/configs/lead.toml@@ -0,0 +1,32 @@+# One agent leads: it writes no features, hands out the work and keeps TASKS.md. Seven workers.+name = "lead8"+tasks = ["sitkevij__hex.61ae69b"] # ProgramBench task ids. README.md lists the ten in the blog post.+hours = 6 # agent time per task+snapshot_minutes = 30 # save the submission this often, to score it over time. 0 for never.+parallel = 1 # tasks run at once+loop = true # each time an agent ends its turn early, send it back to work++[agent]+# The agent's command-line tool, a Linux x86_64 build. It is mounted read-only into each container.+kind = "claude" # claude, codex or command+binary = "~/.local/bin/claude"+model = "claude-opus-5-5"+effort = "xhigh"+# For Codex instead:+# kind = "codex"+# binary = "~/agents/codex"+# model = "gpt-6-luna"+# effort = "xhigh"++[team]+members = 8++[[team.roles]]+name = "lead" # {{lead}} in a prompt is the name of the agent in this role+count = 1+prompt = "../prompts/lead.md"+loop = "../prompts/lead-loop.md"++[[team.roles]]+name = "workers"+prompt = "../prompts/worker.md"diff --git a/extras/programbench/configs/owner.toml b/extras/programbench/configs/owner.tomlnew file mode 100644index 0000000..f05ca7f--- /dev/null+++ b/extras/programbench/configs/owner.toml@@ -0,0 +1,35 @@+# One agent owns the code and alone pushes to the shared branch. The others send it tests and patches+# through a second repository, /incoming/repo.git, which every agent may push to.+name = "owner8"+tasks = ["sitkevij__hex.61ae69b"] # ProgramBench task ids. README.md lists the ten in the blog post.+hours = 6 # agent time per task+snapshot_minutes = 30 # save the submission this often, to score it over time. 0 for never.+parallel = 1 # tasks run at once+loop = true # each time an agent ends its turn early, send it back to work++[agent]+# The agent's command-line tool, a Linux x86_64 build. It is mounted read-only into each container.+kind = "claude" # claude, codex or command+binary = "~/.local/bin/claude"+model = "claude-opus-5-5"+effort = "xhigh"+# For Codex instead:+# kind = "codex"+# binary = "~/agents/codex"+# model = "gpt-6-luna"+# effort = "xhigh"++[team]+members = 8++[[team.roles]]+name = "owner"+count = 1+prompt = "../prompts/owner.md"+loop = "../prompts/owner-loop.md"++[[team.roles]]+name = "helpers"+push = false # the shared repository is read-only for these agents+prompt = "../prompts/helper.md"+loop = "../prompts/helper-loop.md"diff --git a/extras/programbench/configs/phased.toml b/extras/programbench/configs/phased.tomlnew file mode 100644index 0000000..22a4fe6--- /dev/null+++ b/extras/programbench/configs/phased.toml@@ -0,0 +1,31 @@+# For the first 40 minutes nobody writes the program: the team writes a spec and tests. Then it builds.+name = "phased8"+tasks = ["sitkevij__hex.61ae69b"] # ProgramBench task ids. README.md lists the ten in the blog post.+hours = 6 # agent time per task+snapshot_minutes = 30 # save the submission this often, to score it over time. 0 for never.+parallel = 1 # tasks run at once+loop = true # each time an agent ends its turn early, send it back to work++[agent]+# The agent's command-line tool, a Linux x86_64 build. It is mounted read-only into each container.+kind = "claude" # claude, codex or command+binary = "~/.local/bin/claude"+model = "claude-opus-5-5"+effort = "xhigh"+# For Codex instead:+# kind = "codex"+# binary = "~/agents/codex"+# model = "gpt-6-luna"+# effort = "xhigh"++[team]+members = 8++[team.phase]+minutes = 40 # {{phase_minutes}} in a prompt+loop = "../prompts/phased-loop.md" # what sends an agent back to work during the phase+notice = "../prompts/phased-over.md" # what every agent is told when it ends++[[team.roles]]+name = "members"+prompt = "../prompts/phased.md"diff --git a/extras/programbench/configs/single.toml b/extras/programbench/configs/single.tomlnew file mode 100644index 0000000..09c5493--- /dev/null+++ b/extras/programbench/configs/single.toml@@ -0,0 +1,21 @@+# One agent on its own, set up like the official mini-swe-agent baseline. Its submission is its /workspace.+name = "single"+tasks = ["sitkevij__hex.61ae69b"] # ProgramBench task ids. README.md lists the ten in the blog post.+hours = 6 # agent time per task+snapshot_minutes = 30 # save the submission this often, to score it over time. 0 for never.+parallel = 1 # tasks run at once+loop = true # each time an agent ends its turn early, send it back to work++[agent]+# The agent's command-line tool, a Linux x86_64 build. It is mounted read-only into each container.+kind = "claude" # claude, codex or command+binary = "~/.local/bin/claude"+model = "claude-opus-5-5"+effort = "xhigh"+# For Codex instead:+# kind = "codex"+# binary = "~/agents/codex"+# model = "gpt-6-luna"+# effort = "xhigh"++# A config with no [team] section runs one agent.diff --git a/extras/programbench/configs/testers.toml b/extras/programbench/configs/testers.tomlnew file mode 100644index 0000000..cfcd418--- /dev/null+++ b/extras/programbench/configs/testers.toml@@ -0,0 +1,37 @@+# Builders write the program. Testers never change it: they find differences and turn them into tests.+name = "testers8"+tasks = ["sitkevij__hex.61ae69b"] # ProgramBench task ids. README.md lists the ten in the blog post.+hours = 6 # agent time per task+snapshot_minutes = 30 # save the submission this often, to score it over time. 0 for never.+parallel = 1 # tasks run at once+loop = true # each time an agent ends its turn early, send it back to work++[agent]+# The agent's command-line tool, a Linux x86_64 build. It is mounted read-only into each container.+kind = "claude" # claude, codex or command+binary = "~/.local/bin/claude"+model = "claude-opus-5-5"+effort = "xhigh"+# For Codex instead:+# kind = "codex"+# binary = "~/agents/codex"+# model = "gpt-6-luna"+# effort = "xhigh"++[team]+members = 8++[team.channels]+general = "all"+build = ["builders"]+test = ["testers"]++[[team.roles]]+name = "builders"+prompt = "../prompts/builder.md"++[[team.roles]]+name = "testers"+share = 0.375 # three of eight+prompt = "../prompts/tester.md"+loop = "../prompts/tester-loop.md"diff --git a/extras/programbench/guest.py b/extras/programbench/guest.pynew file mode 100644index 0000000..cc75762--- /dev/null+++ b/extras/programbench/guest.py@@ -0,0 +1,433 @@+"""Runs inside each agent's task container. run.py starts it as `python3 /guest/guest.py`.++The container has no network, as in the official ProgramBench baseline. The agent's model calls go to+127.0.0.1:8765 and its chat to 127.0.0.1:8484, and this script carries both to Unix sockets that run.py serves on+the host. The API key stays on the host.++Then it prepares /workspace and runs the agent until run.py creates /guest/stop:++- claude: Claude Code in print mode. Its PostToolUse hook adds new chat messages and the official time warning to+ the conversation, and its Stop hook sends it back to work each time it ends its turn.+- codex: Codex's app server. New chat messages are added to the running turn, and each later turn sends it back to+ work.+- command: any other agent, run as a command. It reads its prompt from $AGENT_PROMPT_FILE and its new chat+ messages from the files in /notices. When it exits early it is run again with the loop message.++The task images ship Python 3.10, so this file uses only the standard library of Python 3.10.+"""+import json+import os+import queue+import socket+import subprocess+import sys+import threading+import time++GUEST = '/guest'+SOCKETS = '/sockets'+HOME = '/agent-home'+NOTICES = '/notices'+MODEL_PORT = 8765+CHAT_PORT = 8484+++def load():+ with open(os.path.join(GUEST, 'config.json')) as f:+ return json.load(f)+++def save(path, value):+ with open(path+'.tmp', 'w') as f:+ json.dump(value, f)+ os.replace(path+'.tmp', path)+++def stopped():+ return os.path.exists(os.path.join(GUEST, 'stop'))+++def note(kind, **fields):+ with open(os.path.join(HOME, 'guest.jsonl'), 'a') as f:+ f.write(json.dumps({'at': time.time(), 'kind': kind, **fields})+'\n')+++# Relays: loopback TCP in the container to a Unix socket on the host.++def pipe(source, target):+ try:+ while True:+ data = source.recv(65536)+ if not data:+ break+ target.sendall(data)+ except OSError:+ pass+ finally:+ for s in (source, target):+ try:+ s.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+++def relay(port, path):+ server = socket.socket()+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ server.bind(('127.0.0.1', port))+ server.listen(64)+ while True:+ client, _ = server.accept()+ upstream = socket.socket(socket.AF_UNIX)+ try:+ upstream.connect(path)+ except OSError:+ client.close()+ continue+ threading.Thread(target=pipe, args=(client, upstream), daemon=True).start()+ threading.Thread(target=pipe, args=(upstream, client), daemon=True).start()+++# Chat messages and other notices. run.py writes each new chat message as a file in /notices.++def notices(limit=8):+ """The oldest waiting notices, at most `limit`. Returns their paths and their text. The caller removes the files+ once the agent has them."""+ names = sorted(n for n in os.listdir(NOTICES) if n.endswith('.json'))[:limit]+ paths, texts = [], []+ for name in names:+ path = os.path.join(NOTICES, name)+ try:+ with open(path) as f:+ texts.append(json.load(f)['text'])+ except (OSError, ValueError):+ continue+ paths.append(path)+ return paths, '\n\n'.join(texts)+++def take_notices():+ """Like notices(), but each file is claimed by renaming it first, so two hooks running at once never deliver+ the same message twice."""+ texts = []+ for name in sorted(n for n in os.listdir(NOTICES) if n.endswith('.json'))[:8]:+ path = os.path.join(NOTICES, name)+ try:+ os.rename(path, path+'.taken')+ except FileNotFoundError:+ continue+ with open(path+'.taken') as f:+ texts.append(json.load(f)['text'])+ os.remove(path+'.taken')+ return '\n\n'.join(texts)+++def time_warning(config):+ remaining = config['deadline']-time.time()+ return config['time_warning'].replace('{{minutes}}', str(max(0, int(remaining/60))))+++def timekeeper(config):+ """Posts the end of the first phase, and for agents without hooks the official time warning, as notices."""+ while not stopped():+ phase = config.get('phase')+ if phase and time.time() >= phase['until'] and not os.path.exists(HOME+'/phase-over'):+ open(HOME+'/phase-over', 'w').close()+ save(os.path.join(NOTICES, '0-phase-over.json'), {'text': phase['notice']})+ if config['kind'] != 'claude' and config['deadline']-time.time() < 600 and not os.path.exists(HOME+'/warned'):+ open(HOME+'/warned', 'w').close()+ save(os.path.join(NOTICES, '0-time-warning.json'), {'text': time_warning(config)})+ time.sleep(5)+++def loop_message(config):+ """What sends the agent back to work: the first phase's own message while that phase lasts."""+ phase = config.get('phase')+ if config['loop'] and phase and time.time() < phase['until']:+ return phase['loop']+ return config['loop']+++# Claude Code hooks. Claude Code runs them as `python3 /guest/guest.py warn` and `... loop`.++def hook_warn():+ """PostToolUse: the official time warning in the last ten minutes, and new chat messages."""+ sys.stdin.read()+ config = load()+ texts = []+ if config['deadline']-time.time() < 600:+ texts.append(time_warning(config))+ text = take_notices()+ if text:+ texts.append(text)+ if texts:+ print(json.dumps({'hookSpecificOutput': {'hookEventName': 'PostToolUse',+ 'additionalContext': '\n\n'.join(texts)}}))+++def hook_loop():+ """Stop: block the end of the turn and send the agent back to work, with any new chat messages."""+ sys.stdin.read()+ config = load()+ if stopped() or not config['loop']:+ return+ text = take_notices()+ print(json.dumps({'decision': 'block', 'reason': loop_message(config)+('\n\n'+text if text else '')}))+++# Setup.++def git(*args):+ subprocess.run(['git', *args], cwd='/workspace', check=True, capture_output=True)+++def setup(config):+ # The reference is mounted read-only at /reference/executable. The workspace copy goes, so the agent's own+ # build at ./executable replaces nothing.+ if os.path.exists('/workspace/executable'):+ os.remove('/workspace/executable')+ git('config', 'user.name', config['id'])+ git('config', 'user.email', config['id']+'@programbench.local')+ if config.get('shared'):+ git('remote', 'add', 'origin', config['shared'])+ git('fetch', '-q', 'origin')+ git('branch', '-u', 'origin/'+config['branch'])+ if config.get('incoming'):+ git('remote', 'add', 'incoming', config['incoming'])+ git('fetch', '-q', 'incoming')+++def environment(config):+ env = dict(os.environ)+ env.update(HOME='/home/agent', PATH='/opt/swarmchat/bin:'+env.get('PATH', '/usr/local/bin:/usr/bin:/bin'))+ env.update(config['env'])+ if config.get('chat_token'):+ env.update(SWARMCHAT_SERVER=f'http://127.0.0.1:{CHAT_PORT}', SWARMCHAT_TOKEN=config['chat_token'])+ return env+++def end(process):+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=30)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+++# The agents.++def run_claude(config):+ """Claude Code processes, one after another, all in one conversation, until run.py stops the run."""+ env = environment(config)+ seconds = str(config['command_seconds']*1000)+ env.update(CLAUDE_CONFIG_DIR=HOME+'/config', ANTHROPIC_BASE_URL=f'http://127.0.0.1:{MODEL_PORT}',+ ANTHROPIC_AUTH_TOKEN='relay', DISABLE_AUTOUPDATER='1', CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC='1',+ BASH_DEFAULT_TIMEOUT_MS=seconds, BASH_MAX_TIMEOUT_MS=seconds,+ BASH_MAX_OUTPUT_LENGTH=str(config['output_chars']), API_TIMEOUT_MS=str(3600*1000))+ env.pop('ANTHROPIC_API_KEY', None)+ projects = HOME+'/config/projects'+ restarts = 0+ while not stopped():+ # Claude Code saves the conversation under projects/ once it starts, and later processes resume it.+ first = not any(os.path.exists(os.path.join(projects, d, config['session']+'.jsonl'))+ for d in (os.listdir(projects) if os.path.isdir(projects) else ()))+ command = [config['binary'], '-p', '--output-format', 'stream-json', '--verbose', '--model', config['model'],+ '--dangerously-skip-permissions', '--setting-sources', 'user',+ '--append-system-prompt-file', GUEST+'/system.txt']+ if config.get('effort'):+ command += ['--effort', config['effort']]+ if config.get('tools'):+ command += ['--tools', ','.join(config['tools'])]+ command += ['--session-id', config['session']] if first else ['--resume', config['session']]+ prompt = open(GUEST+'/prompt.txt').read() if first else loop_message(config) or config['resume']+ with open(HOME+'/events.jsonl', 'a') as out, open(HOME+'/stderr.log', 'a') as err:+ process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=out, stderr=err, env=env,+ cwd='/workspace', text=True)+ process.stdin.write(prompt)+ process.stdin.close()+ while process.poll() is None and not stopped():+ time.sleep(1)+ end(process)+ note('exit', code=process.returncode)+ if stopped() or not config['loop']:+ return+ # Claude Code ended before the time limit, on an error or a turn the Stop hook did not catch. Wait a little+ # and resume the conversation.+ restarts = restarts+1 if process.returncode else 0+ time.sleep(min(60, 2**restarts))+++def run_codex(config):+ """Codex's app server, restarted if it exits. It keeps one conversation until run.py stops the run."""+ env = environment(config)+ env.update(CODEX_HOME=HOME, RELAY_API_KEY='relay')+ cycles = 0+ with open(HOME+'/events.jsonl', 'a', buffering=1) as events, open(HOME+'/stderr.log', 'a', buffering=1) as err:+ while not stopped():+ thread = open(HOME+'/thread-id').read().strip() if os.path.exists(HOME+'/thread-id') else None+ process = subprocess.Popen([config['binary'], 'app-server'], env=env, cwd='/workspace',+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=err, text=True, bufsize=1)+ incoming = queue.Queue()++ def reader():+ try:+ for line in process.stdout:+ incoming.put(json.loads(line))+ finally:+ incoming.put(None)++ threading.Thread(target=reader, daemon=True).start()+ requests, serial = {}, 0+ ready, active, waiting, interrupted = False, None, False, False+ retry_after, errors = 0.0, 0++ def send(method, params, paths=()):+ nonlocal serial+ serial += 1+ requests[serial] = (method, list(paths))+ process.stdin.write(json.dumps({'id': serial, 'method': method, 'params': params})+'\n')+ process.stdin.flush()++ try:+ send('initialize', {'clientInfo': {'name': 'swarmchat-programbench', 'version': '1'}})+ while True:+ try:+ event = incoming.get(timeout=.2)+ except queue.Empty:+ event = {}+ if event is None:+ raise RuntimeError('app server exited')+ method, params = event.get('method'), event.get('params', {})+ # The whole conversation, less the streamed pieces that the completed items repeat.+ if method and not method.lower().endswith('delta'):+ events.write(json.dumps({'at': time.time(), **event})+'\n')+ # Subagents' turns come on the same stream. Only the agent's own thread's turns are its turns.+ own = params.get('threadId', thread) == thread+ if method == 'turn/started' and own:+ active = params['turn']['id']+ elif method == 'turn/completed' and own:+ active = None+ if params['turn'].get('error'):+ errors += 1+ retry_after = time.monotonic()+min(60, 2**errors)+ else:+ errors = 0+ if not config['loop'] and os.path.exists(HOME+'/started'):+ # Without a loop message, the end of the agent's turn ends its work.+ return+ # Replies to this script's requests. A request from the app server has a method as well as an id.+ if 'method' not in event and event.get('id') in requests:+ request, paths = requests.pop(event['id'])+ if request in ('turn/start', 'turn/steer'):+ waiting = False+ if 'error' in event:+ note('request_error', method=request, error=event['error'])+ if request not in ('turn/start', 'turn/steer', 'turn/interrupt'):+ raise RuntimeError(str(event['error']))+ retry_after = time.monotonic()+1+ else:+ for path in paths:+ os.remove(path)+ if request == 'initialize':+ process.stdin.write(json.dumps({'method': 'initialized', 'params': {}})+'\n')+ process.stdin.flush()+ args = {'cwd': '/workspace', 'model': config['model'], 'approvalPolicy': 'never',+ 'sandbox': 'danger-full-access', 'developerInstructions': config['system']}+ if thread:+ send('thread/resume', {**args, 'threadId': thread})+ else:+ send('thread/start', args)+ elif request in ('thread/start', 'thread/resume'):+ thread, ready = event['result']['thread']['id'], True+ with open(HOME+'/thread-id', 'w') as f:+ f.write(thread)+ elif request == 'turn/start':+ open(HOME+'/started', 'w').close()+ if event['result'].get('turn', {}).get('status') == 'inProgress':+ active = event['result']['turn']['id']+ if stopped():+ if not active:+ return+ if not interrupted:+ interrupted = True+ send('turn/interrupt', {'threadId': thread, 'turnId': active})+ continue+ if not ready or waiting or time.monotonic() < retry_after:+ continue+ paths, text = notices()+ if active:+ if paths:+ waiting = True+ send('turn/steer', {'threadId': thread, 'expectedTurnId': active,+ 'input': [{'type': 'text', 'text': text}]}, paths)+ continue+ first = not os.path.exists(HOME+'/started')+ prompt = open(GUEST+'/prompt.txt').read() if first else loop_message(config) or config['resume']+ if text:+ prompt += '\n\n'+text+ waiting = True+ params = {'threadId': thread, 'input': [{'type': 'text', 'text': prompt}]}+ if config.get('effort'):+ params['effort'] = config['effort']+ send('turn/start', params, paths)+ except Exception as exc:+ note('restart', error=f'{type(exc).__name__}: {exc}')+ finally:+ end(process)+ cycles += 1+ time.sleep(min(30, 2*cycles))+++def run_command(config):+ """Any other agent, run as a command. It is run again with the loop message each time it exits early."""+ env = environment(config)+ env.update(AGENT_SYSTEM_FILE=GUEST+'/system.txt', AGENT_MODEL=config['model'], AGENT_EFFORT=config.get('effort') or '',+ AGENT_MODEL_URL=f'http://127.0.0.1:{MODEL_PORT}', AGENT_NOTICES=NOTICES,+ AGENT_DEADLINE=str(config['deadline']))+ runs = 0+ while not stopped():+ if runs == 0:+ prompt_file = GUEST+'/prompt.txt'+ else:+ paths, text = notices(limit=10**6)+ prompt_file = f'{HOME}/prompt-{runs}.txt'+ with open(prompt_file, 'w') as f:+ f.write((loop_message(config) or config['resume'])+('\n\n'+text if text else ''))+ for path in paths:+ os.remove(path)+ env['AGENT_PROMPT_FILE'] = prompt_file+ with open(HOME+'/stdout.log', 'a') as out, open(HOME+'/stderr.log', 'a') as err:+ process = subprocess.Popen(config['command'], stdin=subprocess.DEVNULL, stdout=out, stderr=err, env=env,+ cwd='/workspace')+ while process.poll() is None and not stopped():+ time.sleep(1)+ end(process)+ note('exit', code=process.returncode)+ runs += 1+ if stopped() or not config['loop']:+ return+ time.sleep(5)+++def main():+ config = load()+ threading.Thread(target=relay, args=(MODEL_PORT, SOCKETS+'/model.sock'), daemon=True).start()+ if config.get('chat_token'):+ threading.Thread(target=relay, args=(CHAT_PORT, SOCKETS+'/chat.sock'), daemon=True).start()+ setup(config)+ threading.Thread(target=timekeeper, args=(config,), daemon=True).start()+ try:+ {'claude': run_claude, 'codex': run_codex, 'command': run_command}[config['kind']](config)+ except Exception as exc:+ save(HOME+'/exit.json', {'at': time.time(), 'error': f'{type(exc).__name__}: {exc}'})+ raise+ save(HOME+'/exit.json', {'at': time.time()})+ # The container stays up until run.py has copied the workspace and removes it.+ while True:+ time.sleep(3600)+++if __name__ == '__main__':+ {'warn': hook_warn, 'loop': hook_loop}.get(sys.argv[1] if sys.argv[1:] else '', main)()diff --git a/extras/programbench/prompts/LICENSE-mini-swe-agent.md b/extras/programbench/prompts/LICENSE-mini-swe-agent.mdnew file mode 100644index 0000000..503821c--- /dev/null+++ b/extras/programbench/prompts/LICENSE-mini-swe-agent.md@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2025 Kilian A. Lieret and Carlos E. Jimenez++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.\ No newline at end of filediff --git a/extras/programbench/prompts/builder.md b/extras/programbench/prompts/builder.mdnew file mode 100644index 0000000..768f7af--- /dev/null+++ b/extras/programbench/prompts/builder.md@@ -0,0 +1,7 @@+The team has two groups. The builders, {{builders}}, write the program. The testers, {{testers}}, never change+the program: they run the team's build against the reference executable, add each difference they find as a test+under `tests/` on the shared branch, and report it in #general. The builders also have the #build channel, and the+testers #test.++You are a builder. Work out with the other builders in #build how to split the program, fix the differences the+testers report, and keep the shared branch building and passing the tests in `tests/`.diff --git a/extras/programbench/prompts/chat.md b/extras/programbench/prompts/chat.mdnew file mode 100644index 0000000..c0ec654--- /dev/null+++ b/extras/programbench/prompts/chat.md@@ -0,0 +1,3 @@+Talk to the others with the `swarmchat` command. All of you are in the #general channel. You may also make new+channels, send direct messages and organize yourselves however you like. Run `swarmchat --help` to see how. New+messages for you appear in this conversation as they arrive.diff --git a/extras/programbench/prompts/features.md b/extras/programbench/prompts/features.mdnew file mode 100644index 0000000..e5041d0--- /dev/null+++ b/extras/programbench/prompts/features.md@@ -0,0 +1,5 @@+The team is three sub-teams: part 1, {{part-1}}; part 2, {{part-2}}; and part 3, {{part-3}}. You are in+{{role}}, and your sub-team's channel is #{{role}}. First agree in #general on three areas of the program, one for+each part, and write them in `AREAS.md` on the shared branch. From then on your sub-team owns its area: it writes+that code and its tests. Ask the sub-team that owns an area before changing it. Keep the shared branch building and+passing the team's tests.diff --git a/extras/programbench/prompts/flat.md b/extras/programbench/prompts/flat.mdnew file mode 100644index 0000000..7f6c90f--- /dev/null+++ b/extras/programbench/prompts/flat.md@@ -0,0 +1,2 @@+Work out together how to split the work. Write your own tests against the reference executable, share them, and+keep the shared branch building and passing them.diff --git a/extras/programbench/prompts/helper-loop.md b/extras/programbench/prompts/helper-loop.mdnew file mode 100644index 0000000..4038e26--- /dev/null+++ b/extras/programbench/prompts/helper-loop.md@@ -0,0 +1,2 @@+There is still time left, so do not stop yet. Try harder: find more behavior where the team's build differs+from the reference executable, and send the owner a report, tests or a patch.diff --git a/extras/programbench/prompts/helper.md b/extras/programbench/prompts/helper.mdnew file mode 100644index 0000000..e76c3c4--- /dev/null+++ b/extras/programbench/prompts/helper.md@@ -0,0 +1,5 @@+{{owner}} owns the program, and is the only one who can push to `{{branch}}`. You can fetch it, but not push to+it. You are a helper. Find where the team's build differs from the reference executable, write tests for it, and+report each difference to {{owner}} with the exact command, the reference's output and the build's output. When you+have a fix or tests, push them as a branch named `{{id}}/<topic>` to the `incoming` remote of your /workspace,+`{{incoming}}`, and tell {{owner}}. Keep each patch small and on a recent `{{branch}}`, so it is quick to take.diff --git a/extras/programbench/prompts/lead-loop.md b/extras/programbench/prompts/lead-loop.mdnew file mode 100644index 0000000..72693de--- /dev/null+++ b/extras/programbench/prompts/lead-loop.md@@ -0,0 +1,2 @@+There is still time left, so do not stop yet. Find the largest remaining differences between the team's build+and the reference executable, and hand them out.diff --git a/extras/programbench/prompts/lead.md b/extras/programbench/prompts/lead.mdnew file mode 100644index 0000000..1fce946--- /dev/null+++ b/extras/programbench/prompts/lead.md@@ -0,0 +1,4 @@+You lead the team, and you write no features yourself. Split the program into pieces of work, give each of the+others its piece, and keep the list of open work and who has it in `TASKS.md` on the shared branch. Review what+lands. When the team's progress slows, find the largest remaining differences between the team's build and the+reference executable, and hand them out. Keep the shared branch building.diff --git a/extras/programbench/prompts/loop.md b/extras/programbench/prompts/loop.mdnew file mode 100644index 0000000..130e8c6--- /dev/null+++ b/extras/programbench/prompts/loop.md@@ -0,0 +1,2 @@+There is still time left, so do not stop yet. Try harder: find more behavior where your implementation differs+from the reference executable, fix it, and commit.diff --git a/extras/programbench/prompts/owner-loop.md b/extras/programbench/prompts/owner-loop.mdnew file mode 100644index 0000000..b036c9e--- /dev/null+++ b/extras/programbench/prompts/owner-loop.md@@ -0,0 +1,2 @@+There is still time left, so do not stop yet. Try harder: take in the helpers' patches, find more behavior+where your implementation differs from the reference executable, fix it, commit, and push it to the shared branch.diff --git a/extras/programbench/prompts/owner.md b/extras/programbench/prompts/owner.mdnew file mode 100644index 0000000..43db648--- /dev/null+++ b/extras/programbench/prompts/owner.md@@ -0,0 +1,5 @@+You own the program. You are the only one who can push to `{{branch}}`. The others, {{others}}, are helpers:+they never change the program in the shared repository. They compare your build with the reference executable,+write tests, and send you bug reports and patches. They push patches and tests as branches named after themselves,+such as `<name>/flags`, to the `incoming` remote of your /workspace, `{{incoming}}`. Fetch them, take what is right,+tell the helpers what to look at next, and keep `{{branch}}` building and passing the team's tests.diff --git a/extras/programbench/prompts/phased-loop.md b/extras/programbench/prompts/phased-loop.mdnew file mode 100644index 0000000..bbc123e--- /dev/null+++ b/extras/programbench/prompts/phased-loop.md@@ -0,0 +1,2 @@+There is still time left in the first phase. Probe more of the reference executable, extend SPEC.md and the+tests, and push them.diff --git a/extras/programbench/prompts/phased-over.md b/extras/programbench/prompts/phased-over.mdnew file mode 100644index 0000000..607b158--- /dev/null+++ b/extras/programbench/prompts/phased-over.md@@ -0,0 +1,2 @@+The first phase is over. Build the program now: split the work using SPEC.md and the tests, and keep the shared+branch building and passing them.diff --git a/extras/programbench/prompts/phased.md b/extras/programbench/prompts/phased.mdnew file mode 100644index 0000000..cdfed5a--- /dev/null+++ b/extras/programbench/prompts/phased.md@@ -0,0 +1,4 @@+The team works in two phases. For the first {{phase_minutes}} minutes, nobody writes the program. Split the+reference executable's behavior between you in #general, probe it, and write down what you find: a spec in+`SPEC.md` and tests under `tests/`, both on the shared branch. A message tells you when this phase ends. Then split+the building between you using the spec and the tests, and keep the shared branch building and passing them.diff --git a/extras/programbench/prompts/resume.md b/extras/programbench/prompts/resume.mdnew file mode 100644index 0000000..232f76f--- /dev/null+++ b/extras/programbench/prompts/resume.md@@ -0,0 +1 @@+Continue the task where you left off.diff --git a/extras/programbench/prompts/single.md b/extras/programbench/prompts/single.mdnew file mode 100644index 0000000..1515e6a--- /dev/null+++ b/extras/programbench/prompts/single.md@@ -0,0 +1 @@+When you are done, end your turn. The contents of /workspace at that point are your submission.diff --git a/extras/programbench/prompts/system.md b/extras/programbench/prompts/system.mdnew file mode 100644index 0000000..3fd9907--- /dev/null+++ b/extras/programbench/prompts/system.md@@ -0,0 +1,55 @@+You are a helpful assistant that can interact with a computer.++Your task is to recreate a program from scratch based only on its observable behavior and bundled documentation.+You are given a reference executable and its documentation.+Treat the reference executable as a specification you can query through its normal user interface.++Your submission must be an independent implementation.+Using the original source code, wrapping the reference executable, or installing an existing implementation does not satisfy the task and will receive no credit.+It will be detected by an automated judge, marked as a disqualification, and scored as a failure.++<RULES>+## What is NOT allowed++### 1. Using an existing implementation++The only source of truth about what the executable does is the executable itself and its+bundled documentation. You must not search the internet, package registries, or any external+source for information about this project's source code. Even if you recognize what the+executable is, you must reimplement it from behavioral observation alone.++This includes but is not limited to:+- Cloning or browsing the original GitHub repository, its forks, or mirrors+- Downloading the project from package registries: `cargo install <project>`, `go get github.com/<org>/<project>`, `pip install <project>`, `apt-get source <project>`, `npm install <project>`, etc.+- Fetching source tarballs from project websites (e.g., `curl https://lua.org/ftp/lua-5.5.0.tar.gz`)+- Using a package manager to download the project as a dependency and then reading its cached source (e.g., navigating into `~/.cargo/registry/src/` or `$(go env GOPATH)/pkg/mod/`)+- Searching the web for the project's source code or implementation details++### 2. Wrapping or reusing the reference executable++Your submission must be a genuine reimplementation. The reference `/reference/executable` is for+observation only — your final solution must not depend on it or any other pre-built version+of the same tool at runtime.++This includes but is not limited to:+- Writing a wrapper script that delegates to the reference executable (e.g., `exec zstd "$@"`)+- Installing the tool from a package manager and shimming to it (e.g., `apt-get install nnn && cp $(which nnn) ./executable`)+- Writing a `compile.sh` that only runs `chmod +x ./executable` or copies the reference executable (`cp /reference/executable ./executable`)+- Building a binary whose main function shells out to an external tool (e.g., `Command::new("miniserve").args(args).exec()`)+- Re-linking prebuilt `.o` object files found in the workspace without writing new source code++### 3. How the reference executable may be observed++All information about the reference `/reference/executable` must be obtained by interacting with it+through its normal user interface (CLI flags, stdin/stdout, etc.).+- You MUST NOT decompile `/reference/executable` or use disassemblers (objdump, Ghidra, etc.) on it+- You MUST NOT use strace, ltrace, or similar tracing/instrumentation tools on `/reference/executable`++Note: this restriction applies ONLY to the reference `/reference/executable`. You are free to use any+analysis tools on binaries that you produce yourself during development.++## What IS allowed++- Running the executable with any inputs, flags, and arguments to observe its behavior+- Reading any documentation files bundled in the workspace+</RULES>diff --git a/extras/programbench/prompts/task.md b/extras/programbench/prompts/task.mdnew file mode 100644index 0000000..cd13bf7--- /dev/null+++ b/extras/programbench/prompts/task.md@@ -0,0 +1,42 @@+## Task context++Build a new implementation from scratch that matches the behavior of the reference executable.+The reference executable is located at `/reference/executable`. It is read-only. Your own build goes to `./executable` in the workspace root.++You also have access to the existing documentation.++## Your task++Implement a program whose externally observable behavior matches the reference executable.++No project-specific dependencies are pre-installed.+You do NOT have access to the internet.+**IMPORTANT**: Make sure that the executable(s) and everything else that is an artifact is not committed, i.e., is in your `.gitignore` file.+Finally, commit your changes.++Make sure that you have a `./compile.sh` file that produces an executable `./executable` in the workspace root.+`compile.sh` should be executable and should install any dependencies needed to compile the executable.+If your compile.sh fails to compile on a fresh checkout, your task has failed.++## Important: Build an independent implementation++Your goal is to create an independently authored implementation that reproduces the reference executable's externally observable behavior.+Use the bundled documentation and experiments with the reference executable to determine the required behavior.++Attempting to obtain source code — whether successful or not — or wrapping/reusing the+reference executable does not satisfy the task and will receive no credit.+See the full rules in the system prompt above. Key points:++- Do NOT search the internet, clone repos, or download the project from any package registry+- Do NOT wrap, shim, or delegate to the reference `/reference/executable` or any installed version of the same tool+- Do NOT decompile the reference `/reference/executable` or use strace/ltrace on it (analyzing your own binaries is fine)+- You SHOULD extensively test the executable to understand its behavior before writing code.+ If you are dealing with a TUI, tmux/libtmux has been installed to help you test/inspect/it.++## Recommended Workflow++1. Explore all documentation files+2. Play with the executable to understand its behavior (however, you MUST NOT decompile `/reference/executable` or perform any other form of binary or strace/ltrace analysis on it)+3. Write the source code to implement the behavior++{{submission}}diff --git a/extras/programbench/prompts/team-loop.md b/extras/programbench/prompts/team-loop.mdnew file mode 100644index 0000000..a2497d2--- /dev/null+++ b/extras/programbench/prompts/team-loop.md@@ -0,0 +1,2 @@+There is still time left, so do not stop yet. Try harder: find more behavior where your implementation differs+from the reference executable, fix it, commit, and push it to the shared branch.diff --git a/extras/programbench/prompts/team.md b/extras/programbench/prompts/team.mdnew file mode 100644index 0000000..6a85f04--- /dev/null+++ b/extras/programbench/prompts/team.md@@ -0,0 +1,14 @@+## Working as a team++You are {{id}}, one of {{n}} agents doing this task together. The others are {{others}}. Each of you has your own+container and /workspace, with the same reference executable and documentation.++The team has one shared git repository, `{{shared}}`. It is the `origin` remote of your /workspace. The team's+submission is its `{{branch}}` branch when the time runs out, built on a fresh checkout with `./compile.sh`. Only work+pushed to that branch counts. Your own /workspace is not submitted.++{{chat}}++{{role_prompt}}++When you are done, end your turn.diff --git a/extras/programbench/prompts/tester-loop.md b/extras/programbench/prompts/tester-loop.mdnew file mode 100644index 0000000..a9b1de9--- /dev/null+++ b/extras/programbench/prompts/tester-loop.md@@ -0,0 +1,2 @@+There is still time left, so do not stop yet. Try harder: find more behavior where the team's build differs+from the reference executable, add it to the tests, push them, and report it in #general.diff --git a/extras/programbench/prompts/tester.md b/extras/programbench/prompts/tester.mdnew file mode 100644index 0000000..29a166b--- /dev/null+++ b/extras/programbench/prompts/tester.md@@ -0,0 +1,8 @@+The team has two groups. The builders, {{builders}}, write the program. The testers, {{testers}}, never change+the program: they run the team's build against the reference executable, add each difference they find as a test+under `tests/` on the shared branch, and report it in #general. The builders also have the #build channel, and the+testers #test.++You are a tester. Do not change the program's code. Work out with the other testers in #test how to cover the+program between you. For each difference you find, add a test under `tests/` on the shared branch, and post it in+#general with the exact command, the reference's output and the build's output.diff --git a/extras/programbench/prompts/time-warning.md b/extras/programbench/prompts/time-warning.mdnew file mode 100644index 0000000..58162e2--- /dev/null+++ b/extras/programbench/prompts/time-warning.md@@ -0,0 +1,7 @@+<IMPORTANT>+You are running low on time. You have approximately {{minutes}} minutes remaining before timeout.+Please wrap up your work now:+1. Ensure your solution compiles and produces an executable (it's ok if it is still missing functionality)+2. If there are any steps left to do, or limitations that you are aware of, please write them to a document "AGENT_REPORT.md". Focus on handing off to the next agent, i.e., focus on clearly describing the problems and any todo items that are left over.+3. Finish by ending your turn.+</IMPORTANT>diff --git a/extras/programbench/prompts/worker.md b/extras/programbench/prompts/worker.mdnew file mode 100644index 0000000..eab4aeb--- /dev/null+++ b/extras/programbench/prompts/worker.md@@ -0,0 +1,3 @@+{{lead}} leads the team: it hands out the work and keeps the list of open work in `TASKS.md` on the shared+branch. Take your work from {{lead}}, and tell {{lead}} when you finish it or are stuck. Write your own tests against+the reference executable, share them, and keep the shared branch building and passing them.diff --git a/extras/programbench/run.py b/extras/programbench/run.pynew file mode 100644index 0000000..a2e1bbe--- /dev/null+++ b/extras/programbench/run.py@@ -0,0 +1,795 @@+#!/usr/bin/env python3+"""Run coding agents on ProgramBench tasks, alone or as a team that talks over swarmchat.++ python3 run.py configs/flat.toml # every task in the config+ python3 run.py configs/flat.toml --dry-run # show the prompts and the team, start nothing+ python3 run.py configs/flat.toml --hours 0.2 --task sitkevij__hex.61ae69b --name flat-try++Each agent works in its own container from the task's cleanroom image, with no network, as in the official+baseline. Its model calls and its chat leave the container over Unix sockets that this script serves, so the API key+stays on the host. A team shares one git repository, and its submission is the repository's branch when the time+runs out. A single agent's submission is its /workspace. Both are written where `programbench eval` reads them:++ runs/<name>/submissions/<task>/submission.tar.gz+ runs/<name>/snapshots/<minutes>/<task>/submission.tar.gz every snapshot_minutes+ runs/<name>/work/<task>/ chat, logs and each agent's workspace++Needs Python 3.11 or later, Docker on a Linux x86_64 machine, and the agent's own Linux x86_64 command-line tool.+"""+from __future__ import annotations++import argparse+import http.client+import json+import os+import re+import shlex+import shutil+import signal+import socket+import socketserver+import subprocess+import sys+import tempfile+import threading+import time+import uuid+from concurrent.futures import ThreadPoolExecutor+from http.server import BaseHTTPRequestHandler+from pathlib import Path+from urllib.parse import urlsplit++try:+ import tomllib+except ImportError:+ sys.exit('run.py needs Python 3.11 or later, for tomllib.')++HERE = Path(__file__).resolve().parent+REPO = HERE.parents[1]+sys.path.insert(0, str(REPO))+from swarmchat.client import Client # noqa: E402 the swarmchat in this repository++PROMPTS = HERE/'prompts'+SHARED = '/shared/repo.git'+INCOMING = '/incoming/repo.git'+# The official mini-swe-agent settings for ProgramBench: container limits, command timeout and output length.+OFFICIAL_ENV = {'PAGER': 'cat', 'MANPAGER': 'cat', 'LESS': '-R', 'PIP_PROGRESS_BAR': 'off', 'TQDM_DISABLE': '1'}+COMMAND_SECONDS = 180+OUTPUT_CHARS = 10000+# The largest file and the most processes an agent's container may have. An agent's program that writes into what+# it reads can grow a file without end, and a script that starts itself can fill the process table.+FILE_CAP = 10*2**30+PIDS_CAP = 32768+AGENTS = {+ 'claude': {'api_base': 'https://api.anthropic.com', 'api_key_env': 'ANTHROPIC_API_KEY', 'api_auth': 'x-api-key',+ 'tools': ['Bash', 'Read', 'Edit', 'Write']},+ 'codex': {'api_base': 'https://api.openai.com', 'api_key_env': 'OPENAI_API_KEY', 'api_auth': 'bearer'},+ 'command': {'api_auth': 'bearer'},+}+BASE_PROMPTS = {'system': 'system.md', 'task': 'task.md', 'single': 'single.md', 'team': 'team.md', 'chat': 'chat.md',+ 'loop': 'loop.md', 'team_loop': 'team-loop.md', 'resume': 'resume.md',+ 'time_warning': 'time-warning.md'}+PLACEHOLDER = re.compile(r'\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}')++# Set by Ctrl-C or SIGTERM: every task stops its agents, saves its submission and ends.+interrupted = threading.Event()+++def log(task, text):+ print(f'[{time.strftime("%H:%M:%S")}] {task}: {text}', flush=True)+++# The config.++def load_config(path, args):+ path = Path(path).resolve()+ with open(path, 'rb') as f:+ c = tomllib.load(f)+ base = path.parent++ def need(table, key, kind, where):+ if key not in table:+ raise SystemExit(f'{path}: {where} needs `{key}`.')+ if not isinstance(table[key], kind):+ raise SystemExit(f'{path}: {where}.{key} has the wrong type.')+ return table[key]++ def text_file(name, where):+ file = (base/name).expanduser()+ if not file.is_file():+ raise SystemExit(f'{path}: {where} names {file}, which does not exist.')+ return file.read_text()++ config = {'path': path, 'name': args.name or need(c, 'name', str, 'the config'),+ 'tasks': args.task or need(c, 'tasks', list, 'the config'),+ 'hours': args.hours if args.hours is not None else float(c.get('hours', 6)),+ 'snapshot_minutes': float(c.get('snapshot_minutes', 0)), 'parallel': int(c.get('parallel', 1)),+ 'loop': bool(c.get('loop', True)), 'hide': c.get('hide', {})}+ agent = dict(need(c, 'agent', dict, 'the config'))+ kind = need(agent, 'kind', str, '[agent]')+ if kind not in AGENTS:+ raise SystemExit(f'{path}: [agent] kind is one of {", ".join(AGENTS)}.')+ agent = {**AGENTS[kind], **agent}+ agent['binary'] = (base/Path(need(agent, 'binary', str, '[agent]')).expanduser()).resolve()+ # Helper files the tool needs beside it. Codex runs its tools through codex-code-mode-host, from its own folder.+ helper = agent['binary'].parent/'codex-code-mode-host'+ default = [str(helper)] if kind == 'codex' and helper.exists() else []+ agent['files'] = [(base/Path(f).expanduser()).resolve() for f in agent.get('files', default)]+ if kind == 'command':+ need(agent, 'command', list, '[agent]')+ agent.setdefault('model', '')+ if agent['api_auth'] not in ('x-api-key', 'bearer'):+ raise SystemExit(f'{path}: [agent] api_auth is x-api-key or bearer.')+ config['agent'] = agent+ docker = c.get('docker', {})+ config['docker'] = {'command': docker.get('command', 'docker'),+ 'image_tag': docker.get('image_tag', 'task_cleanroom_v6'),+ 'cpus': str(docker.get('cpus', 20)), 'memory': str(docker.get('memory', '60g'))}+ prompts = {**{k: str(PROMPTS/v) for k, v in BASE_PROMPTS.items()}, **c.get('prompts', {})}+ config['prompts'] = {k: text_file(v, f'[prompts] {k}') for k, v in prompts.items()}++ team = c.get('team')+ if team is None:+ config['team'] = None+ return config+ members = need(team, 'members', int, '[team]')+ roles = need(team, 'roles', list, '[team]')+ for i, role in enumerate(roles):+ need(role, 'name', str, f'[[team.roles]] {i+1}')+ role['prompt_text'] = text_file(need(role, 'prompt', str, f'[[team.roles]] {role["name"]}'),+ f'[[team.roles]] {role["name"]} prompt')+ role['loop_text'] = text_file(role['loop'], f'[[team.roles]] {role["name"]} loop') if 'loop' in role else None+ role.setdefault('push', True)+ config['team'] = {'members': members, 'roles': roles, 'chat': bool(team.get('chat', True)),+ 'channels': team.get('channels', {'general': 'all'}), 'phase': None}+ if 'phase' in team:+ phase = team['phase']+ config['team']['phase'] = {'minutes': float(need(phase, 'minutes', (int, float), '[team.phase]')),+ 'loop': text_file(need(phase, 'loop', str, '[team.phase]'), '[team.phase] loop'),+ 'notice': text_file(need(phase, 'notice', str, '[team.phase]'),+ '[team.phase] notice')}+ config['agents'] = assign(config['team'], path)+ return config+++def assign(team, path):+ """Each agent's id and role. A role takes `count` agents, or `share` of the team, and the roles with neither split+ the rest evenly. Agents are numbered a1, a2, ... in the order of the roles."""+ members, roles = team['members'], team['roles']+ sizes = [r['count'] if 'count' in r else max(1, round(r['share']*members)) if 'share' in r else None for r in roles]+ rest = members-sum(s for s in sizes if s is not None)+ open_roles = [i for i, s in enumerate(sizes) if s is None]+ for k, i in enumerate(open_roles):+ sizes[i] = rest//len(open_roles)+(k < rest % len(open_roles))+ if sum(sizes) != members or min(sizes) < 1:+ raise SystemExit(f'{path}: the roles do not divide {members} members so each has at least one: '+ + ', '.join(f'{r["name"]} {s}' for r, s in zip(roles, sizes)))+ agents, n = [], 0+ for role, size in zip(roles, sizes):+ for _ in range(size):+ n += 1+ agents.append({'id': f'a{n}', 'role': role})+ return agents+++def render(template, values, where):+ def fill(match):+ if match.group(1) not in values:+ raise SystemExit(f'{where}: unknown placeholder {{{{{match.group(1)}}}}}. '+ f'Known here: {", ".join(sorted(values))}.')+ return str(values[match.group(1)])+ return PLACEHOLDER.sub(fill, template)+++def tidy(text):+ return re.sub(r'\n{3,}', '\n\n', text).strip()+'\n'+++def names(ids):+ return ', '.join(ids[:-1])+' and '+ids[-1] if len(ids) > 1 else ids[0]+++def prompts_for(config, agent=None, branch=None):+ """An agent's task prompt and loop message. With no agent, a single agent's."""+ p, team = config['prompts'], config['team']+ if team is None:+ prompt = render(p['task'], {'submission': p['single']}, 'task prompt')+ return tidy(prompt), p['loop'].strip() if config['loop'] else ''+ ids = [a['id'] for a in config['agents']]+ values = {'id': agent['id'], 'n': len(ids), 'others': ', '.join(i for i in ids if i != agent['id']),+ 'team': names(ids), 'role': agent['role']['name'], 'shared': SHARED, 'branch': branch or '<branch>',+ 'incoming': INCOMING}+ for role in team['roles']:+ values[role['name']] = names([a['id'] for a in config['agents'] if a['role'] is role])+ if team['phase']:+ values['phase_minutes'] = f'{team["phase"]["minutes"]:g}'+ where = f'role {agent["role"]["name"]}'+ role_prompt = render(agent['role']['prompt_text'], values, where+' prompt')+ chat = render(p['chat'], values, 'chat prompt') if team['chat'] else ''+ section = render(p['team'], {**values, 'chat': chat.strip(), 'role_prompt': role_prompt.strip()}, 'team prompt')+ prompt = render(p['task'], {'submission': tidy(section)}, 'task prompt')+ loop = render(agent['role']['loop_text'] or p['team_loop'], values, where+' loop') if config['loop'] else ''+ return tidy(prompt), loop.strip()+++def channels_for(config):+ team, ids = config['team'], [a['id'] for a in config['agents']]+ out = {}+ for name, members in team['channels'].items():+ if members == 'all':+ out[name] = ids+ continue+ unknown = set(members)-{r['name'] for r in team['roles']}+ if unknown:+ raise SystemExit(f'{config["path"]}: channel {name} names unknown roles {", ".join(sorted(unknown))}.')+ out[name] = [a['id'] for a in config['agents'] if a['role']['name'] in members]+ return out+++# Docker.++class Docker:+ def __init__(self, command):+ self.base = shlex.split(command)++ def __call__(self, *args, check=True, timeout=900):+ result = subprocess.run([*self.base, *map(str, args)], capture_output=True, text=True, timeout=timeout)+ if check and result.returncode:+ raise RuntimeError(f'docker {args[0]} failed: {result.stderr.strip() or result.stdout.strip()}')+ return result+++def image_name(instance, tag):+ return f'programbench/{instance.replace("__", "_1776_")}:{tag}'+++# The host side of the relays.++class UnixServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):+ daemon_threads = True++ def __init__(self, path, handler):+ super().__init__(str(path), handler)+ os.chmod(path, 0o666)+++# Headers the container sends that do not go on: its placeholder key, and those that describe its own connection.+DROP = {'host', 'content-length', 'connection', 'keep-alive', 'transfer-encoding', 'authorization', 'x-api-key',+ 'cookie', 'accept-encoding', 'proxy-connection', 'upgrade'}+HOP = {'connection', 'keep-alive', 'transfer-encoding', 'content-length'}+++class ModelHandler(BaseHTTPRequestHandler):+ """One model request from an agent's container, sent on to the real API with the real key. The answer streams+ back as it arrives, and the connection closes after it."""+ protocol_version = 'HTTP/1.1'++ def address_string(self):+ return 'agent'++ def log_message(self, *args):+ pass++ def body(self):+ if 'chunked' in self.headers.get('Transfer-Encoding', '').lower():+ data = b''+ while True:+ size = int(self.rfile.readline().split(b';')[0], 16)+ if size == 0:+ self.rfile.readline()+ return data+ data += self.rfile.read(size)+ self.rfile.readline()+ return self.rfile.read(int(self.headers.get('Content-Length') or 0))++ def relay(self):+ server, started = self.server, time.time()+ self.close_connection = True+ if self.headers.get('Upgrade'):+ self.send_error(426, 'Use HTTP') # Codex falls back from WebSockets to HTTP+ return+ body = self.body()+ url = urlsplit(server.api_base)+ headers = {k: v for k, v in self.headers.items() if k.lower() not in DROP}+ if server.api_key and server.api_auth == 'x-api-key':+ headers['x-api-key'] = server.api_key+ elif server.api_key:+ headers['Authorization'] = 'Bearer '+server.api_key+ connection = (http.client.HTTPSConnection if url.scheme == 'https' else http.client.HTTPConnection)(+ url.hostname, url.port, timeout=3600)+ status, sent = None, 0+ try:+ connection.request(self.command, url.path.rstrip('/')+self.path, body=body, headers=headers)+ response = connection.getresponse()+ status = response.status+ self.send_response_only(response.status, response.reason)+ for k, v in response.getheaders():+ if k.lower() not in HOP:+ self.send_header(k, v)+ length = response.getheader('Content-Length')+ if length and 'chunked' not in (response.getheader('Transfer-Encoding') or '').lower():+ self.send_header('Content-Length', length)+ self.send_header('Connection', 'close')+ self.end_headers()+ while True:+ data = response.read1(65536)+ if not data:+ break+ self.wfile.write(data)+ self.wfile.flush()+ sent += len(data)+ except (OSError, http.client.HTTPException) as exc:+ if status is None:+ self.send_error(502, f'model API unreachable: {exc}')+ finally:+ connection.close()+ server.record({'at': started, 'method': self.command, 'path': self.path, 'status': status,+ 'seconds': round(time.time()-started, 3), 'bytes': sent})++ do_GET = do_POST = do_PUT = do_DELETE = relay+++class ModelRelay(UnixServer):+ def __init__(self, path, agent, key, log_file):+ self.api_base, self.api_auth, self.api_key = agent['api_base'], agent['api_auth'], key+ self.log_file, self.lock, self.requests, self.failed = open(log_file, 'a', buffering=1), threading.Lock(), 0, 0+ super().__init__(path, ModelHandler)++ def record(self, entry):+ with self.lock:+ self.requests += 1+ self.failed += entry['status'] is None or entry['status'] >= 400+ self.log_file.write(json.dumps(entry)+'\n')+++class ChatHandler(socketserver.BaseRequestHandler):+ def handle(self):+ upstream = socket.create_connection(self.server.chat_address)++ def pipe(source, target):+ try:+ while data := source.recv(65536):+ target.sendall(data)+ except OSError:+ pass+ finally:+ for s in (source, target):+ try:+ s.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass++ other = threading.Thread(target=pipe, args=(upstream, self.request), daemon=True)+ other.start()+ pipe(self.request, upstream)+ other.join()+ upstream.close()+++class ChatRelay(UnixServer):+ def __init__(self, path, chat_address):+ self.chat_address = chat_address+ super().__init__(path, ChatHandler)+++def start_chat(work, ids, channels):+ """The team's swarmchat server, one user per agent and the channels. Returns the server process, its URL and+ each agent's token."""+ data = work/'chat'+ with socket.socket() as s:+ s.bind(('127.0.0.1', 0))+ port = s.getsockname()[1]+ env = {**os.environ, 'PYTHONPATH': str(REPO)+os.pathsep+os.environ.get('PYTHONPATH', '')}+ process = subprocess.Popen([sys.executable, '-m', 'swarmchat', 'serve', '--data', str(data), '--port', str(port)],+ stdout=open(work/'chat-server.log', 'a'), stderr=subprocess.STDOUT, env=env)+ for _ in range(200):+ if (data/'admin.token').exists() and (data/'address').exists():+ break+ if process.poll() is not None:+ raise RuntimeError(f'swarmchat exited at start, see {work/"chat-server.log"}')+ time.sleep(.1)+ url = (data/'address').read_text().strip()+ admin = Client(url, (data/'admin.token').read_text().strip())+ tokens = {i: admin.user_add(id=i, name=i)['token'] for i in ids}+ for name, members in channels.items():+ Client(url, tokens[members[0]]).channel_create(name=name, members=','.join(members))+ return process, url, tokens+++def notify(client, notices, stop):+ """Each new chat message for the agent becomes a file in its notices folder, which the guest hands to the agent.+ Peeking marks nothing read, so `swarmchat read` still shows it."""+ after = {}+ while not stop.is_set():+ try:+ reply = client.call('wait', {'timeout': 20, 'after': after, 'peek': True}, http_timeout=60)+ except Exception:+ stop.wait(5)+ continue+ after.update(reply.get('positions') or {})+ for m in reply.get('messages', []):+ title = (reply.get('chats') or {}).get(m['chat'], {}).get('title') or m['chat']+ text = m.get('text') or ''+ if len(text) > 2000:+ text = text[:2000]+' [cut here: `swarmchat read` shows all of it]'+ files = f' [{len(m["attachments"])} attachment(s)]' if m.get('attachments') else ''+ name = f'{time.time_ns()}-{m["id"].replace(":", "-")}.json'+ temp = notices/(name+'.tmp')+ temp.write_text(json.dumps({'text': f'[swarmchat] {title}, from {m["from"]} ({m["id"]}):\n{text}{files}'}))+ os.chmod(temp, 0o666)+ temp.replace(notices/name)+++# Submissions.++def git(*args, timeout=600):+ return subprocess.run(['git', '-c', 'safe.directory=*', *args], capture_output=True, text=True, check=True,+ timeout=timeout)+++def export_branch(repo, branch, destination):+ """A team's submission: a fresh checkout of its branch, packed like the official copy of /workspace."""+ destination.parent.mkdir(parents=True, exist_ok=True)+ checkout = Path(tempfile.mkdtemp(prefix='pb-export-'))+ try:+ git('clone', '-q', '--branch', branch, str(repo), str(checkout/'w'))+ temp = destination.with_name(destination.name+'.tmp')+ subprocess.run(['tar', '-czf', str(temp), '-C', str(checkout/'w'), '.'], check=True, timeout=600)+ temp.replace(destination)+ finally:+ shutil.rmtree(checkout, ignore_errors=True)+++def copy_workspace(docker, container, destination):+ """The official submission of a single agent: a gzipped tar of its /workspace, made in the container."""+ destination.parent.mkdir(parents=True, exist_ok=True)+ docker('exec', container, 'tar', '-czf', '/tmp/_submission.tar.gz', '-C', '/workspace', '.', check=False)+ temp = destination.with_name(destination.name+'.tmp')+ docker('cp', f'{container}:/tmp/_submission.tar.gz', temp)+ temp.replace(destination)+++# One task.++def writable(path):+ path.mkdir(parents=True, exist_ok=True)+ os.chmod(path, 0o777) # the container's own user, whose id may differ from yours, writes here+ return path+++def readable(path, text):+ path.write_text(text)+ os.chmod(path, 0o644)+++def codex_config(agent):+ effort = f'model_reasoning_effort = "{agent["effort"]}"\n' if agent.get('effort') else ''+ return f'''model = "{agent['model']}"+{effort}model_provider = "relay"+approval_policy = "never"+sandbox_mode = "danger-full-access"+web_search = "disabled"++[model_providers.relay]+name = "relay"+base_url = "http://127.0.0.1:8765/v1"+env_key = "RELAY_API_KEY"+wire_api = "responses"++[shell_environment_policy]+inherit = "all"++[analytics]+enabled = false++# As in the blog post's runs.+[features]+multi_agent = false+multi_agent_v2 = false+apps = false+plugins = false+skill_search = false+browser_use = false+computer_use = false+enable_request_compression = false+shell_snapshot = false+'''+++CLAUDE_HOOKS = {'PostToolUse': [{'matcher': '*', 'hooks': [+ {'type': 'command', 'command': 'python3 /guest/guest.py warn', 'timeout': 30}]}],+ 'Stop': [{'hooks': [{'type': 'command', 'command': 'python3 /guest/guest.py loop', 'timeout': 30}]}]}+++def run_task(config, instance, out, docker):+ work = out/'work'/instance+ final = out/'submissions'/instance/'submission.tar.gz'+ if (work/'result.json').exists():+ log(instance, 'already done, skipped')+ return+ if work.exists():+ raise RuntimeError(f'{work} is from a run that did not finish. Delete it to run this task again.')+ team, agent_cfg = config['team'], config['agent']+ key = os.environ.get(agent_cfg['api_key_env'], '') if agent_cfg.get('api_key_env') else ''+ image = image_name(instance, config['docker']['image_tag'])+ if docker('image', 'inspect', image, check=False).returncode:+ log(instance, f'pulling {image}')+ docker('pull', image, timeout=3600)+ work.mkdir(parents=True)+ sockets = Path(tempfile.mkdtemp(prefix='pb-')) # short paths: a Unix socket path has at most 107 bytes+ os.chmod(sockets, 0o755)+ stop, agents, servers, containers, chat_process = threading.Event(), [], [], [], None+ started, status = time.time(), 'Interrupted'+ try:+ # The reference executable, copied out of the image and mounted read-only at /reference/executable.+ (work/'reference').mkdir()+ holder = docker('create', image).stdout.strip()+ try:+ docker('cp', f'{holder}:/workspace/executable', work/'reference'/'executable')+ finally:+ docker('rm', '-f', holder, check=False)+ mounts = ['-v', f'{work/"reference"}:/reference:ro']+ hidden = config['hide'].get(instance, [])+ if hidden:+ # Files in the image that would hand the agent the original program read as empty.+ empty = work/'hidden'+ empty.write_bytes(b'')+ empty.chmod(0o444)+ mounts += [arg for p in hidden for arg in ('-v', f'{empty}:{p}:ro')]+ ids = [a['id'] for a in config['agents']] if team else ['a1']+ tokens, branch, incoming = {}, None, False+ if team:+ # The shared repository starts as a bare clone of the image's /workspace repository.+ writable(work/'shared')+ docker('run', '--rm', '--network', 'none', '--user', 'agent', '-v', f'{work/"shared"}:/shared', image,+ 'git', 'clone', '-q', '--bare', '/workspace', SHARED)+ branch = git('-C', str(work/'shared'/'repo.git'), 'symbolic-ref', '--short', 'HEAD').stdout.strip()+ incoming = not all(a['role']['push'] for a in config['agents'])+ if incoming:+ # Agents that may not push to the shared branch push their branches here.+ writable(work/'incoming')+ docker('run', '--rm', '--network', 'none', '--user', 'agent', '-v',+ f'{work/"incoming"}:/incoming', image, 'git', 'clone', '-q', '--bare', '/workspace', INCOMING)+ if team['chat']:+ chat_process, chat_url, tokens = start_chat(work, ids, channels_for(config))+ (work/'chat-tokens.json').write_text(json.dumps(tokens))+ os.chmod(work/'chat-tokens.json', 0o600)+ bin_dir = work/'swarmchat-bin'+ bin_dir.mkdir()+ (bin_dir/'swarmchat').write_text(+ '#!/bin/sh\nPYTHONPATH=/opt/swarmchat/lib exec python3 -m swarmchat "$@"\n')+ os.chmod(bin_dir/'swarmchat', 0o755)+ mounts += ['-v', f'{REPO/"swarmchat"}:/opt/swarmchat/lib/swarmchat:ro',+ '-v', f'{bin_dir}:/opt/swarmchat/bin:ro']+ log(instance, f'watch the chat: PYTHONPATH={REPO} {sys.executable} -m swarmchat view '+ f'--data {work/"chat"}')+ started = time.time()+ deadline = started+config['hours']*3600+ phase = team['phase'] if team else None+ binary = f'/opt/agent/{agent_cfg["binary"].name}'+ for aid in ids:+ agent = next(a for a in config['agents'] if a['id'] == aid) if team else None+ folder = work/'agents'/aid+ guest, home, notices = folder/'guest', writable(folder/'home'), writable(folder/'notices')+ guest.mkdir()+ os.chmod(guest, 0o755)+ prompt, loop = prompts_for(config, agent, branch)+ readable(guest/'prompt.txt', prompt)+ readable(guest/'system.txt', config['prompts']['system'])+ readable(guest/'guest.py', (HERE/'guest.py').read_text())+ readable(guest/'config.json', json.dumps({+ 'id': aid, 'kind': agent_cfg['kind'], 'binary': binary, 'command': agent_cfg.get('command'),+ 'model': agent_cfg['model'], 'effort': agent_cfg.get('effort'), 'tools': agent_cfg.get('tools'),+ 'system': config['prompts']['system'], 'loop': loop, 'resume': config['prompts']['resume'].strip(),+ 'time_warning': config['prompts']['time_warning'].strip(), 'deadline': deadline,+ 'phase': phase and {'until': started+phase['minutes']*60, 'loop': phase['loop'].strip(),+ 'notice': phase['notice'].strip()},+ 'shared': SHARED if team else None, 'branch': branch, 'incoming': INCOMING if incoming else None,+ 'chat_token': tokens.get(aid), 'env': OFFICIAL_ENV, 'command_seconds': COMMAND_SECONDS,+ 'output_chars': OUTPUT_CHARS, 'session': str(uuid.uuid4())}, indent=1))+ if agent_cfg['kind'] == 'claude':+ readable(writable(home/'config')/'settings.json', json.dumps({'hooks': CLAUDE_HOOKS}))+ elif agent_cfg['kind'] == 'codex':+ readable(home/'config.toml', codex_config(agent_cfg))+ socket_dir = sockets/aid+ socket_dir.mkdir()+ os.chmod(socket_dir, 0o755)+ relay = None+ if agent_cfg.get('api_base'):+ relay = ModelRelay(socket_dir/'model.sock', agent_cfg, key, folder/'model-requests.jsonl')+ servers.append(relay)+ if tokens:+ address = urlsplit(chat_url)+ servers.append(ChatRelay(socket_dir/'chat.sock', (address.hostname, address.port)))+ threading.Thread(target=notify, args=(Client(chat_url, tokens[aid]), notices, stop),+ daemon=True).start()+ agent_mounts = ['-v', f'{agent_cfg["binary"]}:{binary}:ro', '-v', f'{guest}:/guest:ro',+ *[a for f in agent_cfg['files'] for a in ('-v', f'{f}:/opt/agent/{f.name}:ro')],+ '-v', f'{socket_dir}:/sockets', '-v', f'{home}:/agent-home', '-v', f'{notices}:/notices']+ if team:+ # An agent that may not push to the shared branch can still fetch it.+ agent_mounts += ['-v', f'{work/"shared"}:/shared'+('' if agent['role']['push'] else ':ro')]+ if incoming:+ agent_mounts += ['-v', f'{work/"incoming"}:/incoming']+ name = re.sub(r'[^a-zA-Z0-9_.-]+', '-', f'pb-{config["name"]}-{instance}-{aid}')+ agents.append({'id': aid, 'folder': folder, 'guest': guest, 'home': home, 'relay': relay,+ 'container': name, 'mounts': agent_mounts})+ for server in servers:+ threading.Thread(target=server.serve_forever, daemon=True).start()+ for a in agents:+ docker('run', '-d', '--name', a['container'], '--network', 'none', '--user', 'agent',+ '--cap-drop', 'SYS_PTRACE', '--cpus', config['docker']['cpus'],+ '--memory', config['docker']['memory'], '--memory-swap', config['docker']['memory'],+ '--ulimit', f'fsize={FILE_CAP}:{FILE_CAP}', '--pids-limit', PIDS_CAP, '-w', '/workspace',+ *[f'--env={k}={v}' for k, v in OFFICIAL_ENV.items()], *mounts, *a['mounts'],+ image, 'python3', '/guest/guest.py')+ containers.append(a['container'])+ log(instance, f'{len(agents)} agent(s) started for {config["hours"]:g} hour(s)')++ def submit(destination):+ if team:+ export_branch(work/'shared'/'repo.git', branch, destination)+ else:+ copy_workspace(docker, agents[0]['container'], destination)++ snapshots, checked, lost = 0, time.time(), set()+ status = 'TimeLimit'+ while time.time() < deadline:+ if interrupted.is_set():+ status = 'Interrupted'+ break+ if all((a['home']/'exit.json').exists() for a in agents):+ status = 'Finished'+ for a in agents:+ error = json.loads((a['home']/'exit.json').read_text()).get('error')+ if error:+ status = 'AgentsFailed'+ log(instance, f'{a["id"]} failed: {error}. See {a["folder"]/"container.log"}')+ break+ if time.time()-checked > 60:+ checked = time.time()+ for a in agents:+ running = docker('inspect', '-f', '{{.State.Running}}', a['container'], check=False).stdout.strip()+ if running != 'true' and a['id'] not in lost:+ lost.add(a['id'])+ log(instance, f'{a["id"]}\'s container stopped early, see `docker logs {a["container"]}`')+ if len(lost) == len(agents):+ status = 'ContainersStopped'+ break+ minutes = config['snapshot_minutes']+ if minutes and time.time()-started >= (snapshots+1)*minutes*60:+ snapshots += 1+ try:+ submit(out/'snapshots'/f'{round(snapshots*minutes):05d}'/instance/'submission.tar.gz')+ except (subprocess.SubprocessError, RuntimeError) as exc:+ log(instance, f'snapshot failed: {exc}')+ time.sleep(5)+ # Stop the agents, and give them two minutes to end their turns.+ for a in agents:+ readable(a['guest']/'stop', '')+ wait_until = time.time()+120+ while time.time() < wait_until and not all((a['home']/'exit.json').exists() for a in agents):+ time.sleep(1)+ submit(final)+ log(instance, f'{status}: submission saved')+ finally:+ stop.set()+ if team:+ for a in agents:+ if a['container'] in containers:+ try:+ copy_workspace(docker, a['container'], a['folder']/'workspace.tar.gz')+ except (subprocess.SubprocessError, RuntimeError) as exc:+ log(instance, f'{a["id"]}: workspace not copied: {exc}')+ for a in agents:+ if a['container'] in containers:+ logs = docker('logs', a['container'], check=False)+ (a['folder']/'container.log').write_text(logs.stdout+logs.stderr)+ docker('rm', '-f', a['container'], check=False)+ for server in servers:+ server.shutdown()+ server.server_close()+ if chat_process:+ chat_process.terminate()+ chat_process.wait()+ shutil.rmtree(sockets, ignore_errors=True)+ # Files the container's user wrote, made deletable by you.+ docker('run', '--rm', '--network', 'none', '--user', 'agent', '-v', f'{work}:/work', image, 'sh', '-c',+ 'chmod -R a+rwX /work 2>/dev/null; true', check=False)+ # A task with a submission is done, and a later run of the same config skips it.+ if final.exists():+ (work/'result.json').write_text(json.dumps({+ 'task': instance, 'status': status, 'started': started, 'seconds': round(time.time()-started),+ 'agents': {a['id']: {'model_requests': a['relay'] and a['relay'].requests,+ 'failed_model_requests': a['relay'] and a['relay'].failed} for a in agents}},+ indent=1))+++# Checks before anything starts.++def preflight(config, docker):+ agent = config['agent']+ for file in [agent['binary'], *agent['files']]:+ if not file.exists():+ raise SystemExit(f'{file} does not exist. The agent\'s files must be Linux x86_64 builds.')+ if agent['kind'] == 'codex' and not agent['files']:+ print('Note: no codex-code-mode-host beside the codex binary. Codex 0.159 and later need it to run tools.')+ if agent.get('api_key_env') and not os.environ.get(agent['api_key_env']):+ raise SystemExit(f'Set {agent["api_key_env"]} to your API key. It stays on this machine.')+ if shutil.which(docker.base[0]) is None:+ raise SystemExit(f'{docker.base[0]} is not installed.')+ info = docker('info', '--format', '{{.Architecture}}', check=False)+ if info.returncode:+ raise SystemExit(f'docker does not answer: {info.stderr.strip()}')+ if info.stdout.strip() not in ('x86_64', 'amd64'):+ raise SystemExit(f'Docker runs on {info.stdout.strip()}. The ProgramBench images are for Linux x86_64 only.')+++def dry_run(config):+ team = config['team']+ if team is None:+ prompt, loop = prompts_for(config)+ print(f'One agent, {config["hours"]:g} hour(s).\n\n=== prompt\n{prompt}\n=== loop message\n{loop or "(none)"}\n')+ return+ print(f'A team of {team["members"]}, {config["hours"]:g} hour(s), chat {"on" if team["chat"] else "off"}.')+ for a in config['agents']:+ print(f' {a["id"]}: {a["role"]["name"]}{"" if a["role"]["push"] else " (cannot push to the shared branch)"}')+ if team['chat']:+ for name, members in channels_for(config).items():+ print(f' #{name}: {", ".join(members)}')+ for role in team['roles']:+ agent = next(a for a in config['agents'] if a['role'] is role)+ prompt, loop = prompts_for(config, agent)+ print(f'\n=== prompt of {agent["id"]} ({role["name"]})\n{prompt}\n=== loop message\n{loop or "(none)"}')+ if team['phase']:+ print(f'\n=== for the first {team["phase"]["minutes"]:g} minutes the loop message is\n'+ f'{team["phase"]["loop"].strip()}\n=== and then every agent is told\n{team["phase"]["notice"].strip()}')+++def main():+ parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])+ parser.add_argument('config', help='a TOML file, such as configs/flat.toml')+ parser.add_argument('--task', action='append', help='run only this task (repeat for more)')+ parser.add_argument('--hours', type=float, help='agent time per task, in place of the config\'s')+ parser.add_argument('--name', help='the run\'s name, in place of the config\'s')+ parser.add_argument('--out', default=str(HERE/'runs'), help='where runs go (default: runs/ next to run.py)')+ parser.add_argument('--dry-run', action='store_true', help='show the team and its prompts, and start nothing')+ args = parser.parse_args()+ config = load_config(args.config, args)+ if args.dry_run:+ dry_run(config)+ return+ docker = Docker(config['docker']['command'])+ preflight(config, docker)+ out = Path(args.out).expanduser().resolve()/config['name']+ out.mkdir(parents=True, exist_ok=True)+ shutil.copy(config['path'], out/'config.toml')+ signal.signal(signal.SIGTERM, lambda *_: interrupted.set())+ failures = []++ def one(instance):+ try:+ run_task(config, instance, out, docker)+ except Exception as exc:+ failures.append(instance)+ log(instance, f'failed: {exc}')++ with ThreadPoolExecutor(max_workers=config['parallel']) as pool:+ futures = [pool.submit(one, t) for t in config['tasks']]+ try:+ while not all(f.done() for f in futures):+ time.sleep(1)+ except KeyboardInterrupt:+ print('Stopping: saving submissions and removing containers. This takes a minute or two.', flush=True)+ interrupted.set()+ for f in futures:+ f.cancel()+ print(f'\nSubmissions: {out/"submissions"}\nScore them: programbench eval {out/"submissions"}')+ if config['snapshot_minutes']:+ print(f'Snapshots: {out/"snapshots"}, each folder scored the same way.')+ if failures:+ sys.exit(f'{len(failures)} task(s) failed: {", ".join(failures)}')+++if __name__ == '__main__':+ main()