# The language-package protocol, version 1

What a language package provides, and how a host talks to it. Read this to make a language
playable. Approved by the author 2026-11-30 (`docs/plan.md` D2–D4).

- The TypeScript types and validators are `packages/protocol`.
- The JSON Schemas generated from them are in `schemas/`.
- The types, validators, schemas and `packages/worker` are MIT OR Apache-2.0, so an implementer
  of any licence may link them (`docs/plan.md` D73).
- A site may also run a package's workers on a machine it operates, a **remote** (§3.2, §8).
- The conformance kit (`packages/conformance`, `lib.checkLanguage` in Nix) checks a package
  against this document.

## 1. A package

A package is a directory:

```
manifest.json           written by mkLanguage from what you give it
<grammar>.tmLanguage.json
<worker files>          scripts, .wasm modules, data: anything the workers read
<examples>
```

Each file is named by its content in the built package. `manifest.json` lists every file
with its sha256 and sizes. The host fetches the manifest and the grammar on its own origin
before the reader activates anything. It fetches the worker files only on activation, then
checks their hashes and hands them to the sandbox frame.

In a built directory (docs/plan.md D68) the worker files are not under the package's path: each
is `blobs/<sha256>.<ext>` beside `index.json`, named by the hash of the stored bytes (a part by
its own), and the host fetches it from there. `index.json` lists the packages, `frames` and
`blobs`; a package's path holds the manifest, grammar and examples.

**No file in the built package is larger than 25 MiB** (26 214 400 bytes). Why: Cloudflare
Workers static assets refuse a larger file, so a site that serves the package from there could
not deploy it. `mkLanguage` (`assemble`) stores a larger file as parts: `<path>.part0`,
`<path>.part1`, … of at most 24 MiB each, and removes the original. A file of exactly 25 MiB
stays whole. The worker is not affected: the host joins the parts, so `fetch(path)` and
`self.playground.files` give the whole file under its own path. A script's embedded data
takes more room than the data (js_of_ocaml's `--file` about 2.5 times).

A file's manifest entry then carries `parts`: `{ path, hash, bytes, compressed }` for
each piece, in order. The entry's own `hash` and `bytes` are the whole file's, and `compressed`
is the pieces' added up. The host fetches each part, checks its sha256, and hands the worker
one file made of them, without a joined copy in memory; the whole file's sha256 is checked at
build time (the conformance kit), since the parts' hashes come from the same manifest. A
worker's entry script is never stored in parts.

**Files a host does not compress are stored as gzip.** A static host compresses a response
only for some content types (Cloudflare: JavaScript, WebAssembly, JSON, HTML, CSS, SVG, plain
text, source maps). A file with another extension (`.bin`, `.so`, `.zip`, …) goes out at full
size. `assemble` therefore gzips (maximum level) every file whose extension is not `.js`,
`.mjs`, `.json`, `.wasm`, `.html`, `.css`, `.svg`, `.txt` or `.map`, if that makes it at least
10 % smaller. It does so before splitting, so parts are pieces of the gzip stream. The entry
then carries `encoding: "gzip"` and `decoded`, the size after decoding. Its `hash`, `bytes`
and its parts' are the stored bytes' (the stream's), and `compressed` is `bytes`: the stored
file is what a reader downloads. A worker's entry script is never encoded.

The host checks each part's or the file's sha256 on the stored bytes, then decodes the stream
(`DecompressionStream("gzip")`, piped from the joined Blob, so no extra whole-file buffer) and
hands the worker the decoded file under its own path. The worker is not affected: `fetch(path)`
and `self.playground.files` give the original bytes. The conformance kit decodes the same way
and checks that the decoded size equals `decoded`.

## 2. The manifest

Schema `schemas/manifest.v1.json`. A host ignores keys it does not know, so a field can be
added without a new version.

| Field | Meaning |
|---|---|
| `manifest` | `1` |
| `id` | `[a-z][a-z0-9-]*`: the package's name, and what code fences say |
| `name`, `version`, `description?`, `license` | for people; `license` is an SPDX expression, or `NOASSERTION` for a package that states none |
| `languageId?` | what `textDocument/didOpen` says as `languageId`, and what the package's own `code` items may name; default `id`. A package published under another id stays the same language to its server. |
| `aliases` | more code-fence labels (`ml` for OCaml) |
| `extensions` | file extensions, with the dot |
| `grammar` | `{ scopeName, path, embedded?, hash? }`: a TextMate grammar (§6). `hash` is its sha256 (hex), which `assemble` writes and the host checks before use. |
| `editor?` | `{ comments?, brackets?, indentUnit?, wordChars?, module? }`. `wordChars` lists the characters a word has besides letters, digits and `_` (Koka's `-'?`, OCaml's `'`): completion filters by the word at the cursor. `module` is a CodeMirror `LanguageSupport` module that replaces the grammar inside the editor. |
| `document?` | `{ terminator? }`: how the host builds the document (§4.2). `terminator` is text the host puts on a line of its own after a non-empty hidden setup and after a non-empty prelude (OCaml: `;;`). |
| `workers` | one or more workers (§3) |
| `outputs` | what the package can produce (§5): tabs the UI shows before activation |
| `retired?` | ids of outputs that are gone: a host that holds stored snapshots drops those of these outputs (§5.1, `replaces`) |
| `examples` | `{ name, path, expected?, expectedOutputs?, status?, setup?, prelude?, tests? }`. The conformance kit runs each and compares the text (text, ANSI and code items) of every output that runs on Run, in order, with `expected`; each output's printed text (`itemsToText`, §5.3), whatever its triggers, with its file in `expectedOutputs` (`{ <output id>: path }`); and each Run output's status with `status` (default `ok`; `error` for an example that shows an error). `setup`, `prelude` and `tests` are the example's hidden parts, as a page gives its own: the kit composes the document as a host does (§4.2) and sends `firstLine` and the tests. |
| `renderers?` | `{ kind, module, hash? }` for each kind of your own (§5.4); `hash` as for the grammar |

## 3. Workers

```ts
{ id: "server", serves: ["lsp", "outputs"], variants: [wasmVariant, jsVariant], remote?: { build, startMs? } }
```

- **`serves`** tells the host's router (§4.3) which methods go to the worker. One worker
  serving both is the usual case. A package whose language server and runner are separate
  programs (Merlin and the OCaml toplevel, say) declares two.
- **`variants`** are tried in order. The host takes the first whose `probes` (WebAssembly
  features: `gc`, `exceptions`, `exnref`, `tail-calls`, `jspi`, `simd`, `memory64`,
  `multi-memory`) all validate in the reader's browser. If that variant then fails to
  start, the host takes the next one for the rest of the page's life.
- **`remote?`** `{ build, startMs? }` says the worker can also run on a remote with a program of
  its own (§3.2). With it, `variants` may be empty. `build` is the sha256 (hex) of the worker's
  entry in `remote.json` (§8.2). `startMs` (at least 1000) is how long a host waits for a cold
  start of the engine behind it, in place of its default (60 s): a prover that loads libraries
  before it answers `initialize`. A worker with no `remote` needs at least one variant.
- **A variant** has these fields:
  - `runtime`: `wasm` or `js`.
  - `entry`: the worker script.
  - `files`: everything the worker may read, the entry included. A file with `lazy: true`
    is fetched, checked and handed to the worker when it first asks for it, not at start (an
    interface pack a compiler reads on demand). A host that does not know `lazy` loads it at
    start; the worker sees no difference.
  - `module?`: a module worker, instead of classic. Chromium does not start a module
    worker from the frame's `blob:` URL (Firefox and WebKit do), so prefer a classic script:
    bundle to one file and load asynchronously; the world queues early messages.
  - `policy`:
    - `wasm` if it compiles WebAssembly;
    - `eval` if it also evaluates JavaScript at run time (a js_of_ocaml toplevel, a compiler
      whose output is JavaScript);
    - `plain` if it does neither: plain JavaScript, in a frame that allows no WebAssembly and
      no eval. A host that does not know `plain` refuses the manifest.

### 3.1 The worker's world

A worker runs in a dedicated Web Worker, started by the sandbox frame from a `blob:` URL.
The frame's origin is opaque, and its policy allows no request.
- **No network.** `fetch` answers only the package's own files. `XMLHttpRequest`,
  `WebSocket` and `EventSource` fail.
- **No storage.** IndexedDB, caches and cookies are unavailable.
- **Your files.** Before your entry runs, the frame's bootstrap installs:
  - `fetch(path)` for any path in your variant's `files`, relative to the package's root
    (`fetch("stdlib/prims.cmi")`). WebAssembly is served as `application/wasm`, so
    `WebAssembly.instantiateStreaming(fetch("x.wasm"))` works.
  - `importScripts(path)` (classic workers) for any of your scripts.
  - `self.playground.url(path)`: a `blob:` URL of a file, for a loader that wants URLs.
  - `self.playground.files`: the paths you have.
  - `self.playground.node`, only under the conformance kit in Node.js, never in a browser:
    `{ getBuiltinModule }`, for code that must work differently there (Node cannot
    `import()` a `blob:` URL). The kit's world has no `process`, as a browser worker has
    none.
  - `self.playground.starting(promise)`: your worker is not ready until every promise given
    to it resolves, and is *unavailable* if one rejects. For a runtime that loads after your
    entry returned (a WebAssembly module): without it the host would call the worker ready
    too soon, and a module that does not compile could not fall back to the next variant.

  `self.location` and `import.meta.url` are `blob:` URLs. Never build a file's URL from
  them; use `fetch(path)` or `playground.url(path)`.
- **Messages.** Every message you receive is one JSON-RPC 2.0 message as a string. Every
  message you send must be one too, sent with `self.postMessage(string)`. Anything else you
  post is dropped. Messages that arrive before your entry has added its `message` listener
  are kept and delivered when it does.
- **Failure.** If your entry throws, or a promise given to `starting` rejects, or an
  unhandled rejection happens before the worker is ready, the frame tells the host that
  this variant is *unavailable*, and the host tries the next one. Later
  failures restart the worker (§4.4).

You need no library for this. In TypeScript, `serve({ … })` gives you the loop
(`code-playgrounds/worker` in the npm package, `packages/worker` here). `templates/rust` shows it
by hand in Rust; `languages/koka` and `languages/rocq` drive an existing server from a worker
of their own.

### 3.2 A worker on a remote

A site may run a package's workers on a machine it operates (§8). It decides which, in its own
configuration, never the package. A worker runs there in one of two ways:

| Way | The manifest says | The remote runs |
|---|---|---|
| hosted | nothing: the worker has variants | the first variant whose `probes` the remote's Node.js passes, in the conformance kit's world: the package's files are read from disk, `fetch` answers only them, no `process`, no network. `playgrounds worker world <package-dir> <worker>` |
| native | `remote` | the program named by the worker's entry in `remote.json` |

Either way the remote starts one process per connection, and the worker is that process:

- **stdin and stdout** carry JSON-RPC 2.0 with LSP's base-protocol framing: `Content-Length:
  <bytes>\r\n\r\n` and the body, UTF-8. The remote turns each message into one WebSocket text
  frame and back (§8). stdout carries frames and nothing else; stderr is the operator's log.
  `FrameDecoder` and `encodeFrame` in `packages/protocol` do the framing.
- **In TypeScript**, `serve(server, stdioEndpoint())` (`packages/worker`) gives the same
  handlers as in a browser worker. A program in any language that speaks the framing needs no
  library.
- **Its world** is an empty working directory (`PLAYGROUND_WORK`) and its own files. It has no
  network and sees no other session.
- **Ready** when the process runs. Exiting before its first message is a failed start. The exit
  status 3 says "nothing here can run this worker" (`worker world` gives it when no variant's
  probes pass), and the remote reports it as 4404.
- **Fresh state** per run stays the worker's duty, as in a browser (§4.4).

## 4. The connection

One JSON-RPC 2.0 connection per page and language, with LSP's conventions:
- request ids are numbers or strings;
- `$/cancelRequest` cancels a request;
- errors use LSP's codes (`RequestCancelled` -32800, `MethodNotFound` -32601, and so on).

### 4.1 Initialisation

The host sends `initialize`. Its `capabilities` are LSP's, plus:

```json
"experimental": { "playground": { "version": 1, "kinds": ["text/plain", "text/x-ansi", …] } }
```

`kinds` lists the item kinds the host renders (§5.3). Answer with your LSP capabilities,
plus, from the worker that serves `outputs`:

```json
"experimental": { "playground": { "version": 1, "outputs": [ …the manifest's outputs… ] } }
```

The conformance kit checks that these equal the manifest's.

### 4.2 Documents

Each playground on a page is one document: `playground:///<id>/<name><extension>`. The
host sends `textDocument/didOpen`, `didChange` and `didClose` to every worker. Changes use
full-document sync (`TextDocumentSyncKind.Full`) unless your `initialize` result asks for
incremental. Many documents may be open at once: they are separate playgrounds, sharing
your worker. `languageId` is the manifest's `languageId`, or else its `id`.

**What the document holds.** The host this repository builds composes a playground's document
from its parts, and the same function (`composeDocument` in `packages/protocol`, the
`playgrounds compose` command) serves the editor, the build-time step, the conformance kit and
the exercises harness, so their line numbers agree:

```
setup, a line break, [terminator, a line break],
prelude, a line break, [terminator, a line break],
the reader's code
```

Each hidden part is there only if it is not empty, and its terminator only if the manifest
declares `document.terminator`. A trailing line break of a part is not significant. Without a
terminator, a hidden definition and the reader's first expression can read as one phrase
(OCaml: `let f x = x + 1` followed by `print_int 1` is one definition); with one, the language
server and the run both see closed phrases. `firstLine` (§5.2) counts the terminator lines.

### 4.3 The router

When a package has several workers, the host routes each message as follows:
- `initialize`, `shutdown` and document sync go to all workers;
- every other LSP method goes to the worker that serves `lsp`;
- `playground/*` goes to the worker that serves `outputs`.

It merges `initialize` results and renumbers requests a worker sends the host, so ids never
collide. A worker therefore never needs to know about the others.

### 4.4 Timeouts and restarts

The host times every `playground/produce` and `playground/action` request:
- `timeoutMs` from the output's declaration;
- otherwise 5 s for `run` and `demand`, and 2 s for `change`.

A worker that announces its steps (`playground/progress`, §5.2) gets the limit for each step:
every notice starts the time again.

When the time is up, the host:
1. sends `$/cancelRequest`;
2. waits 250 ms;
3. if there is still no answer, terminates the worker and starts it again;
4. replays `initialize` and every open document.

The editor's requests (hover, completion, semantic tokens and the rest) are timed too: one
left unanswered for 60 s restarts the workers the same way, so a check that never ends
cannot hold the editor.

A worker that computes without yielding cannot see a cancel, and that is fine: the restart
is the cancel. Keep nothing a reader would miss in a worker's memory beyond what replay
restores.

## 5. Outputs

### 5.1 Declarations

```ts
{ id: "desugar", title: "Desugared", triggers: ["change"], kinds: ["application/vnd.playground.code+json"] }
```

| Field | Meaning |
|---|---|
| `id` | `[a-z][a-z0-9-]*`. By convention, `run` is the program's output and `check` is exercises' verdicts. |
| `title` | the tab's label |
| `triggers` | when the host asks for it; at least one. `run` (the Run button, which produces every output with this trigger, in order), `change` (after a pause in typing), `demand` (when the reader asks, such as a selection's tree). The table below says what each does. |
| `needs?` | for `demand`: `selection` or `position`, which is then sent as `range`. A manifest with `needs` and no `demand` trigger is refused. |
| `timeoutMs?` | the host's limit (§4.4) |
| `kinds` | the item kinds it may produce |
| `replaces?` | ids this output had before. A host that holds snapshots stored under one of them maps them to this output; ids the manifest lists as `retired` are dropped. Neither may be a declared id. |

**What runs when.** An output is *live* when a tab shows it, a pane or a bound items element
shows it, or the page's `live` setting names it (`all`: every `change` and `demand` output;
default: those shown). Nothing is produced before the engine is ready, and no row below starts
it.

| Triggers | The host produces the output |
|---|---|
| `run` | on Run (the button, Ctrl/⌘+Enter, a command, `run()`): all such outputs, in the manifest's order. Never produced before: "Press Run". |
| `change` | while live: 500 ms after the reader's edit (not the host's write), and once when it becomes live or the engine becomes ready while it is empty or stale. |
| `demand` | once when it becomes live or the engine becomes ready while it is empty or stale; on its Refresh button; on `run(id)`. After an edit it turns stale and waits: it may be costly. |
| `run` with `change` or `demand` | both rows. |

Items from older code stay shown, marked stale, until replaced.

An output may declare `run` and `change` both. Do it only when producing is bounded (nothing
that can loop or run long), has no side effect a reader would mind, and answers well within the
`change` limit (§4.4). Running the reader's own program on each pause in typing does not qualify.

### 5.2 Methods

**`playground/produce`** (request, host → worker)

```ts
params: {
  output: string;                       // a declared id
  textDocument: { uri: string };
  trigger: "run" | "change" | "demand";
  range?: Range;                        // when the output needs one
  context?: { name: string; text: string; role: "prelude" | "setup" | "tests" }[];
  args?: unknown;                       // the page's parameters for this run (a seed, a count)
  firstLine?: number;                   // the line (from 0) where the reader's code starts
}
result: { status: "ok" | "error"; items?: Item[] }
```

- **`args`**, when present, are the page's parameters for this run, passed through as the page
  gave them (`el.run(output, { args })`): read what your outputs understand, ignore the rest.
- **`firstLine`**, when present, is the line of the document (counted from 0) where the
  reader's code starts, after a hidden setup and prelude the host put before it (see below).
  Absent means 0. A package whose own messages carry line numbers (a compiler's, an
  exception's) may count from this line, so that they match the editor's numbers; positions
  in items stay the document's.
- **`context`** carries hidden files the page's author adds, in order:
  - a `prelude` runs before the document, and the reader sees it;
  - a `setup` runs before the document, and the reader does not see it;
  - `tests` run after the document, for a `check` output.

  The host this repository builds puts a page's setup and prelude at the start of the
  document instead (§4.2, D49), so the language server sees them too: a package needs nothing
  for them, and its line numbers include them, unless it reads `firstLine`.
- **Status.** `status: "error"` means the program failed, through a compile error or an
  exception, and the items say how. A JSON-RPC error means the worker failed to produce at
  all.
- **An output that cannot be produced from this text.** The host reruns `change` outputs while
  the reader types, and keeps the last `ok` result on screen until a new one arrives. So a
  `change` output whose document does not parse, or does not check, for what that output shows,
  answers `status: "error"` with the reason (diagnostics or text), never `ok` with an error
  message as its items and never `ok` with no items. `ok` with no items means the document
  has nothing to show (no headings, no term). Declare `application/vnd.playground.diagnostics+json`
  or `text/plain` among the output's kinds for the reason. The conformance kit checks it for
  a document the package names (`invalid`, D64).
- **Fresh state.** Each `run` starts from a fresh environment: nothing of an earlier run or
  of another document is visible.

**`playground/items`** (notification, worker → host)

```ts
params: { request: number | string; items: Item[] }   // request: the produce's id
```

Stream items while the request runs, then answer it. Any items in the answer come after the
streamed ones.

**`playground/progress`** (notification, worker → host)

```ts
params: { request: number | string; step: string }   // step: "the phrase at line 3"
```

A step of the request begins. Once a worker sends one, the host's limit (§4.4) applies to
each step instead of the whole request, and a timeout names the step that ran too long. A
toplevel that runs phrases one by one sends one per phrase.

**`playground/action`** (request, host → worker)

```ts
params: { output: string; textDocument: { uri }; item: string; action: string; args?: unknown }
result: same as produce
```

This is a button that an item offered (`item.actions`), pressed by the reader. Its items
update the output, usually by `replace` of the item's `id`.

**`playground/release`** (notification, host → worker)

```ts
params: { refs: string[] }
```

The host no longer shows items carrying these `ref`s, so forget the state they stood for.

**`playground/reset`** (request, host → worker, no params, result `null`)

Forget every session and environment. The reader pressed Reset.

`$/cancelRequest` applies to `produce` and `action`. Answer a cancelled request with
error -32800, or at least stop streaming.

### 5.3 Items

```ts
interface Item {
  kind: string;            // below
  data: unknown;           // shape fixed by kind
  id?: string;             // a later item with the same id replaces it
  op?: "append" | "replace" | "clear";   // default append; clear removes the item with this id
  ref?: string;            // server-side state this item stands for (§5.2 release)
  actions?: { id: string; title: string; args?: unknown }[];   // buttons
  source?: Range;          // the part of the document it came from
}
```

An item's `source`, a mapping's `to` and a tree or graph node's `range` link the output to the
document: while the pointer is on that part of the output (or it has focus), the editor marks
the range, and a click scrolls to it.

Where the ranges of several mappings, tree nodes and graph nodes hold the same position,
only the smallest links (a later one on a tie), in both directions: hovering the output marks
the document, and a position in the document marks the output. A mapping or node never links
for the ranges of its ancestors.

The host validates every item, and treats every string as text, never as markup.

| Kind | `data` | The host shows |
|---|---|---|
| `text/plain` | `string` | text |
| `text/x-ansi` | `{ stream: "stdout" \| "stderr", text }` | text with SGR colours |
| `application/vnd.playground.code+json` | `{ language, text, mappings? }` | code highlighted by that package's grammar (`language` is a package id or alias, or `text`). `mappings: { from, to }[]` pairs a range of `text` (`from`) with the document's range it came from (`to`); hovering one highlights the other. |
| `application/vnd.playground.tree+json` | `{ label, kind?, range?, children? }` | a collapsible tree; a node's `range` highlights the document |
| `application/vnd.playground.graph+json` | `{ nodes: { id, label, kind?, range? }[], edges: { from, to, label? }[], layout? }` | a graph that the host lays out (`layered`, `tree` or `force`); a node's `range` highlights the document. Self-loops are drawn. |
| `application/vnd.playground.table+json` | `{ columns: string[], rows: (string \| number \| boolean \| null)[][] }` | a table |
| `application/vnd.playground.diagnostics+json` | LSP `Diagnostic[]` | a list linked to the editor. Live diagnostics while typing still use `textDocument/publishDiagnostics`. |
| `application/vnd.playground.verdicts+json` | `{ name, ok, message? }[]` | check results |
| `image/svg+xml` | `string` | an image; its scripts never run. `var(--pg-<name>)` (with an optional fallback) and `currentColor` take the page's values, so `fill="var(--pg-fg)"` follows the site's theme. Tokens: `fg`, `bg`, `muted`, `border`, `code-bg`, `accent`, `error`, `warning`, `ok`, `info`, `token-*`, `ansi-0`–`ansi-15`. |
| `text/html` | `string` | only through a renderer you declare (§5.4) |
| `application/vnd.<package>.<name>+json` | anything | only through a renderer you declare (§5.4) |

A `kind` attribute such as a node's `kind` is a class hook for styling (`pg-kind-<kind>`),
not a colour. Colours are the host's.

**How items print.** `itemsToText(items)` (`packages/protocol`, no DOM) is the one text form:
what the conformance kit compares with `expectedOutputs`, and what a server may keep for
search. The items' ops are applied first. Then:

| Kind | Printed as |
|---|---|
| `text/plain` | its text, as given |
| `text/x-ansi` | its text without escapes, as given |
| code | its text as a block of its own: a line break ends it |
| table | tab-separated rows, the columns first |
| tree | one label a line, indented two spaces a level |
| graph | `a -> b label` for each edge (the nodes' labels, or ids), then the nodes no edge touches |
| verdicts | `ok name` and `FAIL name: message` |
| diagnostics | `line:col severity: message`, from 1, severity `error`, `warning`, `info` or `hint` |
| SVG, HTML, a kind of your own | nothing |

Text and ANSI carry their own line breaks; every other form is whole lines. `itemsToMarkdown`
(Markdown for a host's own document), `validateItems`, `validateSnapshot` and `toStorable` are
in the same layer.

### 5.4 Renderers of your own

For a kind the host does not know, declare `renderers: [{ kind, module }]`.

The host runs `module` in a sandboxed frame of its own, separate from your workers. That
frame has no network, no eval and no WebAssembly, and allows inline styles. The module
exports:

```ts
export function render(data: unknown, element: HTMLElement, host: {
  tokens: Record<string, string>;   // the page's resolved design tokens: --pg-bg, …
  action(id: string, args?: unknown): void;   // as an item action
  resize(): void;                   // after a change of height
  // Links document ranges as hovering a part of an output does (null: none); the editor and
  // every output mark them. At most 64 ranges, 30 calls a second.
  link(ranges: Range[] | null, options?: { scroll?: boolean }): void;
  // What is linked and marked now (a part hovered anywhere, the page's marks), at once and on
  // every change: mark your own parts that overlap.
  onLinks(handler: (links: { linked: Range[]; marked: Range[] }) => void): void;
}): void | (() => void);            // optional cleanup
```

Prefer a built-in kind where one fits. A tree or a graph from your language looks like
everyone else's and follows the page's theme with no work from you.

## 6. The grammar

A TextMate grammar (JSON) with your `scopeName`. It colours everything:
- the editor before activation;
- static code blocks at build time (Shiki);
- client-side colouring of code blocks, in apps without a build step;
- your code items;
- VS Code, if you like.

Use the conventional scope names (`keyword.control`, `entity.name.function`,
`variable.parameter.function`, `string.quoted`, `comment.line`, `constant.numeric`, …). The host
maps scopes to its classes by prefix, so the conventional names get colours with no work.
Parameters are `variable.parameter.function` (the shorter `variable.parameter` has no colour),
operators `keyword.operator`.

**Not `markup.*`.** A theme gives `markup.underline`, `markup.italic`, `markup.inserted` and the
like the styles of prose: underline, italics, strings, diff colours. A scope list that borrows
them to get a colour makes code look wrong. The conformance kit warns of every `markup.*` scope.

**Regular expressions.** These must work under Shiki's JavaScript engine, which translates
Oniguruma syntax to JavaScript's. The kit runs your grammar through it on your examples and
fails on any rule it cannot translate.

After activation, LSP semantic tokens (`textDocument/semanticTokens/full`) refine the
colours, if your server offers them.

## 7. Versioning

- **This is version 1.** Optional fields and new kinds or probes may be added within it; a
  host ignores what it does not know.
- **A breaking change** becomes version 2: `manifest: 2`, `experimental.playground.version:
  2` and methods under `playground/v2/`. A host may speak both.
- **Added within version 1 (D67), each optional:** the `plain` policy (§3: a host that does not
  know it refuses the manifest, as with an unknown `encoding`); `outputs[].replaces` and
  `retired` (§5.1); `languageId`; `document.terminator` (§4.2); `examples[].expectedOutputs`
  and the examples' `setup`, `prelude` and `tests`; `files[].lazy`. A host ignores what it
  does not know, and an older host runs a package with them except for what they add: it
  keeps no mapping of stored snapshots, sends no terminator and loads a lazy file at start. The
  validator also refuses what it accepted by mistake: an output with no `triggers`, and `needs`
  without `demand`.
- **`workers[].remote` (§3) and the wire (§8) are additions, each optional.** An older host
  ignores `remote` and refuses a worker with no variants, rightly: it cannot run one. The wire
  has a version of its own in the subprotocol's name, `playgrounds-remote.1`.
- **`parts` (§1) is such an addition.** A host that does not know it fetches the file's own
  path, which a package with parts does not have, and fails with `HTTP 404` for it. It never
  loads part of a file.
- **`encoding` and `decoded` (§1) are such an addition, with a catch.** A host that does not
  know them hands the worker the stored gzip bytes, so the worker fails on reading the file;
  there is no clean refusal as with `parts`. `manifest` stays 1: `assemble` and the host come
  from one release and serve a package together (`mkPlaygrounds`), and a host older than
  this change cannot run a package built after it. The schema accepts `encoding: "gzip"` only.
  A second encoding is a new value of the same field and needs the host to know it first; a
  change to what the existing fields mean is version 2.

## 8. The wire to a remote

For implementers of a remote, and of a client other than the page's core. Schema
`schemas/remote.v1.json`; the types and validators are `packages/protocol/remote.ts`. Schemas
check the shapes; this section says what each side does with them.

### 8.1 One WebSocket, one worker

A host opens a WebSocket with the subprotocol `playgrounds-remote.1` (a client that does not
offer it fails the handshake). The socket's life is the worker's: opening starts a process,
closing ends it. Text frames only, no compression.

1. **`Hello`**, the client's first frame, within 5 s of the open (strict; any other key is
   refused):
   `{ playgrounds: 1, package, build, worker, token?, resume? }`. `package` is the package's id;
   `build` the sha256 (hex) of the `manifest.json` the client holds; `worker` a worker's id;
   `token` a ticket (§8.3); `resume` is reserved.
2. **`queued`**, zero or more times while the remote has no room: `{ playgrounds: 1, queued: n }`,
   `n` places ahead, sent again as it changes.
3. **`welcome`**, once: `{ playgrounds: 1, session, resumed, received, limits: { up, down,
   idleMs, sessionMs, resumeMs }, features, source? }`. `up` and `down` are the largest frame
   each way, in bytes; `features` lists what the remote adds within version 1 (a side sends only
   what the other announced); `source` says where the remote's source is (an AGPL service owes
   it to its users).
4. After the welcome, **every text frame either way is one JSON-RPC message** (§4, §5), as to a
   frame's worker. The remote parses none of them.

A binary frame ends the connection (1003), and so does a frame over the limit (1009). A frame
between the hello and the welcome is a protocol error (4400 `protocol`).

| Close code | Means | Reason words |
|---|---|---|
| 1000 | the client ended the worker | |
| 1001, 4001 | the page went away, or is hidden | |
| 1003, 1009 | a binary frame; a frame over the size | |
| 4400 | a bad or late hello, a message out of turn | `bad-hello`, `late-hello`, `protocol` |
| 4401 | the ticket is missing, expired or wrong | `ticket` |
| 4403 | the page's `Origin` is not allowed | `origin` |
| 4404 | the remote holds no such build or worker, or nothing runnable | `unknown-build`, `unknown-worker`, `no-runtime` |
| 4429 | this client's caps | `client-limit`, `rate`, `busy-sockets` |
| 4500 | the process could not start, or exited | `start`, `exited` |
| 4503 | the queue is full, or the wait passed its limit | `queue-full`, `queue-timeout` |
| 4507 | a limit ended the process | `memory`, `cpu`, `processes`, `disk`, `output`, `time`, `idle` |
| 4512 | the remote is draining for a deploy | `draining` |

A close reason is a word from this list, or `<word>; retry=<seconds>`. It never holds a
program's text, a path or a ticket. The remote accepts the handshake of a page whose origin is
not listed and closes at once with 4403, having read nothing: a page cannot read a failed
handshake's status, and a wrong origin is the commonest setup error. A client that sends no
`Origin` (not a browser) is not refused for it.

The remote pings every 25 s and closes a socket that missed two pongs; a session ends after
10 minutes with no frame either way (4507 `idle`) and after 30 minutes in all (4507 `time`).
Limits an engine asks for in `remote.json` are held to the operator's caps. A remote closes a
worker that writes a frame over `down`, or that breaks the framing (4507 `output`).

### 8.2 What a remote holds: `remote.json`

An engines directory holds `<id>.<build>/` for each build of a package: the package's own
files, as a site serves them, and `remote.json`:

```json
{ "remote": 1, "id": "echo", "build": "<sha256 of manifest.json>",
  "workers": { "server": { "command": ["node", "cli.ts", "worker", "world", "{engine}", "server"],
                           "closure": [], "env": {}, "limits": {}, "warm": true } } }
```

- **`build`** is the sha256 of the directory's `manifest.json`, and the directory's name says
  it. A client's `Hello.build` must equal it, or the remote closes 4404.
- **A worker's `command`** is an argv; `{engine}` in an argument stands for the build's
  directory. `closure` lists the store paths a sandbox binds read-only. `limits` (`memoryMiB`,
  `cpuSeconds`, `wallSeconds`, `idleSeconds`, `busyMs`) is what the worker asks for.
- **`workers[].remote.build`** in the manifest is the sha256 of the worker's own entry in this
  file (its JSON with sorted keys and no whitespace), not of the file, so the manifest's hash,
  which holds it, and `remote.json`'s `build`, which is the manifest's, are not circular.
  `assemble`, the remote's loader and the kit check both.
- `playgrounds engines <package-dir> <engines-dir>` writes this directory for a package whose
  workers are hosted.

`GET <url>info` answers `{ "playgrounds-remote": 1, version, engines: [{ id, build }], source? }`
for operators; a client never asks.

### 8.3 Tickets

A site with accounts can require a ticket in the hello. It is `v1.<base64url claims>.<base64url
mac>`, the claims `{ exp, aud, sub? }` (unix seconds, at most 300 s ahead; the remote's own URL;
an opaque subject the remote's limits count by) and the mac HMAC-SHA-256 over
`v1.<base64url claims>` with the site's secret. One algorithm and no `alg` field: there is
nothing for a forger to choose. The remote compares the mac in constant time and checks `aud`
and `exp`. The ticket goes in the hello, never in a URL, and never in a close reason.
`signRemoteToken` and `verifyRemoteToken` in `packages/protocol/remote.ts` do both.

### 8.4 Checking a remote

`playgrounds check <package-dir> --remote <url> [--secret-file <file>]` runs the kit's checks of a
worker's behaviour with every worker through the remote, after two refusals every remote
owes: a hello that is not one (4400) and a build it does not hold (4404). `--engines <dir>`
starts a remote of its own on loopback over an engines directory and does the same.

`playgrounds serve [<dir>] --engines <dir> --sandbox bubblewrap|unsafe-process [--origin <origin>]…
[--listen <host:port>] [--secret-file <file>] [--seccomp <file>] [--bwrap <path>] [--cgroup <dir>]
[--trusted-proxy <cidr>]… [--public-url <url>] [--limits-file <file>]` runs a remote over engines directories on one
port: the upgrade and `GET /info` are the remote's, every other request is the built directory's
(none without `<dir>`). `bubblewrap` is the jail (`docs/remote.md`); `unsafe-process` contains
nothing, so a `--listen` beyond loopback is refused for it alone. The remote's code (`packages/remote`) is
AGPL-3.0-or-later and not in the `code-playgrounds` npm package: `--engines` works from this
repository only.
