Sn Tin

Learn Tin · Part 3: Real programs · Chapter 27

A command-line tool

tin new, input, formatting and building a .wasm.

This chapter makes small programs you run from a terminal: starting a project, reading input, formatting the code, and building a .wasm file.

Start a project

$ tin new hello
created hello/ (main.tin, README.md, .gitignore)
$ cd hello && tin run main.tin

The new main.tin is a working agent program on the mock model, with a guarded tool and tests. You know every line of it by now. Here it is, with what it prints:

new-project.tintin run new-project.tin
// hello: a Tin program with one agent.
//
//   tin run main.tin            run it (offline: the model is "mock")
//   tin test main.tin           run the test blocks at the bottom
//   tin tools main.tin          the JSON Schemas the model sees
//   tin caps main.tin           what the agent can reach, and what needs approval
//
// To talk to Claude, change `model: "mock"` to `model: "claude-opus-5-5"` and set
// ANTHROPIC_API_KEY.

type Mood = | Calm | Busy | Stuck

type Status = {
  /// How the project feels right now
  mood: Mood
  /// One sentence on what to do next
  next: string
}

/// List the open tasks.
tool fn tasks(): string[] => ["write the README", "add a second agent"]

/// Close a task for good. A person approves every call.
guarded tool fn close(task: string): string => "closed '{task}'"

agent Helper {
  model: "mock"
  system: "You help a developer keep track of a small project."
  tools: [tasks, close]
  on toolCall(name, input) => print("  -> {name} {input}")
}

fn main() {
  print(Helper("what is in tasks?"))

  // ask for a type and you get a real value back
  let s: Status = Helper("one line of status, please: 'start with the README'")
  print("mood: {s.mood}, next: {s.next}")

  // run with --yes to approve, or answer the prompt
  print(Helper("close 'write the README'"))
}

test "a tool fn is still a function" {
  assertEq(tasks().len, 2)
}

test "the agent uses its tools" {
  // the mock model calls the tool a prompt names, so this runs offline
  assert(Helper("what is in tasks?").contains("README"), "Helper should list the tasks")
}
  -> tasks {}
mock: ["write the README","add a second agent"]
  -> tasks {}
mood: Calm, next: start with the README
  -> close {"task":"write the README"}
mock: error: Tool call denied by the user. Do not retry it; continue without it.

Use tin new hello --plain for a plain hello world instead.

Reading input

input(prompt) prints the prompt and returns the next line the user types, or "" once input ends. Here's a tally, with some typing shown after each prompt:

tally.tintin run tally.tin
// Reads numbers, one per line, until a blank line. Then prints a small report.
fn main() {
  var numbers: int[] = []
  loop {
    let line = input("number (blank to finish): ")
    if line.trim() == "" { break }
    match parseInt(line.trim()) {
      Some(n) => numbers.push(n)
      None => print("  '{line}' is not a number, skipped")
    }
  }
  print()
  print("count {str(numbers.len).padLeft(6, " ")}")
  print("total {str(numbers.sum()).padLeft(6, " ")}")
}
number (blank to finish): 12
number (blank to finish): 7
number (blank to finish): seven
  'seven' is not a number, skipped
number (blank to finish): 30
number (blank to finish): 

count      3
total     49

Notice how a line that isn't a number is handled: parseInt returns an Option, so you can't forget that case (chapter 7). You can also pipe a file in: tin run tally.tin < numbers.txt.

Environment variables

env("NAME") reads one. It returns "" when it isn't set:

greet.tintin run greet.tin
fn main() {
  let set = env("GREET_NAME")              // "" when the variable isn't set
  let name = if set == "" { "world" } else { set }
  print("hello, {name}")
}
hello, world
$ GREET_NAME=ada tin run greet.tin
hello, ada

Arguments and exit codes

args() gives the words after the file name, as a string[]. exit(code) stops the program right there with that exit status; like panic, it never returns, so it fits in any branch:

fn main() {
  let names = args()                       // the words after the file name
  if names.len == 0 {
    print("usage: tin run hello.tin <name>...")
    exit(2)                                // stop here, with exit status 2
  }
  for n in names {
    print("hello, {n}")
  }
}
$ tin run hello.tin Ada Grace
hello, Ada
hello, Grace
$ tin run hello.tin
usage: tin run hello.tin <name>...
$ echo $?
2

Arguments that start with - are tin's own (--yes); put the program's after --: tin run hello.tin -- --verbose. In the browser playground, args() is empty.

One style: tin fmt

tin fmt file.tin rewrites a file in Tin's one style. It has no options, so there is nothing to argue about. tin fmt --check only lists files that need it, which suits CI. This file:

type Point={x:int,y:int}
fn   add(a:Point,b:Point):Point=>Point{x:a.x+b.x,y:a.y+b.y}
fn main(){
let p=add(Point{x:1,y:2},Point{x:3,y:4})
      print("{p.x}, {p.y}")
}

becomes:

type Point = { x: int, y: int }
fn add(a: Point, b: Point): Point => Point { x: a.x + b.x, y: a.y + b.y }
fn main() {
  let p = add(Point { x: 1, y: 2 }, Point { x: 3, y: 4 })
  print("{p.x}, {p.y}")
}

Build a .wasm

tin build tally.tin writes tally.wasm, 4416 bytes for the tally above. The module describes itself: it carries its tool schemas and type layouts, so a host needs only the file. There's no tin run tally.wasm yet. A built module runs through the JavaScript API, which chapter 28 uses in the browser.

Exit codes

tin run exits with 0 on success, 1 when the program doesn't compile or panics, and with code when it calls exit(code). So a Tin program works in a shell script or a CI step like any other command: tin test main.tin && deploy.

Tasks

●○○ Task 1: A better tally

Change the tally to print the count, the average to one decimal place, and the largest number. Say "no numbers" when nothing was typed.

Solution
task-1.solution.tintin run task-1.solution.tin
fn main() {
  var numbers: int[] = []
  loop {
    let line = input("number (blank to finish): ")
    if line.trim() == "" { break }
    match parseInt(line.trim()) {
      Some(n) => numbers.push(n)
      None => print("  '{line}' is not a number, skipped")
    }
  }
  print()
  if numbers.len == 0 {
    print("no numbers")
  } else {
    let avg = float(int(float(numbers.sum()) / float(numbers.len) * 10.0)) / 10.0   // one decimal
    print("count   {numbers.len}")
    print("average {avg}")
    print("largest {numbers.sortBy((a, b) => a > b)[0]}")
  }
}
number (blank to finish): 12
number (blank to finish): 7
number (blank to finish): 30
number (blank to finish): 

count   3
average 16.3
largest 30

●●● Task 2: A to-do list

Write a to-do list that reads commands: add <text>, done <number>, list and quit. Print a short help line for anything else, and "no such item" for a bad number.

Solution
task-2.solution.tintin run task-2.solution.tin
// A to-do list driven by commands: add <text>, done <number>, list, quit.
fn main() {
  var todos: string[] = []
  loop {
    let line = input("> ").trim()
    if line == "quit" || line == "" { break }
    if line.startsWith("add ") {
      todos.push(line.slice(4, line.len))
    } else if line.startsWith("done ") {
      match parseInt(line.slice(5, line.len)) {
        Some(n) if n >= 1 && n <= todos.len => {
          print("done: {todos[n - 1]}")
          var rest: string[] = []
          for i, t in todos { if i != n - 1 { rest.push(t) } }
          todos = rest
        }
        _ => print("no such item")
      }
    } else if line == "list" {
      for i, t in todos { print("{i + 1}. {t}") }
    } else {
      print("commands: add <text>, done <number>, list, quit")
    }
  }
}
> add buy tin
> add write chapter 27
> list
1. buy tin
2. write chapter 27
> done 1
done: buy tin
> done 9
no such item
> list
1. write chapter 27
> help
commands: add <text>, done <number>, list, quit
> quit

Removing an item builds a new array without it. Arrays are values (chapter 11), so todos = rest replaces the whole list.

What's next

Next: Tin in the browser. What runs in the playground and how agents work there.

In the reference: The tin command · Standard library