<!-- A command-line tool · Tin · https://tin.ad/docs/learn/cli/ · generated from the built page -->

[Learn](https://tin.ad/docs/learn/) · Real programs · 27 of 34

# A command-line tool

**Goal.** Build a command-line tool: a project, input, arguments, formatting and 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

<!-- output -->
```text
$ 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.tin · tin run new-project.tin*

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

<!-- output -->
```text
  -> 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.tin · tin run tally.tin*

```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, " ")}")
}
```

<!-- output -->
```text
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.tin · tin run greet.tin*

```tin
fn main() {
  let set = env("GREET_NAME")              // "" when the variable isn't set
  let name = if set == "" { "world" } else { set }
  print("hello, {name}")
}
```

<!-- output -->
```text
hello, world
```

<!-- output -->
```text
$ 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:

```tin
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}")
  }
}
```

<!-- output -->
```text
$ 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:

```tin
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:

```tin
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`, 5231 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.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-1.solution.tin · tin run task-1.solution.tin*

```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]}")
  }
}
```

<!-- output -->
```text
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 · harder

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.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-2.solution.tin · tin run task-2.solution.tin*

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

<!-- output -->
```text
> 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.

## Recap

- `tin new` starts a project.
- Input, environment variables, arguments and exit codes are in the standard library.
- `tin fmt` keeps one style; `tin build` makes a `.wasm`.

In the reference: [The tin command](https://tin.ad/docs/ref/cli/) · [Standard library](https://tin.ad/docs/ref/stdlib/)
