<!-- A fleet of agents · Tin · https://tin.ad/docs/learn/fleet/ · generated from the built page -->

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

# A fleet of agents

**Goal.** Read a larger program: a planner, robots with their own tools, and checked parallel actions.

This chapter reads one larger program, piece by piece: a planner and two robots that restock a workbench. It
uses most of Part 2, and shows how those features fit together. The whole file is at the end, with its real
output.

## 1. The plan is a type

```tin
type Zone = | Dock | Shelves | Bench

type Crew = | Wheels | Hands

type Step = {
  /// Who does it: Wheels (the rover) or Hands (the arm)
  crew: Crew
  /// One short instruction for that robot
  task: string
}

type Plan = {
  goal: string
  steps: Step[]
}
```

 The planner won't answer in prose. It answers with a `Plan` (chapter 17), so the rest of the program
works with real values. The `///` comments go into the schema the model sees. Because
`Crew` has only two cases, the model can't invent a third robot.

## 2. Each robot's tools

```tin
/// Drive the rover to a zone. Reports the travel time.
tool fn drive(to: Zone): string {
  sleep(30ms)
  let t = match to { Dock => 40, Shelves => 25, Bench => 10 }
  "arrived at {to} after {t}s"
}

/// Count how many of an item are on the shelves.
tool fn stock(item: string): int => if item.contains("filament") { 3 } else { 0 }

/// Pick items with the arm and place them on the bench.
tool fn pick(item: string, quantity: int): string {
  sleep(30ms)
  "placed {quantity} x {item} on the bench"
}

/// Scrap an item for good. A person approves every call.
guarded tool fn scrap(item: string, reason: string): string => "scrapped {item} ({reason})"
```

 Ordinary functions, marked `tool` (chapter 16). Scrapping can't be undone, so it's
`guarded`: a person approves each call (chapter 18).

## 3. Three agents, each with only its own tools

```tin
/// Breaks a goal into steps for the robots. Never acts itself.
agent Planner {
  system: "Plan for two robots: Wheels drives and counts, Hands picks and scraps. Short steps."
}

/// The rover. Drives between zones and counts stock.
agent Rover {
  system: "You are the rover. Use your tools, then report in one line."
  tools: [drive, stock]
  on toolCall(name, input) => print("    rover  {name} {input}")
}

/// The arm. Picks and scraps items on the bench.
agent Arm {
  system: "You are the arm. Use your tools, then report in one line."
  tools: [pick, scrap]
  on toolCall(name, input) => print("    arm    {name} {input}")
}
```

 The planner has no tools at all, so it can only plan. The rover can't scrap anything, because it was never
given `scrap`. The compiler's capability report (chapter 19) confirms this:

*fleet.tin · tin caps fleet.tin*

<!-- output -->
```text
agent Planner
  tools:           none
  can call freely: nothing
  needs approval:  nothing
  capabilities:    model

agent Rover
  tools:           drive, stock
  can call freely: drive, stock
  needs approval:  nothing
  capabilities:    model, clock, output

agent Arm
  tools:           pick, scrap (guarded)
  can call freely: pick
  needs approval:  scrap
  capabilities:    model, clock, output

tools
  drive  free     clock
  stock  free     pure
  pick   free     clock
  scrap  guarded  pure

main
  capabilities:    clock, model, output, spawn
```

## 4. Plan, check, then act in parallel

```tin
fn worker(crew: Crew): string => match crew { Wheels => "rover", Hands => "arm" }

fn main() {
  let plan: Plan = Planner("Restock the bench with filament and get rid of the cracked spool.")
  print("plan: {plan.goal}")
  for i, step in plan.steps { print("  {i + 1}. {worker(step.crew)}: {step.task}") }

  // The rover and the arm work in parallel; each robot does its own steps in order.
  let rover = spawn run(plan.steps.filter(s => s.crew == Wheels), Rover)
  let arm = spawn run(plan.steps.filter(s => s.crew == Hands), Arm)
  print("rover: {await rover}")
  print("arm:   {await arm}")
}

fn run(steps: Step[], robot: Agent): string {
  var last = "idle"
  for step in steps { last = robot(step.task) }
  last
}
```

 The plan is printed before anything moves, so you can check it first (see task 1). Then each robot gets its own
steps, and the two run at the same time with `spawn` (chapter 21). Each robot's steps still run in
order. `run` takes any `Agent`, so the same loop drives both.

## The whole program

This run replays a recorded session (chapter 23), and `--yes` approves the scrap:

*fleet.tin · tin run fleet.tin --replay tests/tapes/agents-08-fleet.json --yes*

```tin
type Zone = | Dock | Shelves | Bench

type Crew = | Wheels | Hands

type Step = {
  /// Who does it: Wheels (the rover) or Hands (the arm)
  crew: Crew
  /// One short instruction for that robot
  task: string
}

type Plan = {
  goal: string
  steps: Step[]
}

/// Drive the rover to a zone. Reports the travel time.
tool fn drive(to: Zone): string {
  sleep(30ms)
  let t = match to { Dock => 40, Shelves => 25, Bench => 10 }
  "arrived at {to} after {t}s"
}

/// Count how many of an item are on the shelves.
tool fn stock(item: string): int => if item.contains("filament") { 3 } else { 0 }

/// Pick items with the arm and place them on the bench.
tool fn pick(item: string, quantity: int): string {
  sleep(30ms)
  "placed {quantity} x {item} on the bench"
}

/// Scrap an item for good. A person approves every call.
guarded tool fn scrap(item: string, reason: string): string => "scrapped {item} ({reason})"

/// Breaks a goal into steps for the robots. Never acts itself.
agent Planner {
  system: "Plan for two robots: Wheels drives and counts, Hands picks and scraps. Short steps."
}

/// The rover. Drives between zones and counts stock.
agent Rover {
  system: "You are the rover. Use your tools, then report in one line."
  tools: [drive, stock]
  on toolCall(name, input) => print("    rover  {name} {input}")
}

/// The arm. Picks and scraps items on the bench.
agent Arm {
  system: "You are the arm. Use your tools, then report in one line."
  tools: [pick, scrap]
  on toolCall(name, input) => print("    arm    {name} {input}")
}

fn worker(crew: Crew): string => match crew { Wheels => "rover", Hands => "arm" }

fn main() {
  let plan: Plan = Planner("Restock the bench with filament and get rid of the cracked spool.")
  print("plan: {plan.goal}")
  for i, step in plan.steps { print("  {i + 1}. {worker(step.crew)}: {step.task}") }

  // The rover and the arm work in parallel; each robot does its own steps in order.
  let rover = spawn run(plan.steps.filter(s => s.crew == Wheels), Rover)
  let arm = spawn run(plan.steps.filter(s => s.crew == Hands), Arm)
  print("rover: {await rover}")
  print("arm:   {await arm}")
}

fn run(steps: Step[], robot: Agent): string {
  var last = "idle"
  for step in steps { last = robot(step.task) }
  last
}
```

<!-- output -->
```text
plan: filament on the bench, cracked spool gone
  1. rover: drive to the Shelves and check the filament stock
  2. arm: pick 2 filament spools onto the bench
  3. rover: drive back to the Dock
  4. arm: scrap the cracked spool
    rover  drive {"to":"Shelves"}
    rover  stock {"item":"filament"}
    arm    pick {"item":"filament","quantity":2}
    rover  drive {"to":"Dock"}
    arm    scrap {"item":"cracked spool","reason":"cracked"}
rover: Back home, arrived at Dock after 40s.
arm:   Done: scrapped cracked spool (cracked).
```

## Tasks

### Task 1: Check the plan

Before dispatching, a plan should be checked. Write `check(plan): Result<Plan, string>` that
refuses an empty plan, or one with more than five steps. Prove it with tests. You don't need a model for this:
a `Plan` is just a value.

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

**Solution

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

```tin
type Crew = | Wheels | Hands
type Step = { crew: Crew, task: string }
type Plan = { goal: string, steps: Step[] }

/// Checks a plan before anything moves.
fn check(plan: Plan): Result<Plan, string> {
  if plan.steps.len == 0 { return Err("the plan has no steps") }
  if plan.steps.len > 5 { return Err("{plan.steps.len} steps is too many; at most 5") }
  Ok(plan)
}

test "a short plan passes" {
  let p = Plan { goal: "tidy", steps: [Step { crew: Wheels, task: "drive to the dock" }] }
  assert(check(p).isOk())
}

test "an empty plan is refused" {
  assertEq(check(Plan { goal: "nothing", steps: [] }), Err("the plan has no steps"))
}

test "a long plan is refused" {
  let step = Step { crew: Hands, task: "pick" }
  assertEq(check(Plan { goal: "busy", steps: [step, step, step, step, step, step] }), Err("6 steps is too many; at most 5"))
}
```

<!-- output -->
```text
✔ a short plan passes
✔ an empty plan is refused
✔ a long plan is refused

3 passed, 0 failed
```

### Task 2: Who can scrap?

Which agents and functions can reach `scrap`? Ask the compiler.

**Solution

*task-2.solution.tin · tin caps task-2.solution.tin --reach scrap*

```tin
type Zone = | Dock | Shelves | Bench

type Crew = | Wheels | Hands

type Step = {
  /// Who does it: Wheels (the rover) or Hands (the arm)
  crew: Crew
  /// One short instruction for that robot
  task: string
}

type Plan = {
  goal: string
  steps: Step[]
}

/// Drive the rover to a zone. Reports the travel time.
tool fn drive(to: Zone): string {
  sleep(30ms)
  let t = match to { Dock => 40, Shelves => 25, Bench => 10 }
  "arrived at {to} after {t}s"
}

/// Count how many of an item are on the shelves.
tool fn stock(item: string): int => if item.contains("filament") { 3 } else { 0 }

/// Pick items with the arm and place them on the bench.
tool fn pick(item: string, quantity: int): string {
  sleep(30ms)
  "placed {quantity} x {item} on the bench"
}

/// Scrap an item for good. A person approves every call.
guarded tool fn scrap(item: string, reason: string): string => "scrapped {item} ({reason})"

/// Breaks a goal into steps for the robots. Never acts itself.
agent Planner {
  system: "Plan for two robots: Wheels drives and counts, Hands picks and scraps. Short steps."
}

/// The rover. Drives between zones and counts stock.
agent Rover {
  system: "You are the rover. Use your tools, then report in one line."
  tools: [drive, stock]
  on toolCall(name, input) => print("    rover  {name} {input}")
}

/// The arm. Picks and scraps items on the bench.
agent Arm {
  system: "You are the arm. Use your tools, then report in one line."
  tools: [pick, scrap]
  on toolCall(name, input) => print("    arm    {name} {input}")
}

fn worker(crew: Crew): string => match crew { Wheels => "rover", Hands => "arm" }

fn main() {
  let plan: Plan = Planner("Restock the bench with filament and get rid of the cracked spool.")
  print("plan: {plan.goal}")
  for i, step in plan.steps { print("  {i + 1}. {worker(step.crew)}: {step.task}") }

  // The rover and the arm work in parallel; each robot does its own steps in order.
  let rover = spawn run(plan.steps.filter(s => s.crew == Wheels), Rover)
  let arm = spawn run(plan.steps.filter(s => s.crew == Hands), Arm)
  print("rover: {await rover}")
  print("arm:   {await arm}")
}

fn run(steps: Step[], robot: Agent): string {
  var last = "idle"
  for step in steps { last = robot(step.task) }
  last
}
```

<!-- output -->
```text
agents that can reach scrap:    Arm
functions that can reach scrap: main
```

`main` appears because it calls `Arm`, whose loop can call
`scrap`. A person still approves every one of those calls.

## Recap

- The plan is a type, so the model must answer in its shape.
- Each agent gets only its own tools, and the compiler holds it to that.
- Plan, check, then act in parallel with `spawn`.

In the reference: [Typed replies](https://tin.ad/docs/ref/agents/#typed) · [Guarded tools](https://tin.ad/docs/ref/agents/#guarded) · [Concurrency](https://tin.ad/docs/ref/language/#concurrency)
