<!-- Tin in the browser · Tin · https://tin.ad/docs/learn/browser/ · generated from the built page -->

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

# Tin in the browser

**Goal.** Know what runs in the playground, how agents use models there, and how to host Tin yourself.

Tin compiles to WebAssembly, and its compiler and runtime are plain TypeScript with no dependencies. So the
same program runs in a terminal and in a web page, agents included. The [playground](https://tin.ad/docs/play/)
is exactly that: the real compiler and runtime, in your browser.

## The playground

Every single-file example in this tutorial has a link that opens it in the playground. This one asks for your
name, and its guarded tool asks you before it charges:

*shop.tin · tin run shop.tin*

```tin
/// Look up the price of an item, in cents.
tool fn price(item: string): int => if item == "tin cup" { 450 } else { 999 }

/// Charge the customer. A person approves every call.
guarded tool fn charge(cents: int): string => "charged {cents} cents"

agent Till {
  model: "mock"
  tools: [price, charge]
  on toolCall(name, input) => print("  {name} {input}")
}

fn main() {
  let name = input("your name: ")
  print("hello, {name}")
  print(Till("price 'tin cup'"))
  print(Till("charge 450"))
}
```

<!-- output -->
```text
your name: ada
hello, ada
  price {"item":"tin cup"}
mock: 450
  charge {"cents":450}
mock: error: Tool call denied by the user. Do not retry it; continue without it.
```

In the terminal, `input()` reads a line and approval is a y/n prompt (or `--yes`). In the
playground, both are dialogs. The program doesn't change. Above, with no one to approve, the charge was denied.

## Models in the browser

- **`model: "mock"`** works everywhere, offline.
- **Recorded tapes** (chapter 23) replay in the playground, so the Claude examples run with no
key.

- **Your own key.** Pick a provider in the playground (Anthropic, OpenAI or any OpenAI-compatible
server, Gemini, Mistral, a local Ollama or llama.cpp, and more), paste your key, and agents talk to it directly
from the page. The key stays in the browser, in memory or in `localStorage` if you ask. It is sent only
to that provider or the base URL you set, and Tin programs can't read it. Some providers refuse calls from web
pages; for those, use the CLI.

Pausing (`sleep`, `spawn`/`await`, `fetch`, agent calls)
needs WebAssembly JSPI: Chrome or Edge 137 and newer, or Node 24 and newer. Without it, programs that never
pause still run, and the playground tells you why the others can't.

## Hosting Tin yourself

The code that runs a Tin program is called the *host*. It decides where output goes, where input comes
from, who approves guarded tools and which models exist. Everything else (the agent loop, typed replies,
capabilities, tapes) is the same runtime on every host. Here's a whole host in a few lines. It's written for Node
so it can be checked here, but a web page uses the same calls:

*main.host.mjs · node main.host.mjs*

```tin
// A tiny host: compile a Tin program and run it, deciding where output, input and approvals come from.
// A web page does exactly this, with a text field for input() and a dialog for approve.
// Run it from the repo root: node examples/learn/28-browser/main.host.mjs
import { readFileSync } from 'node:fs'
import { compile } from '../../../src/compiler.ts'
import { instantiate, describeError } from '../../../src/runtime.ts'

const source = readFileSync(new URL('./shop.tin', import.meta.url), 'utf8')
const { wasm } = compile(source, 'shop.tin')

const program = await instantiate(wasm, {
  write: (text) => process.stdout.write(text),           // a page appends to an element instead
  input: async (prompt) => {                             // a page shows a text field
    process.stdout.write(prompt + 'grace\n')
    return 'grace'
  },
  approve: async (tool, args) => {                       // a page shows a dialog
    const ok = args.cents <= 500
    console.log(`  [host] ${tool}(${JSON.stringify(args)}) -> ${ok ? 'allowed' : 'denied'}`)
    return ok
  },
})

try {
  await program.run()
} catch (e) {
  console.log('error: ' + describeError(e))
}
```

<!-- output -->
```text
your name: grace
hello, grace
  price {"item":"tin cup"}
mock: 450
  charge {"cents":450}
  [host] charge({"cents":450}) -> allowed
mock: charged 450 cents
```

This host lets a charge through only up to 500 cents. That rule lives in JavaScript, outside the program.

A web page runs the same code in a Web Worker, so the page stays responsive and a Stop button can end the
worker. `input` and `approve` become messages that show a text field and a dialog.
[docs/HOST-API.md](https://github.com/cagataycali/tin/blob/main/docs/HOST-API.md) has the full
options, a worker and page pair, and `fetchModels`, the provider a browser uses.

## What a host can't change

A host chooses who approves, but it can't widen what a program may do. The compiler's capability checks
(chapter 19) happen before anything runs. An ordinary tool still can't reach a guarded one, whatever
`approve` returns. Agent-written code (chapter 22) still runs in its own instance with a step budget.
And with no `approve` at all, the default is to deny.

## Tasks

### Task 1: A host that says no

Write a host for `shop.tin` that never approves anything and, at the end, prints how many times it
was asked.

**Solution

*task-1.solution.host.mjs · node task-1.solution.host.mjs*

```tin
// A host that never approves anything, and counts how often it was asked.
import { readFileSync } from 'node:fs'
import { compile } from '../../../src/compiler.ts'
import { instantiate } from '../../../src/runtime.ts'

const source = readFileSync(new URL('./shop.tin', import.meta.url), 'utf8')
let asked = 0
const program = await instantiate(compile(source, 'shop.tin').wasm, {
  write: (text) => process.stdout.write(text),
  input: async () => 'anonymous',
  approve: async () => (asked++, false),
})
await program.run()
console.log(`asked ${asked} time(s), approved none`)
```

<!-- output -->
```text
hello, anonymous
  price {"item":"tin cup"}
mock: 450
  charge {"cents":450}
mock: error: Tool call denied by the user. Do not retry it; continue without it.
asked 1 time(s), approved none
```

The program still finishes. A denied call goes back to the model as a refusal (chapter 18), so
the agent's reply says so.

### Task 2: One program, many customers

Write a host that runs `shop.tin` once each for `ada`, `grace` and
`linus`, answering `input()` with the name. Approve every charge except linus's, and print
the last line of output for each.

**Solution

*task-2.solution.host.mjs · node task-2.solution.host.mjs*

```tin
// A host that runs shop.tin once per customer, answering input() from a list.
import { readFileSync } from 'node:fs'
import { compile } from '../../../src/compiler.ts'
import { instantiate } from '../../../src/runtime.ts'

const { wasm } = compile(readFileSync(new URL('./shop.tin', import.meta.url), 'utf8'), 'shop.tin')

for (const name of ['ada', 'grace', 'linus']) {
  let out = ''
  const program = await instantiate(wasm, {   // a fresh instance each time: no state carries over
    write: (text) => (out += text),
    input: async () => name,
    approve: async () => name !== 'linus',      // linus's card was declined
  })
  await program.run()
  console.log(`${name}: ${out.trimEnd().split('\n').pop()}`)
}
```

<!-- output -->
```text
ada: mock: charged 450 cents
grace: mock: charged 450 cents
linus: mock: error: Tool call denied by the user. Do not retry it; continue without it.
```

Compile once, instantiate once per run. Each instance starts fresh, so the agent's conversation
doesn't carry over from one customer to the next.

## Where to go from here

That's the whole tutorial. You can now write Tin programs, give agents tools and typed replies, keep them safe
with guarded tools and capabilities, test them with tapes, and run them in a terminal or a page. Next:

- the [reference](https://tin.ad/docs/ref/), when you need the exact rules;
- the [examples](https://tin.ad/docs/examples/), for larger programs;
- the [playground](https://tin.ad/docs/play/), to try your own ideas.

## Recap

- The compiler and your program run in the tab as WebAssembly.
- Agents in a page need Chrome or Edge 137 or newer.
- A host decides where output goes and who approves, but cannot widen what a program may do.

In the reference: [Using the compiler from JavaScript](https://tin.ad/docs/ref/cli/#embed) · [Models](https://tin.ad/docs/ref/agents/#models)
