Skip to content
Muse Code: Async Agents That Survive a Crash — ContentBuffer guide

Muse Code: Async Agents That Survive a Crash

K
Kodetra Technologies··10 min read Intermediate

Summary

Install Meta's Muse Code, run async agents, and recover long jobs from its crash-safe log.

Meta just entered the coding-agent wars

On August 5, 2026, Meta Superintelligence Labs shipped Muse Code, a terminal coding agent, together with Muse Spark 1.2, a model co-trained with the agent that drives it. Within 48 hours it was the loudest developer story of the week: VentureBeat framed it as Meta entering the coding-agent wars against Claude, GPT, Gemini, Grok and Kimi, and the launch trended across r/LocalLLaMA and Hacker News. The hook that got everyone talking is not a benchmark number. It is that a Muse Code session can run for 24 hours across 1,000+ tool calls and survive a crash without losing its place.

Two design choices make that possible, and both are teachable. First, Muse Code keeps a set of async background agents alive for the whole session instead of spawning a fresh subagent per task. Second, every model call, tool run, approval and edit is appended to a local event log that Meta describes as replay-exact and restart-safe. If the process dies, the agent resumes precisely where it stopped.

This guide walks you through installing Muse Code, driving it with its three built-in skills, calling Muse Spark 1.2 from Python for scripted work, and building a tiny crash-safe event-log pattern of your own so the idea sticks. By the end you will know how to run a long, unattended repo task and pick it back up after a failure.


Prerequisites

  • macOS or Linux (Muse Code beta ships for these two only; no Windows build yet).
  • A Meta Model API key from developer.meta.com/ai. The same key works for Muse Code and for direct API calls.
  • Python 3.10+ and pip if you want the scripted API path.
  • A git repository you can experiment in. Muse Code edits files, so use a branch or a throwaway clone.
  • Roughly $2-5 of API budget for a first session. Muse Spark 1.2 is billed at $1.25 per million input tokens and $4.25 per million output tokens.

One caution before you start: Muse Code is an agent that runs shell commands and rewrites files. Treat it like a very fast junior engineer with commit access. Run it in a sandbox or a fresh branch with review gates, never straight against main.


Step 1 - Install Muse Code and add your key

The beta installs with a single shell command on macOS or Linux:

curl -fsSL https://dev.meta.ai/install.sh | bash

# confirm it landed on your PATH
muse --version
# Muse Code 0.4.x (beta)

As with any curl | bash installer, read the script first if you are cautious: curl -fsSL https://dev.meta.ai/install.sh | less. Then authenticate by exporting your Meta Model API key. Muse Code reads it from the environment:

export META_API_KEY="sk-meta-..."      # from developer.meta.com/ai

# start an interactive session inside your repo
cd ~/code/my-service
muse

The first launch drops you into an interactive prompt scoped to the current directory. Muse Code indexes the repo lazily as it works rather than reading everything up front, which is part of how it stays affordable on large codebases.


Step 2 - Drive it with /plan, /grill, /goal

Muse Code ships with three default skills, and using them in order is the difference between a useful session and a runaway one.

  • /plan turns a task into an approval-gated plan. Nothing is edited until you accept the plan.
  • /grill stress-tests that plan, poking holes in it until it holds up. This is where you catch a bad assumption before it costs you an hour.
  • /goal works autonomously toward a stated objective, using the background agents to keep going across many steps.

A realistic session for adding rate limiting to an API service looks like this. Each line is what you type at the Muse Code prompt:

/plan Add token-bucket rate limiting to every route in
      services/api. Read from Redis, 100 req/min per API key,
      return HTTP 429 with a Retry-After header when exceeded.

# Muse Code prints a numbered plan. Review it, then pressure-test:

/grill

# It challenges its own plan: "What about routes without an API
# key? Does Redis being down fail open or closed?" You answer,
# the plan tightens. When you are happy:

/goal Implement the approved plan. Add unit tests for the
      limiter and the 429 path. Run the test suite and fix
      failures before you finish.

Under /goal, the main agent delegates. A background agent might be reading the existing middleware while another writes tests, and they report back to the main loop only when they have something worth reporting. Meta's stated reason for keeping these agents persistent is to avoid the redundant information-gathering you get when every subtask re-reads the same files from scratch.


Step 3 - Call Muse Spark 1.2 from Python

For scripted, non-interactive work you do not need the terminal agent at all. Muse Spark 1.2 is served through the Meta Model API and is also listed on OpenRouter, both of which speak the OpenAI-compatible Chat Completions shape. That means the standard openai Python client works if you point it at the right base URL.

pip install openai

Here is a minimal agentic loop: give the model one tool, let it decide when to call it, feed the result back, and repeat until it answers. Confirm the exact model slug on your provider's models page before running (meta/muse-spark-1.2 on OpenRouter; muse-spark-1.2 on the Meta Model API).

import json, os
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",   # or Meta Model API base URL
    api_key=os.environ["OPENROUTER_API_KEY"],
)
MODEL = "meta/muse-spark-1.2"

# One tool the model can call.
def run_tests(path: str) -> str:
    # In real life you'd shell out to pytest here.
    return json.dumps({"path": path, "passed": 11, "failed": 1,
                       "failing": ["test_retry_after_header"]})

tools = [{
    "type": "function",
    "function": {
        "name": "run_tests",
        "description": "Run the test suite at a path, return a JSON summary.",
        "parameters": {
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"],
        },
    },
}]

messages = [
    {"role": "system", "content": "You are a coding agent. Use tools when useful."},
    {"role": "user", "content": "Run the tests in services/api and tell me what is broken."},
]

while True:
    resp = client.chat.completions.create(
        model=MODEL, messages=messages, tools=tools,
    )
    msg = resp.choices[0].message
    messages.append(msg)

    if not msg.tool_calls:
        print(msg.content)          # final answer, we are done
        break

    for call in msg.tool_calls:      # execute each requested tool
        args = json.loads(call.function.arguments)
        result = run_tests(**args)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": result,
        })

Example output from a run against the rate-limiter branch:

1 test is failing: test_retry_after_header in services/api.
The limiter returns 429 but omits the Retry-After header the
test expects. Add `response.headers["Retry-After"] = str(wait)`
where `wait` is the seconds until the bucket refills, then the
suite should pass 12/12.

That loop is the same primitive Muse Code runs internally, just without the persistence and the event log. The next step shows how to add that durability yourself.


Step 4 - Build your own crash-safe event log

The headline feature of Muse Code is that it is restart-safe: an append-only log is the single source of truth, so after a crash it replays the log and continues. You can reproduce the core idea in about 30 lines, and doing so makes the concept concrete. The rule is simple: append an event before you act, and on startup replay the log to rebuild state and skip work already done.

import json, os, time

LOG = "agent.events.jsonl"

def append(event: dict):
    event["ts"] = time.time()
    with open(LOG, "a") as f:                 # append-only
        f.write(json.dumps(event) + "\n")
        f.flush()
        os.fsync(f.fileno())                  # durable before we act

def replay():
    """Rebuild which steps already completed."""
    done = set()
    if os.path.exists(LOG):
        for line in open(LOG):
            e = json.loads(line)
            if e["type"] == "step_done":
                done.add(e["step"])
    return done

def run(steps):
    done = replay()                           # resume from history
    for name, fn in steps:
        if name in done:
            print(f"skip  {name} (already done)")
            continue
        append({"type": "step_start", "step": name})
        fn()
        append({"type": "step_done", "step": name})
        print(f"done  {name}")

if __name__ == "__main__":
    run([
        ("read_config",   lambda: time.sleep(0.2)),
        ("write_limiter", lambda: time.sleep(0.2)),
        ("run_tests",     lambda: time.sleep(0.2)),
    ])

Run it once and it completes all three steps. Kill it with Ctrl-C partway through the second run (delete a step_done line to simulate a crash mid-step) and start it again. Because replay() reads the log first, finished steps are skipped and the agent picks up exactly where it stopped:

$ python agent.py
done  read_config
done  write_limiter
^C                      # crash before run_tests finishes

$ python agent.py       # restart
skip  read_config (already done)
skip  write_limiter (already done)
done  run_tests         # resumes from the exact point of failure

The two details that make this trustworthy are the same two Muse Code relies on: the log is append-only (you never rewrite history, so a half-written file is still valid up to its last complete line) and each write is fsync'd before the real action runs, so the record can never lag behind reality. That ordering is what earns the phrase replay-exact.


Worked example: an overnight migration

Put the pieces together for the kind of job Muse Code is built for: a long, boring, mechanical migration you would rather not babysit. Say you are moving 200 files from a deprecated logging library to a new one, updating call sites and fixing the tests each change breaks.

cd ~/code/monolith
git checkout -b muse/logging-migration
muse

/plan Migrate every file under src/ from the `oldlog` package
      to `structlog`. Preserve log levels and message text.
      Update imports and call sites. After each directory,
      run its tests and fix regressions before moving on.

/grill        # catch edge cases: custom formatters, log filters
/goal Execute the approved plan across all of src/. Commit
      after each directory passes its tests.

This is where persistence pays off. A migration like this can span hundreds of tool calls over hours. Meta's own kernel-optimization case study pushed the same machinery to 1,000+ tool calls across 24 hours. If your laptop sleeps or the process dies at file 140, the event log means you restart and continue from 140 rather than from zero. The background agents, meanwhile, keep the shared context, so the agent working on src/billing is not re-learning the logging conventions the agent in src/auth already figured out.

Practical tip: commit after each passing directory (as the plan instructs). Git commits and the event log are complementary. The log recovers the agent's in-flight state; commits give you clean, reviewable checkpoints you can roll back to independently.


Common pitfalls and gotchas

  • Skipping /grill. The plan you accept is the plan that runs for hours. Ten seconds of stress-testing catches the wrong assumption that would otherwise cost you an hour of wrong edits. Do not skip it on non-trivial tasks.
  • Running against main. Muse Code writes files and runs shell commands. Always work on a branch or a disposable clone with review gates. This is the single most important habit.
  • Confusing stateless protocol with stateless agent. Muse Code is deliberately stateful on disk via the event log. That is a feature. Do not delete the log directory mid-session to 'clean up' or you lose your resume point.
  • Guessing the model slug. Provider model IDs drift during a beta. Check the OpenRouter models page or the Meta Model API docs for the exact muse-spark-1.2 identifier rather than assuming; a wrong slug returns a 404, not a helpful error.
  • Ignoring token cost on long jobs. At $4.25 per million output tokens, a 24-hour, 1,000-call session is real money. Set a budget, watch the running total, and cap the scope of a single /goal run.
  • Treating background agents as free parallelism. They share context to reduce redundant work, but they still consume tokens and can step on each other's edits if your plan is vague. Precise, well-scoped plans keep them coordinated.
  • Expecting downloadable weights. The launch did not ship open weights for Muse Spark 1.2. Treat it as a hosted dependency; if you need local, Meta's separately released Muse Glimmer 30B is the open-weights option, not Spark.

Quick reference

ItemDetail
Install (macOS/Linux)curl -fsSL https://dev.meta.ai/install.sh | bash
ModelMuse Spark 1.2 (hosted; no open weights)
Pricing$1.25 / 1M input, $4.25 / 1M output
Skills/plan (gated plan), /grill (stress-test), /goal (execute)
DurabilityAppend-only event log: replay-exact, restart-safe
ConcurrencyPersistent async background agents (session-scoped)
API shapeOpenAI-compatible Chat Completions
BenchmarksTerminal-Bench 2.1, DeepSWE v1.1, Meta Internal Coding Bench
Open-weights siblingMuse Glimmer 30B (Apache 2.0)

Next steps

  • Run a small, real migration on a branch: pick one directory, use /plan then /grill then /goal, and read the diff before merging.
  • Extend the event-log pattern from Step 4 to log tool arguments and results, then write a tiny replayer that reprints a full session from the log.
  • Compare Muse Spark 1.2 against a model you already use (Claude Opus 5, GPT-5.6, Kimi K3) on the same task and watch token cost as well as pass rate.
  • Read Meta's methodology report for the exact eval setup (Terminal-Bench 2.1 pass@1 over five attempts, Daytona sandboxes) before you trust any single benchmark number.
  • If you need to run offline, evaluate Muse Glimmer 30B, the open-weights agentic model that runs on one consumer GPU.

The durable, crash-safe agent loop is the pattern worth taking away here, whichever model you land on. Once your agent can resume from a log instead of restarting from zero, hours-long unattended work stops being scary and starts being routine.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get