
Microsoft Freehand: Rebuild Its One-Tool Loop in 200 Lines
Summary
One bash tool, a transcript the model edits, a cost meter. Build it and verify it offline.
On December 2, Microsoft Research published Freehand, an agent harness that does almost nothing on purpose. The model gets a runtime description of about 200 words, a single bash tool, and write access to its own conversation history. No file-edit tool, no search tool, no planner, no automatic compaction. In Microsoft's own benchmarks that setup scored higher and cost less than Codex, Claude Code and Gemini CLI in all 11 settings they ran with frontier models.
That result is why the repo is all over agent-builder feeds this week. If you maintain a harness with 20 tools and a 3,000-word system prompt, it is an uncomfortable read. The fastest way to form your own opinion is to build the thing. The core is small enough to fit in one file.
This guide rebuilds Freehand's three mechanisms in about 200 lines of dependency-free Python, runs them against a scripted mock model so you can verify every behavior offline, and then points the same loop at a real endpoint. You will finish knowing what the model actually sees in a Freehand session and where the design bites.
What Freehand actually changes
The paper is titled "Freehand: The Bitter Lesson Comes to Agent Harnesses" (arXiv 2612.02442). Its argument: prompts full of rules, big tool suites, fixed timeouts and threshold compaction are decisions made before the model has seen the task. They help weak models and hold back strong ones. Freehand hands four decisions to the model:
| Decision | Typical harness | Freehand |
|---|---|---|
| Strategy | Rules, workflows and reminders in a long system prompt | A descriptive runtime prompt with no rules |
| Tools | Dozens of pre-designed tools | One bash tool |
| Command duration | Fixed timeouts and poll intervals | The model passes timeout_s per call and can detach jobs |
| Memory | Auto-compaction at a token threshold | The model edits transcript.json itself |
Headline numbers from the README, all Microsoft's own: 5.1 points higher at 49% lower cost than each model's first-party harness, across Terminal-Bench 4, Terminal-Bench Science, Agents' Last Exam, OSWorld 2.1 and AutomationBench with GPT-6-astra, Claude Opus 5.5 and Gemini 4 Carbon. On OSWorld 2.1 with Opus 5.5, Freehand reports 80.1% at $2.09 per task against Claude Code's 74.9% at $7.49.
There is a caveat the authors put in bold, and it matters for anyone copying the idea: with smaller models the order flips. On Terminal-Bench 4, Claude Code beats Freehand with Sonnet 5.5 (41.6% vs 34.9%) and Codex beats it with GPT-6 Sol (34.9% vs 29.2%). Freedom only pays when the model can use it.
Prerequisites
- Python 3.10 or newer on macOS or Linux (the harness uses process groups, so no native Windows)
- bash on your PATH
- No packages to install. Both files use only the standard library
- Optional: an API key for any OpenAI-compatible Chat Completions endpoint, for the last step
- A throwaway directory. The loop runs whatever the model asks for, with your permissions
Step 1: The prompt and the single tool
Freehand's real system prompt lives in src/freehand/prompt.md and is seven lines long. It describes the runtime and tells the model nothing about how to work. Our version keeps the same four facts: there is one loop, the tool is bash, the context is a file you may edit, and a status line arrives after each turn.
Create freehand_mini.py and start with the configuration, the prompt and the tool schema. The schema follows Freehand's: command is required, timeout_s is optional, and the description teaches the detach pattern in one sentence. (The real tool also requires a short human-readable description argument for the UI, which we skip.)
"""freehand_mini.py - the three Freehand mechanisms in one file, stdlib only.
1. One tool, bash, whose timeout the model sets per call (timeout_s).
2. The conversation lives in transcript.json; if the model edits the file, its version is sent next.
3. After every turn the harness appends one status line: turn, context size, tokens, cost, elapsed.
Talks to any OpenAI-compatible Chat Completions endpoint.
"""
import hashlib, json, os, signal, subprocess, sys, time, urllib.request
from pathlib import Path
API_BASE = os.environ.get("API_BASE", "http://127.0.0.1:8177/v1")
API_KEY = os.environ.get("API_KEY", "not-needed-for-the-mock")
MODEL = os.environ.get("MODEL", "scripted-mock")
PRICE_IN = float(os.environ.get("PRICE_IN", "2.50")) # USD per million input tokens
PRICE_OUT = float(os.environ.get("PRICE_OUT", "10.00")) # USD per million output tokens
DEFAULT_TIMEOUT_S = 120
MAX_OUTPUT_CHARS = 40_000
MAX_TURNS = 30
SESSION = Path(os.environ.get("SESSION_DIR", ".session")).resolve()
TRANSCRIPT = SESSION / "transcript.json"
PROMPT = f"""You are a coding agent. You run inside a minimal framework: one loop that sends this \
conversation to you, executes the tools you call, and appends their results. Nothing else is decided for you.
Tool: bash.
Your editable context is stored in {TRANSCRIPT}. The framework writes it after every turn. You can edit it \
to remove, shorten or reorganize anything; if the file changes, your version is what gets sent next.
After each turn the framework appends one line with the turn number, the current context size, tokens and \
cost so far, and elapsed time. When the task is done, reply without calling a tool: that reply ends the task."""
TOOLS = [{
"type": "function",
"function": {
"name": "bash",
"description": "Run a bash command (bash -lc) in the working directory. Returns combined stdout+stderr "
"and the exit code; the process group is killed after timeout_s seconds (default "
f"{DEFAULT_TIMEOUT_S}). For a job that should keep running, start it detached and log "
"to a file: nohup CMD > LOG 2>&1 & then read LOG later.",
"parameters": {
"type": "object",
"properties": {
"command": {"type": "string"},
"timeout_s": {"type": "integer", "description": "seconds before the command is killed"},
},
"required": ["command"],
"additionalProperties": False,
},
},
}]
Notice what is missing. There is no instruction to plan first, no "always run the tests", no list of forbidden commands. The prompt names the transcript path because the model needs to know where its memory lives, and that is the only operational detail it gets.
Step 2: bash with a timeout the model chooses
Most harnesses hardcode a command timeout, often 120 seconds, and then add polling tools for anything slower. Freehand lets the model pass the number. A model that knows it is about to run a 40-minute test suite asks for 2,400 seconds. A model poking at something that might hang asks for 2.
def run_bash(command: str, timeout_s=None) -> str:
try:
timeout = int(float(timeout_s if timeout_s is not None else DEFAULT_TIMEOUT_S))
except (TypeError, ValueError):
return "bash: timeout_s must be a number of seconds; the command was not run"
if not 1 <= timeout <= 86400:
return f"bash: timeout_s must be between 1 and 86400 seconds, got {timeout}; the command was not run"
t0 = time.time()
# start_new_session puts the command in its own process group, so a timeout kills its children too
p = subprocess.Popen(["bash", "-lc", command], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, errors="replace", start_new_session=True)
try:
out, _ = p.communicate(timeout=timeout)
tail = f"[exit {p.returncode}, {time.time() - t0:.1f}s]"
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL)
out, _ = p.communicate()
tail = f"[killed after {timeout}s timeout]"
if len(out) > MAX_OUTPUT_CHARS: # keep the head and the tail, drop the middle
half = MAX_OUTPUT_CHARS // 2
out = out[:half] + f"\n...[{len(out) - MAX_OUTPUT_CHARS} chars omitted]...\n" + out[-half:]
return (out.rstrip("\n") + "\n" if out.strip() else "") + tail
Three details here follow how Freehand behaves, and each one prevents a specific failure:
- Process group kill.
start_new_session=Truegives the command its own process group, andos.killpgkills all of it. Without this, a timed-outnpm testleaves orphaned children holding ports. - A tail the model can parse. Every result ends with
[exit 0, 1.3s]or[killed after 2s timeout]. The model learns the duration of what it ran, which informs the next timeout it picks. - Middle truncation. Output past 40,000 characters keeps its head and tail. Errors usually sit at the end and context at the start.
Step 3: A transcript the model can rewrite
This is the unusual part. After every turn the harness writes the full message list to transcript.json and remembers its SHA-256. If the hash is different the next time it looks, something edited the file, and the edited version becomes the conversation. The model prunes its own memory with the same bash tool it uses for everything else.
An edit can produce a transcript the API will refuse, for example a tool result whose call was deleted. Freehand reverts a rejected edit and shows the model the error. We run the equivalent check locally before sending:
def sha(raw: bytes) -> str:
return hashlib.sha256(raw).hexdigest()
def save(messages: list) -> str:
raw = json.dumps(messages, indent=1, ensure_ascii=False).encode()
TRANSCRIPT.write_bytes(raw)
return sha(raw)
def validate(messages) -> None:
"""Reject an edit the API would reject: every tool result needs its call, every call its result."""
if not isinstance(messages, list) or not messages or messages[0].get("role") != "system":
raise ValueError("transcript must be a JSON list that starts with the system message")
open_calls = set()
for m in messages:
role = m.get("role")
if role not in ("system", "user", "assistant", "tool"):
raise ValueError(f"unknown role {role!r}")
if role != "tool" and open_calls:
raise ValueError(f"tool call(s) {sorted(open_calls)} have no result")
if role == "assistant":
open_calls = {c["id"] for c in m.get("tool_calls") or []}
if role == "tool":
if m.get("tool_call_id") not in open_calls:
raise ValueError(f"tool result {m.get('tool_call_id')!r} has no matching call")
open_calls.discard(m["tool_call_id"])
if open_calls:
raise ValueError(f"tool call(s) {sorted(open_calls)} have no result")
def adopt_edit(messages: list, last_sha: str):
"""If transcript.json changed on disk since we wrote it, return the edited version (or keep ours + a note)."""
raw = TRANSCRIPT.read_bytes()
if sha(raw) == last_sha:
return messages, None
try:
edited = json.loads(raw)
validate(edited)
except (ValueError, KeyError, AttributeError, TypeError) as e:
return messages, f"[harness] your edit to transcript.json was rejected and reverted: {e}"
before, after = len(json.dumps(messages)), len(json.dumps(edited))
print(f" ~ context edit adopted: {before:,} -> {after:,} chars ({after / before - 1:+.0%})", file=sys.stderr)
return edited, None
Compare this with threshold compaction. A compactor fires at, say, 80% of the window and summarizes everything with a generic prompt, whether or not the old content still matters. Here the model decides when and what. The natural move is to drop bulky tool output it has already digested and leave a one-line note in its place.
Step 4: The loop and the meter
The loop is short. Call the model, run its tool calls, check whether the transcript was edited, append a status line, save. A reply without a tool call ends the task.
def call_model(messages: list) -> dict:
body = json.dumps({"model": MODEL, "messages": messages, "tools": TOOLS}).encode()
req = urllib.request.Request(f"{API_BASE}/chat/completions", data=body, headers={
"Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}"})
with urllib.request.urlopen(req, timeout=600) as r:
return json.load(r)
def status_line(meta: dict, ctx: int) -> str:
return (f"[harness] turn {meta['turn']} | context {ctx:,} tokens | total in {meta['in']:,} "
f"(cached {meta['cached']:,}) out {meta['out']:,} | ${meta['cost']:.4f} | "
f"{(time.time() - meta['t0']) / 60:.1f} min elapsed")
def main(task: str) -> int:
SESSION.mkdir(parents=True, exist_ok=True)
messages = [{"role": "system", "content": PROMPT}, {"role": "user", "content": task}]
last_sha = save(messages)
meta = {"turn": 0, "in": 0, "cached": 0, "out": 0, "cost": 0.0, "t0": time.time()}
while meta["turn"] < MAX_TURNS:
meta["turn"] += 1
resp = call_model(messages)
usage = resp.get("usage") or {}
ctx = usage.get("prompt_tokens", 0)
meta["in"] += ctx
meta["cached"] += (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)
meta["out"] += usage.get("completion_tokens", 0)
meta["cost"] = meta["in"] / 1e6 * PRICE_IN + meta["out"] / 1e6 * PRICE_OUT
msg = resp["choices"][0]["message"]
calls = msg.get("tool_calls") or []
assistant = {"role": "assistant", "content": msg.get("content") or ""}
if calls:
assistant["tool_calls"] = calls
if not calls: # a reply without a tool call ends the task
messages.append(assistant)
save(messages)
print(" " + status_line(meta, ctx)[10:], file=sys.stderr)
print(msg.get("content") or "")
return 0
results, note = [], None
for c in calls:
try:
args = json.loads(c["function"]["arguments"] or "{}")
first = args["command"].splitlines()[0][:70]
print(f" $ {first} (timeout_s={args.get('timeout_s', DEFAULT_TIMEOUT_S)})", file=sys.stderr)
result = run_bash(args["command"], args.get("timeout_s"))
except (ValueError, KeyError) as e:
result = f"bash: bad arguments ({e}); nothing was run"
results.append({"role": "tool", "tool_call_id": c["id"], "content": result})
# the command may have rewritten transcript.json: adopt that version, then add this turn to it
messages, note = adopt_edit(messages, last_sha)
messages.append(assistant)
messages.extend(results)
status = status_line(meta, ctx)
messages.append({"role": "user", "content": "\n".join(x for x in (note, status) if x)})
print(" " + status[10:], file=sys.stderr)
last_sha = save(messages)
print("stopped: turn limit reached", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else sys.stdin.read()))
The status line is a plain user message, which is how Freehand delivers it on Chat Completions (on the Anthropic and Responses APIs it uses a system or developer note). The format mirrors Freehand's own: [harness] turn 3 | context 2,605 tokens | total in 5,312 (cached 0) out 198 | $0.0153 | 0.0 min elapsed. A model that can see its context growing and its bill rising has a reason to prune. The meter is what gives the edit-your-own-context feature a purpose.
One ordering detail is easy to get wrong. The model edits the transcript during a turn, before that turn's tool call and result have been written to the file. So the harness adopts the edited file first, then appends the current assistant message and its results on top. Do it the other way round and the model's edit deletes its own in-flight tool call.
Step 5: Verify it with a scripted model
You could point this at a real model now, but then you cannot tell a harness bug from a model choice. A scripted endpoint makes the run deterministic. mock_model.py speaks just enough of the Chat Completions format to replay five moves, and reports usage as request characters divided by four so the meter has something real to measure.
"""mock_model.py - a scripted stand-in for a Chat Completions endpoint, so the harness can be tested offline.
It replays a fixed list of moves and reports usage as (request characters / 4), which is enough to watch
the context meter rise and fall. Swap API_BASE to a real endpoint when you are done testing.
"""
import json, sys
from http.server import BaseHTTPRequestHandler, HTTPServer
T = sys.argv[1] if len(sys.argv) > 1 else ".session/transcript.json"
PRUNE = f'''python3 - <<'PY'
import json
p = "{T}"
items = json.load(open(p))
for m in items:
if m["role"] == "tool" and len(m["content"]) > 1500:
m["content"] = "[pruned by me: orders.csv dump (400 rows) + failing test. Cause: total() summed floats; fixed with integer cents.]"
json.dump(items, open(p, "w"), indent=1)
PY'''
SCRIPT = [
("bash", {"command": "ls && cat orders.csv && python3 -m unittest -q 2>&1 | tail -12"}),
("bash", {"command": "python3 report.py --watch", "timeout_s": 2}),
("bash", {"command": "sed -i 's/return sum(float(r\\[\"amount\"\\]) for r in rows)/"
"return sum(round(float(r[\"amount\"]) * 100) for r in rows) \\/ 100/' report.py"
" && python3 -m unittest -q 2>&1 | tail -4", "timeout_s": 30}),
("bash", {"command": PRUNE, "timeout_s": 10}),
("text", "Fixed report.py: total() now sums integer cents instead of floats, so 400 rows of 19.99 give "
"7996.0 exactly. The unit test passes. I also found that `report.py --watch` never exits, so run it "
"detached if you need it."),
]
step = 0
class H(BaseHTTPRequestHandler):
def do_POST(self):
global step
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
kind, payload = SCRIPT[min(step, len(SCRIPT) - 1)]
step += 1
if kind == "bash":
msg = {"role": "assistant", "content": None, "tool_calls": [{
"id": f"call_{step}", "type": "function",
"function": {"name": "bash", "arguments": json.dumps(payload)}}]}
else:
msg = {"role": "assistant", "content": payload}
body = json.dumps({
"id": f"mock-{step}", "object": "chat.completion", "model": req.get("model"),
"choices": [{"index": 0, "message": msg, "finish_reason": "tool_calls" if kind == "bash" else "stop"}],
"usage": {"prompt_tokens": len(json.dumps(req["messages"])) // 4,
"completion_tokens": len(json.dumps(msg)) // 4},
}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
HTTPServer(("127.0.0.1", 8177), H).serve_forever()
Now a small broken project for the agent to fix. The bug is a classic: summing prices as floats.
mkdir work && cd work
cat > report.py <<'EOF'
import csv, sys, time
def total(rows):
return sum(float(r["amount"]) for r in rows)
def load(path="orders.csv"):
with open(path) as f:
return list(csv.DictReader(f))
if __name__ == "__main__":
if "--watch" in sys.argv:
while True: # re-prints the total forever
print("total:", total(load()), flush=True)
time.sleep(1)
print("total:", total(load()))
EOF
cat > test_report.py <<'EOF'
import unittest
from report import load, total
class TestTotal(unittest.TestCase):
def test_total_is_exact(self):
self.assertEqual(total(load()), 7996.0)
if __name__ == "__main__":
unittest.main()
EOF
python3 -c "
print('order_id,customer,amount')
for i in range(400): print(f'{1000+i},cust-{i%37:02d},19.99')" > orders.csv
python3 -m unittest -q 2>&1 | tail -5
The test fails before the agent touches anything:
AssertionError: 7995.999999999999 != 7996.0
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
Start the mock in one terminal and the harness in another, both from inside work/:
# terminal 1
python3 ../mock_model.py "$PWD/.session/transcript.json"
# terminal 2
python3 ../freehand_mini.py "The total in report.py is wrong for orders.csv. Find out why and fix it."
This is the output from my run. Activity goes to stderr and the final summary to stdout, the same split Freehand's headless mode uses:
$ ls && cat orders.csv && python3 -m unittest -q 2>&1 | tail -12 (timeout_s=120)
turn 1 | context 220 tokens | total in 220 (cached 0) out 55 | $0.0011 | 0.0 min elapsed
$ python3 report.py --watch (timeout_s=2)
turn 2 | context 2,487 tokens | total in 2,707 (cached 0) out 105 | $0.0078 | 0.0 min elapsed
$ sed -i 's/return sum(float(r\["amount"\]) for r in rows)/return sum(ro (timeout_s=30)
turn 3 | context 2,605 tokens | total in 5,312 (cached 0) out 198 | $0.0153 | 0.0 min elapsed
$ python3 - <<'PY' (timeout_s=10)
~ context edit adopted: 11,104 -> 2,558 chars (-77%)
turn 4 | context 2,776 tokens | total in 8,088 (cached 0) out 364 | $0.0239 | 0.0 min elapsed
turn 5 | context 858 tokens | total in 8,946 (cached 0) out 427 | $0.0266 | 0.0 min elapsed
Fixed report.py: total() now sums integer cents instead of floats, so 400 rows of 19.99 give 7996.0 exactly. The unit test passes. I also found that `report.py --watch` never exits, so run it detached if you need it.
Read the context column. Turn 1 sends 220 tokens: the whole pre-task footprint of prompt and task as the mock counts it. (Freehand reports about 350 tokens for its real one.) The CSV dump pushes turn 2 to 2,487. In turn 4 the scripted model rewrites the transcript, and turn 5 goes out at 858 tokens. Without the edit, every later turn would have carried that CSV.
Turn 2 shows the timeout working. The model asked for 2 seconds on a command that loops forever, and the tool result in the transcript reads:
total: 7995.999999999999
total: 7995.999999999999
[killed after 2s timeout]
And after the edit, the first tool result in .session/transcript.json is no longer 9,000 characters of CSV:
{
"role": "tool",
"tool_call_id": "call_1",
"content": "[pruned by me: orders.csv dump (400 rows) + failing test. Cause: total() summed floats; fixed with integer cents.]"
}
Confirm the fix landed with python3 -m unittest -q, which now prints OK. The dollar figures above use placeholder prices of $2.50 and $10 per million tokens and a character-count token estimate, so treat them as a demonstration of the meter, not a cost benchmark.
Step 6: Point it at a real model
The harness speaks standard Chat Completions with function tools, so any compatible endpoint works. Stop the mock, delete the session, and set the variables below. Do this inside a container or a VM you do not care about. I verified the loop against the mock only, so expect to adjust for provider quirks such as how usage is reported.
rm -rf .session
export API_BASE="https://openrouter.ai/api/v1" # or any OpenAI-compatible base URL
export API_KEY="$OPENROUTER_API_KEY"
export MODEL="<a frontier model id from your provider>"
export PRICE_IN=5 PRICE_OUT=25 # your model's USD per million tokens
python3 ../freehand_mini.py "The total in report.py is wrong for orders.csv. Find out why and fix it."
A real model will not follow my script. It may skip the cat, go straight to the test, and never prune because 3,000 tokens is nothing to it. That is the design working: nobody told it to prune at a threshold. To see self-editing with a real model, give it a task with bulky intermediate output, such as grepping a large log directory, and watch for the context edit adopted line.
Run the real Freehand, safely
The rebuild is for understanding. For actual work, use Microsoft's implementation, which adds streaming, sessions, undo snapshots, MCP, image input and three provider formats. It is MIT-licensed, marked alpha, and on PyPI as freehand-ai (0.1.1 as I write this). These commands are from its usage docs:
pip install freehand-ai # Python 3.10+, macOS or Linux
freehand login anthropic # or: freehand login openai
cd your/project
freehand --provider anthropic # interactive session
freehand -p "fix the failing test" # headless: activity on stderr, summary on stdout
freehand -p "fix the failing test" --json # one JSON event per line
git diff | freehand -p - # task from stdin
The README warning is blunt: Freehand has no sandbox and no approval prompt. Commands run as you, with your credentials and environment variables. The project's own recommendation for untrusted code or unattended runs is a container that sees only the project. This Dockerfile is from docs/container.md:
FROM python:3.12-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends git curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
ARG FREEHAND_SPEC=git+https://github.com/microsoft/FreeHand
RUN pip install --no-cache-dir "$FREEHAND_SPEC"
# Freehand's own home (sign-in, sessions, settings) lives in a volume, not in your home directory.
ENV FREEHAND_HOME=/freehand-home
RUN mkdir -p /freehand-home /work && chmod 777 /freehand-home /work
WORKDIR /work
ENTRYPOINT ["freehand"]
docker build -t freehand .
docker run --rm -v "$PWD":/work -v freehand-home:/freehand-home \
-e ANTHROPIC_API_KEY freehand --provider anthropic -p "fix the failing test"
In CI, the --json stream is what you parse. The event types you will care about are tool_start and tool_end (each bash call), context_edit (the transcript was edited, with counts before and after) and the final result, which carries status, summary and usage. Exit status is 0 for a normal end, 1 for an error or a reached usage limit, 2 when it could not start, and 130 when interrupted.
Pitfalls and gotchas
- No sandbox means no sandbox. One bash tool is also one
rm -rftool. Our rebuild has the same property. Never mount your home directory,~/.sshor the Docker socket into the container, and remember the container still has network access, so anything in the mounted folder can be sent out. - Weak models do worse. The README shows first-party harnesses winning with Sonnet 5.5, GPT-6 Sol and DeepSeek V4.1 Flash. If you run a small or local model, guardrails and purpose-built tools are still earning their keep. Test before you delete them.
- Transcript edits can break tool pairing. Delete a tool result but keep its call and the API returns an error. Validate before sending and revert on failure, as
validate()does. When I removed every tool message from a saved transcript, the harness answered:your edit to transcript.json was rejected and reverted: tool call(s) ['call_1'] have no result. - Self-pruning fights prompt caching. Editing an early message changes the prefix, so everything after it is a cache miss on the next call. Pruning 9,000 characters is a clear win. Trimming 200 characters from turn 1 of a long session can cost more than it saves. The meter's
cachedfigure is what lets the model weigh this. - The model can prune what it still needs. There is no undo in our rebuild. Freehand keeps
transcript.last_good.jsonand writes each command's full output to a file, so dropped content can be read again. If you extend the mini version, save each raw tool output to disk and include the path in the truncated result. - Edit ordering. Adopt the edited file before appending the current turn. Appending first and then loading the file silently drops the in-flight tool call.
- Timeouts are per call, with bounds. Freehand accepts 1 to 86,400 seconds and refuses anything else without running the command. Keep the bounds. A model that passes
timeout_s: 0should get an error message, not an instant kill. - Long jobs should be detached. A 3-hour training run inside one tool call blocks the loop for 3 hours. The tool description teaches
nohup CMD > LOG 2>&1 &so the model can start it, do other work and read the log later. - Portability of what the model types. My scripted fix uses GNU
sed -i, which fails on macOS without an empty suffix argument. A real model usually notices the OS from its first command. A script does not, so on a Mac change that line inmock_model.pytosed -i ''.
Quick reference
| Thing | Freehand | freehand_mini.py |
|---|---|---|
| System prompt | src/freehand/prompt.md, about 200 words | PROMPT, about 110 words |
| Tool | bash(command, timeout_s, description) | bash(command, timeout_s) |
| Default timeout | bash_timeout_s: 120 | DEFAULT_TIMEOUT_S = 120 |
| Timeout bounds | 1 to 86,400 s | 1 to 86,400 s |
| Result tail | [exit N, T s] or [killed after N s timeout] | Same |
| Output cap | tool_output_max_chars, middle cut | MAX_OUTPUT_CHARS = 40,000, middle cut |
| Context file | transcript.json in the session dir | .session/transcript.json |
| Edit detection | Hash of the file after each turn | SHA-256 of the file after each turn |
| Bad edit | Reverted, error shown to the model | Reverted, error shown to the model |
| Meter | status_line: true by default | Always on |
| Auto-compaction | Optional, off by default | None |
| Headless | freehand -p TASK [--json] | python3 freehand_mini.py TASK |
| Providers | OpenAI Responses, Anthropic, OpenAI-compatible chat | OpenAI-compatible chat |
Next steps
- Run your own A/B. Take ten real tasks from your backlog, run each through your current harness and through Freehand in a container with the same model, and compare pass rate and cost. Microsoft's numbers are self-reported, and your codebase is not Terminal-Bench.
- Add a spill file to the mini harness: write each full tool output to
.session/out/N.txtand put the path in the result, so pruning becomes reversible. - Record
prompt_tokens_details.cached_tokensagainst a real endpoint and plot it per turn. You will see what each context edit costs in cache misses. - Try removing things from your existing agent instead of switching. Delete one rule from the system prompt, rerun your evals, repeat. With a frontier model, more of it may be dead weight than you expect.
- Read the paper's ablations to see how much each of the mechanisms contributes.
Sources
- Freehand repository and README: https://github.com/microsoft/FreeHand
- Paper, "Freehand: The Bitter Lesson Comes to Agent Harnesses": https://arxiv.org/abs/2612.02442
- Project page: https://microsoft.github.io/FreeHand/
- PyPI package: https://pypi.org/project/freehand-ai/
- Usage, container and security docs:
docs/usage.md,docs/container.md,docs/security.mdin the repository
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,638 newsletter subscribers.