---
title: "Turnscript: Teaching the Agent to Write Its Own Tool Calls"
description: "How GoDaddy Airo AI Builder uses turnscript to run file operations locally, reduce model round trips and return concise summaries."
pubDate: 2026-11-24
author: ankur-aggarwal
coAuthors:
  - ashish-aggarwal
section: learn
---

How GoDaddy Airo AI Builder uses turnscript to run file operations locally, reduce model round trips and return concise summaries.

## The bill that did not add up

Earlier this year we looked at what one editing turn in GoDaddy Airo AI Builder costs, and the answer surprised us. In one editing workflow we analyzed, repeated context processing was a major share of model costs. Only a small fraction paid for the words the model actually wrote.

The reason is the shape of agent work. A customer asks for a change, and the agent reads a few files, makes a few edits and checks the result. The reads can go out together, but the edits have to wait for what the reads return, and the check has to wait for the edits, so each phase is a separate call to the model, and each call starts by re-reading everything before it. A simple edit can still take many model calls, and the customer waits for all of them.

This post is about turnscript, the change that collapses most of those calls into one, and about what we learned on the way: a prompt that argued with itself, and a result format we had to rethink.

## The round trip is the expensive part

Giving a model tools is simple: the model emits one or more tool calls, the host runs them, the results are added to the conversation, and the model is called again to decide what comes next. Our agent already batched independent calls, so three file reads cost one round trip, not three. But every round trip is a full model call. A file read takes a fraction of a second on our side; the model call that asked for it re-processes the whole prompt to produce a few dozen tokens of decision.

Parallel calls help less than they look, because the work has phases. Edits depend on what the reads return, and checks depend on the edits, so the model returns to the conversation between each phase and pays a round trip every time. And every result it collects stays in the prompt for good, re-read on every later call.

The analogy we kept coming back to is a contractor who drives back to the office between every measurement and every cut. Faster driving helps a little. What you want is for the contractor to take the plan to the site, do the work there, and come back once with a report.

![One trip with the plan instead of three round trips — the contractor analogy: office is the model, site is the files](/airo-assets/images/articles/turnscript-teaching-the-agent-to-write-its-own-tool-calls/contractor-analogy)

On the left the contractor comes back after every phase; on the right the plan travels once and the measuring, cutting and checking happen on site.

## Let the model write the loop

So we let the model write the loop. Instead of calling tools one at a time, it writes a short program that calls them. The program runs in a sandbox next to the customer's files, inspects what comes back, and returns a summary. Only the summary enters the conversation.

We were not the first. Cloudflare's [Code Mode](https://blog.cloudflare.com/code-mode/) argued that models have read far more real TypeScript than synthetic tool-call examples, so they are better at writing code that calls an API than at calling it through tool tokens. OpenAI's [programmatic tool calling](https://developers.openai.com/api/docs/guides/tools-programmatic-tool-calling) takes a similar path with a hosted runtime.

We borrowed the shape and changed where it runs. Our sandbox sits in the same process as the agent, on the same machine as the customer's project. A hosted sandbox crosses the network, and is billed, every time it reads or writes a file; ours reads and writes locally and bills nothing until the summary comes back. In a small internal comparison, a hosted prototype reduced input tokens on one task but did not complete the tested tasks reliably. That became a design rule: the program must check the results it is given.

The API is deliberately familiar. The script calls `turnscript.readFile`, `turnscript.grepSearch` and `turnscript.str_replace_based_edit_tool` with the same parameters as the tools the model already used, and the type signatures it sees are generated from those tools' schemas. A script looks like this:

```typescript
async () => {
  // Read phase: independent reads run in parallel.
  const [home, about, routes] = await Promise.all([
    turnscript.readFile({ path: "src/pages/Home.tsx" }),
    turnscript.readFile({ path: "src/pages/About.tsx" }),
    turnscript.readFile({ path: "src/routes.tsx" }),
  ])
  // Edit phase: sequential, one file at a time.
  const results = []
  for (const path of ["src/pages/Home.tsx", "src/pages/About.tsx"]) {
    const r = await turnscript.str_replace_based_edit_tool({
      command: "str_replace", path, old_str: "...", new_str: "...",
    })
    results.push(r.startsWith("[error]") ? `${path}: ${r}` : `${path}: ok`)
  }
  return `edited: ${results.join("; ")}`
}
```

Three reads, two edits, one model call. Before turnscript the same work took three or four round trips: one for the reads, one or two for the edits, one to check.

## How a script runs

![One tool call: compile, run, format, return — what happens between the model's script and its reply](/airo-assets/images/articles/turnscript-teaching-the-agent-to-write-its-own-tool-calls/execution-flow)

The script travels down the left: compiled, run in the sandbox, formatted, and returned as one result. A script that does not parse goes straight back to the model with the compiler's message, and nothing runs.

To the model, turnscript is one more tool whose argument is a script. On our side, five things happen.

1. **Compile.** We strip any TypeScript and parse the script. One that does not parse is rejected with the compiler's message before anything runs.
2. **Run in a sandbox.** The script executes in a QuickJS worker. The runtime is designed to limit direct file and network access, and its only exit is a message channel to the host.
3. **Dispatch to the same handlers.** Each call becomes a message to the host, and script operations go through the host's existing handlers and validation checks.
4. **Return strings, never throw.** A failed operation resolves to a string beginning `[error]`, and the script is expected to check it. This is the rule the hosted prototype taught us.
5. **Format the result.** Counts and failures first, then the script's summary, then a trailer listing every file the run wrote.

That trailer exists because our editor learns about edits by watching tool calls, and a script hides them inside one call. Anyone adding a batching layer inherits the same rule: every piece of code that keys on tool names has to handle the batched case.

![What comes back to the model — counts and failures first, then the script's summary, then files written for the editor](/airo-assets/images/articles/turnscript-teaching-the-agent-to-write-its-own-tool-calls/formatted-result)

The model reads the first two lines before anything else: how many operations ran, and which failed. The summary is whatever the script chose to return. The last line is for the editor, not the model.

## What we changed after the first version

The first version worked in evaluations. Production use taught us three things.

**The prompt argued with itself.** While turnscript is active, the direct file tools are locked: calling one returns a short error asking for a script instead. One paragraph of our model guidance said "to read three files, make three parallel tool calls." Another said never to call those tools. The model obeyed both as best it could, and a noticeable share of script turns wasted a call on a refusal. A new rule has to be reconciled with every example already in the prompt.

**Almost every fallback was a typo.** Almost every fallback was a compile error with no edits applied: a missing comma, curly quotes pasted from customer content, an unterminated template string. We added a pre-run check for the subtlest class. The fallback stays, so that a model that cannot write a valid script is not stranded, but most conversations that fall back never return to scripts.

**Partial runs and error reporting.** Production use surfaced gaps in how we handled partial runs and reported errors. We updated the workflow to address them, which is why counts and failures now lead the result.

## Two models, two sets of habits

On editing turns the saving is similar on both model families we run. Everything around that number differs.

On our primary model, the cost of a turn scales with the number of model calls rather than their length, so turnscript saves in exactly one way: fewer calls. Anything that adds a call gives the saving back. Refusals do. So does a habit we found in the scripts themselves: a turn that uses turnscript often runs several scripts, not one. A read script, an edit script, a check script. We had shown the model an example with literal search strings, so it read in one script and edited in the next.

On the other model, scripts were larger and failed to compile more often, and first builds got slightly slower. A design that suits one model's training can be mildly hostile to another's, and we only learned that by splitting every number by model before reading it.

## What we would tell another team

1. **Move the loop to the data.** A sandbox beside the files turns a dozen looks at the whole context into a few.
2. **Make the program look at its results.** An `[error]` string the script must check beats an exception, and both beat silence.
3. **Keep the escape hatch, and price it.** The fallback to direct tools is what makes the system safer; measuring how often it opens is what keeps it cheap.
4. **Read the prompt as one document.** The model will try to obey every example in it, including the ones written for another feature.
5. **Split every number by model.** The same tool grows different habits on different models, and a pooled view hides them.

## Frequently Asked Questions

### Does turnscript change what the agent is allowed to do?

No. Script operations go through the host's existing handlers and validation checks, the same ones a direct tool call uses.

### What happens when a script fails?

A script that does not compile is rejected before it runs, with a hint about the error, and the model usually fixes it on the next try. Other failures unlock the direct file tools for the rest of the conversation, so that the agent does not get stuck. A script that the customer stops, or that returns before its work finished, keeps the tools locked and tells the model to verify the state before continuing.

### How are scripts kept in bounds?

The runtime is designed to limit direct file and network access. A script's only way out is the message channel to the dispatcher, which applies the same checks as the direct tools.

*Try [GoDaddy Airo AI Builder](https://airo-builder.godaddy.com) to see the agent at work.*
