Sn Tin

Reference

The tin command

Running, checking, fixing and inspecting programs from the terminal.

Usage

From a checkout, the command is ./bin/tin. It needs Node 24 or newer and nothing else for programs that do not call a real model.

$ tin help
tin 0.1.0 — a small typed language with agents built in, compiled to WebAssembly

start:
  tin new <name> [--plain]                create a project (an agent example; --plain for hello world)
  tin run <file.tin> [args] [flags]       compile and run; args (and all after --) go to args()
  tin repl [--yes]                        type Tin and see the result (every entry is compiled to wasm)
  tin test <file.tin> [--replay <tape>]   run the test "name" { ... } blocks in a file

packages:
  tin add <git url|path> [--name n] [--rev r]   add a dependency to tin.toml, fetch it, pin it in tin.lock
  tin install [--frozen]                  fetch everything in tin.toml at the commits in tin.lock

inspect:
  tin check <file.tin> [--json]           type-check only; --json prints diagnostics with fixes
  tin fix <file.tin>                      apply the compiler's suggested fixes until the file compiles
  tin fmt <file.tin>... [--check]         format in place (one style, no options); --check only lists files that need it
  tin tools <file.tin>                    print the JSON schemas generated for tool fns
  tin caps <file.tin> [--reach <name>]    what each agent and tool can reach, and what needs approval
  tin mcp <file.tin> [--yes]              serve the file's tool fns as an MCP server on stdin/stdout
  tin lsp                                 a language server on stdin/stdout, for any editor
  tin doc [file.tin...] [-o dir] [--json] API docs from /// comments (default: the project's files, into doc/)

ship:
  tin build <file.tin> [-o out.wasm]      compile to a .wasm file (for the JS host: tin run, the browser, Node)
  tin build <file.tin> --target wasi      a .wasm for any WASI runtime, no JS:  wasmtime run hello.wasm
  tin build <file.tin> --native           a native executable (via wasm2c and your C compiler):  ./hello
  tin version

run flags:
  --trace           print each agent-loop step (model calls, tool calls, results) to stderr
  --yes             approve every guarded tool call without asking
  --record <tape>   save every model response, fetch, input and random number to a tape
  --replay <tape>   run from a tape: no network, no model, the same answers
  --mic <file.wav|->      what mic() hears: a WAV file, or raw 24 kHz PCM16 on stdin (default: sox if installed)
  --speaker <file.wav>    where speaker() plays: written as WAV at exit (default: sox, or afplay on macOS)

examples:
  tin new hello && tin run hello/main.tin
  tin run examples/agents/08-fleet.tin --replay tests/tapes/agents-08-fleet.json --yes
  tin caps examples/agents/07-capabilities.tin --reach wireMoney

tin run

Compiles the file in memory and runs it. Nothing is written to disk. Output goes to standard output; compile errors, panics and the agent trace go to standard error.

FlagEffect
--traceprints every step of every agent loop: model calls, tool calls and their results
--yesapproves every guarded tool call. Without it, a terminal is asked y/N, and a run with no terminal denies.
--record <tape>saves model responses, fetch results, input lines and random numbers to a JSON file
--replay <tape>runs from such a file, with no model and no network

Input can be piped: echo "hello" | tin run chat.tin gives each input() call the next line.

tin test

Runs every test "name" { ... } block in a file. Each test gets a fresh instance of the program. A failing test shows why, and anything it printed.

fn half(n: int): int => n / 2

test "even numbers" {
  assertEq(half(10), 5)
}

test "odd numbers round down" {
  print("checking 9")
  assertEq(half(9), 5)
}
$ tin test half.tin
✔ even numbers
✖ odd numbers round down
    expected 5, got 4
    | checking 9

1 passed, 1 failed

The exit code is 1 if any test failed. --replay tape.json gives every test the same recorded model responses; --yes approves guarded tools, which are otherwise denied.

tin check and tin fix

tin check compiles without running. Take this file, sum.tin:

fn main() {
  let total = 0
  for n in [1, 2, 3] {
    total = total + n
  }
  sleep(100)
  print(total)
}
$ tin check sum.tin
error: 'total' is immutable
 --> sum.tin:4:5
  |
4 |     total = total + n
  |     ^^^^^
  = note: declare it with `var total = ...` to allow reassignment
  = fix: declare total with var

error: expected Duration, found int
 --> sum.tin:6:9
  |
6 |   sleep(100)
  |         ^^^
  = note: a Duration needs a unit: write 100ms or 2s, or `n * 1ms` for a number in a variable
  = fix: add a unit: ms

2 errors

The compiler reports every error it can find in one run, in source order: each function, test and agent is checked on its own, and inside a block a failing statement is set aside so the rest is still checked (a statement that uses a name the failing one should have declared is skipped, so one mistake is reported once). A syntax error stops the run at that point. With --json the errors are machine-readable, and its fix is an exact edit: replace the characters from start to end with text.

$ tin check sum.tin --json
{
  "ok": false,
  "diagnostics": [
    {
      "message": "'total' is immutable",
      "file": "sum.tin",
      "line": 4,
      "col": 5,
      "endLine": 4,
      "endCol": 10,
      "notes": [
        "declare it with `var total = ...` to allow reassignment"
      ],
      "fix": {
        "label": "declare total with var",
        "line": 2,
        "col": 3,
        "endLine": 2,
        "endCol": 6,
        "text": "var",
        "start": 14,
        "end": 17
      }
    },
    {
      "message": "expected Duration, found int",
      "file": "sum.tin",
      "line": 6,
      "col": 9,
      "endLine": 6,
      "endCol": 12,
      "notes": [
        "a Duration needs a unit: write 100ms or 2s, or `n * 1ms` for a number in a variable"
      ],
      "fix": {
        "label": "add a unit: ms",
        "line": 6,
        "col": 9,
        "endLine": 6,
        "endCol": 12,
        "text": "100ms",
        "start": 85,
        "end": 88
      }
    }
  ]
}

tin fix applies the first fix the errors offer, checks again, and repeats until the file compiles or no error left has an automatic fix (an error without one does not stop the fixes after it). A let whose value is wrong but whose type is written keeps that type, so code using it is still checked; a typo in a name, function or field gets "did you mean" and a fix. It rewrites the file in place.

$ tin fix sum.tin
sum.tin:4: 'total' is immutable
  fix: declare total with var
sum.tin:6: expected Duration, found int
  fix: add a unit: ms
sum.tin: compiles after 2 fix(es)
$ tin run sum.tin
6

Not every error has a fix. Those that do include habits from other languages ("total: " + n, for (let i = 0; i < n; i++), {"a": 1}, and/or, s[0], Math.sqrt, x.toString(), -> return types), a missing struct field (added with a starting value), a match on numbers or strings without _, a struct literal in an if/for header, an unmet trait bound (a stub method), a missing bound inside a bounded generic, < on a struct without compare, Map(), assigning to a let, mixing int and float, a value where a string, Option or Duration is expected, a match with missing arms, null, a mistyped built-in type name, a plain fn in an agent's tools, and an unguarded tool that reaches guarded code.

tin fmt

Rewrites a file in the one standard layout. There are no options to argue about. tin fmt --check changes nothing and fails if the file is not already formatted.

fn   area(w:int,h:int):int{w*h}
fn main(){print(area(3,4))}
$ tin fmt messy.tin && cat messy.tin
fn area(w: int, h: int): int { w * h }
fn main() { print(area(3, 4)) }

tin lsp and editors

tin lsp is a Language Server Protocol server on stdin and stdout, so any editor with an LSP client can use it (VS Code, Neovim, Helix, Zed, Emacs). It runs the real parser and checker on the unsaved buffer and answers:

  • Problems as you type, with the compiler's suggested fix as a quick fix (the same fix tin fix applies).
  • Hover: the type the checker inferred (let p: Point), or a function's signature, with its /// doc. Standard library functions show their one-line description.
  • Go to definition and find references for locals, parameters, fields, methods, types, variants and agents, across files joined with import "./x.tin".
  • Rename, which refuses keywords and standard-library names.
  • Completion: after x., the fields and methods of x's type; elsewhere, the names in scope first.
  • Outline (document symbols) and Format Document (tin fmt).

The checker stops at the first error, so the editor shows one problem at a time. Everything checked before that error still has its types. In Neovim (0.11+):

vim.lsp.config('tin', { cmd = { 'tin', 'lsp' }, filetypes = { 'tin' }, root_markers = { '.git' } })
vim.lsp.enable('tin')

The VS Code extension in editors/vscode starts tin lsp for you; see its README to install it.

The playground runs the same editor core in a Web Worker: every error is underlined (hover one for its message), hovering a name shows its type and doc, and typing . or Ctrl+Space opens completion.

tin add and tin install

tin add <git url|path> [--name n] [--rev r] adds a dependency to tin.toml (creating it if there is none above the current folder), fetches it into .tin/pkgs/, and writes tin.lock. Without --name, the name comes from the package's own tin.toml, else the repository or folder name. Adding a name again moves it to the newest commit (or to --rev). If anything fails, tin.toml is left as it was.

tin install [--frozen] fetches every dependency at its locked commit and checks its checksum. See Packages for how imports find a package.

tin repl

Type Tin and see the result. Every entry is compiled to WebAssembly like a file is, so the REPL follows the same rules as a program. An expression prints its value; let, var and loops run as statements; fn, type, agent and tool fn are kept and can be redefined; import "./x.tin" (with or without as) brings in a file. :list shows the session as one program, :reset forgets it.

Bindings survive because each entry runs the session again with earlier output hidden. What earlier entries took from outside is replayed, not asked for again: a model reply, a fetch, a line of input, a random number, an approval. Only the new entry reaches the model or the person. The clock is not replayed, and anything an entry does through JavaScript (import js) happens again.

$ tin repl
tin> let name = input("name? ")
name? Ada
tin> "hi " + name               // input is not asked for again
hi Ada
tin> name.len
3

tin tools and tin caps

tin tools file.tin prints the JSON Schemas the compiler generated for every tool fn: exactly what a model is shown. tin caps file.tin reports what each agent can reach and what needs approval; --reach name lists the agents and functions that can reach one function, and --json prints the report as JSON. Both are described, with their output, under Agents and tools.

tin build

Writes the WebAssembly module to a file. The module is self-describing: it carries the tool schemas and type layouts in a custom section, so the runtime needs nothing but the .wasm.

$ tin build hello.tin
hello.wasm  701 bytes

Not yet: there is no tin run hello.wasm; a built module is run through the JavaScript API.

tin mcp

tin mcp file.tin serves the file's tool fns as an MCP server over standard input and output, so any MCP client (Claude Desktop, Claude Code, Cursor, another Tin program) can call them. The tool list carries the same JSON Schemas a Tin agent sends its model: from the parameter types and /// docs. A tool that returns a struct also gets an outputSchema and answers with structured content; Result errors come back as isError results. An argument the schema does not list is refused (the schema says additionalProperties: false), and an int parameter carries its 32-bit minimum and maximum. The file needs no main. What the program prints goes to standard error, never into the protocol.

A guarded tool fn is refused (the call is denied, as for an agent without approval) unless the server was started with --yes: the protocol has no person to ask. For a client config: { "command": "tin", "args": ["mcp", "/path/to/units.tin"] }.

// A Tin program as an MCP server: its tool fns become MCP tools, with schemas from the types.
//
//   tin mcp examples/mcp/units.tin
//
// Add it to any MCP client (Claude Desktop, Claude Code, Cursor, ...) as a stdio server:
//   { "command": "tin", "args": ["mcp", "/path/to/units.tin"] }

/// A temperature in one unit, converted to the others.
type Temperatures = {
  celsius: float,
  fahrenheit: float,
  kelvin: float,
}

/// Convert a temperature. `unit` is "C", "F" or "K".
tool fn convert(
  /// the temperature to convert
  value: float,
  /// its unit: "C", "F" or "K"
  unit: string,
): Result<Temperatures, string> {
  let c = match unit {
    "C" => value,
    "F" => (value - 32.0) * 5.0 / 9.0,
    "K" => value - 273.15,
    _ => return Err("unknown unit '{unit}': use C, F or K"),
  }
  if c < -273.15 {
    return Err("{value}{unit} is below absolute zero")
  }
  Ok(Temperatures { celsius: c, fahrenheit: c * 9.0 / 5.0 + 32.0, kelvin: c + 273.15 })
}

/// How many seconds are in a number of minutes, hours or days.
tool fn seconds(amount: int, unit: string): int {
  match unit {
    "min" => amount * 60,
    "h" => amount * 3600,
    "d" => amount * 86400,
    _ => amount,
  }
}

A session, two messages each way (from this build of the docs):

→ {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"docs","version":"1"}}}
← {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{"listChanged":false}},"serverInfo":{"name":"units","version":"0.1.0"}}}
→ {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"convert","arguments":{"value":212,"unit":"F"}}}
← {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"{\"celsius\":100,\"fahrenheit\":212,\"kelvin\":373.15}"}],"isError":false,"structuredContent":{"celsius":100,"fahrenheit":212,"kelvin":373.15}}}

The other direction, a Tin program calling an MCP server, is import mcp.

tin build --target wasi

Builds a .wasm for any WASI runtime: it imports only WASI and has a _start, so wasmtime, wasmer or Node's node:wasi run it with no JavaScript host and no Tin installed. Output is the same, byte for byte, as tin run: numbers are formatted by the same rules, and a panic prints the same message and exits with 1.

$ tin build hello.tin --target wasi
hello.wasm  66571 bytes
$ wasmtime run hello.wasm
Hello from Tin!

input() reads standard input, env() reads the environment the runtime passes in (wasmtime run --env NAME=value), args() the words after the module (wasmtime run hello.wasm a b), and exit(code) sets the exit status; now() and sleep() use the WASI clocks. A native executable reads its own command line and environment the same way. examples/wasi/stats.tin is a small command-line tool built this way.

Programs that use agents, spawn, fetch, approve or import js are refused, because they need an event loop or the network:

$ tin build ask.tin --target wasi
ask.tin: --target wasi and --native do not support agents yet; use `tin run`

Differences from tin run: sin, cos, tan, ln and pow use fdlibm and can differ from Node in the last bit (about 1 input in 100; the result is the same on every machine). A trap that is not a Tin panic, such as division by zero or a stack overflow, is reported by the runtime in its own words (wasmtime exits with 134). The module is about 65 KB bigger than the JS-host build: the host functions are compiled in.

tin build --native

Builds a native executable: one file, no Node, no wasm runtime. It takes the WASI module from --target wasi, turns it into C with wasm2c and compiles the C with your C compiler (cc, or $CC).

$ tin build hello.tin --native
hello  native executable, 110656 bytes
$ ./hello
Hello from Tin!

It needs wasm2c from wabt 1.0.34 or newer (brew install wabt, or a release download on Linux; TIN_WASM2C points at a specific binary) and a C compiler. Output, panics, traps and exit codes are the same as tin run, and so is the list of what is refused (agents, spawn, fetch, approve, import js). Recursion gets a 512 MiB stack, so it goes much deeper than under Node.

Environment variables

VariableUsed for
TIN_MODELthe model for agents that do not name one
TIN_PROVIDERfetch: call the API without the SDK, with the provider a browser uses
ANTHROPIC_API_KEYthe Anthropic API
TIN_THINKINGClaude's extended thinking: adaptive, or a token budget such as 8000; off by default
TIN_PROMPT_CACHEoff: no prompt caching for Claude (on by default)
OPENAI_API_KEY, OPENAI_BASE_URL, GEMINI_API_KEY, OLLAMA_HOST, …the other model providers: see Model providers

A program reads any variable with env("NAME").

Exit codes

CodeMeaning
0success
1the program did not compile, panicked, or hit a runtime error; or tin fmt --check found unformatted code
2the command line was wrong, or a file could not be read
70a bug in Tin itself

Using the compiler from JavaScript

The compiler and the runtime are plain TypeScript modules with no dependencies. They run in Node and in the browser; the playground is this API in a Web Worker.

import { compile, CompileError } from './src/compiler.ts'
import { instantiate } from './src/runtime.ts'

const { wasm, capabilities } = compile(source, 'main.tin')   // throws CompileError

const program = await instantiate(wasm, {
  write: (text) => process.stdout.write(text),               // print and write
  input: async (prompt) => readLine(prompt),                 // input()
  approve: async (tool, args) => askSomeone(tool, args),     // guarded tools
  models: (name) => ({ model: name, chat: myModel }),        // any model: one async function
  trace: (line) => console.error(line),
})

console.log(program.toolSpecs())                             // the generated schemas
await program.run()                                          // resolves when main and all tasks finish

A model provider is one function, chat(request), that takes the system prompt, the messages and the tool schemas and returns the reply. Pass record or replay with a tape to capture or reproduce a run. A CompileError carries diagnostic, the same object tin check --json prints.