# Writing plugins

Add project-specific commands, effects and system screens as plugins (npm packages). You don't touch the engine itself.
A working example is [examples/stamp-plugin](../examples/stamp-plugin) (`@stamp` and `@stamp-clear`, which press stamps on the screen).

## Adding a plugin

List package names or folders in `plugins` in the project's `liminalia.json`.

```json
{ "plugins": ["./plugins/stamp"] }
```

You can also list folders outside the project (`../my-plugin` or an absolute path). On a computer that doesn't have that folder (another Mac),
the plugin is skipped without being loaded (you're told once, and `lim check`, `lim build` and Studio keep going). Folders inside the project and package names stop with an error if they're missing.

A plugin that can't be loaded (the package isn't found, the folder or `package.json` is missing, loading `./commands` throws, or there's no default export)
stops `lim check`, `lim build` and so on with the one sentence "Can't load plugin X (reason)". `lim studio` and Studio open without that plugin and
show the same sentence in the bar at the top and in the "Plugins" category of the check. That plugin's commands become undefined, so findings about undefined commands are folded into this diagnostic
(the preview's player also skips the entry points it can't load and runs with the rest). Once it's fixed, reopen with "Refresh".

Put the following entry points in `exports` in the package's `package.json` (all optional).

| Entry point | default export | Loaded by |
|---|---|---|
| `./commands` | `CommandPlugin` (`defineCommandPlugin` from `@liminalia/sdk`) | The check, running without a screen, import, export and the player (loaded in both Node and the browser) |
| `./web` | `WebPlugin` (`defineWebPlugin` from `@liminalia/sdk/web`) | The player only (browser) |
| `./import` | `TyranoImportProfile` (`@liminalia/sdk/import`) | Only `lim import`, `lim backport`, `lim reference` and the dev server's sprite position editor (`writeCast`) (Node) |
| `./studio` | `StudioPlugin` (`defineStudioPlugin` from `@liminalia/sdk/studio`) | Studio (Liminalia Studio) only (browser). Adds project-specific screens to the "Plugins" tab |
| `./studio-server` | `StudioServerPlugin` (`defineStudioServerPlugin` from `@liminalia/sdk/studio-server`) | Studio's dev server only (Node). Adds APIs that the `./studio` screens call ([The dev server side](#開発サーバー側の口studio-server)) |

Anything related to importing from TyranoScript (.ks tag names, conversion, imports of `@liminalia/sdk/import`) goes only in `./import`.
`./commands` and `./web` are included in the exported game, so they don't import the import engine (`@liminalia/ks-import`)
(if they do, `lim build` stops and shows where it's imported from).

Integration with desktop stores (GOG Galaxy, Epic Games Store and so on) doesn't use these entry points. Instead, you build it in with a CommonJS file set in `build.store.desktop.module` in `liminalia.json`
(it runs in the main process of the desktop version; see “Other stores” in [distribution.md](distribution.md)).

The standard commands (`@liminalia/std`) are always loaded first, without being listed. When two commands have the same name, the one from the later plugin wins.

**Declaring compatible engines**: the plugin interfaces (`CommandPlugin`, `WebPlugin` and what's passed to their `api`) have a version (`PLUGIN_API_VERSION`, readable from `@liminalia/sdk`; currently 8. Version 8 added the `@liminalia/sdk` entry points).
If you write the interface version the plugin needs in its `package.json` as `"liminalia": { "api": 2 }` or `"engines": { "liminalia": ">=2" }` (`>=`, `<`, `^`, `2 - 3` and `||` are understood),
`lim check` and Studio's check warn when this engine doesn't meet it (`plugin-engine-version`). You can also write it in `apiVersion` of `defineCommandPlugin` and `defineWebPlugin`
(on the command side, `lim check` reports it with `plugin-api-version`; on the rendering side, it's shown in the developer tools of the game screen).
`engines.liminalia`, written the same way, can also go in a theme's `theme.json` ("Themes" in [player.md](player.md)) and in the `liminalia.json` of games and templates.
All of them are compared with the same interface version, and `lim check` warns when they don't match (`theme-engine-version`, `engine-version`). When you create a game from a template someone shares with `lim new <folder> --template <template>`,
`lim new` also tells you before creating it (the template's `engines` and `format` stay in the created game). The interface version also goes up when items are added to what themes can write in `ui` or to the game's settings.
Studio's "New plugin" and "Save the current look as a theme" write `engines.liminalia` from the current interface version (such as `">=2"`).
### The package plugins import (`@liminalia/sdk`)

Plugins import only `@liminalia/sdk` (MIT), the plugin contract, and its entry points.

| Entry point | Contents |
|---|---|
| `@liminalia/sdk` | Command plugins (`defineCommandPlugin`, `t`, `d`, `defineState`, `withEnglish`, `argOrigin`, `PLUGIN_API_VERSION`) and types such as `Cast`, `Value` and `StageState` |
| `@liminalia/sdk/std` | Parts of the standard commands (`leaveParam`, `presentLeaving`) |
| `@liminalia/sdk/web` | Rendering plugins (`defineWebPlugin`, `ui`, `systemText`, `dataText`, `loadScript`, `registerLayerItem`, `ChoiceHistory` and more) and their types |
| `@liminalia/sdk/studio` | Studio plugins (`defineStudioPlugin` and the screen parts) and their types |
| `@liminalia/sdk/studio-server` | Dev server plugins (`defineStudioServerPlugin`, `StudioServerError`, `findRunningStudio`) and their types |
| `@liminalia/sdk/import` | Types for import profiles (`TyranoImportProfile` and more) and `castFromTatieSettings` |

The sdk holds only the contract (types and small functions). Anything that needs an implementation, such as the rendering parts, calls the implementation of the running `lim` or Studio app.
Plugins run inside `lim` and the Studio app, so they work without the sdk installed in the game folder (even if it's installed, the implementation of `lim` and the Studio app is used when they run).
When you write a plugin in a separate repository, put `@liminalia/sdk` in devDependencies and you get the types with your own tsconfig.
To parse and check scenarios and run them without a screen in tests, also put `@liminalia/cli` in devDependencies and import from its test entry point `@liminalia/cli/testing` (`parse`, `check`, `createRegistry`,
`CORE_COMMANDS`, `Runtime`, `HeadlessHost`, `combinePlugins`, `runPluginChecks`, `checkPluginManifest`, `convert`, `resolveImportProfile`).

Names that plugins from earlier versions import, such as `@liminalia/web`, `@liminalia/lang` and `@liminalia/studio/plugin`, still work inside `lim` and the Studio app.
They are part of `lim`, though, and aren't published on npm, so to get the types, change them to the `@liminalia/sdk` entry points.

You can also make a game from a template URL (`lim new <folder> --from github:owner/repo#tag`, `--from https://…/template.zip`, or an https Git URL).
After fetching, it's made the same way as with `--template` (Git fetches shallowly, without submodules or the repository's hooks; unencrypted `http://` is accepted only for localhost).
If the fetched template has code that runs when the project is opened, such as plugins or a signing command, it shows what runs and tells you once to check the contents before opening it if you don't know who made it.

### Opening in restricted mode

Plugins run just by opening a project, and they can read and write files on that computer.
The Studio app and `lim` always run the project's plugins. Each tool handles it as follows (`packages/project/src/trust.ts`).

| Tool | How it's handled |
|---|---|
| `lim` | With `--restricted` (accepted by every command; the same as `LIMINALIA_RESTRICTED=1`) it's restricted |
| VS Code | Follows workspace trust. In an untrusted workspace, plugin code doesn't run, and Play from Here doesn't run the `lim` inside the project either (the `lim studio` it starts is restricted). The `liminalia.lim`, `liminalia.node` and `liminalia.studioApp` settings don't use workspace values until you trust it |
| Browser version | Asks whether to run plugins the first time you open each folder on a PC (see [studio-mobile.md](studio-mobile.md)). Connecting from a phone to desktop Studio uses the desktop version's plugins |

What counts as code that runs: plugins in `plugins` and `import.tyrano.profile` (shown with their entry points), the Windows signing command (`build.windows.sign.command`) and
the command that wraps the executable (`build.windows.wrap`), and the desktop store module (`build.store.desktop.module`; it runs in the check after exporting).

When restricted, the project's plugins and import profile aren't loaded (checks use only the standard commands, and the preview doesn't show plugin rendering), and exporting stops.
Studio shows "The project is open in restricted mode, so it was opened without running its plugins: …" in the banner at the top.

## Official plugins

"Official plugins" in the "Plugins" tab of Studio lists the plugins bundled with the app. "Install" copies a plugin into `plugins/<id>` in the project and
adds `./plugins/<id>` to `plugins` in `liminalia.json` (npm isn't used; it takes effect after a restart). For now there are three: AI consultation (`ai`, from the separate liminalia-ai repository),
Live2D (`live2d`) and Spine (`spine`) (Live2D and Spine are in `plugins/` in this repository. How to use them, and the runtimes authors get themselves, are in [live2d-spine.md](live2d-spine.md)).

The list is `catalog.json`, looked up in this order (`packages/studio/src/server/catalog.ts`).

1. The folder in the `LIMINALIA_PLUGIN_CATALOG` environment variable (the desktop version passes the app's `Resources/plugins`, or `resources/plugins` on Windows.
   `lim` installed from npm passes the `plugins/` inside the cli package when it isn't set)
2. `catalog/` in the repository (for `lim dev` and `lim studio` run from the repository)

```json
{
  "plugins": [
    {
      "id": "ai",
      "name": "AI 相談",
      "nameEn": "AI consultation",
      "description": "…",
      "descriptionEn": "…",
      "folder": "../../liminalia-ai",
      "folderEnv": "LIMINALIA_AI_DIR"
    }
  ]
}
```

| Field | Contents |
|---|---|
| `id` | The name of the `plugins/<id>` folder in the project (starts with a lowercase letter; lowercase letters, digits and `-`) |
| `name`, `nameEn`, `description`, `descriptionEn` | The name and description shown in the list (chosen by Studio's language; `name` and `description` are the Japanese ones) |
| `folder` | The plugin's folder. A path relative to the folder containing `catalog.json`, or an absolute path |
| `folderEnv` | If set, the folder in this environment variable is used before `folder` |
| `version`, `entries` | If left out, they're taken from `version` and `exports` in the folder's `package.json` |

The AI consultation source isn't kept in this repository, and the repository's `catalog/catalog.json` points to a separate repository placed next to it. Live2D and Spine point to `plugins/live2d` and `plugins/spine` in this repository.
and `npm run studio:package`, which builds the desktop version, copies them from there into the app's `Resources/plugins/<id>` (without `node_modules`, `.git` and `test`).
In the `catalog.json` included in the app, `folder` is rewritten to the name of the copied folder, and `version` and `entries` to the values worked out.
AI consultation is copied from `LIMINALIA_AI_DIR`, or from `../liminalia-ai` next to the repository. If it isn't found, a warning is shown and it's left out (the app still builds).
The npm package (`scripts/npm-pack.mjs`) puts them in the cli package's `plugins/` in the same shape, but only the ones in this repository (Live2D and Spine).
AI consultation, which points outside the repository, isn't included (users can pass their own list folder with `LIMINALIA_PLUGIN_CATALOG`).
Bundled plugins can't have dependencies (`dependencies`; if they do, the build stops). For `@liminalia/…`, import only types, or use the app's own.

Once installed in a project, it's the same as any other plugin in the project (you can edit its name and description, and open its folder). If the bundled version is newer than the installed version
(`version` in `plugins/<id>/package.json`), "Update to <version>" appears. Reinstalling keeps the previous contents in `.liminalia/backups/plugins/`.
If `plugins/<id>` holds a different package (one with a different `name`), it isn't installed.

## Commands (`./commands`)

Commands are written as `CommandDefinition` tables. This one table gives both the spec (the checks in `lim check`, completion and `lim reference`) and
what runs at play time. Conversion from .ks tags isn't written here ([Import](#取り込みimport)).

```ts
const stamp: CommandDefinition = {
  name: "stamp",                 // the command name in .lim (lowercase letters, digits and -)
  summary: "Press a stamp on the screen",
  positional: ["image"],         // unnamed parameters (they can't be written with a name)
  params: {
    image: t.required(t.asset("image", "Stamp image")),
    x: t.number("Horizontal center (px)", "640"),
    wait: t.bool("Wait until the stamp is pressed before continuing", true),
  },
  example: "@stamp stamps/ok.png x=900",
  waits: true,
  apply(args, extra) { /* rewrite stage.extra */ },
};
```

- **Parameter types**: `t.string` `t.number` `t.int` `t.bool` `t.duration` `t.color` `t.enum` `t.asset(folder)`,
  `t.variable` (a variable to store a value in, `game.x`), `t.target` (a jump target; `lim check` checks that the label and file exist, and Studio suggests candidates), `t.cast` (a character; for a parameter that acts on a character whose sprite is on screen, use `t.cast(description, default, { shown: true })`, described below),
  `t.condition` (a condition; written as a `(…)` expression, and the truth value evaluated at run time is passed), and `t.dataKey(file, path, description)` (a name inside project data:
  with `t.dataKey("stamps.json", "books", "Stamp book")`, a key of `books` in `data/stamps.json`, or an item's `id` if it's a list. The path is separated with `/`. `lim check` checks that it exists (`unknown-data-key`),
  and Studio's right panel suggests the names). For a number range, use `t.number(description, default, { min, max })` (the same for `t.int`; `lim check` reports values outside it, and Studio's field uses that range too).
  For sprite sets, variants and positions, use `{ type: { kind: "appearance" | "variant" | "position" } }`.
  `asset` checks that the asset exists before export, and is also used to preload each page.
- **Characters on screen**: for a parameter that only makes sense for a character whose sprite is on screen (hiding, moving, shaking, adding an emote and so on),
  use `t.cast("Character to shake", undefined, { shown: true })` (as a type, `{ kind: "cast", shown: true }`). Studio's completion lists the characters shown on that line first
  (the other characters stay in the list; `lim check` and the game don't change). Among the built-in and standard commands, `@chara-hide`, `@chara-move`, `@chara-shake`, `@emote`, `@emote-off`, `@dof`, `@tone`
  and `hide-who` of `@scene-change` have it, and `@chara` (a character you're about to show) and `@face` don't. The mark was added in API version 7; earlier engines don't read it and simply don't list the characters on screen first.
  For a character parameter of a `@define` macro, the characters on screen go first when the first command in the body (in written order) that the parameter is passed to as is (`(who)`) has this mark on that parameter
  (a macro that passes it to `@chara` first is also used for characters not yet shown, so it doesn't).
- **Translatable text**: write text shown to players (chapter titles, on-screen captions, dialog text and so on) with `t.text`, not `t.string`. In a multilingual project,
  the values written in the scenario are listed as command text in the `lim i18n` translation files, and at play time the translation for the language being played is passed to the command instead
  (if the translation is empty, the original is used). Write people's names (speakers, the person being addressed) with `t.name`, and they're listed under `speakers` in the translation files. Names are also used for matching, so
  the runtime doesn't replace them. Translate them when you display them, with `ctx.runtime.translator?.speaker(name) ?? name`.
  Text from project settings, such as the title in `ctx.runtime.chapter`, is passed already translated into the language being played.
  A command that leaves translated text in `stage.extra` gets the origin of the original text with `argOrigin(args, "parameterName")` (`@liminalia/sdk`),
  and puts `i18n: { field: origin }` next to the text. When the language is changed, or a save is loaded in another language, the runtime rewrites that field in the current language.
  To rewrite elements already on screen, use `extensions.relocalizers` (the same shape as `restorers`) to replace the text starting from the already-rewritten state.
- **Default values**: if the command is imported from a .ks tag, make them the same as that tag's value when the parameter is left out. Import writes out only values that differ from the default.
- **bare** is the name of a parameter that takes one unnamed value after the unnamed parameters (`positional`) are filled (it can also be written with its name).
  Use it for the time of a command that takes no target (with `bare: "time"`, `@stamp-off 300ms` is the same as `time=300ms`). The field was added in 0.6.0 with the API version still 6,
  so engines 0.4.0 to 0.5.x don't read it and treat the unnamed value as an extra parameter (`too-many-positional`). To support those engines, write the name in examples and docs.
- **waits** is whether to wait for the effect to end before moving on (a written `wait` takes precedence). For a command with a `wait` parameter, leaving out `waits` makes it follow that parameter's default.
  For commands written with `run`, make it match the wait passed to `ctx.present()`. Studio's "Timeline" and `lim reference` read it.
- **variables** (optional) on a plugin (`defineCommandPlugin`) are the variables that the plugin's commands store values in (`"game.x"`; ending with `.*`, like `"game.codex.*"`, covers every name under it).
  `lim check` and Studio's check report variables that are only read and never set anywhere as possible misspellings (`unset-variable`), so list here the variables you set with `ctx.runtime.setVariable` and the like.
  Flags set through the project data shape declaration (`data`) don't need to be listed.
- **replaces** (optional) is set to `true` when a command deliberately replaces a built-in command or a command with the same name from a plugin loaded earlier (such as the standard commands).
  The command from the plugin loaded later is used. If you make a command with the same name without it, `lim check` and Studio's check warn (`plugin-replaces-command`;
  this is so that you notice when a new version of the engine adds a standard command whose name collides with a command in the project's plugin).
- **category** (optional) is the section of Studio's parts panel (`screen`, `sprite`, `sound`, `motion`, `flow`, `system`). If you leave it out, the command is listed under "Custom commands".
- **keywords** (optional) are words for what you want to do (`["shake", "impact"]` and so on). They let a search in the parts panel find the command even if you don't know its name or description.
- **English** (optional): if you write `summaryEn` (the summary), `docEn` on parameters (the description), `keywordsEn` (words for what you want to do) and `exampleEn` (the example),
  Studio and VS Code in English, `lim reference --lang en` and `lim reference --json` show the English. Where they're missing, the English display shows the main (usually Japanese) text.
  Write `exampleEn` when the example contains a character's name or text that's shown (such as `@chara ユイ` or `@notify 鍵を手に入れた`), with those in English
  (it isn't needed for an example that has only asset names and setting values). For parameters,
  add it like `{ ...t.bool("押し終わるまで次に進まない", true), docEn: "Wait until the stamp is pressed before continuing" }`.
  With many commands, you can also overlay a table keyed by command name with `withEnglish` (`@liminalia/sdk`) (the built-in and standard commands use this form).
  For each name, the table holds `summary`, `params`, `keywords` and `example` (the English example).

  ```ts
  commands: withEnglish([stamp], {
    stamp: { summary: "Press a stamp on the screen", params: { image: "Stamp image", x: "Horizontal center (px)" }, keywords: ["stamp"] },
  }),
  ```
- **State** is written to `stage.extra` in `apply(args, extra)`. It goes into saves, so use only plain values that can be turned into JSON,
  and prefix keys with the plugin's name (`"stamp.list"`). Deleting the whole key when it becomes empty keeps save data small.
  To read and write it with a type, create it once with `defineState<Type>(key, initial)` (`@liminalia/sdk`) and use the same one on both the command side and the rendering side
  (no need to write `as unknown as Value`; `read` returns a copy, `update(extra, (v) => { … })` rewrites it and puts it in, and `clear` removes the whole key)
  ```ts
  interface Stamps { list: { image: string; x: number }[] }
  export const stamps = defineState<Stamps>("stamp.list", () => ({ list: [] }));
  // command: apply(args, extra) { stamps.update(extra, (s) => void s.list.push({ image: String(args.image), x: Number(args.x) })); }
  // rendering: restorers: [async (ctx, stage) => draw(ctx, stamps.read(stage.extra))]
  ```
- Commands that need more than a state update, such as storing a result in a variable, jumping or waiting for a click, are written in full with `run(args, ctx)`
  (`ctx.runtime.jump()` / `setVariable()` / `waitClick()`, and `ctx.present()` to pass things to the rendering side).
  For a command that shows UI and waits, calling `ctx.resumeHere()` before waiting makes saves made in the meantime resume from this command.
  Calling `ctx.atSceneBreak(args)` instead of `ctx.present(args, false)` holds off passing it to the rendering side until the next scene break (`@scene-change`, `@bg` with a different image, `@mask`,
  `@jump` to another file, and choices), and passes it before the next text or choices after the break (`@notify when=scene-break`; while it waits, it goes into saves.
  See "Scene breaks" in section 5 of [format.md](design/format.md)).
  Set variables with `setVariable()` (so the change reaches watchers such as the codex's). If you rewrite `ctx.state.game` or similar directly,
  report it with `ctx.runtime.variablesChanged("game.x")`. To receive changes, use `runtime.onVariableChange(path => …)` (the returned function removes it).
  To make a picture the command showed itself (such as a temporary picture of an investigation spot) a CG in Extras, unlock it with `ctx.unlockCg(image)` (the same as `@cg-unlock`; don't rewrite system variables directly).
- Completion rates (`{ done, total }` for read text, endings, CGs, scene replays, music, movies and achievements, and the overall rate `rate`)
  can be read with `completion()` on the `system` received in `ready` (on extras screens the project makes, `ExtraScreenApi.completion()`; for the current count of a counting achievement, `achievementProgress(achievement)`).
- Commands such as chapter title cards and chapter endings can read the number and title from `ctx.runtime.chapter` (the current chapter from `chapters` in liminalia.json: `{ id, title, number, subtitle, … }` or `null`).
  If the command uses the chapter information when parameters are left out, you don't have to write the same values for every chapter (see “Chapters” in section 10 of [format.md](design/format.md)).
  Before play starts (at the time of `ready`, on the title screen, in Extras), `system.runtime` is null, so read from `system.chapters` on the `system` received in `ready`
  (all of `chapters`; titles, numbers and subtitles are translated into the language being played; empty if there are none) and `system.chapterOf("file")`
  (the chapter of that scenario file, decided the same way as `runtime.chapter`; `null` if there's none). You can also use these to show the chapter for a save slot's position
  ```ts
  ready({ system }) {
    const titles = (system.chapters ?? []).map((c) => c.number ?? c.title); // the chapter list on the title screen
    const first = system.chapterOf?.("chapter1_1"); // the chapter of that file
  }
  ```
- A command that lets players choose where to go on its own screen (a map, investigation spots and so on) builds one list of the possible outcomes (label, jump target, value) and
  decides the result with `await ctx.pick(outcomes, answer)`. The answer is what the rendering side returned, interpreted by the command; if there is one, it becomes the result.
  When the rendering side doesn't return an answer (when running without a screen: Studio's route search, the all-routes test, `lim trace`), the engine offers the list as choices as is,
  so the search and the all-routes test can try every destination (the first item in the list is the default pick). If you include jump targets (`"file"` or `"file#label"`),
  the search tries destinations closer to its goal first
  ```ts
  const outcomes = spots.map((s) => ({ label: s.name, target: `${file}#${s.label}`, value: s.id }));
  const spot = await ctx.pick(outcomes, readAnswer(await ctx.present(args, true)));
  ```
  If you leave a destination out of the list, play without a screen can never go there, and it stays "Unreached" in Studio. If you build `targets` and `run`
  from the same function that makes the list, nothing is left out. (You can also choose with `ctx.choose(options, targets)`, but then you keep two lists.)
- **How automated checks go on** (`autoplay`): for a command that shows a screen waiting for the player (a map, investigation spots, a minigame) or a long effect that should be skipped,
  write `autoplay(args, ctx)`. When nobody is playing (`lim playtest`, `lim shot`, the desktop app's playthrough check, the all-routes test, `lim trace`),
  `ctx.present()` doesn't let the rendering side (`renderers`) draw; it calls this and uses the returned value in place of the rendering side's answer (`args` is what was passed to `ctx.present()`).
  If it returns nothing, there's no answer, and a command that chooses a destination with `ctx.pick` above gets its list offered as choices by the engine. `lim playtest` picks them
  differently on each run like other choices, and `--choose` can pick them too. If an answer is needed, such as the result of a minigame, return it
  ```ts
  const map: CommandDefinition = {
    name: "door-select",
    // …
    async run(args, ctx) {
      const outcomes = doorOutcomes(await ctx.data("doors"));                  // the list of destinations (made by the same function as targets)
      const picked = await ctx.pick(outcomes, readAnswer(await ctx.present(args, true)));
      if (picked) await ctx.runtime.jump(picked.target);
    },
    autoplay: () => undefined,                                                  // no screen; the list becomes choices
  };
  const puzzle: CommandDefinition = { name: "puzzle", /* … */ autoplay: () => ({ solved: true }) }; // goes on as if solved
  ```
  A screen of a command without `autoplay` doesn't advance just by clicking, so `lim playtest` reports it as stuck. Among the standard commands, `@investigate` offers its spots as choices,
  `@movie` doesn't play, `@codex` and `@open-screen` don't open, `@text-input` keeps its initial value, and `@dialog` answers OK.
  For an example, see `@stamp-pick` in `examples/stamp-plugin` (choosing a stamp on a screen). In the player, `?autoplay=1`,
  or a tool that sets `window.__liminalia.host.automated = true`, turns on automated checking.
  `lim shot` turns on automated checking only until it reaches the place to capture (`?autoplay=shot`). The screens of commands with `autoplay` that appear between the start position and the first page (when `--skip` is 1 or less)
  are drawn by their renderers without using `autoplay`, and captured once they've been shown for 0.5 seconds (choices too are captured once they appear).
  With `--skip` 2 or more, such screens before page N go on through `autoplay` as before, and if a choice comes up on the way, the capture doesn't choose, so it fails
  without waiting for the time limit. To capture your own command's screen, put a label right before it and capture with `lim shot <file#label>`
- **How recordings go on** (`ctx.offer`): unlike `autoplay`, a recording (`lim shot --video`) keeps the screen on. While a renderer (`renderers`) shows a screen that waits for the player,
  it tells what can be chosen with `ctx.offer(…)`. The recording shows the screen for `--read`, then picks one the same way as ordinary choices
  (`--choose`, `--avoid-choice`, `--avoid-ending`, and the next one each time it comes back to the same screen). There are two ways to tell it:
  - `{ buttons }`: the elements that can be pressed. It presses the picked one (the text is the element's text, `aria-label` or an image's `alt`, in that order; `disabled` or `aria-disabled="true"` elements aren't picked)
  - `{ options, choose(i) }`: the text of each option (`null` for ones that can't be picked) and a function that picks the i-th one. Steps inside the screen, such as showing a description before deciding or pressing twice to confirm, go here

  Both can also have `targets` (where each one jumps, `file#label`; `--avoid-ending` uses them when known) and `proceed` (always go on with this number instead of picking;
  for screens that only close or boxes with only OK). `ctx.offer` returns a function that withdraws it, so call it when the screen closes (in `finally`). Older engines don't have it, so write `ctx.offer?.(…)`
  ```ts
  renderers: {
    "door-select": async (ctx, args) => {
      const screen = buildDoorSelect(ctx, args);                                   // a screen with a button per destination (pressing one resolves picked)
      ctx.layers.overlay.append(screen.el);
      const withdraw = ctx.offer?.({ buttons: screen.buttons, targets: screen.targets });
      try {
        return await screen.picked;                                              // returns the destination to the command's run
      } finally {
        withdraw?.();
        screen.el.remove();
      }
    },
    "card-game": async (ctx, args) => {
      const game = startCardGame(ctx, args);
      // after picking, the screen plays the card and goes on to the result (the screen returns the answer)
      const withdraw = ctx.offer?.({ options: game.hand.map((c) => c.name), choose: (i) => game.play(i) });
      try {
        return await game.result;
      } finally {
        withdraw?.();
      }
    },
  }
  ```
  A screen that tells nothing doesn't advance just by clicking, so the recording stops there as stuck after `--stuck` seconds (default 60). Among the standard ones, ordinary choices,
  `@investigate` (points at the spot and shows its description before pressing it), `@map-choice` (selects a spot, shows its description, then presses the decide button), `@text-input` (keeps its initial value),
  `@dialog` (OK), and `@codex`, `@open-screen` and `@item-select` (closed) tell it. The recording reads `window.__liminalia.host.offered()` (what's offered now) and picks with `host.chooseOffered(id, i)`
- For commands whose jump targets depend on project data (letting players choose an investigation spot, choosing a destination on a map and so on), returning
  the places they may jump to (`#label`, `file#label`) from `targets(args, data)` makes Studio's flowchart draw those arrows.
  `args` are the values as written in the scenario (unnamed parameters can also be looked up by name), and `data(name)` loads project data (`data/*.json`).
  A command that always jumps somewhere and never moves on to the next line returns `leaves: true` (`{ targets: […], leaves: true }`).
  The all-routes test (`lim coverage`, Studio's check) warns (`target-never-offered`) about destinations returned by `targets` of a command it passed through that were never
  offered as a choice when running without a screen. Don't put destinations that are never chosen from that command on that line into `targets`
- **Checking the whole project**: `check` in `defineCommandPlugin({ name, commands, check(project) { … } })` loads the whole project and returns an array of diagnostics ([below](#作品全体のチェックcheck))
- **Checking each command**: a command's `validate(args, ctx)` is called for each line of that command in the scenario (`lim check`, `lim build`, Studio's check). The engine checks parameter types, required parameters and that assets exist
  from the spec, so write checks here for combinations of parameters and for matching against data. `args` is the text as written (unnamed parameters can also be looked up by name; parameters written as expressions aren't included),
  and `ctx` has `file`, `line`, `data(name)`, `assetExists(folder, path)`, `isCast(name)` and `targetExists(target)`. If you leave out `file` and `line` in a returned diagnostic, it points to that line,
  and you can write fixes in `fix` and `fixes` ([below](#作品全体のチェックcheck)). Write it as a synchronous function; throwing doesn't stop the check
  ```ts
  validate(args, ctx) {
    if (args.x !== undefined && args.at !== undefined)
      return [{ severity: "warning", code: "stamp-both", message: "Don't write x and at together", fix: { kind: "replace", find: ` x=${args.x}`, with: "" } }];
  }
  ```
- **Expression functions**: `defineCommandPlugin({ …, functions: { name: { args, doc, docEn, usage, run(args, env) } } })` adds functions that can be called from the scenario's expressions (`@if`, `@set`, `{…}`, condition expressions).
  `args` is the number of arguments (a number or `[min, max]`), and `run` receives copies of the evaluated values and returns a value (a number, string, boolean, `null`, array or object). For random numbers, use `env.random()`
  (it follows the project's random seed, so loading gives the same values). `lim check` knows the added functions and checks the number of arguments, and they also appear in the table of expression functions in `lim reference`.
  Names of built-in functions can't be used (`plugin-function-clash`; the built-in one is used)
  ```ts
  functions: { rank: { args: 1, doc: "Rank from a score (S, A, B)", run: ([score]) => (Number(score) >= 90 ? "S" : Number(score) >= 70 ? "A" : "B") } },
  ```
- **Loading project data**: inside `run`, use `await ctx.data("items")` (`data/items.json`; the extension can be left out; `undefined` if it's missing). It's loaded only once within the same play.
  The player reads the data included in the export, and `lim coverage` and Studio's search read the project folder
- **Calling a scene and returning automatically**: `await ctx.runtime.callScene("#label", again)` returns when that scene reaches the next label or the end of the file,
  without writing `@return` (it doesn't return if the scene uses `@jump`). With `again`, this command runs once more after returning (to show the investigation screen again, for example)
- **The source of expressions**: `ctx.sources` holds the text inside the parentheses of parameters written as expressions (`(…)`) (parameter name → text). The values in `args` are already evaluated, so for things that should be evaluated again whenever a variable changes
  (`show-if=` of `@hud-button` and so on), keep this text in the state and evaluate it on the rendering side with `parseExpr` and `runtime.eval`
- **State attached to a sprite**: `extra` in a sprite's state (`ctx.state.stage.sprites[character].extra`; prefix keys with the plugin's name) stays when `@chara` changes the sprite
  and goes away when the sprite is hidden (std's `@emote` uses it for manga symbols)
- **Leaving the screen covered at the end of an effect**: use `leaveParam("none")` from `@liminalia/sdk/std` as the parameter `leave`, and call `presentLeaving(args, ctx, wait)` in `run`;
  with `leave=mask`, the cover (`stage.mask`) remains after waiting. The rendering side covers the screen at the end with `ctx.mask.cover("#000000")` (the same as std's `@chapter-end`)
- **Unlocking CGs from data**: `ctx.runtime.unlockCgImage("bgimage", path)` unlocks the image as a CG if it's in extra.cg. Mark that field as a CG in the data shape declaration ([below](#作品のデータの形data))
- Commands that end the play (returning to the title, quitting the game and so on) set `ends: true`. Studio's flowchart puts an end mark on scenes that end with this command
  and doesn't draw a line to the next label (so bad endings show up as separate branches). If the command has an `ending` parameter (and `title`),
  it's read as the kind of ending (the same as `@title-screen ending=bad`; "The end of a playthrough" in [format.md](design/format.md)) and used for the mark, avoiding endings, `lim coverage` and achievements

### Checking the whole project (`check`)

Rules that a single command can't tell, such as mismatches between project data and the scenario, are reported by `check` in `./commands`. `lim check`, `lim build` (its check along the way) and Studio's check call it, and in Studio the results go into the "Plugins" category.

```ts
export default defineCommandPlugin({
  name: "stamp",
  commands: [stamp, stampClear],
  check(project) {
    const memos = (project.data("stamps.json") ?? {}) as Record<string, string>;
    return Object.keys(memos)
      .filter((image) => !project.assetExists("image", image))
      .map((image) => ({
        severity: "warning" as const,
        code: "stamp-memo-orphan",
        message: `スタンプ帳のメモの画像 ${image} が素材にありません`,
        messageEn: `The image ${image} of a stamp memo isn't in the assets`,
        file: "data/stamps.json",
      }));
  },
});
```

- **`project`** (`PluginCheckProject`): `root` (the project folder), `config` (liminalia.json), `scripts` (file → syntax tree), `text(file)` (the scenario's text), `cast`, `speakers`, `registry` (the command specs), `data(name)` (`data/*.json`; `undefined` if it's missing), `assetExists(folder, path)`
- **What to return** (`PluginDiagnostic`): `severity` (`error`, `warning`, `info`), `code` and `message` are required. Optionally `file` (defaults to `liminalia.json`), `line` (defaults to 1), `column` and `hint`. If `file` is a scenario (a name without the extension), clicking the result in Studio goes to that line
- **Fixes**: write fixes that can be applied mechanically in `fix` (one) or `fixes` (a list in order of preference), and "Fix" appears in Studio's check and in the editor.
  `{ kind: "replace", find, with }` (replaces `find` on that line), `{ kind: "delete-line", text }` (deletes that line), `{ kind: "add-speaker", name }` (adds it to the speakers),
  `{ kind: "add-label", file, label }` (adds a label at the end of the scenario). Fixes in the wrong shape are dropped.
  With a `column`, `replace` applies only to a `find` that contains the character at that column or starts inside the word that starts there (up to a space or `}` outside `"…"` and `(…)`), and isn't applied if there's none.
  Without a `column`, it applies to the first `find` on the line. When the same text can appear twice on a line (such as the parameters of `{@…}` in text), give a `column`
- **English display**: if you have translations, put them in `messageEn` and `hintEn`. If not, the English display shows `message` and `hint` as they are
- **Write it as a synchronous function**. It's also called on every save, so avoid heavy work. Returning an `error` stops `lim build`
- **Throwing doesn't stop anything**: exceptions (as well as return values that aren't arrays and malformed diagnostics) don't stop the whole check. They're reported as errors of that plugin (`plugin-check-failed`, `plugin-check-invalid`)
- `./commands` is also included in the exported game (the game doesn't call `check`), so don't import Node modules for `check`. Read files with the functions on `project`

### Project data shapes (`data`)

Declare the shape of the project data a plugin reads (`data/*.json`) in `data` in `./commands`. This one declaration gives you the following.

- `lim check` and Studio's check: checks the shape (types, required fields, duplicate names in lists), that assets exist, characters, jump target files and labels, and expressions, and shows the JSON line (`data-*`)
- Matching flags: a variable the data reads (in a condition expression, or as a flag it reads) that no scenario's `@set` and no data sets gets a warning (`data-flag-unset`),
  and a variable the data sets (that the plugin sets) that nothing reads gets an info (`data-flag-unread`). Variables with an initial value in `variables` in liminalia.json are skipped
- The check for CGs that are never shown (`unshown-cg`): images in fields marked as CGs (`d.asset(…, { cg: true })`) count as shown
- Studio: under "Data" in the left panel of the "Plugins" tab, an automatic form appears for each declaration (assets are picked from a list, lists can be reordered, in lists that hold rectangle fields you add and move rectangles by dragging on the background, and point fields are placed where you click or drag on the picture. The list of an asset field also has the assets in its `also` folders.
  Changes are saved automatically after a short pause, and if the file was changed elsewhere, the changes are merged three ways and saved again. A missing file is made with "Create")
- Renaming: when you rename a scene, file, asset, variable or character in Studio, references in declared data are updated too (the change history is kept in `.liminalia/history/@data/`)

```ts
import { d, defineCommandPlugin } from "@liminalia/sdk";

export default defineCommandPlugin({
  name: "stamp",
  commands: [stamp, stampClear],
  data: [
    {
      file: "stamps.json",
      title: "スタンプ帳",
      titleEn: "Stamp book",
      root: d.map(d.record({ image: d.required(d.asset("image", "Image", { cg: true })), memo: d.text("Memo"), when: d.expr("Condition to show it"), next: d.scene("Jump to when pressed") })),
    },
  ],
});
```

| Form | Contents |
|---|---|
| `d.string` `d.text` `d.number` `d.int` `d.bool` `d.enum([…])` | Text (one line, several lines), a number, true or false, a choice from a list. `d.string(label, { translate: true })` and `d.text(label, { translate: true })` are text shown to the player, and `lim i18n` lists them in the translation file. When drawing, `dataText(file, source)` from `@liminalia/sdk/web` gives the translation for the current language (the source if there's none) |
| `d.asset(folder, label, { cg, also })` | An asset path. With `cg`, the plugin unlocks this image as a CG. `also` lists other folders to look in when it isn't in the folder (for a field whose folder changed, so assets in the old place still pass; the rendering side should look in the same order) |
| `d.flag("set" \| "read")` | A flag (`game.x` or `x`). Whether the plugin sets it or reads it, based on the data |
| `d.expr()` | A condition expression (the variables in it count as flags that are read) |
| `d.cast()` `d.file()` | A character ID, a scenario file |
| `d.scene(label, { base, bare })` | A jump target. `base` is the name of the outer field that holds the file for `#label`; with `bare`, write only the label, without `#` |
| `d.ref("/entries")` | A name within the same data (the `id` of a list item, or a dictionary key) |
| `d.rect(label, { image })` | A rectangle in game-screen px (`x` `y` `width` `height`). `image` is the name of the background asset field (Studio lets you draw the rectangle by dragging on that image) |
| `d.point(label, { image, unit, keys })` | A point on a picture (`{ x, y }`). With `unit` `percent` (the default), a percentage from the top left of the picture (0 to 100); with `px`, game-screen px. `image` is the name of the background asset field; `ref field>asset field` (`category>map`) means the asset field of the item the ref field points to. With `keys` (`["x", "y"]`), the value isn't grouped but goes in two fields of the same record (Studio shows the picture and places the point where you click) |
| `d.list(item, label, { sortable, key })` `d.record({…}, label, { title })` `d.map(value)` `d.json()` | A list (`key` is the field that tells items apart), a record (`title` is the field used as its heading in lists), a dictionary, a value of any shape |
| `d.required(field)` | Makes the field required |

Labels are text or `{ label, labelEn, doc, docEn }`. Write declarations with plain values that can be turned into JSON (they're sent to Studio as is). If two plugins declare the same file, the later one wins.
The standard commands also declare investigation spots (`data/investigation.json`) and the codex (`data/codex.json`) in this form (`packages/std/src/commands/investigate.ts`, `codex.ts`).

## Rendering (`./web`)

```ts
export default defineWebPlugin({
  name: "stamp",
  extensions: {
    renderers: { stamp: async (ctx, args, wait, stage) => { /* draw; if wait, wait until it's done */ } },
    restorers: [async (ctx, stage) => { /* on load, rebuild from stage alone */ }],
  },
});
```

- **renderer**: one per command name. The parameters have their defaults filled in, and `stage` is the state after the command ran.
  Decide the look from the state and parameters alone, and don't keep track of progress yourself. A value you return is received by `ctx.present()` in `run`.
- **restorer** is called on load. It plays no effects and builds the current look straight from `stage`.
  You can check that a save and load round trip gives the same screen with `lim shot --eval`, running `window.__liminalia.system.saveTo(1)` → `loadFrom(1)`.
- **Game screen size**: `ctx.screen` (`{ width, height }`, the `screen` in `liminalia.json`; in `setup(host)`, `host.screen`). It's portrait if `ctx.screen.height > ctx.screen.width`. In CSS, use the game screen class `lm-portrait` and the variables `--stage-w` and `--stage-h` (both in px).
  Game screen coordinates (px for things placed in `ctx.layers`) are in `screen` coordinates. The exception is inside the message window, choices and system screens: there, px are at the base size and scaled up or down by the `ctx.uiScale` factor (for projects at the base size, 1280×720 landscape or 720×1280 portrait, it's 1).
  A plugin used only at 1280×720 works with numbers written as they are (the engine adds nothing to the game screen of a 1280×720 project, so the look doesn't change). A plugin also used in projects of other sizes reads `ctx.screen` instead of `1280` and `720`.
- Main members of **RenderContext**:
  - Layers: `layers.background` / `sprites` / `images` (inside the camera), `fx` (outside the camera, below the message window), `hud` (above the message window and below the blackout; hidden while the screen is fully blacked out and during chapter cards), `overlay` (above the message window and the blackout)
  - For `<video>` and `<audio>` that the project plays itself, `ctx.audio.bindMedia(element, volume)` gives them the same volume as standard movies (volume × the volume of the `ui.sound.movie` group × the master volume; mute applies too,
    it follows setting changes right away, and on iOS it goes through Web Audio). The element's `muted` is left as it is
  - `asset(kind, path)`, `image(url)` (waits for loading and decoding), `spriteReady(who?)` (waits until sprites being placed with `@chara` are in place; `@chara` moves on without waiting, so a command that operates on sprite elements right after it should wait for this), `fade(el, to, ms)`, `audio`, `loadData(name)`
    (`name` is a path from the project's `data/`. `loadData("items.json")` and `loadData("items")` are the same; if `.json` is left out, it's added. The name may contain dots (`loadData("code.en")` reads `data/code.en.json`).
    It reads the file as JSON and returns it)
  - `time(ms)` returns 0 while skipping, and while drawing a command whose effect was fast-forwarded with a click. Always pass effect durations through it
  - Fast-forwarding effects: if the player clicks while an effect command (one with a time parameter that waits for its end, that is, one with `waits` or a `wait` parameter) is being drawn,
    the `Element.animate` animations in `layers` and `message` (except repeating ones) jump to their end state, and until that command finishes drawing, animations that start afterward
    also end right away. Use `delay(ms)` instead of waiting with setTimeout (it also ends on fast-forward). For effects you animate yourself with requestAnimationFrame and the like,
    register a function that finishes them with `onFastForward(finish)`, and remove it with the returned function when done. So that fast-forwarding can be turned off for each command, add `skip: t.skip()` to the command's parameters
    (effects of commands written with `skip=false` aren't fast-forwarded)
  - `waitClick()`, `cast` (the character definitions), `message` (the message window element)
  - APIs that save you from operating on internal elements directly (the engine's element structure and classes may change, so don't look for `camera.parentElement` or `.layer.mask`):
    - `world`: the layer outside the camera (the layer `@quake` shakes; it holds the background, sprites and foreground images, but not the message window). For effects that tilt, zoom or tint the whole screen,
      apply them with individual CSS properties (`translate`, `rotate`, `scale`, `filter`) so they don't clash with `@quake` and `@camera`
    - `mask.cover(color)`, `mask.uncover()`: cover or uncover the fade-to-black layer (`@mask`) without animation. This is only the look, so a command that moves on while it's covered also writes `stage.mask` itself
    - `window.hideWhile(job)`, `window.hide()`: hide the message window until job is done (for hide, until you call the returned function). They don't change the `@window` state, can overlap, and are cleared on load
    - `systemLayer`: the system screen layer (the front of the game screen, for things above notifications, such as a loading curtain). In projects that replace the system screens, it's `overlay`
    - `setBackground(image, { fade, method, folder })`: changes the background, shown the same way as `@bg`. It's only the look and doesn't change the state, so use it for temporary pictures that may go back on load
    - `toStage(clientX, clientY)`: converts page coordinates to game screen coordinates (px in `screen`), undoing the game screen's scaling and position
  - `scope({ keepOnSkip })`: cleanup for one-off effects. What you hand to `setTimeout`, `setInterval`, `requestAnimationFrame`, `frame(perFrame)`, `add(element)`, `listen(target, type, handler)` and
    `defer(cleanup)` is cleaned up by the engine on load (rebuilding) and when skipping starts (with `keepOnSkip`, not when skipping).
    `sleep(ms)` doesn't wait while skipping or during a fast-forwarded command, and ends on the spot when fast-forwarded.
    It also ends when cleaned up, so after that, check `scope.disposed` and don't continue. Call `dispose()` when the effect is over
    ```ts
    const scope = ctx.scope();
    const el = scope.add(document.createElement("div"));
    ctx.layers.fx.append(el);
    await el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: ctx.time(200) }).finished;
    await scope.sleep(800);
    scope.dispose();
    ```
  - `on(type, handler)`: events on the rendering side (the returned function removes the handler). They save you from watching the name box or sprite layers with MutationObserver
    - `page` (a page started showing; `at`, `speaker`, `label`), `speaker` (the speaker changed from the previous page; `null` for narration; `previous`)
    - `sprites` (the characters, sprite sets or variants on screen changed; `sprites`, `stage`. To operate on the elements, wait for `spriteReady(character)`)
    - `restore` (rebuilt from state, after the restorers), `load-end` (a system load finished; `from`)
    - `screen-close` (a system screen closed; `name`), `menu-close` (the menu closed)
  - `notify(text, { kind, title, time, delay, se, key, max })`: stacking notifications (the same as `@notify`; see “Notifications” below). `toast(text, ms)`: a short notice like the ones on system screens
  - `offer({ buttons } or { options, choose })`: a screen that waits for the player tells a recording (`lim shot --video`) what can be chosen (see “How recordings go on” above). The returned function withdraws it
  - `host.coverUi()`: call it while showing something that covers the in-game controls, like a full-screen movie. Meanwhile, the system doesn't show the quick menu or
    the menu button (`status.menuBar` is false too). The returned function removes the cover (`@movie` uses this during playback, but not with `menu=true`)
  - `studio` is true when running in Studio's preview. The preview rebuilds from a save every time you move to another line (calling the restorers too), so
    don't show effects that get in the way when shown on every rebuild, such as a loading curtain, when `ctx.studio` is true
  - `reduceShake` is true when the player has set screen shake to reduced, and `reduceFlash` when they've set flashing lights to reduced.
    Effects that shake the screen shouldn't shake when `reduceShake` is true, and effects that flash shouldn't flash when `reduceFlash` is true
  - `system` (`RenderSystem`): the system screen API. Use it from command rendering, restorers and project screens, without keeping the `system` from `ready`
    in a module variable. It's set after the system screens are made, and is `null` during `setup`
    - `openScreen("save")`, `openScreen("gung.map")`: open a screen by name and wait until it closes (the standard screens save, load, log, menu, config, extra,
      items, help and flowchart, or a project screen registered with `defineScreen`; `false` if it can't be opened). `openScreen(build, options)` is
      the same as `system.openScreen`: instead of stacking your own screen on the overlay, you leave blocking input, stacking, Esc and saving to the system
    - `status`, `onStatusChange(…)` (auto, skip, the open screen, whether choices are shown and so on; `SystemStatus`)
    - `perform("save")`, `perform("backlog")`, `perform("screen:gung.map")` (a standard action or a project screen; does nothing when play isn't in progress)
    - `systemVariables` (variables shared by all saves; readable and writable, and `saveSystemVariables()` stores them right away), `defineScreen(…)`, `controller` (the system screens themselves)
    - `callScene("#memo")`: calls a scene from the page being read, and shows that page again when the scene returns at @return or the next label (the same as `call=` of `@hud-button`; it can be called while a page waits for a click and while choices are shown, and the choices are shown again when it returns. It returns `true` when it calls)
    - `announce("Chapter 1 The Rainy Station")`: passes something shown outside the text (such as a chapter card's title) to screen readers and text-to-speech right away (text-to-speech only when the player has turned on Read aloud; nothing is passed while skipping)
    - `ask("There are places you haven't examined yet. Finish anyway?", "investigate-finish")`: asks yes or no (the standard confirmation box, or the game's `screens.confirm`; `true` for yes. If the player has turned confirmations off in Settings, it returns `true` without asking)
- To place your own kind of thing on the foreground layers (fg0 to fg2), push its state onto the standard image list with a `kind`,
  and register how to build it on load with `registerLayerItem(kind, build)` from `@liminalia/sdk/web` (it disappears along with its layer on `@free-image`).
- **Replacing the look**: `extensions.text` (`TextTheme`: the font, how read text is shown, the click-wait icon, how text appears),
  `extensions.sprites` (`SpriteTheme`: the time multiplier for changes of expression only).
- **One character of text** (a public interface; changes to it are announced as version changes):
  - The text becomes one `span.ch` per character (ruby is one `.ch.ruby` for the base text and its ruby, `{img}` is `.ch.lm-inline-image-unit`). Upright digits in vertical writing are `.ch.tcy`.
  - The time a character starts to appear is the element's `animation-delay` (the character's index × the time per character). Once it's fully shown (a click, skipping, or a page shown at once), `.ch.shown` is added and the animation is removed.
  - How characters appear is set by the CSS variables `--lm-reveal-animation` (the animation name; `lim-reveal` fades, `lim-reveal-rise` floats up), `--lm-reveal-time` (time for one character to appear)
    and `--lm-reveal-easing`. `ui.text.reveal` (`fade` / `none` / `rise`) and `revealTime` in `liminalia.json` write them on the stage, and the project's CSS can override them.
    For your own animation, create `@keyframes` and write its name in `--lm-reveal-animation` (end it at `opacity: 1`).
  - `TextTheme.reveal(units, perChar)` is called once right after the characters are put in the window, and `TextTheme.char(el, { index, delay, perChar })` is called for each character.
    Animations added in `char` with `el.animate(…)` (starting at `delay`) are moved to their end state by the engine when a click finishes the page,
    so you can add motion to a character without rewriting the reveal animation (lighting an ellipsis one dot at a time, and so on). `perChar` is 0 when the page is shown at once (also while skipping).

  ```ts
  text: {
    char(el, { delay, perChar }) {
      if (perChar < 100 || el.textContent !== "…") return;
      el.animate([{ clipPath: "inset(0 100% 0 0)" }, { clipPath: "inset(0 0 0 0)" }], { duration: perChar, delay, easing: "steps(3, jump-start)", fill: "both" });
    },
  },
  ```
- **Stacking the text on another screen**: `extensions.dialogue` (`DialogueView`). In projects with `ui.chat.dialogue`, the text of each page goes into the element that `page` returns (the standard `std` uses this for chat bubbles; a later plugin replaces it). The runtime stacks finished pages in `std.chat` in `stage.extra` (`RuntimeOptions.chatDialogue`).
- **Sprites drawn instead of images** (Live2D, Spine and so on; the official `live2d` and `spine` plugins are written with this too): in `extensions.spriteParts`, put a builder (`SpritePartFactory`) for each `model.type` of a character's variants.
  It receives `{ who, variant, name, appearance, el, asset, skipping(), holdShot() }`, adds a canvas or similar inside `el` (the element that holds the sprite's position and size),
  and returns `{ update(variant, at), tick(now, mouth), dispose(), coversImage }`. `name` and `appearance` are the variant's name (`smile` for `smile+blush` in `@chara`,
  or the default variant if none is written) and the sprite set, and `update` is called when the same character's variant changes (switching expression or motion), with the new `variant` and `{ name, appearance }`.
  `variant.model` is the character's `model` with the variant's `model` of the same `type` laid over it. `tick` is called every frame, where `mouth` is how open that character's mouth is (0 to 1; from the voice's loudness or,
  without a voice, opening and closing while the text appears). `skipping()` tells whether it's skipping (finish changes without blending), and
  `holdShot()` holds screenshots (`lim shot` and the check after export) until you call the function it returns (to wait until the model is loaded and the first frame is drawn).
  With `coversImage: true`, the variant's `image` is hidden (and used as the still image that decides position and size; to hide it only after drawing, add the `sprite-covered` mark to `el` yourself).
  Showing, hiding, position, `frame` changes, speaker emphasis and tone (the CSS `filter` of `el`) work the same as engine sprites. For flipping (`flip=true` in `@chara`), the engine flips the canvases directly under `el` (including ones added after loading)
  on the same axis as the image (`flipAxis` in `frame`; write the canvas's `left` and `width` in % of the frame so a canvas larger than the frame lines up with the axis too). Outside libraries for drawing (the Cubism SDK and so on) are
  built in on the project's side, following that library's license terms. A script placed in the assets can be loaded once with `loadScript(asset("others", …))` from `@liminalia/sdk/web`
  (the CSP of exported games only allows scripts from the same place as the game, so outside URLs can't be loaded).
- To replace the **system screens** entirely, return `system: (env) => SystemController`.
  Screenshots and the check after export use `boot()`, `mode`, `screen`, `pages`, `devSkipUntil` and `startAt()`, so keep this contract.
  Studio's preview (`lim studio`) uses the optional `loadSave(save)`. It starts from save data, resolves once it starts showing the page (or choices) at that position,
  and doesn't go back to the title when it ends (built the same way as `loadFrom` in the default system screens,
  but taking a save directly instead of going through a slot). Without it, Studio's preview can't be used (the player only shows a warning).
  "Reload from Here" (⇧R) in test play uses the optional `reloadHere()`. It keeps the current state, reloads the script in a new `Runtime`, continues from the same page and returns true
  (false when play isn't in progress). Without it, the save of the current page is loaded again with `loadSave` (the history isn't carried over).
  The screen for a command line (before the text) is built by the player stopping the current play with `runtime.dispose()` and then using only the rendering side's `restore` and `restorers`,
  so there's nothing to add to the system screens (`restorers` are also called this way at times other than loading).
  Pass `env.onAssign` as is to `onAssign` of the `Runtime` you create. When play advances in Studio's preview, the "State at this line" panel uses it to show
  where values decided in the preview came from (the line that set them). It works without it, but then only "← preview" is shown, with no line.
  Projects that don't replace them use the engine's default system screens (`packages/web/src/system/`).
  "Previous choice" and "Next choice" can be built with `ChoiceHistory` and `findChoiceAhead` from `@liminalia/sdk/web`. When choices are shown
  (`setChoosing(true)`), call `history.remember(runtime, logLength)`; to go back, start a new play from `point.save` of `history.previous(choosing)`,
  and put back the kept history with `history.replace(before)`. To go forward, `findChoiceAhead({ runtime, loadSource, present })`
  gives you the point of the next choice (`save`, `temp`, `system`); start a new play from there (`present` receives what's sent to the rendering side along the way,
  so use it for things that should happen even when skipped over, such as the backlog and unlocking CGs; null if you don't need it). The runtime that runs ahead is built
  with the settings `runtime` was created with (`runtime.options`) and the current language and translation (it doesn't get `beforeStep`, which waits for the game's screens, or `afterLoad`).
  To keep it in save data, save `history.forSave(dropped)` (the number of history entries to leave out) along with it, and put it back with `replace` after loading.
  Even with replaced system screens, the player input that doesn't depend on how the screens are built (long press, swipe, gamepad, choosing
  buttons with arrow keys, the menu button on touch devices, the notice shown when a landscape game is held upright) is available with `bindPlayerInput({ stage, controls })` from
  `@liminalia/sdk/web`. In `controls`, pass whether play is in progress, the range to choose from with arrow keys, and functions for
  the menu, backlog, hiding the window, closing a screen, config, skipping while held and so on (actions you don't pass do nothing).
  A horizontal swipe calls `rollback` or `rollforward` (swiping right goes back; with `choosing` passed, also while choices are shown; `swipeSide: false` turns it off).
  On a gamepad, RT and L3 call `auto` and `skip`, R3 calls `mute`, and right and left on the D-pad during play call `quickSave` and `quickLoad`.
  During play (when there's no `navRoot`), up and down on the arrow keys and the D-pad select the visible buttons inside elements on the stage marked with `data-lm-play-nav`
  (such as the root of the standard HUD buttons); A on a gamepad presses the selected one and B stops selecting (left and right on the D-pad only move while one is selected).
  Arrow keys for which `reserved(key)` returns true aren't used for selecting (they're keys assigned to game actions). A plugin's own HUD parts can be selected the same way by putting `data-lm-play-nav` on their root.
  Parts with a `KeyboardEvent.key` name in `data-lm-key` are pressed with that key by the default system screen while playing and while choices are shown
  (upper and lower case letters are the same, and it comes before the default keys of other actions), and are listed on the Controls screen. A selected button inside `data-lm-play-nav`
  is pressed with the key that advances the text, and Esc stops selecting it.
  The right stick scrolls the scrollable elements in the open screen (`navRoot`). Gamepad buttons send `lm-pad` (`detail.button`) to what's selected (or `navRoot` if nothing is),
  and the right stick sends `lm-stick` (`detail.x`, `y`, `dt`); if the receiver calls `preventDefault()`, they aren't handled further
  (for screens that handle the gamepad themselves; viewing CGs in Extras uses this too). A gamepad without the standard mapping is reported with `onNonstandardPad(id)`.
  To match button labels to the controller model, use `padLabel(button, style)` (style is `xbox`, `playstation` or `nintendo`; `""` means from the connected gamepad).
  If you handle keys yourself, call it before your key handling. The default system screens use this too (the list of controls is in docs/player.md).
  Replaced system screens receive Android's app back button and the phone browser's back through `system.back()` (return true if handled; if not, the app goes to the background
  and the browser goes back to the previous page). When the mobile app recreates the screen's process and reloads it with `?resume=1`, call `system.resumeLeft()` (if there's nothing to resume, it starts normally).
  Device features are available from `@liminalia/sdk/web`: `keepAwake(reason, on)` (keeps the screen on; counted per reason), `vibrate([vibration, pause, …])` (an empty list stops it)
  and `openExternal(URL)` (the mobile app opens it in the device's browser)
- `setup(host)` is called once right after the rendering side is created (for loading fonts and so on).
  For fonts, use `host.fonts.add(name, url)` (registers and loads it once; true if it loaded), `host.fonts.load('500 16px "Name"')` and `host.fonts.ready(ms)`
  (waits up to ms milliseconds for the fonts in use to load; 3000 by default). None of them throw even if nothing loads (the project doesn't need to write FontFace registration and timeouts)
- **Notifications** (`@notify`, `ctx.notify`): stacked at the top right. When more are shown at once than the limit (`max`, 3 by default), the oldest are removed first, and if a notification with the same key (`key`, the text by default) is showing,
  they're merged into one and shown again (the display time is extended and `data-lm-count` goes up by one). During full-screen effects (`host.coverUi()`) they wait, and when the cover is removed they appear one after another.
  While skipping, their time is cut to 1/10, and they're cleared on load. Change the look with CSS (`.lm-notices`, `.lm-notice`, `.lm-notice--<kind>`, and `enter`, `in`, `out` in `data-lm-state`), or
  replace each notification's element with `screens.toast(api)` (`api` has `text`, `kind`, `title` and `args` (the `@notify` parameters)). For full-screen effects such as chapter title cards,
  calling `host.coverUi()` while they're shown makes notifications wait in the meantime. With `@notify when=scene-break`, the runtime holds the notification until a scene break before passing it to the rendering side (while it waits, it goes into saves)
- **Screen transition curtains** (`transitions`): with `load: { cover(ctx, { from }), reveal(ctx, { from }) }`, a load (from a slot, the backlog, the previous choice, a chapter or the flowchart) waits for `cover` to finish before discarding the current play,
  and calls `reveal` after rebuilding from state (without waiting). `screen(ctx, { name, open })` is called right after a system screen opens and right after it closes (without waiting;
  to draw above the screen, put it in `ctx.systemLayer`). If you only need the events, listen for `load-start` and `load-end` with `system.onEvent`. Works only with the standard system screens
  ```ts
  transitions: {
    load: {
      async cover(ctx) { curtain.show(ctx.systemLayer); await curtain.closed(); },
      reveal() { curtain.hide(); },
    },
  },
  ```
- **Scrollbars** (`ui.scrollbar(content, { track, thumb, back, forward, orientation, minThumb, step })`): attaches a track and thumb that the project made to scrolling content (`overflow: auto`).
  The thumb's length and position are written in px (`height` and `top` when vertical), the scrolled fraction goes to `--lm-value` (0 to 1) on the content, and whether it can scroll goes to `data-lm-scrollable` on the track. Even when the game screen is scaled,
  dragging keeps up with the thumb. The `back` and `forward` buttons get `data-lm-disabled` (`disabled` for a `<button>`) when they can't scroll
- The check after export (`lim build`) and `lim shot` wait `build.verifyWait` (2500 milliseconds by default) after the title screen appears, then take the screenshot.
  If the project decides when the screenshot may be taken, such as for a title that starts with a long fade from white, hold it with `const release = host.holdShot()`,
  and call `release()` when it may be taken (no screenshot is taken until then; after 60 seconds it gives up and takes one).
- **Calling standard actions from the project's buttons**: `ready({ host, system })` is called once right after the system screens are made, so
  keep `system` and call actions like `system.perform("auto")`. The actions are `SYSTEM_ACTIONS` (`quick-save` `quick-load` `save` `load`
  `auto` `skip` `prev-choice` `next-choice` `backlog` `config` `hide` `title` `exit` `fullscreen` and so on. They behave the same as the quick menu buttons, and `title`, `exit` and
  `prev-choice` ask for confirmation first. `fullscreen` switches between full screen and a window. It isn't in the standard menu, so to put it in the quick menu, write it in `ui.menuBar.items`).
  The selected theme (`ui.system.preset`) can be read from `system.theme` (also `RenderContext.system.theme`; `null` for the standard theme).
  When play isn't in progress (on the title screen, while a system screen is open), they do nothing. Whether auto, skip and window hiding are on can be read from
  `system.toggles` (to match the look of the project's buttons). If you don't use the standard quick menu, set `ui.menuBar.position` in liminalia.json
  to `hidden`, and if you don't need the menu button on touch devices either, set `ui.menuBar.touchButton` to `false`.
  To show and hide the quick menu partway through the scenario, use `@menu-button` (it's kept in the state, so it's the same after loading).
- **Changing the look with the project's CSS**: all of the engine's CSS is in the cascade layer `liminalia` (`@layer liminalia { … }`).
  Project CSS written outside the layer takes precedence without competing on specificity (no need to strengthen selectors like `.stage .message …`; `.nvl-page { margin: 0 }` takes effect).
  Project CSS can be loaded without a plugin by listing CSS files in `ui.css` in liminalia.json (it's loaded after the theme and plugin CSS, so at equal
  specificity it wins over plugin CSS. Files that `url()` points to are exported too; "Project CSS" in [player.md](player.md)).
  From a plugin, add a `<style>` in `setup(host)`, or `import "./my.css"` from the plugin's `./web`.
  Change values with CSS variables where you can (set on the game screen element, they apply to everything inside):
  - Message window: `--message-left` `--message-top` `--message-right` `--message-bottom` `--message-width` `--message-height` `--message-min-height`
    (the `ui.message` game setting is also passed through these), `--message-padding` `--message-bg` `--message-image` `--message-border` `--message-radius`,
    the width of the vertical (top-to-bottom) message window `--vertical-width`, NVL padding and background `--nvl-padding` `--nvl-bg`
  - Text size setting: `--text-scale` for the text and choices, `--lm-text-scale` for the name box, backlog and standard system screens (both 1 = 100%; multiply your project screens' text by them to match).
    Above 100%, the game screen gets `lm-text-large` (the standard screens tighten their layout then)
  - Text: `--font` `--text-size` `--text-line` `--text-letter-spacing` `--text-shadow` `--text-align` `--message-fg` `--read-fg`,
    ruby (small reading aids above characters) `--ruby-size` `--ruby-gap`, paragraph spacing `--paragraph-gap`, characters per line `--line-chars`, Japanese line-breaking rules (kinsoku) `--line-break`, hanging punctuation `--hanging`
  - Name box `--name-fg` `--name-size` `--name-bg` `--name-image` `--name-border`, click-wait icon `--glyph-fg` `--glyph-size` `--glyph-gap`,
    choices `--choice-*`, speech balloons `--balloon-*`, the chat screen `--chat-*` (`--chat-bg` `--chat-head-bg` `--chat-other-bg` `--chat-me-bg` `--chat-radius` and so on; what you write in `ui.chat` is applied to the game screen through these), the standard system screens `--lm-*` (docs/player.md)
  The engine's CSS works in browsers that support `@layer` (Chrome, Edge and Android WebView 99 or later, Safari and iOS 15.4 or later, Firefox 97 or later).
- **Project screens** (investigation, maps, deduction, the original game's save screen and so on) are opened with `system.openScreen(content, options)`. The project makes the look (elements, CSS and images),
  and the system handles the rules:
  - It's placed on the same layer and in the same stacking order as the standard system screens (the one opened later is on top; `system.screen` is its name)
  - It blocks input underneath. Clicks and the wheel that advance the text (backlog, advancing) stop inside the screen, and right-click, Esc and B on a gamepad
    become this screen's "back" (with `closeOnBack: true`, it closes and the result is `null`; otherwise nothing happens). Auto and skip stop until it closes
  - `allowMenu: true` marks an in-game screen that waits for the player (investigation, maps, the codex and so on). While it's open, the player can still open the menu, save, load,
    the backlog and the settings (the shortcut keys, the menu button on phones and START on a gamepad too), and closing them returns to this screen. Right-click, Esc and B on a gamepad
    open the menu when this screen's back (`onBack`, `closeOnBack`) doesn't handle them. For a screen a scenario command opens and waits on, the save stays at that command, and the command opens it again on load.
    On touch devices the menu button appears at the top right, so keep the screen's top-right buttons clear by `var(--lm-menu-room-x, 0px)` (from the right) or `var(--lm-menu-room-y, 0px)` (from the top) in CSS (0 when the button isn't shown)
  - With `pauseScenario` (`true` by default), the scenario's next command doesn't run while it's open (for the standard screens, `ui.screen.pauseScenario`; they pause by default)
  - When it closes, `handle.result` (a Promise) resolves to the value passed to `handle.close(value)`
  - If you write `key`, the state (`handle.state`, `handle.setState(newState)`; values that can be turned into JSON) goes into saves. Reopening with the same `key`
    starts from the saved state, so a screen opened inside a command (the command calls `ctx.resumeHere()`) comes back when the command opens it again on load.
    For screens opened from outside commands (the project's buttons and so on), register how to build them with `system.defineScreen(key, build, options)`,
    and the system reopens them in the same state on load. You don't have to write a record in stage.extra and a restorer for each screen
  - Screens registered with `defineScreen` can be opened by name: `@open-screen gung.map` in the scenario (waits until it closes), `"screen:gung.map"` in
    `ui.menuBar.items` of the quick menu (also passed to the project's own quick menu through `items`), `system.perform("screen:gung.map")` and `ctx.system.openScreen("gung.map")`.
    `label` in options (text or `{ ja, en }`) becomes the button text, and with `menu: true` it's listed before "Title" in the right-click and Esc menu.
    With `extra: true` (or a function that returns true), it's also placed among the Extras tabs, and "Extras" appears on the title screen even if nothing else is unlocked (when opened from Extras, play isn't in progress, so `system.runtime` is null).
    `state` is the initial state (used when the save has no state)
  ```ts
  const h = system.openScreen((h) => buildMap(h), { key: "gung.map", state: { page: 0 }, closeOnBack: true });
  const picked = await h.result; // the value from close(value); null if backed out or discarded by a load
  ```
  ```ts
  // register in ready, and open from the quick menu ("screen:gung.notebook" in ui.menuBar.items), the menu, @open-screen gung.notebook or the project's buttons
  ready({ system }) {
    system.defineScreen?.("gung.notebook", (h) => buildNotebook(h), { label: { ja: "手帳", en: "Notebook" }, menu: true, closeOnBack: true });
  },
  // from inside command rendering (extensions.renderers)
  extensions: { renderers: { "open-notebook": async (ctx) => void (await ctx.system?.openScreen("gung.notebook")) } },
  ```
- **UI parts without a look** (`import { ui } from "@liminalia/sdk/web"`) add only behavior to elements the project made. State is exposed as attributes on the element, so
  the project's CSS decides the look (`data-lm-hover`, `data-lm-focus`, `data-lm-pressed`, `data-lm-disabled`, `data-lm-selected`, `data-lm-on`,
  `aria-pressed`, and the thumb position `--lm-value` (0 to 1)). Clicks that press them aren't passed on to advancing the text. They work outside system screens too
  - `ui.button(el, { onPress, disabled, hit, se, hoverSe, sound, tapToSelect, label })`: the pressable area `hit` is the element's rectangle (the default),
    `{ x, y, width, height }` (px from the element's top left), or `{ alpha: true, threshold }` (the non-transparent part of the image: an `img` or the background image, or another image given with `image`).
    Where buttons overlap, the topmost one whose pressable area contains the point is pressed, and transparent parts pass the press through to the button below (elements that aren't buttons don't pass it through).
    Elements other than `<button>` are made keyboard-selectable (select with Tab and the arrow keys, press with Enter and Space), and with `tapToSelect`, on touch devices
    the first tap selects and the second presses. `se` and `hoverSe` are sound effects (paths from `sound`). If you leave them out, the sounds in `ui.sound.ui` in liminalia.json are used
    (on press, the kind in `sound`: `select` by default, `"cancel"` for a close button, `"page"` for a tab, `false` for no sound; on mouseover, `hover`)
  - `ui.playSound(kind)`: plays a sound from `ui.sound.ui` (`hover`, `select`, `cancel`, `open`, `close`, `page`, `choice`; does nothing if it isn't set).
    Use it when a project screen opens or closes and so on. `open` and `close` don't play right after a press sound
  - `ui.slider(el, { min, max, step, value, onChange, onCommit, orientation, thumb, setting })`: moved by dragging (with a finger too), the arrow keys,
    Page Up/Down and Home/End, calling `onChange` on every change of value while it moves. For an `<input type="range">`, its own behavior is used
  - `ui.toggle(el, { value, onChange, setting, se })` (on and off), `ui.choice([{ el, value }, …], { value, onChange, setting })` (choose one)
  - `setting: { system, key }` binds it to a setting (`key` is `bgm` and so on, or `"custom.name"` for a project-specific value). A change is
    saved with `system.updateSettings` and applied right away, and it follows changes made elsewhere
  - `dispose()` on the returned handle removes it (it also goes away when you discard the element)
- **Replacing only the look of the standard screens**: pass functions that build the elements in `screens: { config?(api), saveload?(api), backlog?(api), menuBar?(api), menu?(api), confirm?(api), ending?(api), extra?(api), flowchart?(api), indicator?(api), codex?(api), toast?(api), choice?(api), name?(api), dialog?(api), help?(api), items?(api) }`. Opening, closing,
  blocking input and stacking work the same as the standard screens, and the function builds the contents. For config, `api` has `system` (settings can be
  bound with `setting` on `ui.slider` and the others), `languages`, `defaults` (the values for "Reset to defaults"; `ui.defaults` in liminalia.json), `reset()` (resets to defaults, keeping the language, full screen and so on), `close`, `exportSaves` and `importSaves`.
  For save and load, `mode`, `system` (`slots`, `slot`, `deleteSlot`, `autoSlots`; a slot's `chapterId` is the chapter at the saved position),
  `slotCount`, `autoSlotCount` (the number of autosave slots), `lastSlot` (the slot saved to last), `latestSlot` (the newest save, including autosaves and quick saves),
  `pageSize` (the number of slots on one page of the standard save screen), `chapterId` (the chapter being played), `inGame`, `save(slot)`, `load(slot)`, `ask(message, kind)`, `notify(message)` and `close`.
  For the backlog, `entries`, `playVoice(i)`, `jump(i)`, `color(speaker)`, `textStyle(speaker)` (`text` in cast.json), `asset(kind, path)` and `close`. For the flowchart, `flow` (scenes and connections), `title(scene)`, `reached(scene)`, `canJump(scene)`, `jump(scene)`,
  `readRate`, `endings` (for each ending scene, `scene`, `reached`, `kind` (the kind), `label` (the kind's wording), `title` (the name in `title=`) and `name` (the line in the list)), `close` and `onBack`.
  A scene's `scene.end.ending` is the kind (`bad` and so on), `scene.end.title` is the original name, and `scene.end.legacy` is the wording of the earlier way of writing in projects not yet migrated. You don't need this if you only change CSS (the standard screens are built from these parts inside too)
  - Every screen's `api` has `onClose(handler)` (when it's closed, or discarded by a load; the returned function removes it) and `leave`. In the function that builds the screen,
    put in a closing effect such as `api.leave = (el) => el.animate([{ opacity: 1 }, { opacity: 0 }], 200).finished`, and on closing it's called with that element,
    and the screen is removed after it finishes (it can't be pressed in the meantime; it's cut off after 2 seconds; there's no wait while fast-forwarding, or when screens are discarded all at once on a load or a return to the title).
    Project screens (`openScreen`, `defineScreen`) have the same `onClose` and `leave` on their `handle`, and `handle.onBack(handler)` receives back (Esc, right-click, B) first
  - Quick menu `menuBar(api)`: built once and placed by the system, and shown only when the quick menu should be shown (`status.menuBar`: play is in progress, no screen is open,
    the window isn't hidden, the message window is showing, no choices are shown, and nothing like a full-screen movie is covering it). It's also false while `hide-window` hides the window until the next text. `api` has `items` (`ui.menuBar.items` or the default list),
    `label(action)`, `perform(action)`, `status` and `onStatusChange` (to match the pressed look of auto and skip)
  - Auto and skip indicator `indicator(api)`: built once and placed by the system, and shown only during auto or skip (`hidden`; `auto` or `skip` in `data-state`,
    and the position is the class `lm-indicator-at-<position>` from `ui.indicator`). `api` has `status`, `onStatusChange` and `label("auto" | "skip")`.
    In projects that replace only the quick menu (`menuBar`), it isn't shown unless you write `ui.indicator`
  - Menu `menu(api)` (right-click, Esc, START on a gamepad; from the project's buttons, `system.perform("menu")`): `items`, `label`, `perform(action)` (runs after closing), `status`, `close`,
    `onClose(handler)` (when it's closed, or discarded by a load; you don't need to watch for the element's removal with MutationObserver)
  - Notifications `toast(api)`: see “Notifications” above
  - Confirmation `confirm(api)`: `kind` (`title`, `exit`, `end-replay`, `backlog-jump`, `prev-choice`, `import`, `delete`, `overwrite`, `load`, `investigate-finish` (finishing an investigation without examining everything),
    or the name given in `ask(message, kind)` from a project screen or `ctx.system.ask` from a renderer), `message`, `yes`, `no`, `answer(trueForYes)`. Esc and right-click mean "No"
  - Ending name `ending(api)` (shown before returning to the title when a playthrough ends with `@title-screen ending=`): `kind` (the kind of ending, such as `bad`), `label` (the kind's wording, such as BAD END;
    empty for `other` and the earlier way of writing), `title` (the name in `title=`; empty if none), `name` (the name shown large: `title`, or `label` if there's none; the written wording in the earlier way), `text` (the end mark; the Japanese mark or The End if omitted),
    `proceed` (the label of the action that moves on, for screen readers) and `close` (move on to the title). All are in the language being played. Esc and right-click also move on, and during auto the system shows it for 4 seconds and then moves on
  - Extras `extra(api)`: `extra` (extra in liminalia.json), `tab`, what's unlocked (`cgImages(cg)` for the unlocked images, `replayUnlocked`,
    `musicUnlocked`, `movieUnlocked`, `achievement`), `chapters` (chapters in liminalia.json, translated into the language being played), `asset`, `audio`, `replay(scene)`, `close`,
    `onBack(handler)` (return true if something should close first on Esc) and `onKey(handler)` (keys such as the arrows and Enter; the gamepad's D-pad, A, B, LB and RB also
    arrive with names such as `ArrowUp`, `Enter`, `Escape` and `PageUp`. Returning true skips the standard behavior, such as moving between buttons and pressing them. For paging while a CG is shown large, for example).
    A CG's `group` (a heading such as a chapter) and `description` can be used in the list
  - Codex `codex(api)` (only in projects with `data/codex.json`; opened from `@codex`, the menu or Extras): `data` (headings and categories; a category's `type` is `list`, `timeline`, `relations` or `map`,
    and for `map`, the map image), `entries` (the unlocked entries; `sections` and the relation chart's lines `links` include only unlocked ones, `fresh` marks entries not read yet, `date`, `order`, `x`, `y`),
    `entry` (the entry when opened with `@codex name`), `playing` (`false` when opened from Extras), `markSeen(key)` (marks as read; an entry's `id` and a paragraph's `key`),
    `text(ja, en)` (the text in the language being played), `asset`, `close` and `onBack`. Which entries, paragraphs and lines to unlock, and the new marks and notifications, are handled by the standard commands
  - Choices `choice(api)` (`@choice` and choice blocks; built each time): the returned element is placed in the choice layer (`.choices`) and no standard buttons are made. `api` has `options` (for each choice `index`, `text` (translated into the language being played),
    `locked` (cannot be pressed), `read` (the destination has been read before) and `look` (look parameters such as `image`, `x`, `y`, `width`, `height` and `tip`; `null` if none)), `time` (the time limit in ms; 0 if none),
    `choose(index)` (chooses; locked ones are ignored; also plays the choice sound) and `asset`. The time-limit bar (`.choice-timer`), number keys (counting the pressable `button`s in the choice layer from the top),
    telling the recorder and handing over to the chat screen are handled by the system. The placement (`ui.choice.position`) is not used, so position the element with CSS (while it is shown, the layer has `lm-choices-custom` and the standard button look does not apply)
  - Name box `name(api)` (built once): the returned element goes inside the message window's `.name` (`.name` gets `lm-name-custom`, which removes its backdrop, lines and padding), and the listener of
    `api.onChange(listener)` is called whenever the speaker changes (`speaker` (`null` for narration), `label` (the text for the name box; the translation, and both names on a page where two speak at once) and `color` (`color` in cast.json)).
    The current speaker is `api.current`. On pages with no name, `.name` gets `is-empty` and is hidden. Its position stays at `x` and `y` of `ui.name`. Not used in NVL and on the chat screen
  - Dialog and text input `dialog(api)` (`@dialog`, `@text-input`; built each time): the returned element is placed on the box's backdrop (`.lm-panel` with `lm-panel-custom`) and the standard box (`.lm-panel-box`) is not made.
    `api` has `kind` (`alert`, `confirm`, `input`, and `text` for `@text-input`), `message` (`text` of `@dialog`, `prompt` of `@text-input`), `input` (the field's `initial`, `placeholder`, `max`, `mode` and `required`; `null` without a field),
    `okLabel` and `cancelLabel` (`ok-label`, `cancel-label` or the standard wording; `null` for boxes without a cancel button), `accepts(text)` (whether `required=` and `pattern=` allow it), `ok(text)` (confirms) and `cancel()` (cancels).
    Back (Esc, right-click, B) is `cancel`. Keeping keys away from advancing the text, telling the recorder and clearing up on load are handled by the system
  - Controls help `help(api)` ("Controls" in the menu and `@open-screen help`): `rows` (each action's `label`, `keyboard`, `touch` and `pad`, made from the current bindings), `pages` (`ui.help.pages`), `asset`, `close` and `onClose`
  - Inventory `items(api)` ("Items" in the menu, `@open-screen items`, `@item-select`): `items` (`items` in liminalia.json), `held` (the counts held), `asset`, `select` (only for `@item-select`: `title` and `pick(name)`, which passes the chosen item), `close` and `onClose`
  - Which of text, theme values, CSS and replacement hooks can change each screen is in the table in [screens.md](screens.md)
- **Screens and effects for each theme**: `themes: { <id>: { rootClass, text, title, splash, screens, texts } }`. Only when `ui.system.preset` is `<id>` are these laid over the items of the same name (other themes go back to the standard screens).
  Values (the message window, text, choice colors and so on) go in the project's `themes/<id>/theme.json` (“Themes” in [player.md](player.md)), and screens that can't be written as values are registered here.
  `rootClass` is put on the game screen only while the theme is selected, so theme CSS scoped under it goes away with it. To override the same class names as the standard screens without changing specificity, use `:where(.class)`.
  Things that should work in every theme (rendering of the project's commands, `setup`, `ready`, `slotMeta`) go outside `themes`
- **Changing the text of the standard screens**: `texts: { "confirm.title": "Back to the title screen. Are you sure?", … }` (the keys are the nesting of
  `TEXT` in `system/strings.ts`; laid over after `ui` in the language's translation). The screens of the standard commands (codex `codex.*`, investigation `investigate.*`, map choice `mapChoice.*`, chapter end `chapter.end`) read the same table.
  To read the current language's wording from a plugin's screen, use `systemText()` from `import { systemText } from "@liminalia/sdk/web"` (its contents change with the language, so read it each time you show text)
- **Startup effect**: return `splash(ctx)` to play it once after "Click to start" and before the title (a Promise that resolves when it's done).
  To show only logos and notices, write them in `ui.splash` in liminalia.json without writing a plugin (“Startup effect” in [player.md](player.md))
- **Ending effect**: return `endSplash(ctx)` to play something before the title every time the scenario ends and goes back to the title (for example, the startup effect again after the game is cleared). When there's nothing to play, resolve without doing anything
- **Status and events** (the `system` received in `ready`; use them for buttons the project places itself, for showing and hiding the quick menu, and for inserting the project's own effects):
  - `system.status` (`mode`, `screen`, `choosing`, `hidden` (the player hid the window), `window` (the message window is showing), `waiting`
    (waiting for a click), `auto`, `skip`, `replay`, `menuBar`, `canPrevChoice`, `canRollback`, `canRollforward`), `system.onStatusChange((s) => …)` (only when something changes)
  - `system.onEvent((e) => …)`: `start` (right after a play is created with "New Game"; to put variables into `e.runtime`, set up the game screen and so on),
    `load-start` (right before the current play is discarded for a load, a return from the backlog or the previous choice; to lower a curtain and so on), `screen-open` / `screen-close`
    (`name`, and `from` when opened), `rollback` (right before rebuilding for a rollback; `direction` is `back` or `forward`; it isn't a load, so
    don't lower a curtain), `title`, `load-end` (after rebuilding for the load from `load-start`; raise the curtain). For `start` and `load-start`, play doesn't go on until the returned Promise settles
  - `system.systemVariables` (variables shared by all saves; also readable on the title screen), `system.importData({ slots, system, read, settings })`
    (carrying data over from an earlier storage format; stores the slots, shared variables, read status and settings, and returns the number of slots that couldn't be stored)
- **The project's setting ranges and input** (ui in liminalia.json): `ui.settings` (`textSpeedMin`, `textSpeedMax`, `textSpeedStep`, `autoWaitMin`,
  `autoWaitMax`, `autoWaitStep`, `autoPerChar`; `samples` for previewing volumes, `voiceSpeakers` for which characters the per-speaker voice volumes in Settings list) sets the ranges of the settings and the auto wait time, `ui.input.rightClick: "hide"` makes right-click
  hide the window, and `ui.title.bgmVolume` changes the volume of the title BGM. During play, the game screen gets
  the class `lm-choosing` while choices are shown, and `lm-window-hidden` while the window is hidden
- **Using settings, the backlog and save slots from project screens** (the `system` received in `ready`; provided by the default system screens):
  - Settings: `system.settings` (read-only: text speed `textSpeed`, auto wait `autoWait`, master volume `master`, mute `mute`, volumes `bgm` `se` `voice`, also skip unread text
    `skipUnread`, stop the voice on the next page `voiceStopOnPage`, volume per speaker `speakerVoice`, fullscreen `fullscreen`, language `language`),
    `system.updateSettings({ bgm: 60 })` (clamps the value to its range, saves it and applies it right away; returns the settings after the change),
    `system.onSettingsChange((s) => …)` (also called for config, `@config` and toggling fullscreen; the returned function removes it).
    The numeric ranges are in `SETTING_RANGES`. Put project-specific settings in `custom` (`updateSettings({ custom: { windowAlpha: 0.8 } })`;
    merged by name and removed with `undefined`; stored in the same place, and the engine doesn't read them)
  - Backlog: `system.backlog` (oldest first: the speaker `speaker`, the name shown `label` (on a page where two people speak at once, both names joined as in the name box), the other speakers who spoke at once `with`, pieces of the text `parts` (text `text`, ruby `ruby`, bold, italic, color,
    line break `{ br: true }`), voice `voice`, position `at`, whether it can be replayed from there `canJump`, whether it's a chosen choice `choice`), `system.playBacklogVoice(i)`,
    `system.jumpToBacklog(i)` (asks first, then plays again from that entry)
  - Save slots: `system.slots({ from, to })` (numbered slots, including empty ones), `system.slot("quick")`. They have the date `date`, the start of the text `title`,
    a thumbnail `thumb` and the project's metadata `meta`. The metadata is what the plugin's `slotMeta({ runtime, host })` returns on each save
    (it's attached to saves made from the standard save screen too), with `meta` from `system.saveTo(slot, meta)` laid over it. Delete one with `system.deleteSlot(slot)`.
    They read the same way with the setting that protects save data (`saves.protect`), so don't read localStorage directly. They also hold the chapter name `chapter` and the play time `playTime` (in milliseconds)
    (save data made with earlier versions doesn't have them). If the project decides chapter names, return them from the plugin's `slotChapter({ runtime, host, label })`
    (`label` is the current file and label; return `null` for the standard way, or `""` to show nothing)
  - Autosaves: `system.autoSlots()` (newest first, with empty slots at the end; `slot` is `"auto:0"` and so on), `system.autosave(meta)` (the same as `@autosave`).
    `system.loadFrom("auto:0")`, `system.slot("auto:0")` and `system.deleteSlot("auto:0")` work too. Autosaving when quitting and when going to the background is
    `ui.autosave.leave` (projects that replaced the load screen have it off unless they write it; set it to `true` if you list autosaves).
    If the project detects switching to the background itself, call `system.leave()` (it stores what's shared by all saves and autosaves according to the setting)
  - Quick saves: `system.quickSlots()` (newest first; `slot` is `"quick"`, `"quick:1"` and so on; the number of slots is `ui.quickSave.slots`,
    and `quickSlotCount` in the api of the save and load screens). `system.perform("quick-save")` saves to an empty slot or the oldest one, and
    `system.perform("quick-load")` loads from the newest. `system.saveTo("quick")` saves to the first slot
- **Replacing only the title screen**: return `title: (api) => HTMLElement`. The returned element fills the game screen, and the other system screens
  (save, config, backlog and so on) stay standard. `api` behaves the same as the standard title buttons (`start()` New Game, `load()` Continue
  (opens the list), `loadLatest()` from the newest save, `hasSave()`, `config()`, `extra()`, `hasExtra()`, `exit()`, `canExit()`), and also has
  `project`, `host` (asset paths are `host.context.asset(kind, path)`), `ask(message, kind)` (the standard confirmation) and
  `intro` (whether this is the first title since startup; use it to decide whether to show an intro effect). It's called every time the title is shown (and rebuilt when the language changes).
  The background and BGM from `ui.title` are shown as usual. Not available in projects that replace the system screens entirely.

## Import (`./import`)

Settings for importing a TyranoScript project with `lim import`. `lim import` uses the built-in conversion table for the standard commands,
with each plugin's `./import` (and `./import` of the package that `import.tyrano.profile` points to) laid over it in the order of `plugins`.
Command specs (parameter types, unnamed parameters, defaults) are looked up from the command tables in `./commands`, so here you write only how they correspond to .ks.

```ts
const profile: TyranoImportProfile = {
  mappings: [
    // turn [stamp_show storage=… x=…] into @stamp; storage in .ks is image in @stamp
    { command: "stamp", tags: ["stamp_show"], params: { image: "storage" } },
    { command: "stamp-clear", tags: ["stamp_clear"] },
  ],
};
export default profile;
```

- `mappings` (an array of `TagMapping`): the conversion table from .ks tags to commands.
  - `command` is the name of the command to convert to, and `tags` are the names of the .ks tags to convert from.
  - `params` maps ".lim parameter name → .ks parameter name". Parameters you don't list use their name with `-` turned into `_`, and `null` means there's no counterpart in .ks.
  - If you don't write anything else, the conversion is mechanical (of the values written in the .ks, only those that differ from the command's defaults are written out, and parameters that weren't converted are left in the diagnostics).
  - When mechanical conversion isn't enough, use `convert(pm, tag, ctx)`. `ctx.spec` is the command's spec, `ctx.mechanical(pm)` is for converting mechanically after tidying the values,
    and `ctx.convertAs(command, pm, tag)` is for handing off to another conversion table. Returning null falls back to mechanical conversion.
  - For forms you want to leave to the built-in conversion, use `defer(pm)` (to turn only certain destinations of `[jump]` into your own command, for example);
    list .ks parameters not to convert in `ignore`; and use `swallowStop` to remove the `[s]` right after.
- `scriptRules` / `scriptProfile`: replace JS in `[iscript]` with commands (return the replacement .lim lines, or null if the rule doesn't apply)
- `unsupportedTags`: tags that aren't handled, and why (importing them gives an error with the reason, and they're listed in `lim reference` too)
- `tags`: conversions for tags that can't be written in the table (tag name → `(pm) => TagConversion | null`; takes precedence over the table)
- `plugins`: TyranoScript plugins whose work is taken over (they aren't reported as manual work even if they have JS)
- `skipFiles`: .ks files not to convert as story text (ones the system screens take care of, such as the title screen)
- `afterImport(ctx)`: writes out project-specific data (JSON under `data/`) and returns the character definitions
  (if the project keeps settings in the same form as Tyrano Tatie under another name, `castFromTatieSettings` can turn them into character definitions)
- `writeCast(ctx)`: writes character definitions saved in the sprite position editor back to the import source
- `backport`: for writing back (`lim backport`), the reverse conversion that turns command lines back into .ks tags (command name → `(line, originalTag) => tag text | null`).
  Writing back finds parameters by rewriting them with the conversion table and the original tag as a model, so you usually don't need this. Use it for commands that can't be turned back from a model alone, such as conversions written with `tags`
  ([tyrano-backport.md](tyrano-backport.md))

The conversion table for the standard commands (`@image` and so on) is `STD_MAPPINGS` in the engine (`packages/ks-import/src/std-tags` in the public repository).
You can read it as an example of how to write conversion tables.

## Studio (`./studio`)

Adds project-specific management screens (settings tables, data editing and so on) to the "Plugins" tab of Studio. Only Studio (the dev server) reads it, and
it isn't included in the exported game. In the tab's left panel, the screens are grouped by plugin name (`name`) and listed in the order of `views`.
You can start a new plugin from a template with a working example, with "Create new" in the "Plugins" tab.

```ts
import { defineStudioPlugin } from "@liminalia/sdk/studio";

export default defineStudioPlugin({
  name: "stamp",
  views: [{ id: "stamp-book", title: "Stamp book", mount: (el, ctx) => { /* build inside el */ return { flush, refresh }; } }],
});
```

- `mount(el, ctx)` is called only once, the first time the tab is opened. What it returns (optional): `show`, `hide` (entering and leaving the tab), `flush` (saves anything waiting to be saved right away;
  called before the window closes, on ⌘S and before "Refresh"; if it can't save, it refuses with a string giving the reason), `refresh` (when "Refresh" reloads the project),
  `navState`, `restoreNav` (for "Back" and "Forward": `navState` returns the current place within the screen as a value that can be turned into JSON, and `restoreNav` goes back to that place; the screen is already in front by then)
- The `ctx` API:
  - `readData(name)`, `writeData(name, text, baseHash)`: project data (.json in `paths.data`). Pass the `hash` you got when reading back as `baseHash`;
    if the file was rewritten elsewhere, nothing is saved and you get `{ ok: false, current }` (the screen decides what to do, such as laying its changes over the current contents and saving again).
    The change history is kept in `.liminalia/history/@data/`
  - `onDataChanged(listener)`: data changed elsewhere (in another editor, by AI, through git). `onProjectChanged(listener)`: the list of files, characters or assets changed
  - `project` (the title, the screen size, and the lists of files, characters and assets), `assetUrl(kind, path)`, `uploadAsset(kind, path, file, overwrite)` (images, sounds, videos and fonts only)
  - `openScript(file, line)` (opens that line of the scenario in the "Script" tab), `notify(text)` (a notice shown at the bottom of the screen)
  - `remember()`: call it before moving within the screen (before changing the open page or the selected item) to keep the current `navState` in the back history. It does nothing while moving with "Back" and "Forward"
  - `server(path, init)`, `stream(path, init)`: call the dev server side API of the same plugin ([The dev server side](#開発サーバー側の口studio-server))
  - `script`: the scenario being edited in the "Script" tab ([The script API](#台本の口ctxscript))
- Match the look with Studio's CSS variables (colors `--sheet`, `--paper`, `--rule`, `--ink`, `--ink-soft`, `--cue`, `--cue-wash`, `--mark` and so on;
  text `--fs-s` (12px), `--fs-m` (14px), `--fs-l` (20px, headings), `--fs-xl` (36px); lines `--line`; corner radii `--r-s`, `--r-m`, `--r-l`.
  They all point to Radix Colors steps and work with the dark color scheme too. Grays are mauve, and actions and the current position are violet. No shadows).
  Buttons, input fields and select fields get Studio's default look as they are (`button.primary`, `button.ghost`)
- `Splitter`, a handle for changing a panel's width by dragging its border, is also available from `@liminalia/sdk/studio` (it records the width in px in a CSS variable on the container:
  ``new Splitter({ host, side: "left", variable: () => "--list-w", min: 200, max: (w) => w - 480, storageKey: (v) => `project.screen${v}` })``).
  The handle's look is `.splitter` (`position: absolute`; decide where it goes in the screen's CSS, like `left: calc(var(--list-w) - 4px)`)
- An example is [examples/stamp-plugin/src/studio.ts](../examples/stamp-plugin/src/studio.ts) (it saves a memo for each image asset in `data/stamps.json`)

### UI parts (`@liminalia/sdk/studio`)

- `dataDocument(ctx, name, { fallback, delay, indent, history })`: holds project data as a single document. Read `value`, and when you change it with `update(copy => …)` or `set(value)`,
  it's saved automatically after a short wait (`delay`, 800 milliseconds by default). If the file was rewritten elsewhere (in another editor, by AI, through git), it merges three ways, based on the contents when it was read, and saves again
  (items changed by only one side take that side's value; if both changed an item, this side's value is used; `mergeJson` is also available). If the file changes elsewhere while nothing is waiting to be saved, it reloads.
  `undo()`, `redo()` and `bindKeys(element)` give you ⌘Z and ⇧⌘Z within the element (undoing text inside input fields is left to the browser). `onChange((value, reason) => …)`
  (`local`, `remote`, `undo`, `redo`, `load`), `flush()` (can be returned as is from the screen's `flush`), `reload()` (from the screen's `refresh`), `dispose()`
  ```ts
  const memos = dataDocument<Record<string, string>>(ctx, "stamps.json", { fallback: {} });
  memos.update((m) => void (m[path] = text));
  return { flush: () => memos.flush(), refresh: () => memos.reload() };
  ```
- `assetField(ctx, { kind, value, onChange, placeholder, allowEmpty, preview, label })`: a field for choosing an asset (place its `el`). It suggests candidates from the project's asset list, shows a preview for image folders,
  and marks paths that aren't in the list with `data-missing`. It reloads the candidates when the project changes
- `askConfirm(text, { ok })`, `askText(label, { ok, placeholder, value })`: dialogs that look the same as Studio's own ("Yes" and "Cancel" in the screen's language)
- `ctx.apiVersion` (and `STUDIO_PLUGIN_API_VERSION`): the plugin API version. From 2, the parts in this section and `cast`, `speakers`, `assets`, `scripts` and `parse` on the dev server side are available.
  It's `undefined` in older versions of Studio, so plugins that use the newer API check it and branch
- `ctx.language` (from 3): Studio's display language (`"ja"` or `"en"`). Match your screens' text to it. For the names of screens, panels and actions,
  write `titleEn` alongside `title`, and the English display shows that instead
- `suggestAssets(request, ctx)` (from 4; write it in the plugin definition alongside `views`, `panes` and `commands`): adds assets that fit the scene being written to the script's completion.
  It's called where you type the value of an asset-type parameter (`@bg`, `@se`, `@bgm` and so on). `request` has the command and parameter names, the asset folder and the candidates (`candidates`),
  the three lines of dialogue and narration before that line (`before`) and the two after it (`after`), and a `signal` that aborts when typing continues. Return a list of `{ path }`, and up to five of them, in order of fit,
  are listed at the top of the suggestions with a "Fits the scene" mark (the usual suggestions appear below them as they are, without waiting for the answer; if it fails, nothing is added)

### Right panel and actions (`panes`, `commands`)

Things you use while writing (AI consultation, dictionaries and so on) go in the right panel of the "Script" tab, not in a tab.

```ts
export default defineStudioPlugin({
  name: "stamp",
  panes: [{ id: "stamp-pane", title: "Stamp", mount: (el, ctx) => { /* build inside el */ } }],
  commands: [{ id: "stamp-first", title: "Add a line that presses the first stamp", key: "Mod-Alt-s", run: (ctx) => { /* … */ } }],
});
```

- **`panes`**: listed in the right panel as collapsible sections, like the timeline (below the comments section). They start collapsed, and the first time one is opened,
  `mount(el, ctx)` is called once. Opening calls `show` and collapsing calls `hide`; otherwise, as with screens, there are `flush` and `refresh` (`navState` isn't used).
  The whole right panel scrolls vertically, so something that grows tall, like a conversation pane, should set its own height and scroll inside it
- **`commands`**: listed at the end of the "More" menu in the top bar. If you write `key` (in CodeMirror notation; `Mod` is ⌘ on Mac and Ctrl elsewhere),
  it can be called with that key in the "Script" tab. If `run(ctx)` throws, the error is shown as a notice

### The script API (`ctx.script`)

Reading and writing the scenario open in the "Script" tab and its text. Lines are counted from 1, and positions within a line from 0.

- `current()`: `{ file, line, selection, readOnly }`. `selection` is the selected range (`{ from: { line, ch }, to, text }`; null if nothing is selected).
  null if no scenario is open
- `text()`: the open scenario's text, including what hasn't been saved yet. `read(file)`: reads a scenario (for the open scenario, the text being edited)
- `onChange(listener)`: the scenario was reopened, the cursor moved, or the selection changed. Not called while you're typing
- `apply(edits)`: rewrites lines of the open scenario. ⌘Z undoes them together as one change, and they're saved automatically afterward
  ```ts
  // rewrite lines 3–4 and add a line before line 10
  ctx.script.apply([
    { file, from: 3, to: 4, expect: "line 3 before the rewrite\nline 4 before the rewrite", text: "a new line" },
    { file, from: 10, to: 9, expect: "", text: "@stamp stamps/ok.png" },
  ]);
  ```
  - Replaces lines `from` to `to` (both included) with `text`. `text` may contain line breaks; null deletes the lines. Setting `to` to `from - 1` adds the text before line `from`
  - `expect` is those lines before the rewrite (joined with line breaks). The writer keeps typing while AI is drafting a suggestion, so instead of the whole file,
    it checks only that the lines being rewritten are unchanged. If they differ, nothing is rewritten and `{ ok: false, reason: "changed", index }` is returned
  - Other reasons: `not-open` (the scenario isn't open; save it with `ctx.writeScript` on the dev server side), `readonly` (a scenario in an imported project that hasn't been opened up for editing yet),
    `invalid` (a line range is out of bounds or overlaps another)
- An example is the “スタンプ” (Stamp) pane and action in [examples/stamp-plugin/src/studio.ts](../examples/stamp-plugin/src/studio.ts) (it adds `@stamp` before the cursor line)

### The dev server side (`./studio-server`)

For things the browser screen alone can't do, such as starting child processes (AI CLIs and so on) or reading files outside the project, add APIs on the dev server (Node) side and
call them from the screen. Only the dev server (`lim studio`, `lim dev`, the desktop version) reads it, and it isn't included in the exported game.
Make `name` the same as `name` in the same plugin's `./studio` (the endpoint paths become `STUDIO_API/plugin/<name>/…`).

```ts
import { defineStudioServerPlugin, StudioServerError } from "@liminalia/sdk/studio-server";

export default defineStudioServerPlugin({
  name: "stamp",
  routes: {
    "GET /total": (req, ctx) => ({ count: 3 }),            // return a value → JSON
    "POST /scan": async function* (req, ctx) {             // async iterator → sent one at a time
      const { folder } = await req.json<{ folder: string }>();
      if (!folder) throw new StudioServerError(400, "Send a folder");
      for (const f of list(folder)) {
        if (req.signal.aborted) return;                    // the screen stopped it
        yield { path: f };
      }
    },
  },
  dispose() { /* when the dev server closes; stop the child processes you started */ },
});
```

On the screen side, `ctx.server` receives a value, and `ctx.stream` receives what's sent, one item at a time.

```ts
const total = await ctx.server<{ count: number }>("/total");
for await (const s of ctx.stream<{ path: string }>("/scan", { body: { folder: "stamps" } })) show(s);
```

- **`routes`** keys are the method and the path after `name`, like `"GET /status"`. Return
  a value (turned into JSON; no body if `undefined`), an async iterator (each item it yields is sent as one line) or a `Response` (to return images or sounds as they are).
  Throwing `StudioServerError(status, message)` (or an `Error` with a number from 400 to 599 in `status`, for plugins outside the project that don't import the sdk)
  returns that status, and the screen's `server` and `stream` throw an `Error` with `status`
- **Cancellation**: when the screen leaves its `for await` (`break`) or aborts `init.signal`, the connection is closed and the server side's `req.signal` is aborted.
  If it's in the middle of sending, the iterator is closed and `finally` runs. Stop long work (child processes) by watching `req.signal`
- **`req`**: `method`, `path`, `query`, `json()` (null if there's no body), `text()`, `signal`
- **`ctx` (server side)**:
  - `root`, `paths` (the project folder, and where the scenarios, assets and data are)
  - `stateDir()`: a folder this plugin can use freely (`.liminalia/plugins/<name>/`; created if it doesn't exist). Use it for Studio-only data such as conversation history and settings
  - `readScript(file)`, `writeScript(file, text, baseHash)`: scenarios (without the extension). Pass the `hash` you got when reading back as `baseHash`; if the file was rewritten elsewhere,
    nothing is saved and you get `{ ok: false, current }`. Saving keeps the previous contents in the change history and tells Studio about an outside change (if the scenario is open, Studio merges it with the text being edited)
  - `readData(name)`, `writeData(name, text, baseHash)`: the same project data as the screen's `ctx`. Saving notifies the screen's `onDataChanged`
  - `commands()`: the specs of the commands available in the project (built-in, standard and plugin). Built-in commands include words for what you want to do (`keywords`; `command-meta.ts`).
    Use them as guidance when you let AI choose commands
  - `check(file, text)`: checks a scenario's contents without saving and returns that file's diagnostics (taking other files' labels, characters and assets into account, with the same rules as `lim check`).
    Use it to check AI suggestions before applying them
  - `log(message)`: writes to the dev server's log
  - `apiVersion` (from 2), and APIs that save you from reading the project's contents yourself (all from 2; older versions of Studio don't have them, so call them like `ctx.parse?.(…)`):
    `cast()` (cast in cast.json), `speakers()` (speakers in cast.json and the characters' speaker), `assets()` (folder → list of paths), `scripts()` (the list of scenario names),
    `parse(file, text?)` (the parsed scenario, a `Script` from `@liminalia/sdk`. Pass `text` to parse a draft before it's saved. null for a file that doesn't exist)
- **Loading**: loaded only once, the first time the API is called. After you change it, Studio's "Refresh" asks for a restart. A plugin that can't be loaded is
  reported in the dev server's log, and calling its API returns the reason
- **Protection**: the API accepts only requests from the same origin as Studio that carry the header `x-liminalia-studio: 1` (`ctx.server` and `ctx.stream` add it).
  This keeps other pages from calling the API (including the parts that start child processes)
- An example is [examples/stamp-plugin/src/studio-server.ts](../examples/stamp-plugin/src/studio-server.ts) (an API that measures the stamp images' sizes on the Node side and returns the total, and an API that sends them one at a time)

## Checking your plugin

```bash
lim check     # errors in command names, parameters, types and characters, with positions and suggested fixes (plugin checks too)
lim reference # how your commands appear in the reference
lim trace <file>  # run without a screen and see the state (stage.extra) as JSON
lim shot <file> --skip N --settle  # a screenshot of page N (the [N] in lim trace)
lim shot <file#label>             # if your command's screen comes right after the label, a screenshot of that screen
lim playtest --rebuild --runs 2       # play the exported browser version to the end (commands with screens go on through autoplay)
```

For unit tests, the quickest way is to pass `implementations` from `combinePlugins([plugin])` to `Runtime`, run it with `HeadlessHost` and
check `runtime.state.stage.extra`. For import, pass a registry built from `specs` and the `./import` to
`resolveImportProfile`, and check the result by using its `tags` as `profile` for `convert`
([examples/stamp-plugin/test](../examples/stamp-plugin/test)).
