GitHub · PyPI · Examples · Docs

An rlmflow run drawn as a graph: a root agent launches agents that launch their own, results flow back up, and a fork of the run gets a message and takes a different path

pip install "rlmflow[openai]"

tldr

rlmflow is a Python library for recursive and multi-agent systems: agents that launch, message and coordinate other agents. It starts from the Recursive Language Model interface (a model in a REPL that launches sub-agents from code), records every agent, turn, message and result in a graph, and runs from that graph.

Four examples: a recursive document search, rounds of training experiments, peers building an app on a shared task list, and a failed game rewound and retried eight ways.

Introduction

Models degrade well before their advertised context limit, a failure mode called context rot. Fixes like retrieval, summarization and context folding shorten the input by a fixed rule, and Sutton’s Bitter Lesson argues that fixed rules lose over time to methods that let the model decide.

Recursive Language Models let the model decide. The long input sits as a variable in a Python REPL, and the model writes code to read it, search it, or hand a piece to a sub-agent: a fresh model call that sees only that piece. In the paper, GPT-5-mini working this way beats GPT-5 on a hard long-context benchmark at about the same cost.

Left: a standard model call reads the query and the whole document in one prompt. Right: a recursive language model keeps the document as a variable in a Python REPL; the root model writes code that splits it and launches one sub-agent per chunk, and each sub-agent's submitted value returns to the REPL
Left: the whole document in one prompt. Right: the document stays in the REPL, and the root model's code hands each chunk to a sub-agent.

Once agents can launch agents from code, long-context reading is only the start. Prime Agent (Karten et al., 2026) is a coding and research agent built on the RLM interface, whose agents spawn children and message each other directly. Teams of agents take other shapes too: autoresearch runs rounds of parallel experiments, DeLM’s peers share a task queue, and Shepherd rewinds a failed agent and retries. Most tools log each agent’s chat separately, so you can’t see who launched whom, or rerun one step without redoing everything before it.

rlmflow records the team in a graph and runs it from there. Each agent is a chain of nodes, one per message or model turn, and edges connect agents wherever one launches another, returns a result, or sends a message. The four examples below build four of these team shapes.

Recursive agents as graphs

The first example is a needle-in-a-haystack search. The haystack is 6,600 lines of one filler sentence, 297,000 characters in all, with a decoy and the real line hidden near the end:

lines = ["The quick brown fox jumps over the lazy dog.\n"] * 6_600
lines[5_200] = "Some say the magic number is hidden in the appendix.\n"   # the decoy
lines[5_900] = "The magic number is 84721.\n"                             # the real line
text = "".join(lines)

The root gets text as a variable, haystack, and never reads it whole. Its first turn launches a worker per chunk, a child agent with an empty context and its chunk as a variable:

Model code · the root's first turn
chunks = [haystack[i : i + 100_000] for i in range(0, len(haystack), 100_000)]
workers = [
    launch_agent("Find the magic number in `chunk`.", config="worker", chunk=c)
    for c in chunks
]
results = await asyncio.gather(*workers)
print("results:", results)

Each worker searches its chunk. If it finds more than one candidate line, it launches a checker per line, one level down:

Model code · each worker's first turn
hits = [line for line in chunk.splitlines() if "magic number" in line]
if len(hits) > 1:
    checks = [
        launch_agent("Is `line` the real magic number line?", config="checker", line=h)
        for h in hits
    ]
    verdicts = await asyncio.gather(*checks)
    print("verdicts:", verdicts)
else:
    submit(hits[0].split()[-1] if hits else "")

Each agent ends with submit(value), which is what its parent’s await returns. Once the workers finish, the root’s next message is just what its code printed:

results: ['', '', '84721']

If you only keep each agent’s returned value, that line is all the root ever learns. Which worker found the number, the decoy, and the checker that rejected it are gone. rlmflow keeps the whole run as a graph:

The needle run's final graph: root launches three workers; two find nothing; worker-2 finds two candidate lines and launches two checkers; one rejects the decoy, the other returns 84721, which flows back up to the root

Each column is an agent, and each shape is a node: the agent’s task, its model turns, and the turn that called submit. Solid edges launch agents, and dashed edges return results.

The runtime works from this graph alone: it runs whichever agents have work, and a waiting agent gets work back when a child returns.

1 / 7 · The run starts as one node

The run starts as one node
User code
flow = Flow(configs=[
    AgentConfig(model="gpt-5", max_depth=2),
    AgentConfig(name="worker", model="gpt-5-mini", max_depth=2),
    AgentConfig(name="checker", model="gpt-5-mini", max_depth=0),
])
g = Graph()
g.start("Find the magic number in `haystack`.", haystack=text)
flow.run(g)

The task becomes the root agent: one node holding the question, with the 297,000-character haystack as a variable in its REPL.

2 / 7 · The root answers with code

The root answers with code
root's turn
chunks = [haystack[i : i + 100_000] for i in range(0, len(haystack), 100_000)]
workers = [
    launch_agent("Find the magic number in `chunk`.", config="worker", chunk=c)
    for c in chunks
]
results = await asyncio.gather(*workers)
print("results:", results)

The root cuts the haystack into three chunks and launches a worker on each. Each launch adds a spawn edge to a new agent.

3 / 7 · Two workers come back empty

Two workers come back empty
each worker's turn
hits = [line for line in chunk.splitlines() if "magic number" in line]
if len(hits) > 1:
    checks = [
        launch_agent("Is `line` the real magic number line?", config="checker", line=h)
        for h in hits
    ]
    verdicts = await asyncio.gather(*checks)
    print("verdicts:", verdicts)
else:
    submit(hits[0].split()[-1] if hits else "")

Workers 0 and 1 find no candidate lines and submit an empty string. The dashed return edges point back at the root turn that is waiting on them.

4 / 7 · The third worker recurses

The third worker recurses
worker-2, same code, the if branch
hits = [line for line in chunk.splitlines() if "magic number" in line]
if len(hits) > 1:
    checks = [
        launch_agent("Is `line` the real magic number line?", config="checker", line=h)
        for h in hits
    ]
    verdicts = await asyncio.gather(*checks)
    print("verdicts:", verdicts)
else:
    submit(hits[0].split()[-1] if hits else "")

Worker 2's chunk has two lines that mention a magic number, one of them the decoy, so it takes the if branch and does what the root did, one level down: a checker per line.

5 / 7 · The checkers decide

The checkers decide
each checker's turn
import re
m = re.fullmatch(r"The magic number is (\d+)\.", line.strip())
submit(m.group(1) if m else "")

Checker 0 gets the decoy line and returns an empty string. Checker 1 returns 84721.

6 / 7 · The answer comes back up

The answer comes back up
worker-2's next turn
verdicts: ['', '84721']
submit(next(v for v in verdicts if v))

The verdicts arrive as the worker's next message, and it submits the real answer.

7 / 7 · The root submits

The root submits
root's next turn
results: ['', '', '84721']
submit(next(r for r in results if r))

The root submits 84721, and every step, decoy included, is saved in the graph.

When the run ends, the graph is plain Python data you can walk, down to the checker that rejected the decoy:


root.final_result()          # '84721'
worker2 = root.children()[2]        # children(): the agents it launched
decoy, real = worker2.children()

decoy.input["line"]          # 'Some say the magic number is hidden in the appendix.'
decoy.final_result()         # '' : it rejected the line
decoy.nodes()[-1].code       # nodes(): its own turns; this is the code that rejected the line

g.save("runs/needle")        # Graph.load("runs/needle") reads the whole run back

Same interface, any harness

Every agent so far has been a model writing Python, but nothing in the graph depends on that. Each agent gets the same interface: a REPL holding its inputs as variables, with launch_agent to start an agent, submit to return a result, and agent.send to message another agent. What produces the agent’s turns is its harness, set per config:

flow = Flow(configs=[
    AgentConfig(model="gpt-5"),                           # the root: rlmflow's REPL loop
    AgentConfig(name="searcher", harness="claude_code"),  # each searcher: a Claude Code session
])

A claude_code agent is a Claude Code session with the same REPL tools, and each of its replies becomes a turn node. So one run can mix harnesses: your own REPL agent as the root with Claude Code sessions as its workers, or the other way around. On the repo’s needle example, searching 100 files for the magic-number line, every combination finds it, and the graphs have the same shape:

Needle with a REPL root and REPL searchers
REPL root, REPL searchers.
Needle with a Claude Code root and Claude Code searchers
Claude Code root, Claude Code searchers.

The root can also be the Claude Code session you’re typing in. rlmflow’s plugin adds a /rlmflow:run command:

$ claude --plugin-dir "$(rlmflow plugin path)"
> /rlmflow:run There are 100 text files in haystack/. Exactly one line in one file matches
  `The magic number is <number>`. Find the number and the file it's in. Use rlmflow agents
  to search the files in parallel.
The plugin run: the root launches four searchers, goes idle three times as their results come back, and submits
Your session as the root. Gold stars mark the turns where it stopped to wait for a searcher's result.

pi works the same way (harness="pi"), or you can bring your own harness.

Fan out, then consolidate: autoresearch

The needle root fanned out once. Research fans out in rounds: try a batch of ideas in parallel, read the scores, and build the next batch on the best result.

Karpathy’s autoresearch gives one coding agent a small training setup: it edits the training script, trains, and keeps what helps. This example runs that loop with a team of Claude Code sessions, trying to lower a small GPT’s validation bits per byte (val bpb, lower is better). The planner decides what to try. Each implementer gets one idea and its own copy of the code, edits it, and calls submit_trial, which trains the copy and returns its score. The planner worked in rounds of eight until its budget ran out after 32 trials.

1 / 10 · The planner starts with the baseline

The planner starts with the baseline
User code
flow = Flow(
    configs=[planner, implementer],   # implementer: a Claude Code session, max_depth=0
    tools=research_tools(modal),      # submit_trial, trials, ...
    workers=8,
)
g = flow.init("Run autoresearch: 48 trials, 8 at a time.", config="planner",
              task_instructions=program_md, baseline=seed)
flow.run(g, hooks=[Budget(usd=20)])

The run starts as one planner holding the task and the baseline's score: 0.903 validation bits per byte. Lower is better.

2 / 10 · Round 1: one change each

Round 1: one change each
the planner's turn, trimmed
notes = """Baseline val_bpb 0.903174, 3055 steps ...
KEY FACT: prepare.py TRAIN_TOKENS=2M only -> baseline does ~25 epochs
Round 1: 8 single-knob probes from baseline."""
H1 = [
    "LR too low for a 16M-param model: ... Raise LEARNING_RATE to 1e-3.",   # r1_0
    "... Increase dropout from 0.1 to 0.2.",                                 # r1_1
    ...  # r1_2 to r1_5
    "Modernize architecture: RMSNorm, no biases, SwiGLU MLP, rotary embeddings ...",  # r1_6
    ...  # r1_7
]
r1 = [launch_agent("Implement: " + h, config="implementer", hypothesis=h, name=f"r1_{i}")
      for i, h in enumerate(H1)]

The planner writes eight single-change hypotheses, launches an implementer for each, and ends its turn.

3 / 10 · r1_6 rewrites the block

r1_6 rewrites the block
r1_6's edit to train.py, from its commit
+class RMSNorm(nn.Module):
+    def forward(self, x):
+        xf = x.float()
+        xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
+        return xf.type_as(x) * self.weight
 ...
-        self.net = nn.Sequential(
-            nn.Linear(config.n_embd, 4 * config.n_embd),
-            nn.GELU(),
-            nn.Linear(4 * config.n_embd, config.n_embd),
-            nn.Dropout(config.dropout),
-        )
+        hidden = int(8 / 3 * config.n_embd)
+        hidden = 64 * ((hidden + 63) // 64)
+        self.w_gate = nn.Linear(config.n_embd, hidden, bias=False)
+        self.w_up = nn.Linear(config.n_embd, hidden, bias=False)
+        self.w_down = nn.Linear(hidden, config.n_embd, bias=False)
 ...
     def forward(self, x):
-        return self.net(x)
+        return self.dropout(self.w_down(F.silu(self.w_gate(x)) * self.w_up(x)))
 ...
+        q = apply_rope(q, cos, sin)
+        k = apply_rope(k, cos, sin)

Each implementer is a Claude Code session in its own copy of the code. r1_6 got the most ambitious hypothesis and swapped the transformer block for a modern one: RMSNorm, a SwiGLU MLP, rotary embeddings, no biases.

4 / 10 · r1_6 trains it

r1_6 trains it
r1_6's turn
notes = "Implemented RMSNorm, no biases, SwiGLU (hidden 704), RoPE (rotate-half) in train.py."
row = submit_trial(hypothesis)
for k in row:
    if k != "stdout_tail":
        print(k, row[k])
val_bpb 0.848357
status succeeded
num_steps 3024
...
commit 808fa39f40f297ba36fde6b7e3c6e27f476db2d5

submit_trial trains the copy and returns its score, which is saved on this node.

5 / 10 · Round 2: combine the wins

Round 2: combine the wins
the planner's turn, trimmed
LR1 = "791345c5..."   # lr1e-3, 0.804
MOD = "808fa39f..."   # modern arch lr3e-4, 0.848
notes += """
R1 results: lr1e-3 0.8040 (best); modern arch 0.8484; ... drop0 0.8879 (helps); ..."""
R2 = [
    (LR1, "Combine the two R1 wins: from the lr=1e-3 run (0.804), set dropout 0.0."),
    (MOD, "... combine with the LR win: LEARNING_RATE=1.5e-3, dropout 0.0."),
    ...  # six more
]
r2 = [launch_agent("Implement: " + h, config="implementer", hypothesis=h, workspace=w,
                   name=f"r2_{i}") for i, (w, h) in enumerate(R2)]

Woken by round 1's results, the planner combines the best changes, starting each trial from a winner's code. None beats round 1's best of 0.804.

6 / 10 · Round 3: learn from the failures

Round 3: learn from the failures
the planner's turn, trimmed
notes += """
R2 results (all dropout 0.0!): lr1e-3 drop0 0.8947 (vs drop0.1 0.804) ...
LESSON: at lr>=1e-3 we're in overfitting regime; regularization matters. Keep dropout>=0.1."""
R3 = [
    (MOD, "Modern arch gave 0.848 vs 0.903 at lr 3e-4/dropout 0.1; its high-LR runs failed "
          "only because dropout was 0.0. Set LEARNING_RATE=1e-3 and keep dropout 0.1."),
    ...  # seven more
]

Removing dropout hurt at the higher learning rate, so the planner keeps dropout and retries the modern block at that rate, which reaches 0.775.

7 / 10 · Round 4: stack on the best

Round 4: stack on the best
the planner's turn, trimmed
M = "28ae99c8..."   # MOD lr1e-3 drop0.1 0.7751
notes += """
R3 results: MOD lr1e-3 drop0.1 0.7751 BEST ... R4: stack wins on M."""
R4 = [
    "On the old arch, lr 2e-3 beat 1e-3 (0.791 vs 0.804) at dropout 0.1. Apply to the "
    "modern arch best (0.7751 at lr 1e-3): set LEARNING_RATE=2e-3.",
    ...  # seven more
]
r4 = [launch_agent("Implement: " + h, config="implementer", hypothesis=h, workspace=M,
                   name=f"r4_{i}") for i, h in enumerate(R4)]

Every trial now starts from the 0.775 commit, and each hypothesis cites a number from an earlier round.

8 / 10 · r4_5 stacks two changes

r4_5 stacks two changes
r4_5's edit to train.py, from its commit
-    n_layer: int = 4
+    n_layer: int = 8
 ...
+    # Untimed compile warmup: one forward+backward, no optimizer step, not counted.
+    t_warm = time.time()
+    x, y = next(train_loader)
+    with autocast:
+        loss = model(x, y)
+    loss.backward()
+    optimizer.zero_grad(set_to_none=True)
+    if device == "cuda":
+        torch.cuda.synchronize()
+    print(f"warmup_seconds: {time.time() - t_warm:.1f}", flush=True)
+
     t_start = time.time()

Starting from the best trial so far, r4_5 doubles the depth.

9 / 10 · The budget ends the run

The budget ends the run
the planner's last turn
t = trials()
best = t["trials"][0]
summary = f"""Autoresearch, 4 rounds (30 trials finished; r4_4 and r4_5 were still
running when the budget ran out). Baseline val_bpb 0.903174 -> best {best['val_bpb']} ...
What worked: LR 3e-4 -> 1e-3: 0.804; modern arch at lr 1e-3, dropout 0.1: 0.7751; ..."""
submit(summary)

The $20 budget stops the run after 32 trials, and the planner gets one last turn to summarize while two trials are still training.

10 / 10 · The best trial lands after it

The best trial lands after it
r4_5's last turn
notes += " Result: val_bpb 0.764375 (beats 0.7751), 2518 steps."; submit(row); print("ok")

r4_5 finishes after the summary at 0.764, the best of the run. The planner never saw it, but it's in the graph.

Every score is saved on the node that produced it, so the saved graph holds every trial.

Validation bits per byte across 32 trials, falling from the 0.903 baseline to 0.764 over 7 kept improvements
Each dot is one trial, in the order it finished; green dots set a new best. The best score fell from the 0.903 baseline to 0.764.

Peers on a shared board: Boids

DeLM (Mao et al., 2026) drops the root: equal agents coordinate through a shared board, posting tasks, claiming them, and publishing notes everyone reads. On OOLONG, RLM agents organized this way scored 64.0% against 56.0% for plain RLMs.

rlmflow’s TaskBoard is a DeLM-style board, and every agent can call its functions:

board_read()                  # every task (status, owner, result) and every published note
board_post(id, task)          # add a task anyone can take
board_claim(id)               # take an open task: the first claim wins, later ones get ok=False
board_publish(topic, text)    # publish a note, such as an interface the others build against
board_finish(id, result)      # mark your task done, with a one-line result
Four of the peers' turns, each listing the board writes saved on it with their numbers, are applied in order to produce the final table of tasks, owners and findings
Each peer's board writes are saved on the turn that made them, and the board is those writes in order. Here two peers race to claim the same task, and the first claim wins.

Three Claude Code peers share one board and one directory, with the same spec for a browser boids simulation and no manager. One rule keeps them from all planning at once: claim the plan task first, and if someone else has it, wait for their plan. peer2 got it, and the other two built against its interface.

1 / 14 · Three peers, one empty board

Three peers, one empty board
User code
flow = Flow(
    configs=[AgentConfig(name="peer", harness="claude_code", max_depth=0)],
    tools=[FILE_TOOLS, TaskBoard(), open_page],
)
g = Graph()
for name in ["peer1", "peer2", "peer3"]:
    g.start(TEAM.format(name=name, spec=SPEC), name=name, config="peer")
flow.run(g)

Starting three peers means adding three roots to the graph. The lane on the right is the board, empty so far.

2 / 14 · peer2 claims the plan

peer2 claims the plan
peer2's turn
b = board_read(); print(json.dumps(b, indent=1))
r1 = board_post("plan", "split the app into tasks and publish the interface"); print(r1)
r2 = board_claim("plan"); print(r2)

All three peers try to claim plan within a second, and peer2's writes land first.

3 / 14 · The others are refused

The others are refused
peer1's turn
print(board_read())
r1 = board_post("plan", "split the app into tasks and publish the interface")
r2 = board_claim("plan")
print(r1, r2)
{'n': 3, 'op': 'post', 'by': 'peer1', 'ok': False, ...} {'n': 4, 'op': 'claim', 'by': 'peer1', 'ok': False, ...}

peer1 and peer3 are refused, so by the rule they wait.

4 / 14 · They wait for the plan

They wait for the plan
peer3's turn
import time, json
for i in range(60):
    b = board_read()
    if b['tasks']['plan']['status'] == 'done':
        break
    time.sleep(3)
print(json.dumps(b, indent=1))

Both read the board every few seconds until plan is done. Each dotted line is a read.

5 / 14 · peer2 publishes the interface

peer2 publishes the interface
peer2's interface, as published to the board
BOIDS INTERFACE (plain <script> tags, no modules; works over file://). Single global namespace: window.BOIDS.
Load order in index.html: config.js, grid.js, sim.js, render.js, main.js. All coordinates are CSS pixels.

config.js  -> window.BOIDS = { CONFIG: {...} }   (every other file does `const B = window.BOIDS;` and attaches to it)
  CONFIG = {
    COUNT: 2000, SPECIES: 4,
    MAX_SPEED: 1.5, MIN_SPEED: 0.7,      // px per frame at 60fps (dt=1)
    MAX_FORCE: 0.03,                      // steering clamp per frame
    PERCEPTION: 34,                       // neighbor radius (px); also grid cell size
    SEPARATION_DIST: 13,
    W_ALIGN: 1.0, W_COHESION: 0.55, W_SEPARATION: 1.6,
    W_OTHER_SPECIES: 0.9,                 // separation weight vs. other species (they avoid, never flock)
    MAX_NEIGHBORS: 24,                    // stop sampling after this many in-range neighbors (perf cap)
    BOID_LENGTH: 7, BOID_WIDTH: 3.2,      // dart shape size, px
    BACKGROUND: '#1d232c',                // deep slate
    COLORS: ['#8fb4c8', '#c8a98c', '#9fc39c', '#b7a0c6'],  // dusty blue, sand, sage, lavender (similar luminance)
    FPS_COLOR: 'rgba(200,210,220,0.55)', FPS_FONT: '12px ui-monospace, Menlo, monospace',
  }
  Edges WRAP (toroidal).

sim.js
  B.createState(count, width, height) -> state = {
     count, x: Float32Array, y: Float32Array, vx: Float32Array, vy: Float32Array,
     species: Uint8Array   // 0..3, assigned i % SPECIES
...

peer2 publishes every function's signature and data layout, posts a task per file, and claims three of them.

6 / 14 · peer3 claims the grid and the renderer

peer3 claims the grid and the renderer
peer3's turn
mine = []
for t in ['render.js', 'grid.js']:
    r = board_claim(t); print(r)
    if r['ok']: mine.append(t)
{'n': 18, 'op': 'claim', 'id': 'render.js', 'by': 'peer3', 'ok': True}
{'n': 19, 'op': 'claim', 'id': 'grid.js', 'by': 'peer3', 'ok': True}

The plan is done, and both waiting peers read the file tasks peer2 posted. peer3 goes for the renderer and the grid.

7 / 14 · peer1 asks for the same two

peer1 asks for the same two
peer1's turn
claims = [board_claim(t)['ok'] for t in ['grid.js', 'render.js']]
print(claims)
[False, False]

Half a second later peer1 asks for the same two tasks and is refused. Its next call claims main.js and style.css instead.

8 / 14 · peer1 writes the loop

peer1 writes the loop
main.js, written by peer1
  // Smoothed FPS: count frames over ~0.5s windows, then ease the display value.
  let fps = 60;
  let frames = 0;
  let windowStart = performance.now();
  let last = windowStart;

  function frame(now) {
    let elapsed = now - last;
    last = now;
    let dt = elapsed / 16.667;
    if (!(dt > 0)) dt = 0;
    if (dt > 2) dt = 2;

    frames++;
    const span = now - windowStart;
    if (span >= 500) {
      const measured = (frames * 1000) / span;
      fps = fps * 0.5 + measured * 0.5;
      frames = 0;
      windowStart = now;
    }

    grid.build(state, width, height);
    B.step(state, grid, dt, width, height);
    renderer.draw(state, Math.round(fps));

    requestAnimationFrame(frame);
  }

None of the functions peer1 calls exist yet, but the published interface fixes their names and arguments, so it codes against them now.

9 / 14 · peer2 writes the flocking step

peer2 writes the flocking step
sim.js, written by peer2
    for (let i = 0; i < n; i++) {
      const px = x[i], py = y[i], s = sp[i];
      let cx = Math.floor(px / cellW); if (cx < 0) cx = 0; else if (cx >= cols) cx = cols - 1;
      let cy = Math.floor(py / cellH); if (cy < 0) cy = 0; else if (cy >= rows) cy = rows - 1;

      let aX = 0, aY = 0, cX = 0, cY = 0, sX = 0, sY = 0, oX = 0, oY = 0;
      let same = 0, seen = 0;

      const y0 = wideY ? 0 : cy - spanY, y1 = wideY ? rows - 1 : cy + spanY;
      const x0 = wideX ? 0 : cx - spanX, x1 = wideX ? cols - 1 : cx + spanX;
      scan:
      for (let gy = y0; gy <= y1; gy++) {
        let ry = gy; if (ry < 0) ry += rows; else if (ry >= rows) ry -= rows;
        const rowOff = ry * cols;
        for (let gx = x0; gx <= x1; gx++) {
          let rx = gx; if (rx < 0) rx += cols; else if (rx >= cols) rx -= cols;
          const c = rowOff + rx;
          const end = cellStart[c + 1];
          for (let k = cellStart[c]; k < end; k++) {
            const j = items[k];
            if (j === i) continue;
            let dx = x[j] - px;
            let dy = y[j] - py;
            // Shortest offset across the wrapped edges.
            if (dx > halfW) dx -= width; else if (dx < -halfW) dx += width;
            if (dy > halfH) dy -= height; else if (dy < -halfH) dy += height;
            const d2 = dx * dx + dy * dy;
            if (d2 >= r2 || d2 === 0) continue;

            if (sp[j] === s) {
              aX += vx[j]; aY += vy[j];
              cX += dx; cY += dy;
              if (d2 < sep2) {
                // Push away, stronger when closer (1/d falloff on the unit vector).
                sX -= dx / d2; sY -= dy / d2;
              }
              same++;
            } else if (d2 < sep2 * 2.25) {
              oX -= dx / d2; oY -= dy / d2;
            }
            if (++seen >= maxN) break scan;
          }
        }
      }

Each boid checks only the 3×3 grid cells around it instead of all 2,000 boids. Same-species neighbors flock; other species push apart.

10 / 14 · peer3 writes the grid and tests it

peer3 writes the grid and tests it
peer3's turn
test = r'''
global.window = { BOIDS: { CONFIG: {} } };
require(process.cwd() + '/grid.js');
const B = window.BOIDS;
const n = 2000, W = 1280, H = 800;
const s = { count: n, x: new Float32Array(n), y: new Float32Array(n) };
for (let i = 0; i < n; i++) { s.x[i] = Math.random() * W; s.y[i] = Math.random() * H; }
const g = new B.Grid(34); g.build(s, W, H);
let ok = true; const seen = new Set();
for (let c = 0; c < g.cols * g.rows; c++)
  for (let k = g.cellStart[c]; k < g.cellStart[c + 1]; k++) {
    const i = g.items[k]; seen.add(i);
    if (g.cellIndex(s.x[i], s.y[i]) !== c) ok = false;
  }
console.log(ok, seen.size, g.cols, g.rows, g.cellStart[g.cols * g.rows]);
'''
r = subprocess.run(['node', '-e', test], capture_output=True, text=True)
print(r.stdout, r.stderr)
true 2000 37 23 2000

Before finishing the task, peer3 tests that each of 2,000 random boids lands in exactly one cell, the right one.

11 / 14 · peer3 writes the renderer

peer3 writes the renderer
render.js, written by peer3
  Renderer.prototype.draw = function (state, fps) {
    const ctx = this.ctx;
    const w = this.width, h = this.height;

    // Full clear: opaque background, normal compositing, no shadows.
    ctx.globalCompositeOperation = 'source-over';
    ctx.globalAlpha = 1;
    ctx.shadowBlur = 0;
    ctx.fillStyle = C.BACKGROUND;
    ctx.fillRect(0, 0, w, h);

    const n = state.count;
    const xs = state.x, ys = state.y, vxs = state.vx, vys = state.vy, sp = state.species;
    const L = C.BOID_LENGTH;
    const front = L * 0.6;         // nose distance ahead of center
    const back = L * 0.4;          // tail distance behind center
    const notch = L * 0.18;        // inward notch at the tail (dart shape)
    const halfW = C.BOID_WIDTH * 0.5;
    const nSpecies = C.SPECIES;

    for (let s = 0; s < nSpecies; s++) {
      ctx.beginPath();
      for (let i = 0; i < n; i++) {
        if (sp[i] !== s) continue;
        const vx = vxs[i], vy = vys[i];
        let m = Math.sqrt(vx * vx + vy * vy);
        let ux, uy;
        if (m > 1e-6) { ux = vx / m; uy = vy / m; } else { ux = 1; uy = 0; }
        const px = -uy, py = ux;  // perpendicular
        const x = xs[i], y = ys[i];
        const bx = x - ux * back, by = y - uy * back;
        ctx.moveTo(x + ux * front, y + uy * front);
        ctx.lineTo(bx + px * halfW, by + py * halfW);
        ctx.lineTo(x - ux * (back - notch), y - uy * (back - notch));
        ctx.lineTo(bx - px * halfW, by - py * halfW);
        ctx.closePath();
      }
      ctx.fillStyle = C.COLORS[s % C.COLORS.length];
      ctx.fill();
    }

Each species is drawn as one batched path of small darts in a muted color.

12 / 14 · peer3 opens the page

peer3 opens the page
peer3's turn
r = open_page('index.html', seconds=5, screenshots=2)
for k, v in r.items():
    if k != 'screenshots': print(k, str(v)[:800])
print(r.get('screenshots'))
console []

With every file written, peer3 opens the page in a headless browser and looks at the screenshots and the console. It's clean.

13 / 14 · peer2 benchmarks it

peer2 benchmarks it
peer2's turn
res = open_page('.peer2_bench.html', seconds=8, screenshots=1)
print(res["console"])
['log: mix@600 0.746', 'log: sim ms/frame 1.469', 'log: mix@2700 0.853', 'log: draw ms/frame 2.772', 'log: bad 0']

1.5 ms to step the flock and 2.8 ms to draw it, well inside a 60 fps frame. mix rises as the species sort themselves into flocks.

14 / 14 · Every task is done

Every task is done
peer2's last turn
b = board_read()
for k, t in b["tasks"].items():
    print(k, t.get("status"), t.get("owner"))
submit("Boids app complete in index.html, style.css, config.js, grid.js, sim.js, "
       "render.js, main.js. All 8 board tasks done. ...")

30 board writes, 3.3 minutes, and no direct messages: the board did all the coordinating.

The finished app, running live:

Forking a run: Shepherd

The examples so far only run forward. This one goes back: a failed run is rewound to earlier points and retried from each.

Shepherd (Yu et al., 2026) recovers from an agent’s mistakes: a second model, the meta-agent, reads the agent’s saved run, picks earlier points to return to, and starts new attempts from them in parallel. This example builds a small version on Sokoban, a puzzle where a player pushes boxes onto goals. Boxes can’t be pulled, so one bad push can make the puzzle unsolvable. The worker agent makes one push per turn, and the run starts from a scripted failure: eight pushes that jam a box against the wall.

Going back is a fork: g.fork(node) copies the graph and drops every turn node’s agent took after node, leaving the original untouched.

The meta-agent, a gpt-5 agent called the shepherd, previews earlier boards, writes eight plans, and forks the worker once per plan; eight workers play them in parallel, and it picks the best.

The worker's column of eight pushes, the last one jammed. Eight forks branch off it at different pushes, from one push back to the start, and every one plays on to a solve; branch6, forked from the start, solves in 12 pushes and is picked
The worker's eight pushes run down the left; each dashed line is a g.fork, and each column is a branch playing on from there.

1 / 10 · The worker jams the board

The worker jams the board
User code
game = Sokoban(LEVEL, env=ENV)
def goto(row, col=None):
    print(game.goto(row, col))
def push(direction):
    print(game.push(direction))

# then eight scripted turns, each one more shove of B1 to the right:
push("right")
pushed B1 right: (3, 9)->(3, 10)

############
#  .   .  ##
### # # # ##
#        @1#
#   # # # .#
#  2     3 #
#  ## # #  #
# .     .  #
############

The worker's first eight pushes are scripted, so every run starts from the same mistake: box 1 jammed against the right wall.

2 / 10 · The shepherd looks back

The shepherd looks back
the shepherd's turn, trimmed
async def show(k):
    p = await preview(k)
    print(f"\n=== Preview {k} pushes ago ===")
    print(p["board"])
    print("Boxes:", json.dumps(p["boxes"], sort_keys=True))
    print("Goals:", json.dumps(p["goals"], sort_keys=True))
    ...

# Show k=1, midpoint, and deepest
mids = sorted(set([1, (MR+1)//2, MR]))
res = []
for k in mids:
    res.append(await show(k))
=== Preview 4 pushes ago ===
            11
  012345678901
0 ############
1 #  .   .  ##
2 ### # # # ##
3 #    @$    #
4 #   # # # .#
5 #  $     $ #
6 #  ## # #  #
7 # .     .  #
8 ############
Boxes: {"B1": [3, 6], "B2": [5, 3], "B3": [5, 9]}
Goals: {"G1": [1, 3], "G2": [1, 7], "G3": [4, 10], "G4": [7, 2], "G5": [7, 8]}

The shepherd uses preview(k) to see the board k pushes back.

3 / 10 · Eight plans, six rewind depths

Eight plans, six rewind depths
the shepherd's turn, trimmed
notes = """Prepared 8 distinct two-step plans with valid approach squares counted from the printed board.
Entrances verified:
- G1: from (2,3), (1,2), (1,4)
- G2: from (2,7), (1,6), (1,8)
- G3: from (5,10) only
- G4: from (6,2), (7,3)
- G5: from (7,7), (7,9)
..."""

plans = [
  {"rewind": 1, "order": ["B3->G3 entering from (5,10)", "B1->G2 entering from (2,7)"]},
  {"rewind": 1, "order": ["B3->G3 entering from (5,10)", "B2->G4 entering from (6,2)"]},
  {"rewind": 2, "order": ["B1->G2 entering from (2,7)", "B2->G4 entering from (7,3)"]},
  {"rewind": 4, "order": ["B1->G1 entering from (2,3)", "B3->G5 entering from (7,9)"]},
  {"rewind": 4, "order": ["B2->G1 entering from (2,3)", "B3->G3 entering from (5,10)"]},
  {"rewind": 6, "order": ["B3->G2 entering from (2,7)", "B1->G5 entering from (7,7)"]},
  {"rewind": 8, "order": ["B1->G1 entering from (1,2)", "B2->G5 entering from (7,7)"]},
  {"rewind": 3, "order": ["B2->G2 entering from (1,6)", "B3->G5 entering from (7,7)"]},
]

branch(plans)

It writes eight plans, each saying how far to rewind and which goals to aim for, and passes them to branch.

4 / 10 · Each plan becomes a fork

Each plan becomes a fork
User code, trimmed from shepherd.py and recovery.py
# `plans` is what the shepherd's branch() call recorded
branches = []
for index, plan in enumerate(plans):
    # the worker's turn just before the push `rewind` pushes back
    cut, depth = rewind_point(g, worker, plan["rewind"])
    fork = g.fork(cut)                 # a new graph: the worker's turns up to `cut`
    copy = fork.agent(worker.id)
    await flow.replay(fork, copy)      # rebuild its REPL: the board as it was
    fork.send(
        copy,
        f"Rewound {depth} pushes. ...\n\n{board}\n\n"
        f"Lock the boxes in this order: {', then '.join(plan['order'])}.",
    )
    branches.append(Branch(flow, fork, copy, index, depth, plan["order"]))

await asyncio.gather(*(play(branch) for branch in branches))

Each plan forks the worker's graph at its own depth and sends the fork its plan. Then all eight play at once.

5 / 10 · branch6 starts from the fresh board

branch6 starts from the fresh board
branch6's turn
Rewound 8 pushes. This is a fresh recovery attempt, so abandon the plan you were following.

############
#  .   .  ##
### # # # ##
#@$        #
#   # # # .#
#  $     $ #
#  ## # #  #
# .     .  #
############
...
Lock the boxes in this order: B1->G1 entering from (1,2), then B2->G5 entering from (7,7).
goto(3,1)
push("right")
already standing on (3, 1)
pushed B1 right: (3, 2)->(3, 3)

branch6 rewound all eight pushes, so it starts from the board before the first scripted push, with its plan as the latest message.

6 / 10 · The first box locks

The first box locks
branch6's turn
push("up")
pushed B1 up: (2, 3)->(1, 3)

Three pushes in, box 1 locks on a goal. The other seven forks play their own plans meanwhile.

7 / 10 · branch6 solves it

branch6 solves it
branch6's turn
goto(6, 10)
push("up")
walked (5, 9)->(6, 10) in 2 squares
pushed B3 up: (5, 10)->(4, 10)
  SOLVED!

The last box goes onto its goal on branch6's twelfth push, all of them its own.

8 / 10 · The last fork finishes

The last fork finishes
branch7's turn
goto(6, 10)
push("up")
walked (5, 9)->(6, 10) in 2 squares
pushed B1 up: (5, 10)->(4, 10)
  SOLVED!

All eight forks solve the puzzle, in 12 to 36 pushes. branch7, rewound three pushes, is the last to finish, after 36.

9 / 10 · The shepherd gets the results

The shepherd gets the results
User code, trimmed from shepherd.py
meta.send(
    shepherd,
    PICK_QUERY.format(n=len(branches), results=branch_results(branches, jam_pushes)),
    sender="host",
)
async for item in flow.run_streaming(meta):
    show(item, meta)
All 8 branches have played. Each one's plan, outcome and final board:

branch0: rewound 1, order B3->G3 entering from (5,10), then B1->G2 entering from (2,7)
  solved; 20 pushes in total (7 kept from the worker); 3/3 boxes locked; 0 to go
...
branch6: rewound 8, order B1->G1 entering from (1,2), then B2->G5 entering from (7,7)
  solved; 12 pushes in total (0 kept from the worker); 3/3 boxes locked; 0 to go
...
Pick the branch to keep. A solved board beats any unsolved one, and among solves
fewer total pushes is better; a branch's pushes include the ones it kept from the
worker. Check the boards rather than trusting the outcome line alone.

Every branch's outcome goes back to the shepherd as one message.

10 / 10 · The shepherd picks a branch

The shepherd picks a branch
the shepherd's turn
submit("Picked branch6: solved with the fewest total pushes (12) among all solved branches.")

The shepherd picks branch6, and its submit is the run's result. Every fork's return edge points at this turn, where its result was read.

All eight branches solved the puzzle, in 12 to 36 pushes. The shepherd picked branch6, which rewound to the start and solved it in 12; every branch that kept some of the bad pushes needed at least 15, so trying six rewind depths at once showed that starting over was cheapest.

The worker jams the board; eight branches fork off it, each rewinds to its own depth, and all eight play at once until the pick
The run as it played: the worker jams, and all eight branches play at once until the shepherd's pick.

Conclusion

Agents that launch, message and coordinate other agents are becoming a common way to build with models: RLMs split long inputs across sub-agents, autoresearch runs rounds of experiments, DeLM’s peers share a task queue, and Shepherd rewinds and retries.

rlmflow records every agent, turn and message of such a system in a graph and runs from it. A few operations (launching an agent, sending it a message, caching a tool’s result on a node, and forking) build all four examples in this post, and any harness can take a turn: a REPL loop, Claude Code, pi, or your own session.

As models get better at coding, the record of what the agents did matters more than which tool drove each one, since that record is what you inspect, edit and rerun. The model should decide how to split the work, and you should be able to see all of it, change it, and run it again from any point.

full code is on Github

pip install "rlmflow"

Acknowledgements

Thanks to Alex Zhang and Omar Khattab for the original RLM work. I think it’s one of the most important ideas for building LLM agents.

Thanks to ypi for its clean interface and prompts; rlmflow’s session layout and parts of its default prompt come from it. rlmflow’s split between execution, durable state and consumers follows Tau’s harness design, and Anthropic’s Scaling Managed Agents shaped the split between harness, session and sandbox.


Citation

@misc{sudhakaran2026rlmflow,
  author       = {Sudhakaran, Shyam},
  title        = {rlmflow},
  year         = {2026},
  howpublished = {\url{https://shyamsn97.github.io/blog/rflow/}}
}

References

  1. Zhang, A. and Khattab, O. Recursive Language Models. Blog post, 2025. URL: https://alexzhang13.github.io/blog/2025/rlm/. Paper: https://arxiv.org/abs/2512.24601. Code: https://github.com/alexzhang13/rlm-minimal.

  2. Prime Intellect. Recursive Language Models in verifiers. Blog post, 2025. URL: https://www.primeintellect.ai/blog/rlm.

  3. Anthropic. Effective Context Engineering for AI Agents. 2025. URL: https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents.

  4. Chroma Research. Context Rot: How Increasing Input Tokens Impacts LLM Performance. 2025. URL: https://research.trychroma.com/context-rot.

  5. Bertsch, A., Pratapa, A., Mitamura, T., Neubig, G., and Gormley, M. R. Oolong: Evaluating Long Context Reasoning and Aggregation Capabilities. 2025. URL: https://arxiv.org/abs/2511.02817.

  6. Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F., and Liang, P. Lost in the Middle: How Language Models Use Long Contexts. 2023. URL: https://arxiv.org/abs/2307.03172.

  7. Sun, W., Lu, M., Ling, Z., Liu, K., Yao, X., Yang, Y., and Chen, J. Scaling Long-Horizon LLM Agent via Context-Folding. 2025. URL: https://arxiv.org/abs/2510.11967.

  8. Sutton, R. S. The Bitter Lesson. 2019. URL: http://www.incompleteideas.net/IncIdeas/BitterLesson.html.

  9. Reynolds, C. W. Flocks, Herds, and Schools: A Distributed Behavioral Model. SIGGRAPH ‘87, 1987. URL: https://www.red3d.com/cwr/boids/.

  10. Karpathy, A. autoresearch. 2026. URL: https://github.com/karpathy/autoresearch.

  11. Yu et al. Shepherd. 2026. URL: https://arxiv.org/abs/2605.10913.

  12. Hugging Face. Tau. URL: https://github.com/huggingface/tau.

  13. Anthropic. Scaling Managed Agents. URL: https://www.anthropic.com/engineering/managed-agents.

  14. ypi: a recursive coding agent. 2025. URL: https://github.com/rawwerks/ypi.

  15. Mao, Y., Gu, J., Chauhan, A., Zhang, Q., Kang, H., and Mirhoseini, A. Decentralized Multi-Agent Systems with Shared Context. 2026. URL: https://arxiv.org/abs/2606.10662.

  16. Karten, S., Zhang, A. L., Thomas, K., et al. Prime Agent: A Self-Improving RLM Harness. 2026. URL: https://arxiv.org/abs/2608.23552. Code: https://github.com/PrimeIntellect-ai/prime-agent.