Sn Tin

A programming language

Agents are syntax.

Tin is a small typed language that compiles to WebAssembly. tool, agent and guarded are keywords: the compiler writes the JSON a model sees from your types, and refuses any path to a guarded tool that skips a person.

Learn Tin Run this in the playground

/// Send money. A person approves every call.
guarded tool fn wire(to: string, amount: int): string => "sent {amount} to {to}"

/// Look up a balance.
tool fn balance(account: string): int => 120

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

fn main() {
  print(Teller("wire 100 to 'bob'"))
}
a person says yesmock: sent 100 to bob
a person says nomock: error: Tool call denied by the user. Do not retry it; continue without it.

Race it here

Press Run. Your browser runs the same program in Tin (compiled to WebAssembly) and in JavaScript, and in Python too if you tick the box. Each runs in its own worker. The times are measured on your machine, now.

Recursive Fibonacci: function-call overhead.

TinWebAssembly
—ready
JavaScriptyour JS engine
—ready

The native numbers for this program, from the table below: . Tin's compile happened when this site was built; JavaScript's parse and JIT are inside its time; Pyodide's download is not.

Show the three sources
Tin
// Recursive Fibonacci: function-call overhead.
fn fib(n: int): int => if n < 2 { n } else { fib(n - 1) + fib(n - 2) }

fn main() {
  print("fib(36) = {fib(36)}")
}
JavaScript
// Recursive Fibonacci: function-call overhead.
function fib(n) {
  return n < 2 ? n : fib(n - 1) + fib(n - 2)
}

console.log(`fib(36) = ${fib(36)}`)
Python
# Recursive Fibonacci: function-call overhead.
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(f"fib(36) = {fib(36)}")

How fast, honestly

The same 9 programs in four languages, on one machine. Rust wins raw compute: Tin is 2.2× faster (trees) to 4.0× slower (nbody) against it. Against JavaScript, Tin ranges from 5.0× faster (sort) to 1.5× slower (agent), 1.3× faster on the geometric mean of 8. Against Python, from 20.8× faster (sieve) to 1.6× faster (agent). Every Tin and JavaScript time includes about 26 ms and 24 ms of process startup (the hello row).

hello startup only
26 ms24 ms14 ms3.2 ms
agent Tin is slower than JS and Rust
112 ms72 ms184 ms32 ms
fib Tin is slower than Rust
53 ms99 ms667 ms25 ms
mandelbrot Tin is slower than JS and Rust
72 ms69 ms1.22 s45 ms
nbody Tin is slower than JS and Rust
55 ms47 ms1.13 s14 ms
sieve Tin is slower than Rust
78 ms96 ms1.62 s20 ms
sort Tin is slower than Rust
74 ms366 ms834 ms35 ms
trees Tin is slower than JS
128 ms122 ms758 ms276 ms
words Tin is slower than Rust
109 ms177 ms314 ms46 ms
Median of 7 runs after 1 warm-up, whole process wall time (startup included), log scale; the line is the fastest to slowest run. Measured 2026-11-15 22:21 UTC on Apple M5 Pro (15 cores, 24 GB), macOS 27.2 arm64. Tin 0.1.0 (b9a1376) · Node v26.13.0 · Python 3.15.2 · rustc 1.100.0 (0ef1bc386 2026-11-09). Full tables, memory, compile times, method and all 36 source files.

About the agent row

It is Tin's headline feature and its slowest row against JavaScript, so here is what it measures. 50,000 agent runs, each one model call, one tool call and a second model call, against an offline mock model. In Tin that is the built-in loop: every call is checked against the tool's schema, decoded into typed values, passed through the capability check and the on handlers, and crosses between WebAssembly and JavaScript as JSON. In the other languages it is a bare loop written by hand, with none of that.

Measured inside the process, that is 1.7 µs per agent run in Tin, 0.9 µs in JavaScript and 3.4 µs in Python. A real model call takes hundreds of milliseconds, so with a real model this overhead does not show. What you get for it is in Only in Tin.

The same program in four languages

Each snippet runs in its own language when this site is built, and all four print the same output. Line counts skip blank lines.

Hello

String interpolation is the same idea everywhere.

Tin6 lines Run in playground
fn greet(name: string): string => "Hello, {name}!"

fn main() {
  for name in ["Ada", "Linus"] {
    print(greet(name))
  }
}
Python4 lines
def greet(name: str) -> str:
    return f"Hello, {name}!"

for name in ["Ada", "Linus"]:
    print(greet(name))
JavaScript6 lines
function greet(name) {
  return `Hello, ${name}!`
}

for (const name of ["Ada", "Linus"]) {
  console.log(greet(name))
}
Rust8 lines
fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}

fn main() {
    for name in ["Ada", "Linus"] {
        println!("{}", greet(name));
    }
}
Hello, Ada!
Hello, Linus!

Structs

Tin records are values: copying one copies the data.

Tin11 lines Run in playground
type Point = { x: float, y: float }

fn dist(a: Point, b: Point): float {
  let dx = a.x - b.x
  let dy = a.y - b.y
  sqrt(dx * dx + dy * dy)
}

fn main() {
  let a = Point { x: 0.0, y: 0.0 }
  let b = Point { x: 3.0, y: 4.0 }
  print("distance {dist(a, b)}")
}
Python11 lines
import math
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

def dist(a: Point, b: Point) -> float:
    return math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)

a = Point(0.0, 0.0)
b = Point(3.0, 4.0)
print(f"distance {dist(a, b)}")
JavaScript7 lines
// plain objects; the shape is a convention (or a TypeScript type)
function dist(a, b) {
  return Math.hypot(a.x - b.x, a.y - b.y)
}

const a = { x: 0.0, y: 0.0 }
const b = { x: 3.0, y: 4.0 }
console.log(`distance ${dist(a, b).toFixed(1)}`)
Rust12 lines
struct Point {
    x: f64,
    y: f64,
}

fn dist(a: &Point, b: &Point) -> f64 {
    ((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt()
}

fn main() {
    let a = Point { x: 0.0, y: 0.0 };
    let b = Point { x: 3.0, y: 4.0 };
    println!("distance {:.1}", dist(&a, &b));
}
distance 5.0

Errors

Tin and Rust return a Result and pass failures up with ?. Python and JavaScript throw.

Tin20 lines Run in playground
fn parsePort(text: string): Result<int, string> {
  match parseInt(text) {
    Some(n) => if n > 0 && n < 65536 { Ok(n) } else { Err("port {n} is out of range") }
    None => Err("'{text}' is not a number")
  }
}

fn address(line: string): Result<string, string> {
  let parts = line.split(":")
  if parts.len != 2 { return Err("expected host:port") }
  let port = parsePort(parts[1])?
  Ok("{parts[0]} on {port}")
}

fn main() {
  for line in ["localhost:8080", "example.com:http", "nonsense"] {
    match address(line) {
      Ok(a) => print("ok    {a}")
      Err(why) => print("error {why}")
    }
  }
}
Python20 lines
class ConfigError(Exception):
    pass

def parse_port(text: str) -> int:
    try:
        n = int(text)
    except ValueError:
        raise ConfigError(f"'{text}' is not a number")
    if not 0 < n < 65536:
        raise ConfigError(f"port {n} is out of range")
    return n

def address(line: str) -> str:
    parts = line.split(":")
    if len(parts) != 2:
        raise ConfigError("expected host:port")
    return f"{parts[0]} on {parse_port(parts[1])}"

for line in ["localhost:8080", "example.com:http", "nonsense"]:
    try:
        print(f"ok    {address(line)}")
    except ConfigError as why:
        print(f"error {why}")
JavaScript18 lines
function parsePort(text) {
  const n = Number(text)
  if (!Number.isInteger(n)) throw new Error(`'${text}' is not a number`)
  if (n <= 0 || n >= 65536) throw new Error(`port ${n} is out of range`)
  return n
}

function address(line) {
  const parts = line.split(":")
  if (parts.length !== 2) throw new Error("expected host:port")
  return `${parts[0]} on ${parsePort(parts[1])}`
}

for (const line of ["localhost:8080", "example.com:http", "nonsense"]) {
  try {
    console.log(`ok    ${address(line)}`)
  } catch (why) {
    console.log(`error ${why.message}`)
  }
}
Rust20 lines
fn parse_port(text: &str) -> Result<u16, String> {
    let n: i64 = text.parse().map_err(|_| format!("'{text}' is not a number"))?;
    if n > 0 && n < 65536 { Ok(n as u16) } else { Err(format!("port {n} is out of range")) }
}

fn address(line: &str) -> Result<String, String> {
    let parts: Vec<&str> = line.split(':').collect();
    if parts.len() != 2 {
        return Err("expected host:port".into());
    }
    let port = parse_port(parts[1])?;
    Ok(format!("{} on {port}", parts[0]))
}

fn main() {
    for line in ["localhost:8080", "example.com:http", "nonsense"] {
        match address(line) {
            Ok(a) => println!("ok    {a}"),
            Err(why) => println!("error {why}"),
        }
    }
}
ok    localhost on 8080
error 'http' is not a number
error expected host:port

Concurrency

Tin has no async keyword: any function may suspend, spawn starts a task, await waits for it.

Tin12 lines Run in playground
fn brew(drink: string, wait: Duration): string {
  sleep(wait)
  "{drink} is ready"
}

fn main() {
  let t0 = now()
  let tea = spawn brew("tea", 200ms)
  let coffee = spawn brew("coffee", 300ms)
  print(await tea)
  print(await coffee)
  print(if now() - t0 < 500ms { "both in parallel" } else { "one after another" })
}
Python13 lines
import asyncio
import time

async def brew(drink: str, wait: float) -> str:
    await asyncio.sleep(wait)
    return f"{drink} is ready"

async def main():
    t0 = time.monotonic()
    tea = asyncio.create_task(brew("tea", 0.2))
    coffee = asyncio.create_task(brew("coffee", 0.3))
    print(await tea)
    print(await coffee)
    print("both in parallel" if time.monotonic() - t0 < 0.5 else "one after another")

asyncio.run(main())
JavaScript11 lines
const sleep = (ms) => new Promise((done) => setTimeout(done, ms))

async function brew(drink, wait) {
  await sleep(wait)
  return `${drink} is ready`
}

const t0 = performance.now()
const tea = brew("tea", 200)
const coffee = brew("coffee", 300)
console.log(await tea)
console.log(await coffee)
console.log(performance.now() - t0 < 500 ? "both in parallel" : "one after another")
Rust15 lines
use std::thread;
use std::time::{Duration, Instant};

fn brew(drink: &str, wait: Duration) -> String {
    thread::sleep(wait);
    format!("{drink} is ready")
}

fn main() {
    let t0 = Instant::now();
    let tea = thread::spawn(|| brew("tea", Duration::from_millis(200)));
    let coffee = thread::spawn(|| brew("coffee", Duration::from_millis(300)));
    println!("{}", tea.join().unwrap());
    println!("{}", coffee.join().unwrap());
    let both = t0.elapsed() < Duration::from_millis(500);
    println!("{}", if both { "both in parallel" } else { "one after another" });
}
tea is ready
coffee is ready
both in parallel

Agent with a tool

Tin writes the tool schema from the function's types and runs the loop. Elsewhere you write both. Python, JavaScript and Rust use an offline stand-in for the model client, with the same behaviour as Tin's model: "mock".

Tin10 lines Run in playground
/// Add two integers.
tool fn add(a: int, b: int): int => a + b

agent Calculator {
  model: "mock"
  system: "Use the tools for every calculation."
  tools: [add]
}

fn main() {
  print(Calculator("please add 19 and 23"))
}
Python30 lines
import json
# client = anthropic.Anthropic()

def add(a: int, b: int) -> int:
    return a + b

TOOLS = [{
    "name": "add",
    "description": "Add two integers.",
    "input_schema": {
        "type": "object",
        "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
        "required": ["a", "b"],
    },
}]
RUN = {"add": add}

def ask(prompt: str) -> str:
    messages = [{"role": "user", "content": prompt}]
    while True:
        reply = client.messages.create(
            model="mock", max_tokens=1024, tools=TOOLS, messages=messages,
            system="Use the tools for every calculation.")
        messages.append({"role": "assistant", "content": reply.content})
        if reply.stop_reason != "tool_use":
            return "".join(b.text for b in reply.content if b.type == "text")
        results = []
        for call in reply.content:
            if call.type == "tool_use":
                out = RUN[call.name](**call.input)
                results.append({"type": "tool_result", "tool_use_id": call.id, "content": json.dumps(out)})
        messages.append({"role": "user", "content": results})

print(ask("please add 19 and 23"))
JavaScript29 lines
// const client = new Anthropic()

const tools = [{
  name: "add",
  description: "Add two integers.",
  input_schema: {
    type: "object",
    properties: { a: { type: "integer" }, b: { type: "integer" } },
    required: ["a", "b"],
  },
}]
const run = { add: ({ a, b }) => a + b }

async function ask(prompt) {
  const messages = [{ role: "user", content: prompt }]
  while (true) {
    const reply = await client.messages.create({
      model: "mock", max_tokens: 1024, tools, messages,
      system: "Use the tools for every calculation.",
    })
    messages.push({ role: "assistant", content: reply.content })
    if (reply.stop_reason !== "tool_use") {
      return reply.content.filter((b) => b.type === "text").map((b) => b.text).join("")
    }
    const results = reply.content.filter((b) => b.type === "tool_use").map((call) => ({
      type: "tool_result", tool_use_id: call.id, content: JSON.stringify(run[call.name](call.input)),
    }))
    messages.push({ role: "user", content: results })
  }
}

console.log(await ask("please add 19 and 23"))
Rust35 lines
// let client = Client::new(api_key);

fn add(a: i64, b: i64) -> i64 {
    a + b
}

const TOOLS: &[Tool] = &[Tool {
    name: "add",
    description: "Add two integers.",
    input_schema: r#"{"type": "object",
        "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
        "required": ["a", "b"]}"#,
}];

fn ask(client: &Client, prompt: &str) -> String {
    let mut messages = vec![Message { role: "user", content: vec![Block::Text(prompt.into())] }];
    loop {
        let reply = client.create("mock", TOOLS, &messages);
        messages.push(Message { role: "assistant", content: reply.content.clone() });
        if reply.stop_reason != "tool_use" {
            return reply.content.iter().filter_map(|b| match b { Block::Text(t) => Some(t.clone()), _ => None }).collect();
        }
        let mut results = vec![];
        for block in &reply.content {
            if let Block::ToolUse { id, name, input } = block {
                let out = match name.as_str() {
                    "add" => add(input["a"].as_i64().unwrap(), input["b"].as_i64().unwrap()),
                    other => panic!("unknown tool {other}"),
                };
                results.push(Block::ToolResult { tool_use_id: id.clone(), content: out.to_string() });
            }
        }
        messages.push(Message { role: "user", content: results });
    }
}

fn main() {
    println!("{}", ask(&Client, "please add 19 and 23"));
}
mock: 42

Guarded tool

In Tin a guarded tool cannot run without a person's yes, and code that calls it directly does not compile. Elsewhere the check is a line you must remember.

Tin11 lines Run in playground
/// Send money. A person approves every call.
guarded tool fn wire(to: string, amount: int): string => "sent {amount} to {to}"

agent Teller {
  model: "mock"
  tools: [wire]
}

fn main() {
  // The loop stops and asks a person before wire runs.
  // Calling wire("bob", 100) here directly would not compile.
  print(Teller("wire 100 to 'bob'"))
}
Python34 lines
# client = anthropic.Anthropic()

def wire(to: str, amount: int) -> str:
    """Send money. A person approves every call."""
    return f"sent {amount} to {to}"

TOOLS = [{
    "name": "wire",
    "description": "Send money. A person approves every call.",
    "input_schema": {
        "type": "object",
        "properties": {"to": {"type": "string"}, "amount": {"type": "integer"}},
        "required": ["to", "amount"],
    },
}]
GUARDED = {"wire"}

def ask(prompt: str) -> str:
    messages = [{"role": "user", "content": prompt}]
    while True:
        reply = client.messages.create(model="mock", max_tokens=1024, tools=TOOLS, messages=messages)
        messages.append({"role": "assistant", "content": reply.content})
        if reply.stop_reason != "tool_use":
            return "".join(b.text for b in reply.content if b.type == "text")
        results = []
        for call in reply.content:
            if call.type != "tool_use":
                continue
            # approve() is your own UI; forget this check and the tool just runs
            if call.name in GUARDED and not approve(call.name, call.input):
                out = "a person said no"
            else:
                out = wire(**call.input)
            results.append({"type": "tool_result", "tool_use_id": call.id, "content": out})
        messages.append({"role": "user", "content": results})

# nothing stops other code from calling wire("bob", 100) directly
print(ask("wire 100 to 'bob'"))
JavaScript32 lines
// const client = new Anthropic()

/** Send money. A person approves every call. */
const wire = ({ to, amount }) => `sent ${amount} to ${to}`

const tools = [{
  name: "wire",
  description: "Send money. A person approves every call.",
  input_schema: {
    type: "object",
    properties: { to: { type: "string" }, amount: { type: "integer" } },
    required: ["to", "amount"],
  },
}]
const guarded = new Set(["wire"])

async function ask(prompt) {
  const messages = [{ role: "user", content: prompt }]
  while (true) {
    const reply = await client.messages.create({ model: "mock", max_tokens: 1024, tools, messages })
    messages.push({ role: "assistant", content: reply.content })
    if (reply.stop_reason !== "tool_use") {
      return reply.content.filter((b) => b.type === "text").map((b) => b.text).join("")
    }
    const results = []
    for (const call of reply.content.filter((b) => b.type === "tool_use")) {
      // approve() is your own UI; forget this check and the tool just runs
      const ok = !guarded.has(call.name) || (await approve(call.name, call.input))
      results.push({ type: "tool_result", tool_use_id: call.id, content: ok ? wire(call.input) : "a person said no" })
    }
    messages.push({ role: "user", content: results })
  }
}

// nothing stops other code from calling wire({ to: "bob", amount: 100 }) directly
console.log(await ask("wire 100 to 'bob'"))
Rust40 lines
// let client = Client::new(api_key);

/// Send money. A person approves every call.
fn wire(to: &str, amount: i64) -> String {
    format!("sent {amount} to {to}")
}

const TOOLS: &[Tool] = &[Tool {
    name: "wire",
    description: "Send money. A person approves every call.",
    input_schema: r#"{"type": "object",
        "properties": {"to": {"type": "string"}, "amount": {"type": "integer"}},
        "required": ["to", "amount"]}"#,
}];
const GUARDED: &[&str] = &["wire"];

fn ask(client: &Client, prompt: &str) -> String {
    let mut messages = vec![Message { role: "user", content: vec![Block::Text(prompt.into())] }];
    loop {
        let reply = client.create("mock", TOOLS, &messages);
        messages.push(Message { role: "assistant", content: reply.content.clone() });
        if reply.stop_reason != "tool_use" {
            return reply.content.iter().filter_map(|b| match b { Block::Text(t) => Some(t.clone()), _ => None }).collect();
        }
        let mut results = vec![];
        for block in &reply.content {
            if let Block::ToolUse { id, name, input } = block {
                // approve() is your own UI; forget this check and the tool just runs
                let out = if GUARDED.contains(&name.as_str()) && !approve(name, input) {
                    "a person said no".to_string()
                } else {
                    wire(input["to"].as_str().unwrap(), input["amount"].as_i64().unwrap())
                };
                results.push(Block::ToolResult { tool_use_id: id.clone(), content: out });
            }
        }
        messages.push(Message { role: "user", content: results });
    }
}

fn main() {
    // nothing stops other code from calling wire("bob", 100) directly
    println!("{}", ask(&Client, "wire 100 to 'bob'"));
}
mock: sent 100 to bob

Only in Tin

Each of these is produced by the real compiler and runtime while this page is built.

1. The schema comes from your types

The JSON is exactly what the model sees. It is generated from the code, so it can't drift.

type Unit = | Celsius | Fahrenheit

/// Look up the weather for a city.
tool fn weather(
  /// City name, for example "Istanbul"
  city: string,
  unit: Unit,
): string => "sunny in {city}"
{
  "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"
        ]
      }
    },
    "required": [
      "city",
      "unit"
    ],
    "additionalProperties": false
  }
}

2. Skipping the person does not compile

A guarded tool is reachable only through an agent that was given it, where the loop asks a person first. Any other path is a compile error, and the error shows the path.

/// Move money. A person approves every call.
guarded tool fn wire(to: string, amount: int): string => "sent {amount} to {to}"

fn payday() => wire("bob", 100)

fn main() { print(payday()) }
error: 'wire' is a guarded tool, and this call skips approval
 --> pay.tin:4:16
  |
4 | fn payday() => wire("bob", 100)
  |                ^^^^^^^^^^^^^^^^
  = note: path: main → payday → wire
  = note: give the tool to an agent (the agent loop asks before it runs), or call it from another guarded tool fn

3. What each agent can reach, before it runs

The compiler follows every tool, sub-agent and call, and reports what each agent may do on its own and what needs approval. tin caps prints the same report.

tool fn balance(account: string): int => 120

guarded tool fn wireMoney(to: string, amount: int): string {
  // code inside a guarded tool already has approval, so it may call others
  audit("wire {amount} to {to}")
}

fn audit(line: string): string {
  print("  audit: {line}")
  "sent"
}

agent Teller {
  model: "mock"
  tools: [balance]
}

agent Banker {
  model: "mock"
  tools: [Teller, wireMoney]
  on toolCall(name, input) => print("  {name} {input}")
}
agent Teller
  tools:           balance
  can call freely: balance
  needs approval:  nothing
  capabilities:    model

agent Banker
  tools:           Teller (agent), wireMoney (guarded)
  can call freely: balance
  needs approval:  wireMoney
  capabilities:    model, output

tools
  balance    free     pure
  wireMoney  guarded  output

4. Record a session once, replay it anywhere

tin run --record writes every model reply, fetch, input and random number to a tape; --replay runs the same program from it with no model and no network. Tests and this page use that. Below: the first model reply from a session recorded with Claude, and the output of replaying examples/agents/05-claude.tin from it while this page was built.

{
  "agent": "Calculator",
  "response": {
    "content": [
      {
        "type": "tool_use",
        "name": "add",
        "input": {
          "a": 17,
          "b": 25
        }
      }
    ],
    "stop": "tool_use",
    "inputTokens": 661,
    "outputTokens": 66
  }
}
  call add {"a":17,"b":25}
  call multiply {"a":42,"b":3}
(17 + 25) * 3 = 126
…

Learn it

Learn Tin goes from zero to an agent with tools in small chapters with tasks. The tour is the short version:

  1. Hello, Tin
  2. Structs and sum types
  3. No null, no exceptions
  4. Functions, pipelines and closures
  5. Generics
  6. Concurrency without colours
  7. Tools and agents
  8. Guarded tools and teams