# Vibe tools: the verbs a person can ask for by text

> The verbs a person could ask for by text instead of tapping (vote for a place, claim a slot, book a table, add a book to the list), declared in backend.js as a static `export const tools` (at most 8) so an assistant in a group chat can do them for that person. Each tool has a one-line description, typed input fields, who it is for (anyone, members, owner), and either a handler shared with the page's button through a fetch route or a declared one-record write (`key: \` for one record per person). A plain record (a list item, a note) needs no tool, since an assistant saves it directly through access.js; a domain tool takes the steps the app works out (book the next free hour, a legal move) in its handler. A tool always acts as its caller through access.js (`user.backend` is `tool`, never admin mode) and its callAI spends the caller's credits. A tool may carry a short `title`, an `annotations` flag (`readOnly` for a lookup, `consequential` for one the assistant confirms first) and an `output` field list. A picture app may mark one tool `offer: true`, which the assistant offers once per chat with the app's first picture; `offer: { textsLater: true }` records each person's yes, and a scheduled `ctx.notify({ consent: \ })` reaches only people who said yes. A picture app that writes its prompt in code exports it as a read-only hook, `export const hooks = { picturePrompt: { run } }`: it takes the person's words as `addition` and returns the prompt string, and the platform paints from it. An app that writes stories about its cast (episodes, chapters) declares a tool that writes one with ctx.callAI and returns its first scene and picture, and a next_… tool that tells the rest, so a group that plays by text hears it in the chat. An app whose actions only happen on the page does not need it

Source: https://good.vibes.diy/docs/reference/vibe-tools

This doc is in view because the app has things a person does in one step that
they could just as well ask for in a message: vote for a place, claim a slot,
book a table, add a book to the list. A **tool** names one of those verbs, so an
assistant acting for that person (in a group chat, say) can do it for them with
the app's own rules. The page keeps its buttons; the tool is a second door to
the same action.

A tool is declared in `backend.js` as **`export const tools = { … }`**, a
static object whose keys are the tool names. Each tool has:

- **`description`**: one line, at most 280 characters, saying what happens in
  the person's own words ("Vote for one place for the next meetup."). An
  assistant reads it to decide when to use the tool, so name the result, not
  the code.
- **`input`**: the fields the tool takes. A field is `"string"`, `"number"`
  or `"boolean"`, or an object `{ type, description, optional, enum }`. At most
  12 fields; a string is at most 2,000 characters. A field the tool does not
  declare is refused before anything runs, and so is a wrong type or a value
  outside `enum`.
- **`for`**: who may use it. `"anyone"` (the default) is anyone who can open
  the app, `"members"` is the people it is shared with, `"owner"` is the
  owner alone. A tool someone may not use is never even listed for them.
- **Either `handler` or `write`**, never both:
  - `handler(input, ctx)` runs your code, with the same `ctx` as `fetch`.
  - `write: { db, set, key }` saves one record and runs no code at all.
- **`title`** (optional): a short display name, at most 60 characters
  ("Vote for a place"). A host shows it beside the tool's name.
- **`annotations`** (optional): what kind of verb this is, as one static flag.
  `{ readOnly: true }` for a tool that only looks things up, or
  `{ consequential: true }` for one a person would want to be asked about
  first (cancel a booking, send the order). An assistant confirms a
  consequential tool with the person before it calls it. One flag or the
  other, and a declared `write` is never `readOnly`.
- **`output`** (optional, handler tools): the fields the answer holds, written
  the same way as `input`, so a host knows what comes back.
- **`offer`** (optional, on one tool at most): `offer: true` is the tool the
  assistant may offer after it posts this app's picture in a chat, and
  `offer: { textsLater: true }` is an offered tool that texts the person
  later. See below.

**A vibe declares at most 8 tools.** A ninth refuses the save. Names are
lowercase letters, digits and underscores, starting with a letter
(`vote`, `claim_slot`, `add_pick`). Keep the set to the verbs a person would
actually say: eight is a ceiling, and three good verbs beat eight thin ones.
A `backend.js` may export `tools` and nothing else; that saves fine.

## Who the tool acts as

**A tool always acts as the person it is used for, never as the owner.** The
host that runs the tool states that person, and the platform carries them
through:

- `ctx.userInfo` is that person (`ctx.userInfo.userHandle`).
- Every `ctx.db.put` passes `access.js` as them, with `user.backend` set to
  `"tool"`. A tool never runs in admin mode and gets no bypass: it writes what
  `access.js` admits for that person, and `access.js` can tell a tool's write
  from a page's by that origin.
- `ctx.db.query` and `ctx.db.get` read what that person could read.
- `ctx.callAI` spends that person's credits (or the group's, when the host says
  the group pays), never the owner's.

So the rules stay in `access.js`. When a rule treats both doors alike, a vote
the page would refuse, the tool refuses too, with the same reason, and the
reason comes back to the person.

The app's own backend can use its tools too: `ctx.agent.run({ goal, input, tools })`
runs an agent over this `tools` export from any handler, each tool acting as
that handler acts. The `backend` skill's "Let an agent do the work" section has
the pattern.

## Two ways an assistant acts: a record, or a tool

An assistant acting for a person reaches the app two ways, and a good app is
ready for both:

- **A plain record, saved directly.** An item on a list, a log entry, a note,
  an RSVP: the assistant reads a record or two to learn their shape and saves
  one more in that shape, as the person, through `access.js`, just as the
  page's own `database.put` does. This needs no tool at all: an `access.js`
  that admits the record opens both doors.
- **A domain tool, for a step the app works out.** When what lands depends on
  state the app reckons (a free slot, a legal move, whose turn it is), when
  several records change together, or when a step runs only on the server (a
  model call, a payment, a text later), declare a tool whose handler takes the
  steps in order. The assistant passes what the person said, and the app does
  the reckoning.

Declare tools for the second kind, plus the few plain verbs a person names out
loud (vote, add my pick), and let the record tools carry the rest.

### A plain record: an item on the list

The page writes `{ type: "item", name, done }` with `database.put`. Asked to
"add basil", an assistant reads one item, sees that shape, and saves
`{ type: "item", name: "basil", done: false }` the same way, with no tool
declared. Plain field names (`name`, `done`, `when`) make the shape easy to
read and copy.

### `access.js`
```js partial
// Summary: a signed-in person adds or ticks an item; the page and an assistant
// write the same record, and anyone who opens the app reads the list.
export function garden(doc, oldDoc, user, ctx) {
  if (!user) throw { forbidden: "sign in to add" };
  if (doc.type !== "item") throw { forbidden: "unknown record" };
  return { channels: ["list"], grant: { public: ["list"] } };
}
```

### A domain tool: book the court

Booking is several steps that only the app can take in order: read the day,
keep one booking per person, find the asked hour or the next free one, and save
the day back only if nobody changed it in between. The whole day is one record,
so both rules ride one compare-and-set write. The page's button and the `book`
tool share one handler, and the day record comes only from that code.

### `backend.js`
```js
// Summary: bookCourt reads the day's record, keeps one booking per person, books
// the asked hour or the next free one after it, and saves the day with ifRev so a
// booking made in between sends it round again. The /book route and the book tool share it.
const HOURS = ["17:00", "18:00", "19:00", "20:00"];

async function bookCourt(input, ctx) {
  const me = ctx.userInfo && ctx.userInfo.userHandle;
  if (!me) return { error: "sign in to book" };
  const day = String(input.day || "").trim();
  if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return { error: "say the day as 2026-11-21" };
  const from = HOURS.indexOf(String(input.hour || HOURS[0]));
  if (from < 0) return { error: `the court opens at ${HOURS.join(", ")}` };

  for (let attempt = 0; attempt < 3; attempt++) {
    const current = await ctx.db.get(`day:${day}`, { db: "court" });
    const hours = { ...(current ? current.hours : {}) };
    const mine = HOURS.find((h) => hours[h] === me);
    if (mine) return { ok: true, day, hour: mine, message: `You have the court at ${mine} that day.` };
    const hour = HOURS.slice(from).find((h) => !hours[h]);
    if (!hour) return { error: `${day} is full from ${HOURS[from]} on` };
    hours[hour] = me;
    try {
      await ctx.db.put(
        { type: "day", day, hours },
        { db: "court", id: `day:${day}`, ifRev: current ? current._rev : null }
      );
    } catch (err) {
      if (err.code === "conflict") continue; // someone booked in between: read the day again
      throw err;
    }
    const moved = HOURS[from] === hour ? "" : ` (${HOURS[from]} was taken)`;
    return { ok: true, day, hour, message: `Court booked for ${day} at ${hour}${moved}.` };
  }
  return { error: "the court is busy right now; ask again in a moment" };
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);
  if (url.pathname === "/book" && request.method === "POST") {
    return Response.json(await bookCourt(await request.json(), ctx));
  }
  return new Response("not found", { status: 404 });
}

export const tools = {
  book: {
    title: "Book the court",
    description: "Book the court on a day, at the hour asked or the next free one after it. One booking per person a day.",
    input: {
      day: { type: "string", description: "The day, as 2026-11-21" },
      hour: { type: "string", optional: true, enum: ["17:00", "18:00", "19:00", "20:00"], description: "The hour they want" },
    },
    output: { day: "string", hour: "string", message: "string" },
    handler: bookCourt,
  },
};
```

### `access.js`
```js
// Summary: a day's bookings come only from the app's own code (the /book route or
// the book tool), as the person booking: each save adds one hour for them, keeps
// every earlier booking, and leaves them one booking that day. Anyone who opens
// the app sees the day.
export function court(doc, oldDoc, user, ctx) {
  if (!user) throw { forbidden: "sign in to book" };
  if (doc.type !== "day" || doc._id !== `day:${doc.day}`) throw { forbidden: "unknown record" };
  ctx.requireBackend(); // bookCourt read the day before it wrote
  const before = (oldDoc && oldDoc.hours) || {};
  const after = doc.hours || {};
  for (const hour of Object.keys(before)) {
    if (after[hour] !== before[hour]) throw { forbidden: "a booking stays with its booker" };
  }
  const added = Object.keys(after).filter((hour) => !(hour in before));
  if (added.length !== 1 || after[added[0]] !== user.userHandle) throw { forbidden: "you book one hour for yourself" };
  if (Object.values(after).filter((who) => who === user.userHandle).length !== 1)
    throw { forbidden: "one booking each a day" };
  return { channels: ["court"], grant: { public: ["court"] } };
}
```

### `App.jsx`
```jsx
import React from "react";
import { useFireproof } from "use-fireproof";
import { apiFetch } from "use-vibes";
import { Button, Heading, Row, Stack, Text } from "@vibes.diy/ui";

const HOURS = ["17:00", "18:00", "19:00", "20:00"];

export default function App() {
  const { useLiveQuery } = useFireproof("court");
  const [day] = React.useState(() => new Date().toLocaleDateString("en-CA"));
  const { docs } = useLiveQuery("day", { key: day });
  const hours = (docs[0] && docs[0].hours) || {};
  const [note, setNote] = React.useState("");

  async function book(hour) {
    const res = await apiFetch("/book", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ day, hour }),
    });
    const out = res.ok ? await res.json() : { error: "try again" };
    setNote(out.error || out.message);
  }

  return (
    <Stack gap={4}>
      <Heading level={1}>The court, {day}</Heading>
      <Row gap={2} wrap>
        {HOURS.map((hour) => (
          <Button key={hour} disabled={Boolean(hours[hour])} onClick={() => book(hour)}>
            {hour} · {hours[hour] ? `@${hours[hour]}` : "free"}
          </Button>
        ))}
      </Row>
      {note && <Text muted>{note}</Text>}
    </Stack>
  );
}
```

`ctx.requireBackend()` with no name admits the route and the tool alike, so
the button and the assistant book through the same checks. The day is one
record saved with `ifRev`, so two people booking at once, or one person asking
twice, each get a fresh read of the day: one booking lands, and the other hears
the next free hour or the booking they already hold.

## One handler, a button and a tool

The page and the tool share one function: the button reaches it through a
`fetch` route, the tool names it as its `handler`. The rule lives once, so the
two doors can never disagree. Each vote is its own record keyed by the voter,
so voting again changes your vote instead of adding a second one.

### `backend.js`
```js
// Summary: one recordVote function behind a /vote route (the page's button) and
// the vote tool (an assistant acting for the person). Both act as the voter.
async function recordVote(input, ctx) {
  const me = ctx.userInfo && ctx.userInfo.userHandle;
  if (!me) return { error: "sign in to vote" };
  const place = String(input.place || "").trim();
  if (!place) return { error: "say which place" };
  await ctx.db.put(
    { type: "vote", place, voterHandle: me, at: new Date().toISOString() },
    { db: "meetup", id: `vote:${me}` }
  );
  return { ok: true, place };
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);
  if (url.pathname === "/vote" && request.method === "POST") {
    return Response.json(await recordVote(await request.json(), ctx));
  }
  return new Response("not found", { status: 404 });
}

export const tools = {
  vote: {
    description: "Vote for one place for the next meetup. Voting again changes your vote.",
    input: {
      place: { type: "string", description: "The place, as the poll lists it" },
    },
    handler: recordVote,
  },
};
```

### `access.js`
```js
// Summary: a signed-in person votes, one record each, keyed by their own
// handle; anyone who opens the app reads the votes.
export function meetup(doc, oldDoc, user, ctx) {
  if (!user) throw { forbidden: "sign in to vote" };
  if (doc.type !== "vote") throw { forbidden: "unknown record" };
  if (doc.voterHandle !== user.userHandle || doc._id !== `vote:${user.userHandle}`)
    throw { forbidden: "you vote for yourself" };
  return { channels: ["meetup"], grant: { public: ["meetup"] } };
}
```

### `App.jsx`
```jsx
import React from "react";
import { useFireproof } from "use-fireproof";
import { apiFetch } from "use-vibes";
import { Button, Heading, Row, Stack, Text } from "@vibes.diy/ui";

const PLACES = ["Thai Basil", "The Dock", "Rosa's"];

export default function App() {
  const { useLiveQuery } = useFireproof("meetup");
  const { docs: votes } = useLiveQuery("type", { key: "vote" });
  const [note, setNote] = React.useState("");

  async function vote(place) {
    const res = await apiFetch("/vote", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ place }),
    });
    const out = res.ok ? await res.json() : { error: "try again" };
    setNote(out.error || `You voted for ${out.place}`);
  }

  return (
    <Stack gap={4}>
      <Heading level={1}>Where next?</Heading>
      <Row gap={2} wrap>
        {PLACES.map((place) => (
          <Button key={place} onClick={() => vote(place)}>
            {place} · {votes.filter((v) => v.place === place).length}
          </Button>
        ))}
      </Row>
      {note && <Text muted>{note}</Text>}
    </Stack>
  );
}
```

The handler returns a small object, and the person sees it as the answer.
Keep it short and plain: a result over 8,000 characters is cut. Return
`{ error: "…" }` for a "no" the person should read: the host reports it as the
tool's error, in your words, and the assistant passes them on. Return it
before the handler saves anything: a record already saved stays saved, so an
error after a save says what was done. A throw comes back as "the tool
failed", with no words of yours.

### Say what kind of verb it is

```js partial
export const tools = {
  standings: {
    title: "Standings",
    description: "See which place is ahead for the next meetup.",
    annotations: { readOnly: true },
    output: { leader: "string", votes: "number" },
    handler: readStandings,
  },
  cancel_meetup: {
    title: "Cancel the meetup",
    description: "Cancel the next meetup and tell everyone who voted.",
    for: "owner",
    annotations: { consequential: true },
    handler: cancelMeetup,
  },
};
```

A tool that changes something small and easy to redo (a vote, a pick) needs no
annotation. Mark `readOnly` only on a tool that writes nothing, and
`consequential` on the few a person would want a say in first.

## A declared write: one record, no code

When the verb is "save this" and the person would name it out loud (add my
pick, suggest a theme), declare the record instead of writing a handler. The
record stays a plain one an assistant could save directly too; the tool gives
the verb a name and fixes its `type`:

### `backend.js`
```js
// Summary: two tools-only verbs. add_pick saves a book on the picks list, one
// pick per person; suggest saves a new suggestion every time it is used.
export const tools = {
  add_pick: {
    description: "Add a book to this month's picks. Adding again replaces your pick.",
    for: "members",
    input: {
      title: "string",
      author: { type: "string", optional: true },
    },
    write: { db: "picks", set: { type: "pick" }, key: "caller" },
  },
  suggest: {
    description: "Suggest a theme for a future month.",
    input: { theme: "string" },
    write: { db: "picks", set: { type: "suggestion" } },
  },
};
```

### `access.js`
```js
// Summary: a pick is one per person, written as its author; a suggestion is
// anyone's, added once and never rewritten. Anyone who opens the app reads both.
export function picks(doc, oldDoc, user, ctx) {
  if (!user) throw { forbidden: "sign in first" };
  // A record keeps its type, so nobody turns someone's pick into a suggestion to rewrite it.
  if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" };
  if (doc.type === "pick") {
    if (doc._id !== `add_pick:${user.userHandle}`) throw { forbidden: "you pick for yourself" };
    return { channels: ["club"], grant: { public: ["club"] } };
  }
  if (doc.type === "suggestion") {
    if (oldDoc) throw { forbidden: "a suggestion is added, not edited" };
    return { channels: ["club"], grant: { public: ["club"] } };
  }
  throw { forbidden: "unknown record" };
}
```

The record saved is the input with `set` laid over it, so `set` decides the
`type` and the person cannot. `set` holds literal values only: strings,
numbers, `true` and `false`.

**`key: "caller"` makes the record one per person:** its id is
`<tool name>:<their handle>`, so using the tool again replaces their record
(`add_pick:maya`). The id follows the handle the person uses when they call,
so someone who switches to another handle starts a new record under it; write
`access.js` against `user.userHandle`, as above, and the two stay in step.
Without `key`, every use adds a new record. A declared write
still passes `access.js` as the caller, with `user.backend` set to `"tool"`.

## A record only a tool writes

Most records should be writable both from the page and from a tool, and a
shared handler gives you that for free. When a record must come only from a
tool, gate it on the origin:

### `access.js`
```js partial
if (doc.type === "request") {
  ctx.requireBackend("tool"); // only a tool writes requests, still as the caller
  return { channels: ["desk"] };
}
```

`ctx.requireBackend("tool")` admits writes from a tool and turns away a write
from a browser, the CLI and every other handler. A shared handler reached from
the page writes with `user.backend` set to `"fetch"`, so don't put this gate on
a record your button writes too.

## Offer one tool with the picture

When the app makes pictures (a portrait app a texting chat uses for its
photos), mark the one tool people will want right after their picture as
`offer: true`:

### `backend.js`
```js partial
export const tools = {
  remind_me: {
    description: "Text me a reminder the day before the next meetup.",
    offer: true,
    handler: remindMe,
  },
};
```

When the assistant posts this app's first picture in a chat, it offers the
tool in that same text, once per chat: a short yes/no question the platform
writes from the tool's name (`Want me to set up "remind me" for you?`), with
your description beside it as what the app can do for them. It uses the tool
only after a yes (typed, or a 👍 on that text), and never in a chat that is
paused or opted out. Write the description as one plain line about what the
person gets: it reaches the assistant quoted, as your words, up to 300
characters. At most one tool says `offer: true`; a second refuses the save.

### A tool that texts them later

When the offered tool sends the person a text later (a reminder before the
event), write `offer: { textsLater: true }`. The assistant then asks in its own words, saying
plainly that it will text them later and about what, and the platform keeps a
record of each person's yes: who said it, when, and the words they said yes to.
Your scheduled handler marks that later text with `consent: "text-later"`, and
the platform delivers it only to people holding that yes for this app; anyone
else's notify refuses, and a person who texts STOP is off the list.

### `backend.js`
```js partial
export const tools = {
  remind_me: {
    description: "Text me a reminder the day before the next meetup.",
    offer: { textsLater: true },
    async handler(input, ctx) {
      const handle = ctx.userInfo.userHandle;
      await ctx.db.put({ type: "reminder", handle }, { db: "reminders", id: `remind:${handle}` });
      return { ok: true, message: "Reminder set for the day before the meetup." };
    },
  },
};

export async function scheduled(event, ctx) {
  const docs = await ctx.db.query({ db: "reminders", field: "type", key: "reminder", limit: 100 });
  for (const r of docs) {
    await ctx.notify({
      toHandle: r.handle,
      body: "The meetup is tomorrow at 6!",
      dedupeKey: `meetup-eve:${r.handle}`,
      consent: "text-later",
    });
  }
}
```

A notify without `consent` works as it always has, so an app that already
notifies its members on a schedule keeps doing so.

## Build the picture prompt from the person's words

When the app paints pictures from a prompt it writes in code (a style prompt,
with the person's words added to it), export the function that writes it as a
**hook**: `export const hooks = { picturePrompt: { … } }`. A hook is a function
the platform calls at a set moment. It is separate from `tools`, so an
assistant never sees it among the app's verbs and it takes none of the 8 tool
slots. When a chat sends its first photo through this app,
or asks for a new look ("make it 1920s", "add rain"), the platform runs
`picturePrompt` as the person, with their words as `addition` (nothing on a first
photo), and paints exactly the prompt it returns. The record keeps that prompt
too, so the gallery and the chat show the same picture, and the person's words
arrive just as they said them, ready for your code to place. A picture that
copies a record with its look already set paints from that record's prompt.

### `backend.js`
```js partial
const STYLE = "A warm studio portrait, soft window light, film grain";

function withAddition(addition) {
  const extra = (addition || "").trim();
  return extra === "" ? STYLE : `${STYLE}. ${extra}`;
}

export const hooks = {
  picturePrompt: {
    input: { addition: { type: "string", optional: true, description: "What the person asked to change" } },
    async run(input, ctx) {
      return withAddition(input.addition);
    },
  },
};
```

- **Return the prompt as a plain string.** The platform keeps the first 1,200
  characters of it.
- **Answer within a few seconds.** The picture waits up to 5 seconds for the
  prompt, and the platform ends a hook still running at that mark. When `run`
  is slower, or returns anything other than a non-empty string, a first photo
  paints from the app's newest record's own prompt, and a new-look ask comes
  back unpainted for the assistant to try again.
- **The input is `addition`, an optional string, and nothing else.** The first
  photo comes with no words, and a later look change comes with the person's;
  the save refuses any other input shape. `input` may be left out.
- **A hook reads and computes.** `ctx.db.query` and `ctx.db.get` read what the
  person could read, and `ctx.log` writes to the app's logs. Saving a record,
  `ctx.callAI`, `ctx.notify` and a `fetch` to another service belong in a tool
  or a handler; inside a hook each one throws `a hook is read-only`.
- `picturePrompt` is the one hook name, and it holds a `run` function. An
  older app's `picturePrompt: true` on a tool still saves and runs the same
  read-only way; write new code as a hook.

## One picture from two people's photos

When the app paints one picture from two people's photos of the same moment
(a diptych of two angles, a two-lead movie poster, a then-and-now pair), give
its records a **`pairPrompt`** string beside `prompt`. That makes it a pair
picture app. In a chat, `prompt` paints the first person's photo alone, so
write it as the finished first half ("the left panel shows this photo; the
right panel is a soft empty frame waiting for its partner"). Once someone else
in the chat sends their photo within three hours, the platform paints
`pairPrompt` from both photos together: image 1 is the earlier person's photo
and image 2 is the newer one, so write `pairPrompt` naming them that way.

### A record in the app's database
```js partial
await database.put({
  type: "panel",
  prompt: "A cinematic still: this photo fills the left panel; the right panel is an empty frame waiting for its partner",
  pairPrompt: "A cinematic diptych of one moment: image 1 fills the left panel, image 2 the right, one shared light and grade",
});
```

- **Both strings are prompts, kept to 1,200 characters each.**
- **The picture is billed as one picture**, the same as a picture from one photo.
- The saved record keeps the photo it started from, as any picture app does.

## A story the chat hears one scene at a time

When the app writes stories about its people (episodes starring a cast,
chapters of a quest, rounds of a mystery), a group that plays by text should
get them by text too. Declare two tools: one writes the whole story once and
returns its first part, the other tells the next part. Each part that has a
picture returns it for the assistant to paint, so the chat gets a scene and its
picture together.

### `backend.js`
```js partial
// Summary: write_episode writes a whole episode once with callAI and returns scene 1;
// next_scene tells the next one. `told` counts the scenes the chat has heard.
async function writeEpisode(input, ctx) {
  const me = ctx.userInfo && ctx.userInfo.userHandle;
  if (!me) return { error: "Sign in to write an episode." };
  const cast = await readCast(input.teamId, ctx);
  if (cast.length === 0) return { error: "Someone joins the cast first: send a selfie." };
  const raw = await ctx.callAI(
    `Write a short, fun episode starring ${JSON.stringify(cast)}.${input.idea ? ` About: ${input.idea}.` : ""} A title, a one-line logline, and 4 to 6 scenes, each a title and two sentences.`,
    { schema: { properties: { title: { type: "string" }, logline: { type: "string" }, scenes: { type: "array", items: { type: "object", properties: { title: { type: "string" }, text: { type: "string" } } } } }, required: ["title", "logline", "scenes"] } }
  );
  const out = JSON.parse(raw);
  // Check the answer before the first save, so a reply with no scenes leaves nothing half-written.
  const scenes = (Array.isArray(out.scenes) ? out.scenes : []).filter((s) => s && s.text).slice(0, 6);
  if (scenes.length === 0) return { error: "The episode didn't come out. Ask again in a moment." };
  const id = `ep-${crypto.randomUUID()}`;
  const episode = { type: "episode", teamId: input.teamId, authorHandle: me, title: out.title || "Episode", logline: out.logline || "", scenes, told: 1, createdAt: Date.now() };
  await ctx.db.put(episode, { db: "story", id });
  await Promise.all(episode.scenes.map((s, i) =>
    ctx.db.put({ type: "scene", episodeId: id, authorHandle: me, prompt: `Comic panel: ${s.text}` }, { db: "story", id: `scene:${id}:${i}` })
  ));
  return sceneReply({ ...episode, _id: id }, 0, ctx);
}

function sceneReply(episode, i, ctx) {
  const s = episode.scenes[i];
  const last = i === episode.scenes.length - 1;
  return {
    episodeId: episode._id,
    scene: i + 1,
    of: episode.scenes.length,
    // The assistant hands this to its picture tool, which paints this scene's record in this app.
    picture: { ownerHandle: ctx.appInfo.ownerHandle, appSlug: ctx.appInfo.appSlug, dbName: "story", docId: `scene:${episode._id}:${i}` },
    message: `${i === 0 ? `${episode.title}: ${episode.logline} ` : ""}Scene ${i + 1}, ${s.title}: ${s.text} ${last ? 'That\'s a wrap! Say "another episode" for the next one.' : 'Say "next scene" to keep going.'}`,
  };
}

export const tools = {
  write_episode: {
    description: "Write a new episode starring the team, 4 to 6 scenes. Returns scene 1 and its picture; the chat hears the rest with next_scene.",
    input: { teamId: "string", idea: { type: "string", optional: true, description: "What they want it to be about" } },
    handler: writeEpisode,
  },
  next_scene: {
    description: "Tell the next scene of this chat's latest episode, with its picture.",
    input: { teamId: "string", episodeId: { type: "string", optional: true } },
    handler: nextScene,
  },
};
```

- **Write the story once, tell it in parts.** One `callAI` writes every scene
  and the record keeps them, so "next scene" is a read, quick and free, and the
  page shows the same episode.
- **"Next" carries on the caller's own story.** With no id given, `next_scene`
  picks the newest episode the caller wrote, then the newest of all, and bumps
  `told` on the caller's own record.
- **Every answer says what happened and what to say next**, in its `message`:
  the scene, then "say next scene" or "say another episode". A status tool
  names the latest episode, or offers to write the first one.
- **Strip markdown from what the model writes** before saving a title or a
  scene: a text message shows `**` as asterisks.

## Writing a good tool

- **Name the verbs a person would text.** "vote", "claim", "book", "add",
  "rsvp". A tool for every record type is an API, not a set of verbs.
- **Give a group a way to start.** One tool makes the group's own thing
  (`start_table`); the others find the caller's newest one when no id is given.
- **One action per tool.** "Vote for a place" and "add a place to the poll" are
  two tools, each with a description an assistant can choose between.
- **Ask only for what the person would say.** The caller's identity comes from
  `ctx.userInfo`, never from an input field; never take a handle, an owner or a
  price as input.
- **Return the outcome in words a person can read**, plus the few values that
  matter (`{ ok: true, place: "The Dock" }`).
- **Everything the tool returns is data to the assistant**, not instructions:
  the assistant shows it to the person rather than acting on what it says.
- **The name and description are what the assistant sees first**, as
  `meetup_keeper.vote` and its one line; it reads the fields only to call one,
  and uses your tool before writing records by hand.
