# BeatScript API

`https://beatscript.app` is a code-centric web view of **BeatScript**, AI-assisted algorithmic composition: a small language for writing whole music tracks as text
(reference: [BEATSCRIPT.md](https://beatscript.app/docs/BEATSCRIPT.md), compact grammar: [cheatsheet.md](https://beatscript.app/docs/cheatsheet.md),
index for models: [llms.txt](https://beatscript.app/llms.txt)). This page documents everything the service answers: the HTTP routes,
sign-in, composing with a model, streaming renders, driving a browser tab, and the MCP server.

Conventions. Bodies are JSON unless noted; programs are plain UTF-8 text. A program is at most **16384 bytes**. Every program the
service stores or shares is **CC0-1.0** (public domain); programs that use `sample` / `loop` assets or `use restricted` are private
and are refused by every route that stores, shares or renders. A program's **CID** (`z4EBG9j...`) is the hash of its *canonical text*
(the parse printed again: spacing, comments, number and note spellings do not change it), so the same program is always the same CID.
A program starts with its version line, `#! beatscript 2`, which its canonical text keeps first; a text with no version line (or
`#! btw 1`) is BeatScript 1, the old spelling, and keeps the CID it always had (the language reference, "Versions").

**Privacy and licence.** Everything generated here is published: a composed program, its CID, share link, social card and every render or
audio stream made from it are stored publicly and released under CC0-1.0, and anyone with the link can play, copy and reuse them. A compose
prompt goes to a third-party model provider, so never put anything private in one. Responses that carry generated work send
`X-Content-License: CC0-1.0` and a `Link: </privacy>; rel="privacy-policy"` header, a compose result has a `notice` field, and the human
version is `/privacy`. `GET /.well-known/btw-site` names the site (`site_id`, its origins, `moved_to` once it has moved).

## Routes

| route | auth | does |
|---|---|---|
| `GET /` and `/js/*`, `/css/*`, `/wasm/*` | | the page |
| `GET /?view=stage&cid=<cid>` (or `&example=<name>`, or a share link's `#…`) | | the program on a stage: full screen, read-only, large type, [Stage view](#stage-view) |
| `GET /healthz`, `GET /api/info` | | liveness; name, version, model, compose `{enabled, configured, limits}`, render limits, auth kinds |
| `GET /api/examples`, `GET /examples/<name>.beatscript` | | the public example programs: list as JSON, text as written |
| `GET /api/instruments` | | the voices, families, drum kits and palettes a program may name |
| `POST /api/check`, `/api/fmt`, `/api/share`, `/api/open` | | the language tools, below; limited per IP |
| `PUT /api/programs/<cid>`, `GET /api/programs/<cid>[.beatscript]` | | store and read programs |
| `PUT /api/shares/<cid>` | cookie, bearer or paired phone | store a public program with its rights for a CID-only share link, [Share links](#share-links) |
| `GET /api/render/<cid>?format=opus\|wav` | | stream the offline render, [Render](#render) |
| `POST /api/session`, `GET /api/session/<id>/events`, `POST /api/session/<id>/report`, `POST /api/session/<id>/reply` | cookie optional | the browser to MCP bridge, [Sessions](#sessions) |
| `GET /api/auth/challenge`, `POST /api/auth/login`, `POST /api/auth/logout`, `GET /api/auth/me`, `POST /api/auth/token`, `DELETE /api/auth/token` | | [Sign-in and tokens](#sign-in-and-tokens) |
| `POST /api/compose` | cookie or bearer | [Compose](#compose) |
| `POST /api/feedback` | optional: cookie, bearer, paired phone or a signature | [Feedback](#feedback) |
| `POST /mcp` (and a landing page on `GET`) | write tools need a bearer token | [MCP](#mcp) |
| `GET /c/<cid>`, `GET /c/<cid>.<packed>`, `GET /p/<cid>`, `GET /card/<cid>.png` | | share pages with link previews, and their card images; `/p/<cid>` is the CID-only short link |
| `GET /llms.txt`, `/llms-full.txt`, `/docs/BEATSCRIPT.md`, `/docs/cheatsheet.md`, `/docs/api.md` | | the docs |

## Errors and limits

Every error is JSON with the HTTP status of the failure:

```json
{"error": {"code": "rate_limited", "message": "10 composes an hour is the limit", "retry_after": 30}}
```

`retry_after` (seconds, also the `Retry-After` header) is there when waiting helps. Some errors carry `details` (the diagnostics and
attempts of an `unrepairable` compose). Codes: `auth_required` 401, `bad_signature` 401, `challenge_stale` 401, `bad_request` 400,
`not_found` 404, `no_session` 404, `too_large` 413, `prompt_too_long` 413, `rate_limited` 429, `busy` 429 (all render slots taken),
`cid_mismatch` 422 (a link or body whose CID is not its text's), `restricted` 422, `unrepairable` 422, `model_error` 502,
`spend_cap` 503 (the day's money limit is spent), `disabled` 503 (the compose kill switch is off), `not_configured` 503 (no model key).

Limits are per client address (IPv6 per /64) and, when signed in, per user. `GET /api/info` says the current compose limits.
Ask for `retry_after` seconds and try again; do not loop.

## Sign-in and tokens

Identity is a key, not an account: an Ethereum wallet (`personal_sign`, EIP-191) or a browser-local Ed25519 key. Sign-in is challenge and response:

1. `GET /api/auth/challenge` gives `{"nonce": "...", "message": "beatscript.app sign-in\nnonce: ...\nissued: ...\nexpires: ...", "expires": "..."}`.
   The nonce is single use and lives 5 minutes.
2. Sign `message` (its UTF-8 bytes). Ethereum: `personal_sign(message)`. Ed25519: the raw signature over the bytes.
3. `POST /api/auth/login` with `{"type": "eth", "address": "0x...", "signature": "0x...", "nonce": "..."}`
   (`"type": "ed25519"` takes the 64-hex public key and a 128-hex signature). The answer sets the cookie `btw_session`
   (HttpOnly, Secure, SameSite=Lax, 7 days) and gives the user: `GET /api/auth/me` answers `{"user": {"id", "kind", "address"}}` or `{"user": null}`.
   The user id is `eip155:0xabc...` (lower case) or `ed25519:<hex>`.
4. **Bearer tokens**, for MCP and scripts: with the cookie, `POST /api/auth/token` answers `{"token": "btw_<43 characters>"}` **once**
   (only its SHA-256 is kept; at most 5 per user). The page's **MCP token** button does exactly this. `DELETE /api/auth/token` revokes them all.
   Send it as `Authorization: Bearer btw_...` wherever the cookie is accepted.

Anonymous callers can read, check, format, share, open, render (limited) and play. Signed-in callers can also compose, use MCP's write
tools and drive their own browser tabs.

## Check, format, share, open

`POST /api/check` with `{"text": "<program>"}` answers (always 200; a program with errors is `ok: false`):

```json
{"ok": true, "errors": 0, "warnings": 1,
 "diagnostics": [{"severity": "warning", "line": 3, "col": 14, "end_col": 15, "start": 42, "end": 43,
                  "message": "...", "expected": ["..."], "found": "...", "help": "...", "render": "warning: ...caret form..."}],
 "cid": "z4EBG9j...", "canonical": "#! beatscript 2\ntempo 140\n...", "version": 2, "renamed_cid": "z4EBG9j...",
 "nets": {"A": "z4EB..."}, "song_nets": {"A": "z..."},
 "tempo": 140, "key": "fm", "swing": null, "arranged": true, "song_bars": 64, "ends": true, "loops": false,
 "sections": [{"name": "intro", "start": 0, "bars": 8}], "decks": ["A", "B"], "evolve": [], "lineage": [],
 "uses_assets": false, "restricted": false, "seconds": 109.7}
```

`line` and `col` are 1-based; `start` and `end` are UTF-8 byte offsets into the text you sent; `help` says what would fix it; `render` is the
error in caret form. `version` is the language version of the text (1 or 2) and `renamed_cid` the program's CID in the
other one. `cid` and `canonical` are null when `ok` is false. **Always check before you play, share or render, and fix every
error at its line:col**; a program with an error is refused whole.

- A report that is `ok` also carries `timeline` (derived, so no CID moves): `lanes` (`id` like `B.bass`, `row.vox_a`, `ctl.master`;
  `target`, `role`, `inst`, `route`, `kind` part, audio or control), `blocks` (a part of a deck or a `row: clip` over its bars: `lane`,
  `section`, `play`, `start`, `bars`, `line`, `col`, `end_line`, `end_col`, `span` with `start`/`end` bytes and `start16`/`end16`, `text` or
  `let`, `params`, `placed`, and for audio `sample` and `crop`) and `chips` (a control line with its `start`, `bars`, `every`, `text`, `call`).
  A view edits by patching the text at a block's span. See "The timeline extensions" in [BEATSCRIPT.md](https://beatscript.app/docs/BEATSCRIPT.md).
- `POST /api/fmt` `{"text"}` gives `{"ok", "text", "canonical", "cid", "comments": [...], "diagnostics": [...]}`: `text` is the program formatted with its `#!` header lines, comments and blank lines between blocks kept, and upgraded to BeatScript 2 (`#! beatscript 2` first); `canonical` has none of them but the version line (the CID is of it); `from_cid` is the CID of the text sent, so a BeatScript 1 text's old and new CIDs are both in the answer.
- `POST /api/open` `{"url": "<link, #fragment, <CID>.<packed> or CID>"}` gives `{"ok", "cid", "canonical", "verified", "warnings", "notes_unverified", "error"}`.
  A link whose CID is not its text's is refused (`verified: false`, never trust its text).
- `POST /api/share` `{"text"}` gives `{"ok", "url", "social_url", "cid", "chars", "canonical", "warnings"}`, see [Share links](#share-links).

```bash
curl -s https://beatscript.app/api/check -H 'content-type: application/json' \
  -d '{"text":"tempo 126\nkey am\ndeck A: kick x ~ x ~ | snare ~ x ~ x\n"}'
```

## Programs

- `PUT /api/programs/<cid>`: the body is the program text. Accepted iff its canonical CID is `<cid>`, it checks ok, it is not restricted
  or asset-using and it is at most 16384 bytes (stored as CC0-1.0: [What we store](#what-we-store)); stored content-addressed (idempotent), limited per IP. Answers the stored program.
- `GET /api/programs/<cid>`: `{"cid", "text", "meta": {"license": "CC0-1.0", "visibility", "name", "composed_by", "forked_from", ..., "based_on"}}`.
  `text` is the canonical text (no comments); `based_on` is what the text as saved said it vendored, its `# from: <call> -> <cid>`
  lines as `["<call> -> <cid>"]` (every write path keeps them; absent when there were none).
- `GET /api/programs/<cid>.beatscript`: the program as a `.beatscript` file with its `#!` header (name, license, composed-by, forked-from), then its
  kept `# from:` lines.

## What we store

beatscript.app only stores Creative Commons programs. Users can do whatever they want on their own devices.

- **Stored:** a program that checks, is public, names no `sample` or `loop` and does not `use restricted`, under a Creative Commons
  licence: `CC0-1.0` (the default) or a CC BY family id such as `CC-BY-4.0`, `CC-BY-SA-4.0`, `CC-BY-NC-4.0`. Every write path (`PUT
  /api/programs`, `PUT /api/shares` from the page or a phone, a render from a `<cid>.<packed>` link, MCP `share`, `render` and `record`,
  playlist items and queue items) goes through the same check, and anything else is refused with `422 not_creative_commons`
  ("beatscript.app only stores Creative Commons programs; keep this one local") or `422 restricted`.
- **Never stored:** private programs (`#! visibility:` anything but public), programs with samples or `use restricted`, and anything
  under another licence (all rights reserved, MIT, a cover's rights). They stay on your devices. The self-sealing link still works:
  the program is in the link, not on the server.
- **Private pushes** (MCP `push_private`): a private program goes to one of your own paired phones, end-to-end encrypted for that
  phone's pairing key (X25519, HKDF-SHA256, ChaCha20-Poly1305). The server relays the sealed bytes in memory to the phone's open
  connection and keeps nothing: no file, database row, log line (only the size and the device id), metric or CID. A phone that is
  not connected gets nothing; push again when it is. The phone opens it, checks it and plays it, and resolves samples against its
  own sample library; missing ones are reported back, never fetched. Give `text` (the server seals it, so the text is in its memory
  for that one call) or `sealed` (an envelope you sealed yourself for the `seal_key` the `devices` tool lists: then the server only
  ever sees ciphertext).
- **You are responsible** for what you keep and play privately, and for having the rights to it.

## Examples and instruments

`GET /api/examples` lists `[{"name", "title", "description", "cid", "bpm", "bars", "license"}]`; `GET /examples/<name>.beatscript` is the text as written.
All examples are CC0-1.0, the work of the site's author, and a good second read after the cheat-sheet: `first-beat` is four lines,
`acid-line` shows an accent, a slide and a filter ramp, `evolve-demo` a program that changes itself, and `hand-dubstep-140-v4`, `matrix-130`
and `trance-138` are whole tracks.

`GET /api/instruments` answers `{"voices": [...], "families": [...], "kits": [...], "palettes": [...]}`. A part names a voice with `inst=NAME`
and a drum kit with `kit=NAME`. A name that is not a voice is a check error with the nearest names; a family word (`inst=reese`) is accepted
with a warning that it plays the family's generic voice.

## Compose

`POST /api/compose` writes a program with a language model (Gemini Flash), checks it, and repairs it. **Signed in only**, rate limited,
and the service has a daily spend cap.

```bash
curl -s https://beatscript.app/api/compose -H 'Authorization: Bearer btw_...' -H 'content-type: application/json' \
  -d '{"prompt": "dark techno at 128 with an acid line and a long breakdown", "genre": "techno", "bpm": 128, "key": "am", "length": "medium"}'
```

Request: `prompt` (required, at most 800 characters), `genre`, `bpm` (40 to 300), `key` (`am`, `f#m`, `d:dorian`), `length`
(`short`, `medium`, `long`, or a number of bars), `base_cid` (the CID of a public program, an example or a stored one, to edit instead of starting fresh).

Response 200:

```json
{"program": "<canonical text>", "text": "<as the model wrote it, repaired>", "cid": "z4EBG9j...",
 "check": {"ok": true, "...": "a check report"},
 "attempts": [{"n": 1, "ok": false, "errors": 2, "diagnostics": [], "tokens_in": 4100, "tokens_out": 900}, {"n": 2, "ok": true, "errors": 0}],
 "model": "gemini-3.8-flash", "forkedFrom": null, "license": "CC0-1.0", "composedBy": "gemini-3.8-flash",
 "header": ["#! license: CC0-1.0", "#! composed-by: gemini-3.8-flash"],
 "render_url": "/api/render/z4EBG9j...?format=opus", "share_url": "https://beatscript.app/#z4EBG9j....<packed>",
 "cost_usd": 0.0007, "usage": {"in": 4100, "out": 1700}}
```

What happens: the request is validated and limited (kill switch, per user per hour and per day, per IP per day, the global daily spend); the
model gets the cheat-sheet, the instruments and two or three public CC0 examples; its program is checked, and while it has errors the
diagnostics go back to the model, at most 3 repair rounds. A program that never checks is **422 `unrepairable`** with the last diagnostics
and every attempt in `details`. The result is stored as a public CC0-1.0 program with `composedBy` and `forkedFrom`; the `#!` header lines live in the
stored object and the `.beatscript` download, never in the canonical text. A call takes about 5 to 60 seconds. Errors: `auth_required`,
`rate_limited` (with `retry_after`), `spend_cap`, `disabled`, `not_configured`, `bad_request`, `prompt_too_long`, `model_error`, `unrepairable`.
Never put anything private in a prompt: it goes to Google's model, and what comes back is published as CC0.

## Render

`GET /api/render/<cid>?format=opus|wav&sr=44100` renders a stored program offline and **streams** it as it renders: the first bytes
come within about a second for a typical program and the response is chunked, so a page or a player can start at once.

- `wav`: a streaming WAV header (RIFF and data sizes `0xFFFFFFFF`), then 16-bit stereo PCM. A page can decode it chunk by chunk.
- `opus`: Ogg Opus at 96 kb/s, smaller, for download or an `<audio>` element.
- Headers: `X-Btw-Cid`, `X-Btw-Seconds` (the length of the program), `X-Btw-Cache: hit|miss|joined` (`joined`: another request was already rendering it
  and this one follows the same file). Once complete, `Cache-Control: public, max-age=31536000, immutable`, and `Range` works.
- A render in progress is shared: later requests for the same `(cid, format, sr)` read the growing file from the start.
- The offline render plays the notes and sounds. It does **not** play control lines (filters, reverb, `do ...` lines), so it can sound plainer
  than the browser. A program with no end is cut at the bar limit (256 bars); give it `end at bar N`.
- Limits: uncached renders per IP per hour, a few renders at once (more get `busy` with `retry_after`), a maximum length, and a disk cap
  with eviction of the least recently used. A program must be stored first (`PUT /api/programs/<cid>`, the MCP `render` tool, or compose).
- `GET /api/render/<cid>/status` says how far a render is.

```bash
curl -s https://beatscript.app/api/examples | head -c 300          # find a CID
curl -sL 'https://beatscript.app/api/render/z4EBG9j...?format=opus' -o track.opus
```

**For a DAW** (the same route, `format=` one of these; the full description is the repository's docs/EXPORT.md):

- `midi`: a Standard MIDI File of the notes the render plays, a track per part, at once.
- `stems`, `stems-opus`: a zip of a part's stem each and a deck's, the master, the `.mid` and `manifest.json`; each stem
  is its part as it sits in the mix, and they add up to the master.
- `stems-dry`, `stems-dry-opus`: the same zip with **dry** stems: each part before its deck and the master (no level,
  crossfader, EQ, filter, sends or master effects), the master as it plays, and in `manifest.json` every control move the
  parts leave out (each part's `automation`, `master_automation`, with bar times) and the master's effects.

A stems URL answers `202` with `{"state": "rendering", "file", "done"}` and `Retry-After` while the zip is made (a minute or
two for a long song); ask again until it is the zip. `file` is the stem being made, named as it is in the zip.

## Sessions

The browser and MCP meet in a **session**. The page does `POST /api/session` (answers `{"id": "<22 characters>", "user": ...}`), then opens
`GET /api/session/<id>/events`, a server-sent event stream with the events `eval`, `load`, `stop`, `get`, `queue` and `ping` (`data` is JSON:
`text`, `cid`, `play`, and for `get` a `request_id`). While it matters the page posts its state to `POST /api/session/<id>/report` about every
500 ms (`text`, `cid`, `playing`, `source` engine or stream, `section`, `bar`, `bars_in_section`, `phase`, `marks`, `diagnostics`, `presence`, `ts`), and answers a `get`
with `POST /api/session/<id>/reply` `{"request_id", "state"}`. The server keeps the latest report of each session for 10 minutes.

A session belongs to the user that created it (cookie or token) or is anonymous. An MCP write tool targets the `session` you name, or else every live
session owned by the caller. An anonymous tab is reached only by its explicit id, which the page shows in its **MCP** panel (top bar), and the caller
must still hold a token. This is how `eval`, `load`, `stop` and `get` work.

**Up next.** A session can hold a queue of programs that MCP's `queue` tool writes, and the radio page's playlist too
(`POST /api/session/<id>/queue` `{"action": "add|remove|move|clear", "items": [{"cid"} | {"example"}], "item", "to"}`: an added item is a
stored program's CID or an example's; `item` is an id from the queue or a CID; `to` is the index a `move` puts it at; about 60 a minute per
address; the editor only shows it). When the playing program ends, or a looping one has played its length (an item's `bars` or `minutes`,
else one pass of its arrangement), the page asks
`POST /api/session/<id>/queue/next` `{"reason": "ended|length|skip|resume|pick", "presence": {"visible", "focused", "audio", "idle_ms"}, "item"}` and plays the
`item` it is given from bar 1 (with `item`, that one rather than the first: a row the person chose, `reason` `pick`, or an MCP skip to an
item); `GET /api/session/<id>/queue` reads the queue. The server advances it only while a listener is plausibly present:
it pauses at the boundary (`paused_reason`) when the audio is suspended, when the tab has been hidden with no key, pointer, touch or media key for
30 minutes, or after 8 tracks in a row with no interaction, and the page shows "Still listening? Press play to continue". Only a person on the page
lifts a pause. The queue never composes or renders anything, holds at most 50 items, and goes with its session.

## MCP

`https://beatscript.app/mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server over streamable HTTP (stateless: each request stands alone, there is no event stream: a `GET` that asks for one gets 405).
A browser `GET` shows a page that lists the tools.

```bash
claude mcp add --transport http beatscript https://beatscript.app/mcp --header 'Authorization: Bearer btw_...'
```

The server's name in a client is yours to choose; these docs call it `beatscript` (older installs may show `btw`: the same server).
The token keeps its `btw_` prefix.

Without the header the read tools still work; `eval`, `load`, `get`, `stop`, `devices` and `queue` answer an MCP tool error `auth_required` that says how to get a token
(sign in on the page and press **Create an MCP token**). Other clients take the same URL and header, for example
`{"mcpServers": {"beatscript": {"type": "http", "url": "https://beatscript.app/mcp", "headers": {"Authorization": "Bearer btw_..."}}}}`.

There is **no `compose` tool**: an MCP client is already a model, so it writes the program itself ([Compose](#compose) is the web app's).
The loop: read [cheatsheet.md](https://beatscript.app/docs/cheatsheet.md) and one or two `list_examples` programs, call `instruments`, write the program, call `check`
and fix every `line:col` error until `ok`, then `eval` / `load` to play it and `share` to store it. A voice whose name starts with a digit
(`808-bass`) cannot be written: `inst=808-bass` reads as the sum `808 - bass` and a quoted `inst="808-bass"` is refused ("expected a number or a
name"), so use a voice that starts with a letter (`inst=sub-bass` for a deep bass).

| tool | needs a token | arguments | does |
|---|---|---|---|
| `check` | | `text`, `same_as`? | check a program: diagnostics with line:col, cid, canonical text. **Run it before anything else and fix the errors**. With `same_as` (a CID or another program's text) it also answers whether the two are the same song by their compiled nets and song-level settings, and, when they are not, a `diff` saying what changed in music: song settings, sections inserted/removed/moved/repeated/renamed, and per part a transform (transposed, rotated, reversed, ...) or the notes changed at bar:step, each with a one-line summary |
| `fmt` | | `text` | the program formatted (`text`, header lines and comments kept) and upgraded to BeatScript 2, its canonical form (`canonical`), its CID and `from_cid`, the CID of the text given |
| `share` | for the short links | `text`, `license`, `forked_from`, `credits`, `name` | the self-sealing link, the social link, the CID; with a token also stores the program and gives the CID-only `short_url`, `short_social_url` and `fetch_url` |
| `open` | | `url` | decode a link (self-sealing or CID-only: `/p/<CID>`, `/c/<CID>`, `#<CID>`, a bare CID), verified, with its rights |
| `render` | | `text` or `cid` or `example`, `format` | store the program and answer `stream_url`, `status_url`, `cid`, `seconds` |
| `record` | | `text` or `cid` or `example` | store the program and answer the demo-recording setup: `record_url` (the page in record mode), `record_url_manual_clock` (a fake clock a script steps frame by frame), `audio_url`, and the `recipe` for `site/tools/record-demo.mjs` (captures nothing itself) |
| `list_examples` | | `name` | the example programs (and one's text) |
| `instruments` | | | voices, families, kits, palettes |
| `eval` | yes | `text`, `play`, `session` | send a program to a browser tab, as Cmd+Enter; lands on the next bar |
| `load` | yes | `cid` or `example` or `url`, `play`, `session` | put a stored, example or linked program into a tab |
| `get` | yes | `session` | what a tab is playing: program, cid, section n of m, bar, phase, marks, diagnostics |
| `stop` | yes | `session` | stop the tab |
| `devices` | yes | | your paired phones (pass one's id as `device` to `eval`, `load`, `get`, `stop`, `queue`) |
| `push_private` | yes | `device`, `text` or `sealed`, `load`, `play` | send a private program (a cover, local samples, `use restricted`) to one of your paired phones, end-to-end encrypted and never stored: see [What we store](#what-we-store) |
| `feedback` | optional | `kind`, `text`, `cid`, `page`, `app_version`, `client` | send the team a bug report, a request or anything else; a token attaches your key id and counts it as signed, no token sends it unsigned (limited more tightly): [Feedback](#feedback) |
| `queue` | yes | `action` (list, add, remove, move, clear, skip), `items`, `item`, `to`, `session` | an up-next list on a tab of programs that already exist (`{cid}`, `{example}`, `{url}`, with `bars` or `minutes`); never composes; advances only while a listener is present, else `paused_reason` |

What `eval`, `load`, `queue`, `share` and `push_private` send on is formatted on the way in, as `fmt` prints it (header lines and comments kept, the CID the same). `eval`, `load`, `stop` and `get` need a browser tab open at https://beatscript.app (signed in as the token's account), or the session id from
the page's MCP panel; with no tab connected they answer `no_session` and say so. Tool failures are MCP tool results with `isError: true`
whose text is the error body above (`{"error": {"code", "message", "retry_after", "details"}}`), so a client reads the code and the words.
Calls to the checker are limited per client (about 60 a minute), programs for `render` per hour.

A raw call, to see the wire:

```bash
curl -s https://beatscript.app/mcp -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"check","arguments":{"text":"tempo 126\ndeck A: kick x ~ x ~\n"}}}'
```

## Feedback

`POST /api/feedback` takes `{"kind": "bug", "text": "...", "cid": "z...", "page": "/", "app_version": "...", "client": "web"}`
(`kind` is `bug`, `request` or `other`; `text` is 1 to 4000 characters; the rest is optional) and answers 201
`{"ok": true, "id": "fb_...", "signed": true, "proof": "signature", "key_id": "ed25519:...", "received": "..."}`.
The MCP `feedback` tool is the same call.

**Signing is optional.** A caller with an identity is signed with no extra step: the page signs with the browser's key; an assistant
or a paired phone is known from its token or request signature (`proof: "session"`). A caller with none is stored unsigned
(`signed: false`) and limited more tightly: 3 an hour per hashed address against 10 an hour per key. A page may attach `sig`
`{"type": "ed25519", "address": "<64 hex>", "signature": "<128 hex>", "ts": <unix seconds>}` over the five lines
`beatscript feedback v1`, `kind: <kind>`, `cid: <cid or ->`, `ts: <ts>` and `text-sha256: <hex sha256 of the text>`;
a signature that does not verify is refused (`bad_signature` 401). Feedback is stored privately, apart from the programs,
readable only by the site's owner and erased after 365 days; no IP address is stored. See [the privacy page](https://beatscript.app/privacy#feedback).

## Linked data (JSON-LD)

A program is also published as linked data, in the same convention as pflow.xyz: a stable, versioned `@context` URL.

```text
https://beatscript.app/context/v1.jsonld      the @context (application/ld+json, CORS *, immutable; a change is a new version, v2)
https://beatscript.app/context.jsonld         the latest version (cached five minutes)
https://beatscript.app/c/<CID>.jsonld         a program: @id, @type djrust:Program, cid, name, key, tempo, sections, licenseId, license,
                                              credit, forkedFrom / isBasedOn (as stored), usageInfo (https://beatscript.app/authorship)
https://beatscript.app/c/<CID>.<packed>.jsonld   the same for a program the site has not stored (the link carries it)
```

A stored program's `@context` is `[v1, {schema.org's usageInfo and isBasedOn}]`: v1 stays as published. Its rights statement is the
licence and only what the site keeps beside it (credits, the program it was forked from); `usageInfo` is the page that says plainly
who authored a program and what rights it has.

`/c/<CID>` embeds that document in a `<script type="application/ld+json">` block and answers with `Link: <.../c/<CID>.jsonld>; rel="describedby"`.
The context's vocabulary is the BeatScript ontology (`https://beatscript.app/ontology/ns#`); the MCP `share` tool returns `jsonld_url` and `context`, and `get` does too.
The engine's own JSON-LD export (on the command line, `djctl btw jsonld FILE`) names the same context URL. Genre, tags and Euclidean
rhythms need the engine's ontology, so only that export adds them.

The public-domain phrasebook is open data too: lines of verse, scripture, speech and work song first published before 1929, CC0, each with its
source and its meter as a step pattern, to sing by id (`sing @tempest_such_stuff on melody`). One corpus, in several views:

```text
https://beatscript.app/phrasebook                  the page: every line with its year, meter, stress as a step pattern and a sing example
https://beatscript.app/phrasebook.txt              the corpus as shipped (text/plain, CC0)
https://beatscript.app/phrasebook.jsonld           the same as linked data (application/ld+json), one node a line, in the BeatScript ontology's terms
https://beatscript.app/phrasebook/<CID>.txt        the file, by CID (immutable)
https://beatscript.app/phrasebook/<CID>.jsonld     the linked data, by CID
```

The corpus's CID is a program's CID function over the file's text. The two CID routes answer only for the CID the server ships and are `404`
for any other: a new version of the corpus is a new CID. All are public reads, cross-origin, with no sign-in.

## Share links

```text
https://beatscript.app/#<CID>.<base64url(deflate(canonical text))>
https://beatscript.app/c/<CID>.<base64url(deflate(canonical text))>        (for posts: link unfurlers can fetch it, and it has a card image)
```

The program is **in** the link: nothing is stored for it to work, and whoever opens it recomputes the CID from the text and refuses a link
where they differ. Optional `~<base64url(deflate(notes))>` after the sealed part carries the comments, which are in neither the CID nor the
signature and are shown as unverified; an optional `.<sig>` is the author's signature over the CID. Links over about 2000 characters
may be cut by some apps; `POST /api/share` and the MCP `share` tool report `chars`. `GET /c/<CID>` shows a card for a program the site has stored.
Who authored a program and what rights it has, in plain language: [/authorship](https://beatscript.app/authorship).

**CID-only short links** keep the program on the site instead of in the link:

```text
https://beatscript.app/p/<CID>        (opens the page; it fetches the program and checks it against the CID)
https://beatscript.app/c/<CID>        (for posts: the link-preview page of a stored program)
```

Store one with `PUT /api/shares/<CID>` (signed in with a cookie or `Authorization: Bearer btw_...`, or from a paired phone), body
`{"text": "<the program>", "license": "CC0-1.0", "forked_from": "<CID>", "credits": ["..."], "name": "..."}` (all but `text` optional;
at most 8 credits of 80 characters). The text must check and hash to `<CID>`; only public programs are stored (`use restricted`,
`sample`/`loop` and `#! visibility:` anything but public are refused with `restricted` and stay inline-only); the first share's
rights stay. It is limited per account (60 an hour) and per address. The MCP `share` tool does the same when called with a token.
Reading is public: `GET /api/programs/<CID>` answers `{"cid", "text", "meta"}` (the canonical text and its rights), cross-origin, and the
reader recomputes the CID from the text and refuses a mismatch, exactly as for a self-sealing link. A CID the site has not stored is `404`.

## Stage view

For a projector or a second screen at a gig: the program full screen, read-only, in large high-contrast type, with the firing
markers lit and the follow-scroll on, playing at once.

```text
https://beatscript.app/?view=stage&cid=<CID>
https://beatscript.app/?view=stage&example=<name>
https://beatscript.app/?view=stage#<CID>.<packed>         (a share link's program)
```

It is the page's record mode (`?record=1`, which the demo video is rendered from, and which stays exactly as it is) with a person in
front of it, so it has what a person needs and nothing that edits:

- **Full screen**: the button in the header, or **F**. **Esc** leaves full screen and never stops the music. Where the page cannot go
  full screen (Safari on an iPhone), it fills the window instead and says how to lose the browser's bars (Share, then Add to Home Screen).
- **A set's tracklist**: when the program is a `set { }`, the header says where the set is, `2/5  now <track>  ·  next <track>`, during a
  mix `mix 2→3  <track> → <track>`, and `last` on the last track.
- **Play and stop**, and the browser's "enable sound" banner when it holds the sound until a click. No toolbar, no problems list, no
  completion or scrubbing, no panels (G does nothing here); the text can be selected and copied, not changed.
- **Type and colour**: the code's size follows the window (`width / 60` px, 18 to 44 px, line height 1.36 times that), on a black
  ground; the system's light theme makes it a white ground with dark ink, and `prefers-contrast: more` makes it the most contrast each
  theme has.

When `?record=1` and `?view=stage` are both given, it is record mode: a renderer's URL never changes behaviour.

**One look, two screens.** The booth's projector window (djrust, a viewport on a second display) and this view share a visual
language, so a set looks the same projected from either: the type scale above; the lamp colours of the editor's markers (amber
`#ffc850` for a token that sounded, green `#4cd06a` for a playing line, teal `#56b6c2` for a control line, red `#e05050` for a held one,
purple `#c678dd` for a new generation, a lamp fading to the ground it sits on, `#000` or `#fff`); and the tracklist line's wording.
The values live in `site/web/js/stage-model.js` (`STAGE`, `tracklistLine`) and `markers-model.js` (`COLORS`).

## For models

Start at [llms.txt](https://beatscript.app/llms.txt) (or [llms-full.txt](https://beatscript.app/llms-full.txt), which has the cheat-sheet and the grammar inlined),
read the [cheat-sheet](https://beatscript.app/docs/cheatsheet.md) and two or three [examples](https://beatscript.app/api/examples), take the voices from
[`/api/instruments`](https://beatscript.app/api/instruments), write, `check`, fix, then `share` or `render`.
