# Build an AI product in a day

A tutorial from an empty folder to a deployed AI product on Cloudflare: a booking desk with capabilities, an MCP door, an AI task with evals, a chat that takes bookings, a copilot page and a workflow with an approval, each step tested.

Source: https://docs.omazy.ai/build-on-omazy/tutorial-ai-product-in-a-day/

:::caution[Preview]
This page needs `@omazyai/sdk` 0.5.2 or later. The kits and `create-omazy-app` shipped in 0.5.0,
but the scaffold this page builds on (the code step-up, `actor_confirm`, the setup that builds the
page) is new in 0.5.2. Every command and code block on this page was run end to end on the build
that became 0.5.2, then deployed to Cloudflare and called over HTTPS.
:::

You will build **Booking Desk**: the front desk of a small bike workshop. People book a tune-up,
a repair or a bike fitting in one-hour slots. By the end it has:

- three actions defined once, with honest risk tiers, served as an MCP door that Claude Code,
  Claude Desktop or any MCP client can call;
- an AI task that turns a customer's message into a booking, with an eval set you run against a
  fake model and then the live one;
- a chat that collects a booking and ends with a card the person confirms;
- a copilot page with consent cards and standing grants;
- a workflow that cancels a booking and refunds the deposit after the owner approves;
- a deploy on your Cloudflare account, with the door off until you turn it on.

Each step ends with something that works and a test that proves it. Pick your own domain if you
like: a support desk or a class schedule follows the same steps with different nouns.

You need Node 20 or later, a Cloudflare account, `jq` for the shell examples, and an Omazy
workspace you own.

## 1. Scaffold, install and test

Scaffold from the 0.5.3 release. `create-omazy-app` is not on npmjs.com yet, so `npx` runs it
from its release tarball, and the project it writes pins the SDK to the release tarball of the
same version:

```sh
npx https://github.com/omazyai/omazy-sdk/releases/download/v0.5.3/create-omazy-app-0.5.3.tgz booking-desk --preset full --yes
```

To build on the SDK's `main` instead, build both from the
[SDK repository](https://github.com/omazyai/omazy-sdk) and pass the SDK tarball with `--sdk`:

```sh
(cd omazy-sdk/typescript && npm install && npm run build && npm pack --pack-destination /tmp/sdk)
node omazy-sdk/create-omazy-app/bin/create-omazy-app.mjs booking-desk --preset full --sdk /tmp/sdk/omazyai-sdk-*.tgz --yes
```

The tarball carries the version in its name, so keep `/tmp/sdk` to one of them.

Then:

```sh
cd booking-desk
git init
npm install
npm run check
```

`npm run check` typechecks and runs the tests: parity, the tier snapshot, approvals, tenant
isolation, the MCP door end to end and the injection suite. All pass before you change a line. The
first run writes `catalog.snapshot.json`; commit it with everything else.

`--preset full` wires every kit around a small notes sample: `note_get`, `note_add`, a task, an
actor, a workflow and a copilot. Leave it in place. You add the booking desk beside it, step by
step, and it shows the shape of each kit while you work. Delete the notes files once your own
code covers the same ground.

## 2. A token and the Worker's secrets

The AI parts call Omazy's models through the Core API with an **install token**. A workspace
owner creates one in the console under **Settings**, **API tokens**: see
[Authentication](/reference/core-api/authentication/#getting-one). Give it `ai:complete`. Add
`ai:configure` if you will set spending caps from code in step 9.

For local runs, put it in `.dev.vars`, which git ignores:

```sh
# .dev.vars
OMAZY_TOKEN=cai_...
```

`wrangler.jsonc` already points the Worker at the Core API, `https://mw.omazy.ai/api/v1/core`.
A project scaffolded with 0.5.1 or earlier has `OMAZY_BASE_URL` without `/core`, and every model
call answers 404 (`Cannot POST /api/v1/ai/complete`). Add `/core` if yours does.

`GUARD_SECRET` is already in `.dev.vars`: it signs the guard's confirm tokens and seals approvals.
The deployed Worker gets its own in step 9. The tests never need a token: they run on a fake Core
API.

## 3. Your first capability

A capability is one action your product offers, defined once. The MCP door, the copilot, the
actors and the workflows all call it through the guard, and the tier you give it decides what the
guard asks for:

| Tier | Means | The guard |
|---|---|---|
| R0 | A read with no personal data | Runs it |
| R1 | A read with personal data | Runs it and masks the personal fields |
| R2 | A change inside your product that can be undone | Shows the preview and waits for the person's confirm |
| R3 | Money, messages, anything that leaves your product or is hard to undo | Holds it for an approval |

The booking desk starts with three:

| Capability | Tier | Why |
|---|---|---|
| `slot_list` | R0 | Open hours on a day. No one's data |
| `booking_get` | R1 | Holds the customer's name |
| `booking_create` | R2 | A booking stays inside the workshop and can be cancelled |

### The table and the store

Add a migration after the kits' ones:

```sql
-- migrations/0007_bookings.sql
-- The booking desk's own table. Times are the workshop's local time.
CREATE TABLE bookings (
  id TEXT PRIMARY KEY,
  tenant TEXT NOT NULL,
  customer TEXT NOT NULL,
  service TEXT NOT NULL,
  date TEXT NOT NULL,
  time TEXT NOT NULL,
  deposit_cents INTEGER NOT NULL,
  status TEXT NOT NULL DEFAULT 'booked',
  refunded INTEGER NOT NULL DEFAULT 0,
  created_at TEXT NOT NULL
);

-- One standing booking per hour in a tenant.
CREATE UNIQUE INDEX bookings_one_per_hour ON bookings (tenant, date, time) WHERE status = 'booked';
```

The partial unique index is what stops two people booking the same hour at once. The store reads
and writes that table in D1, and keeps rows in memory for tests:

```ts
// src/bookings.ts
// The booking desk's own data: a bike workshop's bookings, per tenant.
// Services and opening hours are code; bookings are rows in D1, and in
// memory for tests.

import type { D1DatabaseLike } from '@omazyai/sdk/guard'

export const SERVICES = {
  tune_up: { title: 'Tune-up', depositCents: 2000 },
  repair: { title: 'Repair', depositCents: 1000 },
  fitting: { title: 'Bike fitting', depositCents: 3000 },
} as const
export type Service = keyof typeof SERVICES
export const SERVICE_NAMES = Object.keys(SERVICES) as [Service, ...Service[]]

/** One-hour slots. The workshop is open Monday to Saturday. */
export const HOURS = ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00'] as const
export type Hour = (typeof HOURS)[number]

/** Why nobody can book on a day, or null when the workshop is open. */
export function closedOn(date: string): string | null {
  const d = new Date(`${date}T00:00:00Z`)
  if (Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== date) return `${date} is not a date.`
  if (d.getUTCDay() === 0) return 'The workshop is closed on Sundays.'
  return null
}

export interface Booking {
  id: string
  customer: string
  service: Service
  date: string
  time: Hour
  depositCents: number
  status: 'booked' | 'cancelled'
  refunded: boolean
}

export interface NewBooking {
  customer: string
  service: Service
  date: string
  time: Hour
}

export interface BookingsStore {
  get(tenant: string, id: string): Promise<Booking | null>
  /** The hours already booked on a day. */
  taken(tenant: string, date: string): Promise<string[]>
  /** Adds a booking. Null when someone booked the hour first. */
  create(tenant: string, b: NewBooking): Promise<Booking | null>
  cancel(tenant: string, id: string): Promise<void>
  markRefunded(tenant: string, id: string): Promise<void>
  /** The tenant a booking belongs to, for the guard's tenant check. */
  tenantOf(id: string): Promise<string | null>
  /** Every row, so a test can see whether anything was written. */
  count(): Promise<number>
}

const newId = () => `b_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`

interface Row {
  id: string
  tenant: string
  customer: string
  service: Service
  date: string
  time: Hour
  deposit_cents: number
  status: 'booked' | 'cancelled'
  refunded: number
}

const fromRow = (r: Row): Booking => ({
  id: r.id,
  customer: r.customer,
  service: r.service,
  date: r.date,
  time: r.time,
  depositCents: r.deposit_cents,
  status: r.status,
  refunded: r.refunded === 1,
})

const rowOf = (tenant: string, b: NewBooking): Row => ({
  id: newId(),
  tenant,
  ...b,
  deposit_cents: SERVICES[b.service].depositCents,
  status: 'booked',
  refunded: 0,
})

export function d1Bookings(db: D1DatabaseLike): BookingsStore {
  const q = (sql: string, ...bind: unknown[]) => db.prepare(sql).bind(...bind)
  return {
    async get(tenant, id) {
      const r = await q('SELECT * FROM bookings WHERE tenant = ? AND id = ?', tenant, id).first<Row>()
      return r ? fromRow(r) : null
    },
    async taken(tenant, date) {
      const rs = await q("SELECT time FROM bookings WHERE tenant = ? AND date = ? AND status = 'booked'", tenant, date).all<{ time: string }>()
      return (rs.results ?? []).map((r) => r.time)
    },
    async create(tenant, b) {
      const r = rowOf(tenant, b)
      const res = await q(
        'INSERT OR IGNORE INTO bookings (id, tenant, customer, service, date, time, deposit_cents, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
        r.id, tenant, r.customer, r.service, r.date, r.time, r.deposit_cents, new Date().toISOString(),
      ).run()
      return res.meta?.changes ? fromRow(r) : null
    },
    async cancel(tenant, id) {
      await q("UPDATE bookings SET status = 'cancelled' WHERE tenant = ? AND id = ?", tenant, id).run()
    },
    async markRefunded(tenant, id) {
      await q('UPDATE bookings SET refunded = 1 WHERE tenant = ? AND id = ?', tenant, id).run()
    },
    async tenantOf(id) {
      return (await q('SELECT tenant FROM bookings WHERE id = ?', id).first<{ tenant: string }>())?.tenant ?? null
    },
    async count() {
      return (await q('SELECT COUNT(*) AS n FROM bookings').first<{ n: number }>())?.n ?? 0
    },
  }
}

export function memoryBookings(): BookingsStore & { rows: Row[] } {
  const rows: Row[] = []
  const find = (tenant: string, id: string) => rows.find((r) => r.tenant === tenant && r.id === id)
  return {
    rows,
    async get(tenant, id) {
      const r = find(tenant, id)
      return r ? fromRow(r) : null
    },
    async taken(tenant, date) {
      return rows.filter((r) => r.tenant === tenant && r.date === date && r.status === 'booked').map((r) => r.time)
    },
    async create(tenant, b) {
      if (rows.some((r) => r.tenant === tenant && r.date === b.date && r.time === b.time && r.status === 'booked')) return null
      const r = rowOf(tenant, b)
      rows.push(r)
      return fromRow(r)
    },
    async cancel(tenant, id) {
      const r = find(tenant, id)
      if (r) r.status = 'cancelled'
    },
    async markRefunded(tenant, id) {
      const r = find(tenant, id)
      if (r) r.refunded = 1
    },
    async tenantOf(id) {
      return rows.find((r) => r.id === id)?.tenant ?? null
    },
    async count() {
      return rows.length
    },
  }
}
```

### The capabilities

In `src/capabilities.ts`, import the booking helpers and add the three definitions above the
registry:

```ts
import { closedOn, HOURS, SERVICE_NAMES, SERVICES } from './bookings'

const day = () => schema.string({ format: 'date' }).describe('The day, as YYYY-MM-DD.')
const hour = () => schema.enum(HOURS).describe('The start of a one-hour slot, from 09:00 to 16:00.')

export const slotList = capability({
  name: 'slot_list',
  audiences: ['app'],
  title: 'List open times',
  description: 'Lists the one-hour slots still open on one day at the workshop. Every service takes one slot. Not for booking a slot: use booking_create.',
  synonyms: ['free times', 'availability', 'when can I come'],
  permission: 'bookings.read',
  risk: 'R0',
  input: schema.object({ date: day() }),
  output: schema.object({ date: schema.text(10), open: schema.array(schema.text(5)), closed: schema.text(200).optional() }),
  version: 1,
  run: async (ctx, input) => {
    const closed = closedOn(input.date)
    if (closed) return { date: input.date, open: [], closed }
    const taken = await live.bookings().taken(ctx.tenant ?? '', input.date)
    return { date: input.date, open: HOURS.filter((h) => !taken.includes(h)) }
  },
  say: (out) => out.closed ?? (out.open.length ? `Open on ${out.date}: ${out.open.join(', ')}.` : `Nothing is open on ${out.date}.`),
})

const bookingOut = schema.object({
  id: schema.id(),
  customer: schema.text(80),
  service: schema.enum(SERVICE_NAMES),
  date: schema.text(10),
  time: schema.text(5),
  deposit_cents: schema.integer({ min: 0 }),
  status: schema.enum(['booked', 'cancelled']),
  refunded: schema.boolean(),
})

export const bookingGet = capability({
  name: 'booking_get',
  audiences: ['app'],
  title: 'Get a booking',
  description: "Reads one booking of this workshop by its id: the customer's name, the service, the day and hour, the deposit and whether it stands. Not for open times: use slot_list.",
  synonyms: ['show a booking', 'look up a booking'],
  permission: 'bookings.read',
  // The customer's name is personal data, so this read is R1, not R0.
  risk: 'R1',
  input: schema.object({ booking_id: schema.id().describe('The booking id, such as b_3f9a1c2b7d4e.') }),
  output: bookingOut,
  pii: ['customer'],
  version: 1,
  run: async (ctx, input) => {
    const b = await live.bookings().get(ctx.tenant ?? '', input.booking_id)
    if (!b) throw new GuardRefusal('not_found', 'not_found', `There is no booking ${input.booking_id} in this workshop.`)
    return { id: b.id, customer: b.customer, service: b.service, date: b.date, time: b.time, deposit_cents: b.depositCents, status: b.status, refunded: b.refunded }
  },
  say: (out) => `Booking ${out.id}: ${out.service} on ${out.date} at ${out.time}, ${out.status}.`,
})

/** Refuses a closed day or a taken hour, the same way for the preview and the run. */
async function checkSlot(tenant: string, date: string, time: string): Promise<void> {
  const closed = closedOn(date)
  if (closed) throw new GuardRefusal('invalid', 'closed', closed)
  if ((await live.bookings().taken(tenant, date)).includes(time)) throw new GuardRefusal('stale', 'slot_taken', `${date} at ${time} is already booked. Ask slot_list for open times.`)
}

export const bookingCreate = capability({
  name: 'booking_create',
  audiences: ['app'],
  title: 'Book a slot',
  description: 'Books one service for a customer in a one-hour slot and returns the booking id. The person confirms the preview first. Not for changing a booking: cancel it and book again.',
  synonyms: ['make a booking', 'book in', 'reserve a time'],
  permission: 'bookings.write',
  // A booking stays inside the workshop and can be cancelled, so R2: the person confirms it.
  risk: 'R2',
  input: schema.object({
    customer: schema.text(80).describe("The customer's name."),
    service: schema.enum(SERVICE_NAMES).describe('tune_up, repair or fitting.'),
    date: day(),
    time: hour(),
  }),
  output: schema.object({ id: schema.id(), date: schema.text(10), time: schema.text(5), deposit_cents: schema.integer({ min: 0 }) }),
  pii: ['customer'],
  version: 1,
  preview: async (ctx, input) => {
    await checkSlot(ctx.tenant ?? '', input.date, input.time)
    const s = SERVICES[input.service]
    return {
      summary: `Book a ${s.title.toLowerCase()} for ${input.customer} on ${input.date} at ${input.time}, with a deposit of ${(s.depositCents / 100).toFixed(2)}.`,
      after: input,
      // The confirm is refused as stale if the hour is booked in between.
      stateVersion: `${input.date} ${input.time} free`,
    }
  },
  run: async (ctx, input) => {
    await checkSlot(ctx.tenant ?? '', input.date, input.time)
    const b = await live.bookings().create(ctx.tenant ?? '', input)
    if (!b) throw new GuardRefusal('stale', 'slot_taken', `${input.date} at ${input.time} was booked a moment ago.`)
    return { id: b.id, date: b.date, time: b.time, deposit_cents: b.depositCents }
  },
  say: (out) => `Booked ${out.id} on ${out.date} at ${out.time}.`,
})
```

Then add them to the registry, and name the argument that points at a booking so the guard can
check its tenant:

```ts
export const reg = registry([
  noteGet,
  noteAdd,
  slotList,
  bookingGet,
  bookingCreate,
  followupStart,
  ...intakeTools,
])

/** The arguments that name a booking. */
export const BOOKING_FIELDS = ['booking_id'] as const
```

Three things in there do real work:

- `pii: ['customer']` on the R1 read: a client sees `[redacted]` in place of the name.
- `stateVersion` on the preview: if someone books the hour between the preview and the confirm,
  the confirm is refused as stale instead of double booking.
- `checkSlot` runs in both the preview and the run, so a Sunday or a taken hour is refused before
  the person is ever asked to confirm.

### Wire the store

The app reaches the store through `live`, so the registry can be defined before the database
exists. Five small edits:

```ts
// src/types.ts
export type Permission = 'notes.read' | 'notes.write' | 'bookings.read' | 'bookings.write'

// src/access.ts
  member: ['notes.read', 'notes.write', 'bookings.read', 'bookings.write'],

// src/live.ts: import BookingsStore, then beside notes
  bookings?: BookingsStore
  bookings: () => need(held.bookings, 'the bookings store'),

// src/app.ts: import BookingsStore, add it to AppParts, and set it
  bookings: BookingsStore
  live.set({ notes: p.notes, bookings: p.bookings })

// src/index.ts: import d1Bookings, and in buildApp's parts
    bookings: d1Bookings(env.DB),
```

In `src/guard.ts`, import `BOOKING_FIELDS` and add a second loop to `tenantsOf`, after the notes
one:

```ts
      for (const f of BOOKING_FIELDS) {
        const id = args[f]
        if (typeof id !== 'string') continue
        const t = await live.bookings().tenantOf(id)
        if (t) tenants.push(t)
      }
```

In `test/helpers.ts`, import `memoryBookings`, create `const bookings = memoryBookings()` beside
`notes`, and pass `bookings` to `buildApp` and in the returned object.

### Test it

`test/catalog.test.ts` already checks tenant isolation for every capability. Give it a booking in
another tenant and the arguments that name it:

```ts
    const booking = await h.bookings.create('tenant_b', { customer: 'Tenant B only', service: 'repair', date: '2026-12-01', time: '10:00' })
    // in args:
        booking_get: { booking_id: booking!.id },
    // in skip, because they name no record:
        'slot_list',
        'booking_create',
    // and count both tables:
      effects: async () => (await h.notes.count()) + (await h.bookings.count()),
```

And a test of your own on the door:

```ts
// test/bookings.test.ts
// The booking desk on the MCP door: open times, a booking that waits for the
// person's confirm, the masked R1 read, and a taken hour.

import { describe, expect, test } from 'vitest'
import { harness } from './helpers'

const call = (name: string, args: unknown) => ({ name, arguments: args })
const TUESDAY = { customer: 'Ada Park', service: 'tune_up', date: '2026-12-01', time: '10:00' }

describe('bookings', () => {
  test('books a slot only after the person confirms the preview', async () => {
    const h = harness()
    const key = await h.mint()
    const first = await h.rpc('tools/call', call('booking_create', TUESDAY), key)
    const outcome = first.body.result._meta['ai.omazy/outcome']
    expect(outcome.status).toBe('confirm_required')
    expect(await h.bookings.count()).toBe(0)
    const second = await h.rpc('tools/call', call('booking_create', { ...TUESDAY, confirm_token: outcome.confirm_token }), key, 2)
    expect(second.body.result.isError).toBe(false)
    const open = await h.rpc('tools/call', call('slot_list', { date: '2026-12-01' }), key, 3)
    expect(open.body.result.structuredContent.open).not.toContain('10:00')
  })

  test('masks the customer name on the R1 read', async () => {
    const h = harness()
    const key = await h.mint()
    const b = await h.bookings.create('tenant_a', { customer: 'Ada Park', service: 'repair', date: '2026-12-01', time: '11:00' })
    const r = await h.rpc('tools/call', call('booking_get', { booking_id: b!.id }), key)
    expect(r.body.result.isError).toBe(false)
    expect(JSON.stringify(r.body)).not.toContain('Ada Park')
  })

  test('refuses a taken hour and a Sunday before any confirm', async () => {
    const h = harness()
    const key = await h.mint()
    await h.bookings.create('tenant_a', { customer: 'Ben Ode', service: 'repair', date: '2026-12-01', time: '10:00' })
    const taken = await h.rpc('tools/call', call('booking_create', TUESDAY), key)
    expect(taken.body.result.isError).toBe(true)
    const sunday = await h.rpc('tools/call', call('booking_create', { ...TUESDAY, date: '2026-11-29' }), key, 2)
    expect(sunday.body.result.isError).toBe(true)
    expect(await h.bookings.count()).toBe(1)
  })
})
```

Run it:

```sh
npm run check
```

The tier snapshot fails, on purpose:

```
x booking_create added: Book a slot (R2; app); update the snapshot once reviewed
x booking_get added: Get a booking (R1; app); update the snapshot once reviewed
x slot_list added: List open times (R0; app); update the snapshot once reviewed
```

Nothing changes a tier without someone reading it. Read the three lines, then accept them:

```sh
OMAZY_UPDATE_SNAPSHOTS=1 npm test
npm run check
git add -A && git commit -m "Booking desk: three capabilities"
```

## 4. Open the MCP door

```sh
npm run migrate                                        # the tables, in local D1
KEY=$(npm run --silent key -- --person rina --tenant demo)
npm run dev                                            # in a second terminal
```

The key is Rina's seat at the front desk of the `demo` workshop. It reaches R2 at most, lasts 30
days by default, and only its hash is stored.

### With curl

```sh
mcp() { curl -s localhost:8787/mcp -H "authorization: Bearer $KEY" -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' -H 'mcp-protocol-version: 2025-06-18' -d "$1"; echo; }

mcp '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jq '[.result.tools[].name]'
mcp '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"slot_list","arguments":{"date":"2026-12-01"}}}'
```

Book a slot. The first call books nothing: it answers with the preview and a confirm token.

```sh
BOOK='{"customer":"Ada Park","service":"tune_up","date":"2026-12-01","time":"10:00"}'
TOKEN=$(mcp '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"booking_create","arguments":'"$BOOK"'}}' \
  | jq -r '.result._meta["ai.omazy/outcome"].confirm_token')
mcp '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"booking_create","arguments":'"$(echo "$BOOK" | jq -c --arg t "$TOKEN" '. + {confirm_token: $t}')"'}}'
```

```json
{"result":{"content":[{"type":"text","text":"Booked b_55ad8760ed0a on 2026-12-01 at 10:00."}],"structuredContent":{"id":"b_55ad8760ed0a","date":"2026-12-01","time":"10:00","deposit_cents":2000},"isError":false},"jsonrpc":"2.0","id":4}
```

The first answer has `isError: true` and says "Not done yet: this needs the person's
confirmation". That is deliberate: a model that skims results cannot mistake a preview for a
booking. A client shows the person the preview's summary, and calls again only when they agree.

### With the MCP inspector

```sh
npx @modelcontextprotocol/inspector --cli http://localhost:8787/mcp --transport http \
  --header "Authorization: Bearer $KEY" \
  --method tools/call --tool-name booking_get --tool-arg booking_id=b_55ad8760ed0a
```

The answer has `"customer": "[redacted]"`: the R1 mask at work. Leave out `--cli` for the
inspector's browser window.

### With Claude Code or Claude Desktop

```sh
claude mcp add --transport http booking-desk http://localhost:8787/mcp --header "Authorization: Bearer $KEY"
claude mcp get booking-desk          # Status: Connected
```

Ask Claude "what is open on 1 December 2026?", then "book Ben Ode for a repair at 11". Claude
shows you the preview and asks before it confirms. For Claude Desktop, add the same URL and header
as a custom connector.

Every call, refused or not, is in the request log in D1, written by the guard.

## 5. An AI task with evals

A task is one model call with a manifest: a model **role** (never a model name), a versioned
prompt, a context recipe, spend caps, the capability its output is saved through, and an eval
set. This one reads a customer's message and drafts a booking. Its output is `booking_create`'s
input, so saving it goes through the guard and waits for a confirm like any other booking.

In `src/ai.ts`, import `HOURS` and `SERVICE_NAMES` from `./bookings`, and add:

```ts
/**
 * Reads a customer's message and drafts a booking. Its output is
 * booking_create's input, saved through that R2 capability, so the booking
 * waits for a person to confirm the preview.
 */
export const bookingRequest = task({
  id: 'booking_request',
  version: 1,
  owner: 'booking_desk',
  model: { use: 'extract.fast', fallback: 'extract.strong', temperature: 0, maxOutputTokens: 200 },
  prompt: { template: 'tasks/booking-request', version: 1, languages: ['en'] },
  context: { layers: ['platform', 'unit'], budgetTokens: 4000, untrusted: ['message'] },
  memory: { read: [], write: [] },
  input: schema.object({ message: schema.text(2000) }),
  output: schema.object({
    customer: schema.text(80),
    service: schema.enum(SERVICE_NAMES),
    date: schema.string({ format: 'date' }),
    time: schema.enum(HOURS),
  }),
  target: 'booking_create',
  tools: { allow: [], maxTier: 'R0' },
  evals: { path: 'evals/booking-request.jsonl', threshold: 0.9 },
  caps: { perRunUsd: 0.01, perDayUsd: 1 },
})
```

Add its prompt to `PROMPTS`:

```ts
  'tasks/booking-request': {
    1: {
      en: 'A customer wrote to a bike workshop. Fill in the booking they ask for: their name; the service, which is tune_up for a service or tune-up, repair for anything broken, and fitting for a bike fit; the date as YYYY-MM-DD; and the start hour as HH:00 in 24-hour time.',
    },
  },
```

`extract.fast` is a role. The account maps it to a model, and `fallback` is tried once if that
model fails. The customer's message is listed as untrusted, so it goes in a fenced turn of its
own, never into the prompt.

### The eval set

One case a line: the input, what should come out, and the reply the fake model gives.

```json
// evals/booking-request.jsonl
// One customer message a line, the booking it should give, and the reply the fake Core API gives.
// Add real messages until there are at least 30; OMAZY_EVAL_LIVE=1 runs them against the live API.
{"id": "tune_up", "input": {"message": "Hi, this is Ada Park. Could I bring my bike in for a tune-up on 2 December 2026 at 10am?"}, "expected": {"customer": "Ada Park", "service": "tune_up", "date": "2026-12-02", "time": "10:00"}, "fake": {"output": {"customer": "Ada Park", "service": "tune_up", "date": "2026-12-02", "time": "10:00"}}}
{"id": "repair", "input": {"message": "My rear wheel is buckled. Ben Ode here, can you fix it on Friday 4 December 2026 at 2pm?"}, "expected": {"customer": "Ben Ode", "service": "repair", "date": "2026-12-04", "time": "14:00"}, "fake": {"output": {"customer": "Ben Ode", "service": "repair", "date": "2026-12-04", "time": "14:00"}}}
{"id": "fitting", "input": {"message": "I'd like a bike fit please. Name's Chloe Smith. Saturday 5 December 2026, 9 in the morning."}, "expected": {"customer": "Chloe Smith", "service": "fitting", "date": "2026-12-05", "time": "09:00"}, "fake": {"output": {"customer": "Chloe Smith", "service": "fitting", "date": "2026-12-05", "time": "09:00"}}}
{"id": "chain", "input": {"message": "The chain snapped on my way to work. Dev Rao. Is 7 December 2026 at 15:00 free?"}, "expected": {"customer": "Dev Rao", "service": "repair", "date": "2026-12-07", "time": "15:00"}, "fake": {"output": {"customer": "Dev Rao", "service": "repair", "date": "2026-12-07", "time": "15:00"}}}
{"id": "annual", "input": {"message": "Eli Moss here. My road bike is due its yearly service. 9 December 2026 at 1pm works for me."}, "expected": {"customer": "Eli Moss", "service": "tune_up", "date": "2026-12-09", "time": "13:00"}, "fake": {"output": {"customer": "Eli Moss", "service": "tune_up", "date": "2026-12-09", "time": "13:00"}}}
```

```ts
// test/booking-request.test.ts
// The booking_request task against its golden set, on the fake Core API.
// OMAZY_EVAL_LIVE=1 with OMAZY_TOKEN runs the same cases against the live API.

import { assertEval, evalCore, evalUnit, fakeCore, formatReport, jsonFields, loadGoldenSet, reply, schemaValid } from '@omazyai/sdk/testing'
import { describe, expect, test } from 'vitest'
import { bookingRequest } from '../src/ai'
import { harness } from './helpers'

describe('booking_request', () => {
  test('passes its eval set at its threshold', async () => {
    const fake = fakeCore({})
    const h = harness({ fake, core: evalCore({ fake }) })
    const report = await evalUnit(bookingRequest, {
      cases: await loadGoldenSet(bookingRequest),
      fake,
      run: (c) => h.app.ai.run(h.seat(), bookingRequest, c.input as { message: string }, { save: false }),
      scorers: [schemaValid(), jsonFields({ loose: true })],
    })
    console.log(formatReport(report))
    assertEval(report)
  }, 60_000)

  test('saves through booking_create, so the booking waits for a confirm', async () => {
    const h = harness()
    h.fake.on('booking_request', reply.json({ customer: 'Ada Park', service: 'tune_up', date: '2026-12-02', time: '10:00' }))
    const r = await h.app.ai.run(h.seat(), bookingRequest, { message: 'Ada Park, tune-up on 2 December 2026 at 10am' })
    expect(r.outcome).toBe('ok')
    if (r.outcome !== 'ok') return
    expect(r.save?.outcome).toBe('confirm_required')
    expect(await h.bookings.count()).toBe(0)
  })
})
```

In `test/catalog.test.ts`, import `bookingRequest` and add it to `units`, so the parity check
covers its prompt and target.

Against the fake:

```sh
npm run check
```

```
PASS booking_request v1 (prompt 1): 5/5 passed (100.0%), threshold 90.0%
  scorers: schema_valid 1.000, json_fields 1.000
  usage: 5 calls, $0.0003
  warning: 5 cases; a unit's golden set should hold at least 30
```

Against the live model, the same cases with your token:

```sh
export OMAZY_TOKEN=cai_...
export OMAZY_EVAL_LIVE=1
npx vitest run test/booking-request.test.ts
unset OMAZY_EVAL_LIVE
```

```
PASS booking_request v1 (prompt 1): 5/5 passed (100.0%), threshold 90.0%, live
  scorers: schema_valid 1.000, json_fields 1.000
  usage: 5 calls, $0.0037
  warning: 5 cases; a unit's golden set should hold at least 30
  warning: live run: the cases' fake replies were not used
```

The fake run proves the wiring; the live run proves the prompt. Five cases is a start, not a
golden set: add real messages until there are at least 30, and run the live evals before every
prompt change. A new prompt is a new version, so you can compare them.

## 6. Take a booking by chat

An actor turns a form into a conversation. Code owns the order of questions, every check, the
card and the submit. The model only reads what the person wrote into slot values. Its target is
`booking_create`, so nothing is booked until the person confirms the card.

In `src/actor.ts`, import `closedOn`, `SERVICE_NAMES` and `SERVICES` from `./bookings`, and add:

```ts
/**
 * Takes a booking by chat. Code asks for what is missing, checks the day and
 * the hour against slot_list, and ends with a card for booking_create (R2):
 * nothing is booked until the person confirms it.
 */
export const bookingIntake = actor<AppCtx>({
  id: 'booking_intake',
  version: 1,
  owner: 'booking_desk',
  target: 'booking_create',
  title: { en: 'Book a slot' },
  model: { use: 'extract.fast', fallback: 'extract.strong' },
  prompt: { template: 'actors/booking-intake', version: 1, languages: ['en'] },
  evals: 'evals/booking-intake.jsonl',
  caps: { perRunUsd: 0.02, perDayUsd: 2 },
  slots: [
    slot('customer', { label: { en: 'name' }, ask: { en: 'Who is the booking for?' } }),
    slot('service', {
      ask: { en: 'Which service: a tune-up, a repair or a bike fitting?' },
      choices: SERVICE_NAMES.map((id) => ({ id, label: SERVICES[id].title })),
    }),
    slot('date', {
      label: { en: 'day' },
      hint: 'The day, as YYYY-MM-DD.',
      ask: { en: 'Which day?' },
      validate: (v) => closedOn(String(v)) ?? true,
    }),
    slot('time', {
      label: { en: 'time' },
      after: ['date'],
      ask: { en: 'What time? We take bookings on the hour, from 09:00 to 16:00.' },
      check: {
        capability: 'slot_list',
        args: (_v, values) => ({ date: values.date }),
        ok: (r, v) => (r as { open: string[] }).open.includes(String(v)) || 'That hour is taken. Ask for another time.',
      },
    }),
  ],
})
```

The `time` slot waits for the date, then asks `slot_list` through the guard. A taken hour is asked
again; the model cannot talk its way past it.

Three edits put it to work:

```ts
// src/actor.ts, in intakeTools: serve it on the door
  actors: ['note_intake', 'booking_intake'],

// src/ai.ts, in PROMPTS: the kit's extractor prompt
  'actors/booking-intake': { 1: { en: EXTRACT_PROMPT } },

// src/app.ts: import bookingIntake, and run it
  const actors = actorRuntime<AppCtx>({ ai, registry: reg, guard, actors: [noteIntake, bookingIntake], sessions: p.sessions })
```

Add `bookingIntake.unit` to `units` in `test/catalog.test.ts`, and its eval set and test:

```json
// evals/booking-intake.jsonl
// The booking actor's conversations: the person's turns and what should come of them.
{"id": "one_turn", "input": {"turns": ["Ada Park, a tune-up on 2 December 2026 at 10:00"]}, "expected": {"slots": {"customer": "Ada Park", "service": "tune_up", "date": "2026-12-02", "time": "10:00"}, "state": "confirm"}, "fake": [{"output": {"items": [{"slot": "customer", "value": "Ada Park", "confidence": 0.95, "evidence": "Ada Park", "from": "message"}, {"slot": "service", "value": "tune_up", "confidence": 0.95, "evidence": "a tune-up", "from": "message"}, {"slot": "date", "value": "2026-12-02", "confidence": 0.95, "evidence": "2 December 2026", "from": "message"}, {"slot": "time", "value": "10:00", "confidence": 0.95, "evidence": "10:00", "from": "message"}]}}]}
```

```ts
// test/booking-intake.test.ts
// The booking_intake actor: it asks for what is missing, checks the hour with
// slot_list, and books only when the person confirms the card.

import { reply } from '@omazyai/sdk/testing'
import { describe, expect, test } from 'vitest'
import { harness } from './helpers'

const item = (slot: string, value: string) => ({ slot, value, confidence: 0.95, evidence: value, from: 'message' })

describe('booking_intake', () => {
  test('asks for the time, then shows a card, and books only on confirm', async () => {
    const h = harness()
    const ctx = h.seat()
    h.fake.on('booking_intake', reply.json({ items: [item('customer', 'Ada Park'), item('service', 'tune_up'), item('date', '2026-12-02')] }), { times: 1 })
    const r = await h.app.actors.start(ctx, 'booking_intake', { text: 'Ada Park wants a tune-up on 2 December 2026' })
    expect(r.state).not.toBe('confirm')
    expect(r.question?.slot).toBe('time')
    h.fake.on('booking_intake', reply.json({ items: [item('time', '10:00')] }), { times: 1 })
    const card = await h.app.actors.reply(ctx, r.session, { text: '10am' })
    expect(card.state).toBe('confirm')
    expect(await h.bookings.count()).toBe(0)
    const done = await h.app.actors.confirm(ctx, r.session, card.card!.id)
    expect(done.state).toBe('done')
    expect(await h.bookings.count()).toBe(1)
  })

  test('asks again when the hour is taken', async () => {
    const h = harness()
    const ctx = h.seat()
    await h.bookings.create('tenant_a', { customer: 'Ben Ode', service: 'repair', date: '2026-12-02', time: '10:00' })
    h.fake.on('booking_intake', reply.json({ items: [item('customer', 'Ada Park'), item('service', 'tune_up'), item('date', '2026-12-02'), item('time', '10:00')] }))
    const r = await h.app.actors.start(ctx, 'booking_intake', { text: 'Ada Park, tune-up, 2 December 2026 at 10:00' })
    expect(r.state).not.toBe('confirm')
    expect(r.question?.slot).toBe('time')
  })
})
```

`{ times: 1 }` makes each fake reply answer one turn. Without it the first reply answers every
turn.

`npm run check` now stops at the tier snapshot:

```
x actor_start changed: input actor values changed; update the snapshot once reviewed
```

The door's `actor_start` takes a new actor name, and its version moves from 1 to 2: the kit sets
it to the number of actors on the door, so adding one is an additive change. Accept it as in
step 3:

```sh
OMAZY_UPDATE_SNAPSHOTS=1 npm test
npm run check
```

On 0.5.1 or earlier the same edit fails as `actor_start breaking: schema changed but version is
still 1`. Before your first deploy, delete `catalog.snapshot.json` and run `npm run check` to
write it again.

### Try it live

Restart `npm run dev` so it reads the token, then talk to it over the door:

```sh
S=$(mcp '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"actor_start","arguments":{"actor":"booking_intake","text":"Hi, Ben Ode here. My wheel is buckled, can you repair it on 4 December 2026?"}}}' \
  | tee /dev/stderr | jq -r '.result.structuredContent.session')
mcp '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"actor_reply","arguments":{"session":"'"$S"'","text":"2pm please"}}}'
```

The first answer asks "What time? We take bookings on the hour, from 09:00 to 16:00." with the
open hours as choices. The second shows the card:

```
Book a repair for Ben Ode on 2026-12-04 at 14:00, with a deposit of 10.00. Please check every value and confirm.
```

Each row of the card says where its value came from ("2pm please"). Over MCP the answer's
`submit` names the call that books it: `actor_confirm`, with the session and the card id. It is
R2, so the guard asks the person first, with the same confirm as in step 4:

```sh
C=$(mcp '{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"actor_status","arguments":{"session":"'"$S"'"}}}' \
  | jq -c '.result.structuredContent.submit.arguments')
T=$(mcp '{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"actor_confirm","arguments":'"$C"'}}' \
  | jq -r '.result._meta["ai.omazy/outcome"].confirm_token')
mcp '{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"actor_confirm","arguments":'"$(echo "$C" | jq -c --arg t "$T" '. + {confirm_token: $t}')"'}}'
mcp '{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"actor_status","arguments":{"session":"'"$S"'"}}}' \
  | jq -r '.result.structuredContent.state'
# done
```

The booking is made and the session knows it: `actor_status` answers `done`. On 0.5.1 or earlier
`submit` names `booking_create` itself; the client can book with it, but the session never sees
the call and `actor_status` stays at `confirm`.

## 7. The copilot page

The full preset already serves a page at `/`: the ui kit's copilot panel, standing grants and the
approvals inbox. Give the copilot the booking tools and a prompt about the workshop:

```ts
// src/copilot.ts
  prompt: { template: 'copilot/notes', version: 2, languages: ['en'] },
  tools: {
    allow: [
      'note_get',
      'note_add',
      'note_followup_start',
      'slot_list',
      'booking_get',
      'booking_create',
    ],
    maxTier: 'R2',
  },
```

```ts
// src/ai.ts, in PROMPTS['copilot/notes'], beside version 1
    // A function template is rendered on every turn, so the date stays current.
    2: {
      en: () =>
        `You help the front desk of a bike workshop. Find open times with slot_list, read a booking with booking_get, and book with booking_create once you know the name, the service, the day and the hour. Today is ${new Date().toISOString().slice(0, 10)}. Answer in a few sentences.`,
    },
```

Change `PERSONA` in `src/ai.ts` to say the product is a bike workshop's front desk, and the
panel's `screen` in `src/page.ts` to `{ name: 'bookings' }`. Then the tests:

```ts
// test/booking-copilot.test.ts
// The copilot books through a consent card, and a standing grant lets it
// book without one, up to the grant's daily cap.

import { readUiChunks } from '@omazyai/sdk/copilot'
import { fakeCore, reply } from '@omazyai/sdk/testing'
import { describe, expect, test } from 'vitest'
import { harness } from './helpers'

const ADA = { customer: 'Ada Park', service: 'tune_up', date: '2026-12-02', time: '10:00' }

describe('the copilot books', () => {
  test('behind a consent card that only the click runs', async () => {
    const h = harness({ fake: fakeCore({ script: [reply.tool('booking_create', ADA), reply.text('I put up a card for you to confirm.')] }) })
    const ctx = h.seat('rina', 'tenant_a', 'copilot')
    const turn = await h.app.copilot.turn(ctx, { thread: 'th1', text: 'Book Ada Park in for a tune-up on 2 December 2026 at 10' })
    if (!turn.ok) throw new Error(turn.message)
    const chunks = await readUiChunks(turn.stream)
    await turn.done
    const card = chunks.find((c) => c.type === 'data-consent') as { data: { id: string; capability: string } } | undefined
    expect(card?.data.capability).toBe('booking_create')
    expect(await h.bookings.count()).toBe(0)
    expect((await h.app.copilot.confirm(ctx, { thread: 'th1', card: card!.data.id })).outcome).toBe('confirmed')
    expect(await h.bookings.count()).toBe(1)
  })

  test('without a card under a standing grant, once a day', async () => {
    const h = harness({
      fake: fakeCore({
        script: [
          reply.tool('booking_create', ADA),
          reply.text('Booked.'),
          reply.tool('booking_create', { ...ADA, time: '11:00' }),
          reply.text('That one needs your confirm.'),
        ],
      }),
    })
    // What the page's Standing grants section posts, on the console channel.
    const set = await h.app.ui.handle(
      new Request('https://app.test/ui/grants', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ capability: 'booking_create', days: 30, dailyCap: 1 }) }),
      h.seat('rina', 'tenant_a', 'console'),
    )
    expect(set?.status).toBe(200)
    const ctx = h.seat('rina', 'tenant_a', 'copilot')
    for (const thread of ['th1', 'th2']) {
      const turn = await h.app.copilot.turn(ctx, { thread, text: 'Book Ada Park in' })
      if (!turn.ok) throw new Error(turn.message)
      await readUiChunks(turn.stream)
      await turn.done
    }
    expect(await h.bookings.count()).toBe(1)
  })
})
```

### In the browser

Restart `npm run dev` and open `http://localhost:8787/`. Paste Rina's key to sign in; the page
keeps it for the tab only.

1. Ask: "Book Cara Lee in for a repair on 3 December 2026 at 11:00." The copilot checks the hour
   and answers with a **consent card** showing the preview. Nothing is booked yet. Click
   **Confirm** and it is.
2. Under **Standing permissions**, let the copilot run **Book a slot** for 30 days, 5 times a day.
3. Ask again for another customer. This time it books without a card, and the grant's count goes
   down by one.

A grant covers one R2 capability for one person in one workshop. It is set only from the page,
never by the copilot, never at R3, and a run counts only when the guard runs it.

The same routes answer without a browser, which is how the tests and a script drive them:
`POST /copilot/chat`, `POST /copilot/cards/<id>/confirm` and `POST /ui/grants`, each with the key
as a bearer token.

## 8. A workflow with an approval

Cancelling a booking is R2: it stays inside the workshop. Refunding the deposit sends money to
the customer, so it is R3 and the owner approves it. A workflow strings them together: read the
booking, cancel it, wait for the owner, refund, tell the customer.

### Two more capabilities

Add these to `src/capabilities.ts` and to the registry:

```ts
export const bookingCancel = capability({
  name: 'booking_cancel',
  audiences: ['app'],
  title: 'Cancel a booking',
  description: 'Cancels one standing booking and frees its hour. It does not refund the deposit: the booking_cancel_start workflow cancels and then asks the owner to approve the refund.',
  synonyms: ['call off a booking'],
  permission: 'bookings.write',
  risk: 'R2',
  input: schema.object({ booking_id: schema.id() }),
  output: schema.object({ id: schema.id(), status: schema.enum(['booked', 'cancelled']) }),
  version: 1,
  preview: async (ctx, input) => {
    const b = await live.bookings().get(ctx.tenant ?? '', input.booking_id)
    if (!b) throw new GuardRefusal('not_found', 'not_found', `There is no booking ${input.booking_id} in this workshop.`)
    if (b.status === 'cancelled') throw new GuardRefusal('stale', 'already_cancelled', `Booking ${b.id} is already cancelled.`)
    return { summary: `Cancel booking ${b.id}, ${b.service} on ${b.date} at ${b.time}.`, before: { status: b.status }, after: { status: 'cancelled' }, stateVersion: b.status }
  },
  run: async (ctx, input) => {
    await live.bookings().cancel(ctx.tenant ?? '', input.booking_id)
    return { id: input.booking_id, status: 'cancelled' as const }
  },
  say: (out) => `Cancelled ${out.id}.`,
})

export const depositRefund = capability({
  name: 'deposit_refund',
  audiences: ['app'],
  title: 'Refund a deposit',
  description: 'Refunds the deposit of one cancelled booking to the customer. Money leaves the workshop, so the owner approves it first. Not for cancelling: use booking_cancel.',
  synonyms: ['give the deposit back'],
  permission: 'bookings.write',
  // Money goes to someone outside the product and is hard to take back: R3, an approval.
  risk: 'R3',
  approval: 'owner_refund',
  input: schema.object({ booking_id: schema.id() }),
  output: schema.object({ id: schema.id(), refunded_cents: schema.integer({ min: 0 }) }),
  version: 1,
  preview: async (ctx, input) => {
    const b = await live.bookings().get(ctx.tenant ?? '', input.booking_id)
    if (!b) throw new GuardRefusal('not_found', 'not_found', `There is no booking ${input.booking_id} in this workshop.`)
    if (b.refunded) throw new GuardRefusal('stale', 'already_refunded', `The deposit of booking ${b.id} was already refunded.`)
    return { summary: `Refund the deposit of ${(b.depositCents / 100).toFixed(2)} for booking ${b.id}.`, stateVersion: `refunded ${b.refunded}` }
  },
  run: async (ctx, input) => {
    const b = await live.bookings().get(ctx.tenant ?? '', input.booking_id)
    if (b?.status !== 'cancelled') throw new GuardRefusal('stale', 'not_cancelled', `Booking ${input.booking_id} is not cancelled, so its deposit stays.`)
    // Call your payment provider here, with the booking id as its idempotency key.
    await live.bookings().markRefunded(ctx.tenant ?? '', input.booking_id)
    return { id: input.booking_id, refunded_cents: b?.depositCents ?? 0 }
  },
  say: (out) => `Refunded ${(out.refunded_cents / 100).toFixed(2)} for ${out.id}.`,
})
```

`approval: 'owner_refund'` names a policy. Define it in `src/guard.ts`, with a code the owner gets
before approving:

```ts
import { approver, createGuard, type Guard, type GuardStore, policies, type RequestLogSink, type StepUpVerifier, type SwitchStore } from '@omazyai/sdk/guard'

// in createGuard, in place of policies: {}
    // The owner approves a refund with a code sent to them.
    policies: { owner_refund: policies.single({ approver: approver.role('owner'), stepUp: 'code', expires: '24h' }) },
```

The scaffold already proves the decider with a code: `src/app.ts` builds the guard's
`codeStepUp` from the `sendCode` the Worker passes, and gives it to the guard.

A policy without a step-up is refused when it loads: a click alone is not a decision. Who is an
owner comes from `rolesOf` in `src/access.ts`:

```ts
const ROLE_PERMISSIONS: Readonly<Record<string, readonly Permission[]>> = {
  member: ['notes.read', 'notes.write', 'bookings.read', 'bookings.write'],
  owner: ['bookings.read', 'bookings.write'],
}

/** Who owns the workshop and decides refunds. Replace with your own members table. */
const OWNERS = new Set(['sam'])

export function rolesOf(ctx: AppCtx): readonly string[] {
  if (!ctx.seat?.tenant) return []
  return OWNERS.has(ctx.principal.id) ? ['member', 'owner'] : ['member']
}
```

### The workflow

Add to `src/flow.ts`, with `defineCapabilities` and `GuardRefusal` imported and
`const { capability } = defineCapabilities<AppCtx, Permission, Door>()` at the top:

```ts
/** Cancels a booking, then refunds its deposit once the owner approves. */
export const bookingCancelFlow = workflow({
  id: 'booking_cancel',
  version: 1,
  steps: [
    step.read('booking', 'booking_get', { args: (s) => ({ booking_id: s.input.booking_id }) }),
    // The person confirmed the cancel on booking_cancel_start's card.
    step.write('cancel', 'booking_cancel', { confirm: 'upstream', args: (s) => ({ booking_id: s.input.booking_id }) }),
    // R3: the run waits here until the owner approves or refuses.
    step.write('refund', 'deposit_refund', { when: (s) => s.booking.deposit_cents > 0, args: (s) => ({ booking_id: s.input.booking_id }) }),
    step.notify('tell', 'booking_cancelled', { data: (s) => ({ booking: s.input.booking_id }) }),
  ],
})

const runKey = (id: string, dry: boolean) => `cancel:${id}${dry ? ':dry' : ''}`

/** Starts the workflow. A dry run reports what it would do and changes nothing. */
export const cancelStart = capability({
  name: 'booking_cancel_start',
  audiences: ['app'],
  title: 'Cancel and refund a booking',
  description: 'Starts a workflow that cancels one booking and asks the owner to approve refunding its deposit. With dry_run it only reports what it would do. Not for a plain cancel without a refund: use booking_cancel.',
  permission: 'bookings.write',
  risk: 'R2',
  input: schema.object({ booking_id: schema.id(), dry_run: schema.boolean().default(false) }),
  output: schema.object({ key: schema.text(200), outcome: schema.text(20) }),
  version: 1,
  preview: (_ctx, input) => ({ summary: `${input.dry_run ? 'Dry run: report what would happen to' : 'Cancel'} booking ${input.booking_id}, and ask the owner to refund its deposit.` }),
  run: async (ctx, input) => {
    const key = runKey(input.booking_id, input.dry_run)
    const r = await live.flows().start(ctx, bookingCancelFlow, key, { input: { booking_id: input.booking_id }, mode: input.dry_run ? 'dry_run' : 'live' })
    return { key: r.key, outcome: r.outcome }
  },
  say: (out) => `Workflow ${out.key}: ${out.outcome}.`,
})

/** Where a cancel run stands: its status, each step, and a dry run's report. */
export const cancelStatus = capability({
  name: 'booking_cancel_status',
  audiences: ['app'],
  title: 'Check a cancel run',
  description: 'Reads where a cancel-and-refund workflow stands: its status, each step, the approval it waits for, and what a dry run would do. Not for starting one: use booking_cancel_start.',
  permission: 'bookings.read',
  risk: 'R0',
  input: schema.object({ booking_id: schema.id(), dry_run: schema.boolean().default(false) }),
  output: schema.object({ status: schema.text(20), report: schema.array(schema.text(400)), steps: schema.array(schema.object({ step: schema.text(80), status: schema.text(20), approval: schema.text(80).optional() })) }),
  version: 1,
  run: async (_ctx, input) => {
    const key = runKey(input.booking_id, input.dry_run)
    const run = await live.flows().run(key)
    if (!run) throw new GuardRefusal('not_found', 'not_found', `No cancel run for ${input.booking_id}.`)
    const steps = (await live.flows().steps(key)).map((s) => ({ step: s.key, status: s.status, ...(s.approvalId ? { approval: s.approvalId } : {}) }))
    return { status: run.status, report: run.report, steps }
  },
  say: (out) => `${out.status}: ${out.steps.map((s) => `${s.step} ${s.status}`).join(', ')}`,
})
```

In `src/capabilities.ts`, import `cancelStart` and `cancelStatus` from `./flow` beside
`followupStart`, and add both to the registry with the two capabilities above.

`confirm: 'upstream'` lets the cancel run without a second card, because the person confirmed it
when they started the run. The refund ignores that: R3 always waits for an approval. A dry run
reads, previews every write through the guard, and changes nothing.

### Wire it

```ts
// src/env.ts
  BOOKING_CANCEL: WorkflowBindingLike
```

In `src/index.ts`, import `bookingCancelFlow`, start it on its Workflow binding, and export the
entrypoint:

```ts
    starter: () => cloudflareStarter({ [noteFollowup.id]: env.NOTE_FOLLOWUP, [bookingCancelFlow.id]: env.BOOKING_CANCEL }),
```

```ts
export class BookingCancel extends flowEntrypoint(WorkflowEntrypoint, bookingCancelFlow, (env: Env) => appFor(env).flowDeps) {}
```

The code sender is already there: `sendCode` in `src/index.ts` prints the code to the
`wrangler dev` console, because the scaffolder put `STEP_UP_LOG=1` in `.dev.vars`. The page's
routes already serve `POST /ui/approvals/<id>/code`, which sends it.

In `wrangler.jsonc`, add the Workflow beside the notes one:

```jsonc
    {
      "name": "booking-desk-booking-cancel",
      "binding": "BOOKING_CANCEL",
      "class_name": "BookingCancel"
    }
```

A project scaffolded with 0.5.1 or earlier has none of this: no `sendCode`, no `codes` and no
code route. Scaffold a fresh project and move your files over, or copy `src/app.ts`,
`src/guard.ts`, `src/index.ts`, `src/page.ts` and `test/helpers.ts` from one.

### Test it

In `test/helpers.ts`, run the new workflow on the memory runner:

```ts
    starter: (deps) => (runner = memoryRunner(deps, [noteFollowup, bookingCancelFlow])),
```

The harness already catches each approval code the way a mail sender would, in `h.codes`. Then:

```ts
// test/booking-cancel.test.ts
// The cancel-and-refund workflow: a dry run changes nothing; a live run
// cancels, waits for the owner's approval of the refund, then refunds.

import { describe, expect, test } from 'vitest'
import { harness } from './helpers'

describe('booking_cancel', () => {
  test('a dry run reports and changes nothing', async () => {
    const h = harness()
    const ctx = h.seat('rina', 'tenant_a')
    const b = await h.bookings.create('tenant_a', { customer: 'Ada Park', service: 'tune_up', date: '2026-12-02', time: '10:00' })
    const first = await h.app.guard.call(ctx, 'booking_cancel_start', { booking_id: b!.id, dry_run: true })
    if (first.outcome !== 'confirm_required') throw new Error(first.outcome)
    await h.app.guard.call(ctx, 'booking_cancel_start', { booking_id: b!.id, dry_run: true }, { confirmToken: first.token })
    await h.runner().idle()
    const run = await h.app.flows.run(`cancel:${b!.id}:dry`)
    expect(run?.report.join('\n')).toContain('Cancel booking')
    expect(run?.report.join('\n')).toContain('Refund the deposit')
    expect((await h.bookings.get('tenant_a', b!.id))?.status).toBe('booked')
  })

  test('live, the refund waits for the owner and runs on their approval', async () => {
    const h = harness()
    const rina = h.seat('rina', 'tenant_a')
    const b = await h.bookings.create('tenant_a', { customer: 'Ada Park', service: 'tune_up', date: '2026-12-02', time: '10:00' })
    const first = await h.app.guard.call(rina, 'booking_cancel_start', { booking_id: b!.id })
    if (first.outcome !== 'confirm_required') throw new Error(first.outcome)
    await h.app.guard.call(rina, 'booking_cancel_start', { booking_id: b!.id }, { confirmToken: first.token })
    await h.runner().idle()
    expect(h.runner().status(`cancel:${b!.id}`)).toBe('waiting')
    expect((await h.bookings.get('tenant_a', b!.id))?.status).toBe('cancelled')
    const refund = (await h.app.flows.steps(`cancel:${b!.id}`)).find((s) => s.key === 'refund')!
    expect(refund.status).toBe('waiting')

    // The front desk cannot decide it; the owner can, with the code sent to them.
    const row = (await h.app.guard.approval(refund.approvalId!))!
    expect((await h.app.guard.canDecide(row.id, rina)).ok).toBe(false)
    const sam = h.seat('sam', 'tenant_a', 'console')
    await h.app.codes.start(sam, row)
    const d = await h.app.guard.decide(refund.approvalId!, sam, { approve: true, proof: { method: 'code', codes: { email: h.codes.get('sam')! } } })
    expect(d.outcome).toBe('approved')
    await h.runner().idle()
    expect(h.runner().status(`cancel:${b!.id}`)).toBe('ok')
    expect((await h.bookings.get('tenant_a', b!.id))?.refunded).toBe(true)
  })
})
```

The approval invariant in `test/catalog.test.ts` now has an R3 action to check. Replace its
empty `args` with a cancelled booking, a decider and a proof:

```ts
    const b = await h.bookings.create('tenant_a', { customer: 'Ada Park', service: 'tune_up', date: '2026-12-02', time: '10:00' })
    await h.bookings.cancel('tenant_a', b!.id)
    await assertApprovals({
      registry: reg,
      guard: h.app.guard,
      requester: h.seat('rina', 'tenant_a'),
      decider: h.seat('sam', 'tenant_a', 'console'),
      // The owner's code, as the sender would mail it.
      proof: async (approval, who) => {
        await h.app.codes.start(who, approval)
        return { method: 'code', codes: { email: h.codes.get(who.principal.id)! } }
      },
      args: { deposit_refund: { booking_id: b!.id } },
      // Counts refunds: only an approved refund may move it.
      effects: () => h.bookings.rows.filter((r) => r.refunded).length,
    })
```

It drives the refund every way a caller could try to skip the approval (a plain call, a forged
token, a forged approval id) and checks the refund count moves only after the owner decides.
Add `booking_cancel`, `deposit_refund`, `booking_cancel_start` and `booking_cancel_status` to the
tenant isolation `args` with `{ booking_id: booking!.id }`, accept the new tiers with
`OMAZY_UPDATE_SNAPSHOTS=1 npm test`, and run `npm run check`.

### Dry run, then live

Restart `npm run dev`, and mint a key for Sam, the owner:

```sh
SAM=$(npm run --silent key -- --person sam --tenant demo)
```

A small helper that calls a tool and confirms it when the guard asks:

```sh
call() { local args="$2" t
  t=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"'"$1"'","arguments":'"$args"'}}' | jq -r '.result._meta["ai.omazy/outcome"].confirm_token // empty')
  [ -n "$t" ] && args=$(echo "$args" | jq -c --arg t "$t" '. + {confirm_token: $t}')
  mcp '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"'"$1"'","arguments":'"$args"'}}' | jq -c '.result.structuredContent'; }

call booking_cancel_start '{"booking_id":"b_55ad8760ed0a","dry_run":true}'
call booking_cancel_status '{"booking_id":"b_55ad8760ed0a","dry_run":true}'
```

```json
{"status":"ok","report":["cancel: would Cancel booking b_55ad8760ed0a, tune_up on 2026-12-01 at 10:00.","refund: would Refund the deposit of 20.00 for booking b_55ad8760ed0a.","tell: would send booking_cancelled"],"steps":[{"step":"booking","status":"ok"},{"step":"cancel","status":"planned"},{"step":"refund","status":"planned"},{"step":"tell","status":"planned"}]}
```

The booking still stands. Now live:

```sh
call booking_cancel_start '{"booking_id":"b_55ad8760ed0a"}'
call booking_cancel_status '{"booking_id":"b_55ad8760ed0a"}'
```

```json
{"status":"waiting","report":[],"steps":[{"step":"booking","status":"ok"},{"step":"cancel","status":"ok"},{"step":"refund","status":"waiting","approval":"apr_gImto7FX9F6eCmv_"}]}
```

The booking is cancelled and the run sleeps until the owner decides, at no cost. Rina cannot
decide it: her code request answers 403. Sam asks for his code, which the dev console prints,
then approves:

```sh
A=apr_gImto7FX9F6eCmv_
curl -s -X POST localhost:8787/ui/approvals/$A/code -H "authorization: Bearer $SAM" -H 'content-type: application/json' -d '{}'
# {"channels":["email"],"method":"code","expiresAt":"..."}
curl -s localhost:8787/ui/approvals/$A/decide -H "authorization: Bearer $SAM" -H 'content-type: application/json' \
  -d '{"approve":true,"proof":{"method":"code","codes":{"email":"<the six digits>"}}}'
```

```json
{"outcome":"approved","approval":{"id":"apr_gImto7FX9F6eCmv_","action":"deposit_refund","status":"executed","verification":"code",...},"execution":{"outcome":"ok"}}
```

`booking_cancel_status` now answers `ok`, with every step `ok` and the deposit refunded. The
page does the same in the **Approvals** inbox: Sam signs in with his key, opens the request, and
presses **Approve**, then **Send me a code**. He types the code from the console and approves. The
inbox's step-up slot is the ui kit's `CodeStepUpForm`.

`deposit_refund` never appears in Rina's `tools/list`. A personal key reaches R2 at most, so the
door does not offer an R3 tool to it at all. Only the workflow asks for it, and only an owner
approves it.

## 9. Deploy

```sh
npx wrangler login
npm run setup
```

`setup` builds the page, creates the D1 database and the KV namespace, writes their ids into
`wrangler.jsonc`, applies every migration (yours included), deploys, and sets a fresh
`GUARD_SECRET`. On 0.5.1 or earlier it does not build the page: run `npm run build:page` first.
Then the model token:

```sh
npx wrangler secret put OMAZY_TOKEN
```

The door starts **off**. A fresh deploy answers 503 to every MCP call until you decide otherwise:

```sh
KEY=$(npm run --silent key -- --person rina --tenant demo --remote)
U=https://booking-desk.<your subdomain>.workers.dev
curl -s $U/mcp -H "authorization: Bearer $KEY" -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' -H 'mcp-protocol-version: 2025-06-18' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"slot_list","arguments":{"date":"2026-12-01"}}}'
# {"error":"door_off","message":"This door is off until its owner turns it on."}

npm run door -- on --remote
```

Within a few seconds the same call answers with the open hours. Connect Claude Code to the
deployed door:

```sh
claude mcp add --transport http booking-desk $U/mcp --header "Authorization: Bearer $KEY"
```

`npm run door -- off --remote` stops every MCP call within a few seconds, whatever the client.
Later changes ship with `npm run migrate:remote` for new migrations and `npm run deploy`.

Before real customers use it, wire a real code sender in `src/index.ts`. Without one, an owner
cannot ask for a code in production; the deployed Worker refuses rather than print codes to its
logs. Until you do, Sam's `POST /ui/approvals/<id>/code` on the deployed Worker answers 500 with
`{"error":{"code":"error","message":"This could not be done. Try again in a moment."}}`, and
`npx wrangler tail` shows why: `Error: no code sender: wire mail or SMS in src/index.ts`. Trying
again does not help; the refund waits until a code can be sent.

### The production checklist

Read the [production checklist](/build-on-omazy/production-checklist/). For this product:

- One person, one key. Mint a key per person with `--person`, at most 90 days, and never share
  one. Revoke from the page's connected apps list.
- Keep the door off until you have tried it on the deployed Worker yourself.
- Commit `catalog.snapshot.json` and read every change to it in review. A tier that moves is a
  product decision.
- Add real cases to every eval set, and run the live evals before you change a prompt.
- Watch the request log: every refusal is there, with its reason.
- Keep `STEP_UP_LOG` out of production. It belongs in `.dev.vars` only.

### Spending caps

Each AI unit caps its own spend in its manifest (`caps: { perRunUsd, perDayUsd }`), and the kit
enforces it. Omazy enforces a second cap per workspace, per unit, through `/core/budgets`. A call
over a cap is refused with `PAYMENT_REQUIRED` before it costs anything. With a token that has
`ai:configure`:

```ts
import { Omazy } from '@omazyai/sdk'

const omazy = new Omazy({ token: process.env.OMAZY_TOKEN })
await omazy.budgets.set({ label: 'unit', value: 'booking_request', period: 'day', limit_usd: 1 })
console.log((await omazy.budgets.list()).budgets)
```

Leave out `label` and `value` for a cap on the whole workspace. `omazy.budgets.delete(id)`
removes one. The [API explorer](/explorer/) has the fields.

## 10. Next steps

- **Clients that sign in.** Personal keys suit Claude Code, scripts and your own team.
  claude.ai and ChatGPT connect with OAuth. `src/oauth.ts` wires the
  [oauth kit](/build-on-omazy/kits/oauth/), off until you set `OAUTH` to `on`. Read the kit page
  first, including its threat model: replace the stub sign-in with your own, make `chooseSeat`
  and `checkSeat` read your members, set `ISSUER` to your Worker's address, and have the kit's
  security fixes reviewed before you open a door with it.
- **Many workshops.** One Omazy workspace and one token per customer keeps their usage, budgets
  and knowledge apart. The Enterprise API creates them from your backend:
  [Many customers](/build-on-omazy/many-customers/).
- **Speech.** Take bookings by phone: transcribe a call or stream speech to text while the
  customer speaks, and read the card back aloud: [Speech](/build-on-omazy/speech/).
- **The kits in depth.** [Capabilities](/build-on-omazy/kits/capabilities/),
  [guard](/build-on-omazy/kits/guard/), [mcp](/build-on-omazy/kits/mcp/),
  [ai](/build-on-omazy/kits/ai/), [actors](/build-on-omazy/kits/actors/),
  [flows](/build-on-omazy/kits/flows/), [copilot](/build-on-omazy/kits/copilot/),
  [ui](/build-on-omazy/kits/ui/) and [testing](/build-on-omazy/kits/testing/).
