# AnimStream Game SDK · Protocol 1

Baue native Spiele für TikTok LIVE. AnimStream Studio startet das Spiel und sendet Geschenk-Aktionen über einen lokalen WebSocket. Das Spiel verarbeitet Aktionen und meldet ihr Ergebnis zurück.

## Quickstart

1. Wähle eine Engine. Godot 4.3+ enthält eine komplette Spielvorlage. Unreal Engine 5.3+ enthält ein Plugin und Beispielprojekt. Unity 2022.3+ nutzt ein UPM-Paket.

   - [Godot SDK](https://animstream.com/game-sdk/animstream-godot-sdk.zip)
   - [Unreal SDK](https://animstream.com/game-sdk/animstream-unreal-sdk.zip)
   - [Unity SDK](https://animstream.com/game-sdk/animstream-unity-sdk.zip)
   - [Godot README](https://animstream.com/game-sdk/godot/README.md)
   - [Unreal README](https://animstream.com/game-sdk/unreal/README.md)
   - [Unity README](https://animstream.com/game-sdk/unity/README.md)
   - [Agent kit](https://animstream.com/game-sdk/animstream-game-agent-kit.zip)
   - [SHA-256](https://animstream.com/game-sdk/checksums.json)

2. Prüfe die ZIPs gegen checksums.json. Entpacke die Vorlage und das Agent-Kit in den Projektordner. Beschreibe die Aktionen in manifest.json und verbinde sie mit dem Gameplay.

3. Teste mit Mock Studio. Die folgenden Befehle laufen aus dem entpackten Godot-Projekt mit Node.js 20+ und Godot auf dem PATH. Für Unreal oder Unity übergibst du die gepackte ausführbare Datei nach --.

```sh
npm ci --prefix tools/mock-studio
node tools/mock-studio/mock-studio.mjs validate manifest.json
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json -- godot --headless --path .
```

## Mit einem Coding-Assistenten arbeiten

Gib deiner KI diesen Link und deine Spielidee. Nutze die passende Engine-Vorlage und halte dich an das vollständige Protokoll weiter unten. Lies bei Erstinstallation den Startprompt für die gewählte Engine. Führe vor einem Upload die Mock-Studio-Tests aus und berichte die Ergebnisse.

- [Bootstrap prompt](https://animstream.com/game-sdk/agent-kit/BOOTSTRAP-PROMPT.de.md)
- [Agent kit README](https://animstream.com/game-sdk/agent-kit/README.md)
- [TypeScript protocol types](https://animstream.com/game-sdk/agent-kit/animstream-protocol.ts)

## Manifest-Beispiel

[manifest.schema.json](https://animstream.com/game-sdk/agent-kit/manifest.schema.json)

```json
{
  "schemaVersion": 1,
  "gameId": "replace-with-your-game-id",
  "title": { "de": "Community Counter", "en": "Community Counter" },
  "description": { "de": "Zuschauer sammeln in 60-Sekunden-Runden gemeinsam Punkte – oder klauen sie dem Streamer.", "en": "Viewers collect points together in 60-second rounds – or steal them from the streamer." },
  "actions": [
    {
      "id": "spawn",
      "effect": "help",
      "label": { "de": "Punkte hinzufügen", "en": "Add score" },
      "description": { "de": "Gibt dem Streamer sofort Punkte. Mehrere Geschenke werden zusammengezählt.", "en": "Gives the streamer points at once. Several gifts are added up." },
      "image": "media/actions/spawn.png",
      "stackable": "count",
      "parameters": [{ "key": "count", "label": { "de": "Anzahl", "en": "Count" }, "type": "integer", "min": 1, "max": 100, "default": 1 }]
    },
    {
      "id": "double-points",
      "effect": "help",
      "label": { "de": "Doppelte Punkte", "en": "Double points" },
      "description": { "de": "Alle Punkte zählen für ein paar Sekunden doppelt.", "en": "Every point counts twice for a few seconds." },
      "image": "media/actions/double-points.png",
      "parameters": [{ "key": "seconds", "label": { "de": "Sekunden", "en": "Seconds" }, "type": "integer", "min": 5, "max": 30, "default": 10 }]
    },
    {
      "id": "steal-points",
      "effect": "sabotage",
      "label": { "de": "Punkte klauen", "en": "Steal points" },
      "description": { "de": "Nimmt dem Streamer Punkte weg. Der Punktestand fällt nie unter null.", "en": "Takes points away from the streamer. The score never drops below zero." },
      "image": "media/actions/steal-points.png",
      "stackable": "amount",
      "parameters": [{ "key": "amount", "label": { "de": "Punkte", "en": "Points" }, "type": "integer", "min": 1, "max": 500, "default": 10 }]
    },
    {
      "id": "shake-screen",
      "effect": "sabotage",
      "label": { "de": "Bildschirm wackeln", "en": "Shake the screen" },
      "description": { "de": "Lässt das Spielfeld ein paar Sekunden lang wackeln.", "en": "Shakes the playfield for a few seconds." },
      "image": "media/actions/shake-screen.png",
      "parameters": [{ "key": "seconds", "label": { "de": "Sekunden", "en": "Seconds" }, "type": "integer", "min": 2, "max": 10, "default": 3 }]
    }
  ],
  "events": ["GIFT"],
  "defaultBindings": [
    { "giftName": "Rose", "actionId": "spawn", "params": { "count": 1 } },
    { "giftName": "Finger Heart", "actionId": "steal-points", "params": { "amount": 5 } },
    { "giftName": "Perfume", "actionId": "double-points", "params": { "seconds": 5 } },
    { "giftName": "Doughnut", "actionId": "shake-screen", "params": { "seconds": 3 } }
  ],
  "presets": [
    {
      "id": "small-budget",
      "title": { "de": "Kleines Budget", "en": "Small budget" },
      "description": { "de": "Günstige Geschenke bis 30 Münzen: viel Bewegung für wenig Geld.", "en": "Cheap gifts up to 30 coins: lots of action for little money." },
      "bindings": [
        { "giftName": "Rose", "actionId": "spawn", "params": { "count": 1 } },
        { "giftName": "Finger Heart", "actionId": "steal-points", "params": { "amount": 5 } },
        { "giftName": "Perfume", "actionId": "double-points", "params": { "seconds": 5 } },
        { "giftName": "Doughnut", "actionId": "shake-screen", "params": { "seconds": 3 } }
      ]
    },
    {
      "id": "medium",
      "title": { "de": "Mittel", "en": "Medium" },
      "description": { "de": "Geschenke von 99 bis 299 Münzen mit spürbaren Effekten.", "en": "Gifts from 99 to 299 coins with noticeable effects." },
      "bindings": [
        { "giftName": "Hand Hearts", "actionId": "spawn", "params": { "count": 25 } },
        { "giftName": "Confetti", "actionId": "shake-screen", "params": { "seconds": 5 } },
        { "giftName": "Hearts", "actionId": "steal-points", "params": { "amount": 40 } },
        { "giftName": "Corgi", "actionId": "double-points", "params": { "seconds": 15 } }
      ]
    },
    {
      "id": "big-gifts",
      "title": { "de": "Große Geschenke", "en": "Big gifts" },
      "description": { "de": "Ab 500 Münzen: große Momente, die die Runde drehen.", "en": "From 500 coins: big moments that turn the round." },
      "bindings": [
        { "giftName": "Money Gun", "actionId": "spawn", "params": { "count": 100 } },
        { "giftName": "Swan", "actionId": "steal-points", "params": { "amount": 150 } },
        { "giftName": "Galaxy", "actionId": "double-points", "params": { "seconds": 30 } },
        { "giftName": "Fireworks", "actionId": "shake-screen", "params": { "seconds": 10 } }
      ]
    }
  ],
  "leaderboard": { "label": { "de": "Punkte", "en": "Score" }, "order": "desc" },
  "giftWall": { "columns": 4, "sort": "preset", "showCoins": true, "showLabels": true, "title": { "de": "Geschenke", "en": "Gifts" }, "split": true }
}
```

## Build, Prüfung und Store

Lege ein Projekt im Entwickler-Dashboard an. Exportiere einen Build für die gewünschte Plattform und verpacke ihn mit dem Release-Packer. Lade zuerst einen Test-Build hoch, prüfe ihn in Studio und reiche danach die Version zur Prüfung ein.

- [Entwickler-Dashboard](https://animstream.com/de/developers/games/dashboard)
- [Release packer](https://animstream.com/game-sdk/agent-kit/tools/package/README.md)
- [Release CLI](https://animstream.com/game-sdk/agent-kit/tools/release/README.md)
- [Originals-Checkliste](https://animstream.com/de/developers/games/checklist/index.md)
- [Art Direction](https://animstream.com/de/developers/games/art-direction/index.md)

---

## AnimStream Originals — local game protocol 1

This is the normative reference for the WebSocket protocol between AnimStream
Studio and a native Originals game. The Godot, Unity and Unreal SDKs implement it;
a custom client must follow it exactly. Everything added after the first release
is optional, so games built against the first SDK keep working unchanged.

- Transport: one WebSocket text connection to `ws://127.0.0.1:<port>/v1`.
- Encoding: UTF-8 JSON objects, one message per frame, at most 64 KiB per frame.
- Times: Unix milliseconds. IDs: 1–128 characters unless stated otherwise.
- Every message carries `type` and `sessionId`. A frame with another session ID,
  invalid JSON, a binary frame or an oversized frame ends the session.

## 1. Compatibility rules

| Rule | Why |
|------|-----|
| `protocol` stays `1`. New fields are optional. | Old games run unchanged. |
| Clients ignore unknown fields in any Studio message. | Studio may add optional fields. |
| Studio never sends a new message type unprompted. `response` answers a client `request`; `notify` follows only a successful `bindings.list`. | Old clients stop on unknown message types. |
| A client sends `state` or `request` only if `ready.features` lists the capability. | Studio 0.1.285 and older omit `features` and close the session on unknown messages. |
| Manifest extensions reach only Studio versions that announce them. Older Studio versions receive the base manifest without `stackable`, `defaultBindings`, `presets`, action `image`, `leaderboard` and `giftWall` (`giftWall.sort` `preset` arrives as `manifest` without `presets`). Without the `action-effects` extension they receive it without action `effect` and `giftWall.split` — byte-identical to the manifest of a build that never had them. | Older Studio versions reject unknown manifest keys. |

A game must therefore work without stacking, default rules, presets, a
configured Gift Wall, state reporting and leaderboards. It only loses those conveniences on an old Studio.

## 2. Launch

Studio starts the reviewed entrypoint with these environment variables. They are
the only credentials a game receives:

| Variable | Meaning |
|----------|---------|
| `ANIMSTREAM_GAME_ID` | Immutable game ID (`^[a-z0-9][a-z0-9-]{0,95}$`) |
| `ANIMSTREAM_BUILD_ID` | Build ID of this exact release |
| `ANIMSTREAM_SESSION_ID` | ID of this launch session |
| `ANIMSTREAM_GAME_URL` | `ws://127.0.0.1:<ephemeral-port>/v1` |
| `ANIMSTREAM_GAME_TOKEN` | Random one-launch token (`^[A-Za-z0-9_-]{32,256}$`) |

The token is not an account token or the cloud lease secret. Never log, persist,
display or put it on a command line. Without valid variables the game was not
started by Studio: the SDKs stop with `launch_required`.

## 3. Session lifecycle

1. The client connects and sends `hello` within 8 seconds.
2. Studio answers `ready` with the reviewed manifest. Only then may gameplay
   accept stream input.
3. Studio sends `ping` every 2 seconds; the client answers `pong`. After 8 seconds
   without a ping the client stops (`heartbeat_lost`).
4. Studio renews the 90-second cloud lease every 30 seconds and relays each
   renewal as `lease`. At `leaseExpiresAt` the client stops (`lease_expired`).
5. `stop`, a closed socket or any protocol violation ends the session. Default
   SDK behavior quits the game. Custom pause behavior must gate all gameplay and
   never resume a dead session. There is no reconnect and no replay.

Exactly one connection is accepted per launch. If a bundled helper process speaks
the protocol instead of the entrypoint, the entrypoint must not connect as well.

## 4. Messages from Studio

### `ready`

```json
{ "type": "ready", "protocol": 1, "sessionId": "…", "leaseExpiresAt": 1767225600000,
  "heartbeatMs": 2000, "manifest": { "schemaVersion": 1, "gameId": "zombie-prank" },
  "features": ["source", "stack", "state", "leaderboard", "bindings", "leaderboard-avatars"],
  "session": { "language": "de", "streamerHandle": "streamer_name" } }
```

| Field | Type | Notes |
|-------|------|-------|
| `manifest` | object | The reviewed manifest (section 7). The game cannot replace it. |
| `features` | string[]? | Optional. Absent on Studio 0.1.285 and older. Values: `source` (actions carry `source`), `stack` (Studio merges stackable actions), `state` (client may send `state`), `leaderboard` (client may request `leaderboard.*`), `bindings` (client may request `bindings.list`), `leaderboard-avatars` (`leaderboard.top` entries carry `avatarUrl`, section 8). Ignore unknown values. |
| `session.language` | `"de"` \| `"en"` | Optional. Studio UI language. |
| `session.streamerHandle` | string? | Optional TikTok username without `@`: 2–24 characters `[A-Za-z0-9._]`. Present only if the streamer allowed sharing it in Studio. Display data, not an authentication factor. |

### `ping` / `lease` / `cancel` / `stop`

```json
{ "type": "ping",   "sessionId": "…", "at": 1767225600000 }
{ "type": "lease",  "sessionId": "…", "expiresAt": 1767225690000 }
{ "type": "cancel", "sessionId": "…", "id": "<action id>" }
{ "type": "stop",   "sessionId": "…", "reason": "originals-cancelled" }
```

`cancel` asks the game to stop the pending effects of one action. `stop` ends the
session.

### `action`

```json
{ "type": "action", "sessionId": "…", "id": "5b0c…", "actionId": "spawn-zombies",
  "params": { "count": 99 }, "expiresAt": 1767225603000, "dryRun": false,
  "viewer": { "name": "Viewer Name", "handle": "viewer_handle" },
  "source": { "code": "GIFT", "giftId": "5655", "giftName": "Rose", "giftCoins": 1, "giftCount": 99 } }
```

| Field | Type | Notes |
|-------|------|-------|
| `id` | string | Unique request ID. Execute each ID at most once, also after acknowledging it. Ignore a repeated ID silently: no second execution and no second `action-result`. |
| `actionId` | string | An action ID from the manifest. Unknown IDs: reply `rejected`. |
| `params` | object | Primitive values. Validate them against the manifest again; reject unknown keys. |
| `expiresAt` | number | The game rejects a command that arrives after `expiresAt` or more than 15 s in the future. Expired pending work is cancelled. |
| `dryRun` | boolean | Validate and reply `simulated` without calling gameplay code. |
| `viewer` | object? | The viewer who triggered the rule: `name` (≤ 80 chars, display name) and optional `handle` (≤ 80 chars). |
| `source` | object? | Optional (feature `source`). `code` is the triggering event code (`GIFT`, `COMMENT`, `FOLLOW`, …, `HOTKEY` for Studio tests). Gift fields are present for gifts: `giftId` and `giftName` (≤ 160 chars), `giftCoins` (coins per gift), `giftCount` (gifts this action represents; summed when stacked). |

Viewer and gift strings are untrusted display data. Never interpret them as code,
commands, paths or markup.

### `event`

Raw normalized stream events for the event codes the manifest lists in `events`.

```json
{ "type": "event", "sessionId": "…", "id": "9f2e…",
  "event": { "code": "GIFT", "platform": "tiktok", "ts": 1767225600000, "user": "Viewer Name",
             "handle": "viewer_handle", "giftName": "Rose", "giftId": "5655", "giftCount": 5, "giftCoins": 1 } }
```

| Field | Type | Notes |
|-------|------|-------|
| `event.code` | string | Uppercase normalized code (`GIFT`, `LIKE`, `COMMENT`, `FOLLOW`, `SHARE`, `JOIN`, `SUBSCRIBE`, …). |
| `event.platform` | string | `tiktok`, `twitch`, … |
| `event.ts` | number | Event time. Clients ignore events more than 60 s away from their clock. |
| `event.user` | string | Display name (≤ 80 chars). |
| `event.handle`, `giftName`, `giftId` | string? | ≤ 160 chars. |
| `event.comment` | string? | ≤ 1000 chars. |
| `event.giftCount`, `giftCoins` | number? | Finite numbers. |

> **Avoid double triggering.** A gift can reach the game twice: as a raw `event`
> and as an `action` from a Studio gift rule. Use gift rules (actions) for
> gameplay effects — they are streamer-configurable, stackable, shown on the Gift
> Wall and editable in Studio's game control window. Use raw events only for effects that no
> gift rule produces, such as a gift ticker or ambient reactions.

### `response` and `notify`

`response` answers exactly one client `request`. `notify` with topic `bindings`
tells a client that has successfully requested `bindings.list` that the gift
rules changed; request the list again.

```json
{ "type": "response", "sessionId": "…", "id": "req-3", "ok": true, "data": { } }
{ "type": "response", "sessionId": "…", "id": "req-4", "ok": false, "error": "rate_limited" }
{ "type": "notify",   "sessionId": "…", "topic": "bindings" }
```

## 5. Messages from the game

### `hello`

```json
{ "type": "hello", "protocol": 1, "gameId": "…", "buildId": "…", "sessionId": "…", "token": "…" }
```

Exactly these keys. Send once, then forget the token.

### `pong`

```json
{ "type": "pong", "sessionId": "…", "at": 1767225600000 }
```

Echo the `at` value of the ping.

### `action-result`

```json
{ "type": "action-result", "sessionId": "…", "id": "5b0c…", "status": "completed" }
{ "type": "action-result", "sessionId": "…", "id": "5b0c…", "status": "rejected", "error": "busy" }
```

| Field | Type | Notes |
|-------|------|-------|
| `status` | `"completed"` \| `"rejected"` \| `"simulated"` | `completed` after the handler finished, `simulated` for `dryRun`, `rejected` otherwise. |
| `error` | string? | Safe error code, ≤ 160 chars (`invalid_action`, `invalid_parameters`, `busy`, `cancelled`, `expired`, `handler_failed`, …). |

Studio processes one action at a time per game and sends the next action after
the result. Acknowledge as soon as the effect has started (for example when the
zombies are spawned, not when they die). An acknowledgement means the handler
completed, not that an external side effect was transactionally rolled back.

### `event-result`

```json
{ "type": "event-result", "sessionId": "…", "id": "9f2e…", "status": "accepted" }
```

`accepted` if at least one handler consumed the event, otherwise `ignored`.

### `state` (feature `state`)

```json
{ "type": "state", "sessionId": "…", "acceptingActions": false, "phase": "round-over", "score": 1250 }
```

| Field | Type | Notes |
|-------|------|-------|
| `acceptingActions` | boolean | `false` pauses dispatch (see below). |
| `phase` | string | `^[a-z0-9][a-z0-9-]{0,31}$`, for example `lobby`, `playing`, `round-over`. |
| `score` | number? | Current score for Studio flows and overlays. Finite, \|score\| ≤ 10¹⁵. Not a leaderboard submission. |

Send `state` when it changes, at most 10 times per second. Studio applies every
valid message immediately (the latest wins) and does not end the session for a
faster rate, but it raises the Flow event at most 10 times per second, so
intermediate phases can be skipped. Before the first `state` a game counts as
accepting actions.

While `acceptingActions` is `false`, Studio sends no new `action` frames.
Waiting actions stay queued and do not expire for up to 60 seconds of continuous
pause; after resuming, each waiting action gets a fresh expiry window. An action
already sent before the pause continues normally. Use this for menus, round
transitions and cutscenes instead of rejecting every incoming action.

In Studio, phase or acceptance changes trigger the Flow event **Game state**, and
the condition fields *game phase*, *game score* and *game accepting actions* read
the latest state.

### `request` (features `leaderboard`, `bindings`)

```json
{ "type": "request", "sessionId": "…", "id": "req-3", "op": "leaderboard.submit", "params": { "score": 4200 } }
```

| `op` | `params` | `response.data` |
|------|----------|-----------------|
| `leaderboard.submit` | `{ "score": integer }`, 0 ≤ score ≤ 10¹² | `{ "best": number, "rank": number \| null, "improved": boolean }` |
| `leaderboard.top` | `{ "limit"?: 1–50 }` (default 10) | `{ "label": {de, en}, "order": "desc" \| "asc", "entries": [{ "rank", "name", "score", "avatarUrl"? }], "self"?: { "rank", "score", "avatarUrl"? } }` |
| `bindings.list` | `{}` | `{ "bindings": [{ "giftName", "giftId"?, "giftImageUrl"?, "giftCoins"?, "actionId", "label": {de, en}, "params" }] }` |

`params` may be omitted for `{}`. In `leaderboard.top`, `name` is `@` plus the
TikTok username of a streamer who allowed sharing it, otherwise the localized
anonymous label (`Anonym` / `Anonymous`). With feature `leaderboard-avatars`,
every entry and `self` carry `avatarUrl`: a profile picture URL or `null`
(section 8). Without the feature the field is absent; treat it as `null`.

Limits and their error codes: a fifth request while 4 are in flight is answered
`busy`; a second `leaderboard.submit` within 2 seconds `rate_limited` (also when
the cloud rate-limits); parameters out of range or an ID that is already in
flight `invalid`; an unknown `op` or a capability not announced `unsupported`.
Offline, signed-out or cloud errors are `unavailable`. Studio answers every
request within 15 seconds, otherwise with `timeout`.

A `state` or `request` frame with a wrong shape (unknown keys, wrong types, an
invalid phase) is a protocol violation and ends the session, like any other
invalid frame. So does `state` without the `state` feature.

The official SDKs also complete requests locally. Without sending anything:
`unsupported` (capability not announced), `not_ready` (before `ready`),
`invalid` (rejected by local validation), `busy` (4 in flight). After sending:
`timeout` (no response within 15 s), `stopped` (session ended first),
`invalid_response` (malformed `response` data). Studio itself never sends
`not_ready`, `stopped` or `invalid_response`.

## 6. Studio behavior games can rely on

### Gift rules and the game control window

Streamers connect gifts to manifest actions with gift rules. Studio provides the
complete management UI; games implement none of it:

- **Game control window.** When an Originals game connects, Studio opens a
  separate *game control* window beside it without taking focus. It shows the
  connection, queue and reported state, lists the manifest actions with test
  buttons, maps TikTok gifts from the gift catalog to actions with parameters,
  enables, disables and deletes gift rules, recreates a deleted Gift Wall and
  shows the leaderboard.
- **F7.** While a game runs, F7 brings the control window above a borderless or
  windowed fullscreen game and back. Reserve F7: never bind it in a game.
  Exclusive fullscreen can hide Studio windows; prefer borderless fullscreen.
- **Gift Wall.** A Gift Wall widget bound to a game fills itself from the
  game's gift rules: gift icon and coins from the gift catalog, label from the
  localized action label. Walls not bound to a game keep their manual entries.

### First start, Gift Wall and updates

There is no setup button. When a game starts:

- **Presets.** If the streamer has no gift rules for the game and the started
  build has `presets`, Studio opens a picker *before* the game starts: one card
  per preset (title, description, up to 8 combinations with gift image, coins,
  action image and action label) plus *Build your own set*. Picking a preset
  creates its gift rules and the Gift Wall (cells in preset order when
  `giftWall.sort` is `preset` or `manifest`) and starts the game without a
  further question. Presets that are new in an update are offered as a notice,
  never applied over existing rules. Keep preset and action IDs stable.
- **First start without presets** (or on a Studio without the `presets`
  extension). If the streamer has no gift rules for the game, Studio
  creates the rules from `defaultBindings` immediately, without asking, and
  shows a one-time notice with *Undo* (Undo removes exactly the rules and the
  wall this setup created, unless the streamer has changed them since). It also
  creates one Gift Wall bound to the game in the active scene, configured from
  the `giftWall` of the started build (Studio's defaults when it is absent).
  Existing rules and walls are never overwritten or duplicated; a second start
  creates nothing.
- **Split wall (help vs. sabotage).** Studio copies each action's `effect` onto
  the wall cells of its gift rules. With `giftWall.split` (extension
  `action-effects`) the wall is split: help actions on one side (left by
  default), sabotage actions on the other, each under a header; neutral and
  unclassified actions in a row below (or with the side named by
  `split.neutral`). A streamer's later change of a cell's effect or of the split
  settings is never overwritten. Without `split` the wall stays one block (the
  streamer can still switch the split on).
- **Updates.** When a newer build brings a changed `giftWall`, Studio applies
  the changed values at the next start to every field the streamer has not
  changed. Fields the streamer changed stay; the wall settings offer *Reset to
  the game's defaults*.
- **Live.** Creating, deleting, disabling or editing a gift rule updates the
  wall immediately, also while the game runs. Disabled rules disappear from the
  wall. Clients that requested `bindings.list` still receive `notify` with
  topic `bindings`.
- **Deleted wall.** If the streamer deletes the automatically created wall,
  Studio does not create it again; the game control window offers *Recreate
  Gift Wall (game defaults)*.

### Stacking (`stackable`)

TikTok viewers often send the same gift dozens of times per second. For an action
with `"stackable": "count"`, Studio merges waiting actions of the same gift rule,
viewer and gift into one action and sums `count`:

- A gift streak delivers every gift as it arrives. Rose ×99 for an action whose
  rule sets `count: 1` becomes one action with `count: 99` (if `max` ≥ 99).
- With `count: 3` per gift, each gift adds 3. The result stays within the
  parameter's `min`/`max`. Gifts beyond `max` start another action; nothing is
  dropped for exceeding the bound.
- Only actions that were not yet sent are merged. `source.giftCount` is the
  number of gifts the action represents.
- During a rule cooldown, gifts accumulate in one waiting action that is sent
  when the cooldown ends.

A stackable handler must accept any `count` between `min` and `max`.

### Queue limits

Up to 100 actions wait per game. Each action expires after its rule's time to
live (1–10 s) unless it is paused by `state`.

## 7. Manifest

The manifest is reviewed with each build. Studio validates every action and
parameter against it before sending.

```json
{
  "schemaVersion": 1,
  "gameId": "zombie-prank",
  "title": { "de": "Zombie-Streich", "en": "Zombie Prank" },
  "description": { "de": "Zuschauer schicken Zombies.", "en": "Viewers send zombies." },
  "actions": [
    { "id": "spawn-zombies", "label": { "de": "Zombies schicken", "en": "Send zombies" },
      "description": { "de": "Schickt Zombies auf den Streamer los.", "en": "Sends zombies after the streamer." },
      "image": "media/actions/spawn-zombies.png",
      "effect": "sabotage",
      "stackable": "count",
      "parameters": [{ "key": "count", "label": { "de": "Anzahl", "en": "Count" }, "type": "integer", "min": 1, "max": 200, "default": 1 }] },
    { "id": "heal", "label": { "de": "Heilen", "en": "Heal" },
      "description": { "de": "Gibt dem Streamer Leben zurück.", "en": "Gives the streamer health back." },
      "image": "media/actions/heal.png",
      "effect": "help",
      "parameters": [{ "key": "amount", "label": { "de": "Leben", "en": "Health" }, "type": "integer", "min": 1, "max": 100, "default": 20 }] }
  ],
  "events": ["GIFT"],
  "defaultBindings": [
    { "giftName": "Rose", "actionId": "spawn-zombies", "params": { "count": 1 } },
    { "giftName": "Doughnut", "actionId": "heal", "params": { "amount": 10 } }
  ],
  "presets": [
    { "id": "small-budget", "title": { "de": "Kleines Budget", "en": "Small budget" },
      "description": { "de": "Geschenke bis 30 Münzen.", "en": "Gifts up to 30 coins." },
      "bindings": [{ "giftName": "Rose", "actionId": "spawn-zombies", "params": { "count": 1 } }, { "giftName": "Doughnut", "actionId": "heal", "params": { "amount": 10 } }] },
    { "id": "medium", "title": { "de": "Mittel", "en": "Medium" },
      "bindings": [{ "giftName": "Hearts", "actionId": "spawn-zombies", "params": { "count": 25 } }, { "giftName": "Corgi", "actionId": "heal", "params": { "amount": 40 } }] },
    { "id": "big-gifts", "title": { "de": "Große Geschenke", "en": "Big gifts" },
      "bindings": [{ "giftName": "Galaxy", "actionId": "spawn-zombies", "params": { "count": 200 } }, { "giftName": "Money Gun", "actionId": "heal", "params": { "amount": 100 } }] }
  ],
  "leaderboard": { "label": { "de": "Überlebte Wellen", "en": "Waves survived" }, "order": "desc" },
  "giftWall": { "columns": 4, "sort": "preset", "showCoins": true, "showLabels": true, "title": { "de": "Zombies schicken", "en": "Send zombies" }, "split": true }
}
```

| Field | Rules |
|-------|-------|
| `schemaVersion` | `1` |
| `gameId` | Your immutable dashboard game ID. |
| `title`, `description` | `{ "de", "en" }`, non-empty; title ≤ 160, description ≤ 1000 chars. |
| `actions` | ≤ 128. `id`: `^[a-z][a-z0-9-]{0,63}$`, unique. `label` ≤ 160 chars, `description` ≤ 1000 (keep it ≤ 120: Studio's preset builder and the store page show it; the tools warn above 120). |
| `actions[].image` | Optional (extension `action-images`). A path inside the build ZIP: one file directly under `media/actions/`, `.png` or `.webp` (name `[A-Za-z0-9_-][A-Za-z0-9._-]{0,95}`, no reserved Windows name), or the `https://animstream.b-cdn.net/game-media/<gameId>/…` URL of an uploaded image, ≤ 512 chars. The file: a still PNG or WebP **with alpha**, square, 256–1024 px, ≤ 300 KB, extension matching the format. Build verification extracts only the referenced files and serves them from the CDN; Studio (and the game's `ready.manifest`) only ever receives the resolved CDN URL; an image uploaded in the dashboard or with `animstream-release media --action-image` replaces the build's image. `animstream-pack --all` copies the files from next to `manifest.json` into every ZIP. |
| `actions[].parameters` | ≤ 16. `key` like `id`; `type`: `integer`, `number`, `boolean`, `string` (`maxLength` 1–256), `enum` (1–32 `options` `{ value ≤ 128, label }`). Optional `required`, `default`, `min`/`max` (numeric only, \|x\| ≤ 10⁹, `min` ≤ `max`). |
| `actions[].stackable` | Optional. Key of an `integer` parameter of the same action with `min` ≥ 1 and `max` set. |
| `actions[].effect` | Optional (extension `action-effects`). `help` (mercy: helps the streamer — heal, shield, extra time; green in ART-DIRECTION.md), `sabotage` (gets in the streamer's way — enemies, shaking, stealing; red) or `neutral` (neither; use it rarely). Omitted = unclassified, treated like `neutral`. Any other value is rejected. Studio copies it onto the Gift Wall cells and groups the split wall by it; the store page groups the actions into *Helps the streamer* / *Against the streamer*. Every Original classifies **every** action; the tools warn when only some actions have an `effect`. |
| `events` | Event codes for raw `event` messages: `GIFT`, `FOLLOW`, `LIKE`, `SHARE`, `COMMENT`, `JOIN`, `SUBSCRIBE`, `TEAM_JOIN`, `LEVEL_UP`, `MULTIPLIER`, `MULTIPLIER_GIFT`, `BOOSTED_GIFT`, `MULTIPLIER_PREDICT`, `CHEER`, `RAID`, `RESUBSCRIBE`, `SUB_GIFT`, `REWARD`, `SHOUTOUT`, `CHARITY_DONATE`. Unique. May be empty. |
| `defaultBindings` | Optional, ≤ 32. `giftName`: TikTok gift display name (1–80 chars, no control characters or `* \| \ [ ] { }`), unique case-insensitively. Studio matches gifts by name because gift IDs differ between regional servers. Write the English display name: TikTok delivers a gift under the name of the streamer's language ("Donut" for Doughnut on a German system), and Studio recognises it in every language. Studio 0.1.306 and older compared the name as delivered, so such a gift did not start its action there. `giftId`: optional hint `^[A-Za-z0-9_-]{1,40}$`. `actionId`: an action of this manifest. `params`: validated against that action; defaults fill missing values. |
| `presets` | Optional (extension `presets`), 1–6. `id`: `^[a-z0-9][a-z0-9-]{0,31}$`, unique; `title` `{de, en}` ≤ 40 chars; optional `description` ≤ 120; `bindings`: 1–8 gift rules `{ giftName, actionId, params }` with the rules of `defaultBindings` (no `giftId`), `giftName` unique per preset. Studio offers them before the first start (section 6). Recommended for every Original: three presets by coin value — every gift ≤ 30 coins, 99–299 and ≥ 500 — each mixing sabotage and mercy actions — balanced, for example 4 `help` + 4 `sabotage` (the tools warn when a preset has no help or no sabotage action or one side has more than three times the other; Studio shows the count per preset, for example "4 Hilfe · 4 Böse"). Keep `defaultBindings` for Studios without presets. |
| `leaderboard` | Optional. `label` `{de, en}` ≤ 40 chars; `order` `desc` (higher is better, default) or `asc` (lower is better, for example times in ms). |
| `giftWall` | Optional layout of the game's Gift Wall (section 6). `columns`: required integer 1–12. `sort`: `coins-asc`, `coins-desc`, `preset` (order of the chosen preset) or `manifest` (the same: preset order, else the order of `defaultBindings`); without it the rule order. Studios without `presets` receive `manifest` for `preset`. `showCoins`: boolean, default `false`. `showLabels`: show action names, boolean, default `true`. `title`: optional `{de, en}` ≤ 40 chars. `split` (extension `action-effects`, optional, recommended for Originals): `true` (split with the defaults), `false` (plain wall) or `{ helpSide, helpTitle, sabotageTitle, showHeaders, neutral }`, every key optional — `helpSide` `left` (default) or `right`; `helpTitle` / `sabotageTitle` `{de, en}` ≤ 40 chars (default: Studio's texts "Hilft dem Streamer" / "Gegen den Streamer"); `showHeaders` boolean, default `true`; `neutral` `bottom` (default, a row below both sides), `help` or `sabotage`. No other keys. |

The serialized manifest must not exceed 48 KiB (UTF-8).

## 8. Leaderboards

Every published game automatically has one global leaderboard on AnimStream.
Developers need no database or server.

- Players are streamers. Each AnimStream account has one entry per game: its
  best score according to `order`. Submit the final score of a round or run with
  `leaderboard.submit`; submitting a worse score changes nothing.
- Studio submits through the authenticated game session; the game never receives
  account credentials. Scores are integers from 0 to 10¹². Submit durations as
  integer milliseconds with `"order": "asc"`.
- Names: an entry shows the streamer's TikTok username only if they allowed it
  in Studio; otherwise it is listed as anonymous. Usernames are reported by
  Studio and are not verified with TikTok; one username can appear on one
  account per game.
- `leaderboard.top` returns the top entries and the current streamer's own rank.
  The public ranking is shown at `https://animstream.com/<locale>/games/originals/<slug>/leaderboard`
  and as a preview on the game page.
- Pictures (feature `leaderboard-avatars`): see below.

This is cooperative scoring by a game the streamer runs. It is not cheat-proof;
administrators can remove entries.

### Profile pictures (`avatarUrl`)

With feature `leaderboard-avatars`, `leaderboard.top` entries and `self` carry
`avatarUrl` (string or `null`). Studio 0.1.286 and older omit it; games without
picture support need no change.

- **Consent.** A picture appears only if the streamer allowed both sharing the
  TikTok username and *showing the profile picture on leaderboards* in Studio
  (off by default). Anonymous entries always have `null`. Revoking the consent
  or deleting the account removes the picture from every leaderboard and from
  the CDN at once; administrators can hide pictures (`null`).
- **Delivery.** AnimStream copies the TikTok picture to its own CDN as a
  128×128 PNG without metadata. The URL is public and stable: no cookies, no
  `Referer`, no token or tracking parameters. A new picture gets a new URL, so
  cache images by URL. Web clients may load the same path with `.webp`.
- **Validation.** Accept only `https://` URLs on `animstream.b-cdn.net`,
  `animstream.com` or `*.animstream.com` with a path ending in `.png`, at most
  512 characters, without query, fragment, port, credentials or `..`
  (`^https://(?:animstream\.b-cdn\.net|(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*animstream\.com)(?:/[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}){1,8}\.png$`).
  Treat anything else as `null`, never as an error. The official SDKs also accept
  `http://127.0.0.1:<port>/….png`: only the mock Studio sends such URLs.
- **Loading.** Load pictures asynchronously with a short timeout (5 s) and a
  size cap (1 MiB). A missing picture (`null`, 404, timeout, bytes that are not a
  PNG) shows a fallback such as the name's first letter. Never delay gameplay or
  the round-over screen for a picture.

## 9. Packages and helper processes

Packages are ZIP archives of a native export (Windows, macOS or Linux; x64 or
arm64). Action images referenced by the manifest (`media/actions/…`) must be in
every package at that path; verification reads only those files from the ZIP.
Limits: 100 GiB compressed, 100 GiB expanded and 50,000 entries. Standard ZIP and
ZIP64 are supported; no split archives, symlinks, absolute or traversal paths,
duplicate names or encryption. Entries larger than 1 MiB may expand at most
1000:1; stored and deflate are the supported compression methods.

Installing these large packages requires an updated Studio that announces the
`large-packages` catalog capability. Older Studio versions receive the latest
compatible smaller build, when one exists; otherwise Studio must be updated.

**Bundled helper processes are allowed** under these rules. Studio stops the
complete process tree when a session ends (Windows `taskkill /T /F`; macOS and
Linux: the process group).

1. Helpers are native executables inside the same reviewed package (for example
   a `bun build --compile` binary). Nothing is downloaded, unpacked into other
   locations or generated as an executable at runtime.
2. The entrypoint (or one of its children) starts helpers as ordinary child
   processes from the installation directory. They must not detach or escape the
   process tree: no `setsid`/new process groups, no `DETACHED_PROCESS`,
   `CREATE_NEW_PROCESS_GROUP` or `CREATE_BREAKAWAY_FROM_JOB`, no `start`, `open`,
   `nohup`, services, daemons, launch agents, scheduled tasks or autostart entries.
3. Helpers exit when their parent exits and never outlive the session.
4. No elevation (UAC, sudo), no installers, no changes outside the game's own
   files and the user's per-game data directory.
5. Helpers listen only on `127.0.0.1`. At most one process holds the Studio
   protocol connection. The launch token stays in process environments and is
   never written to disk, logs or command lines.
6. Declare each helper (file name and purpose) in the build's review notes.

Verification rejects installer and script launcher formats (`.msi`, `.msix`,
`.appx`, `.pkg`, `.dmg`, `.deb`, `.rpm`, `.bat`, `.cmd`, `.ps1`, `.vbs`, `.wsf`,
`.hta`, `.scr`, `.pif`, `.lnk`, `.reg`, `.command`, `.psm1`, `.vbe`, `.wsh`,
`.msixbundle`, `.appxbundle`, `.mpkg`) and macOS `LaunchAgents`, `LaunchDaemons`,
`LoginItems` and `LaunchServices` folders, and records every additional native
executable for the reviewer.
Administrators reject packages whose helpers violate these rules.

## 10. Security model

This is license enforcement in cooperative game clients, not unbreakable DRM.
Studio trusts authenticated HTTPS catalog metadata and checks the package
SHA-256. The local socket listens on loopback only, accepts one authenticated
peer and rejects browser origins. Games never receive account tokens, download
URLs or the cloud lease secret.

---

## AnimStream mock Studio

A local stand-in for AnimStream Studio. It launches your game the way Studio does
and plays Studio's side of Originals protocol 1 (`PROTOCOL.md`), so you can test a
game without Studio, TikTok, an account or a published build. Every run ends with
a list of PASS, WARN and FAIL checks and an exit code for scripts and CI.

## What it emulates

- **Launch**: the five `ANIMSTREAM_*` variables, Studio's environment allowlist,
  an own process group on macOS and Linux, and ending the whole process tree.
- **Session**: `hello` within 8 s with exactly the documented keys and token,
  `ready` with `features` and `session` (or none with `--legacy`), `ping` every
  2 s with an 8 s pong deadline, lease renewal every 30 s.
- **Action queue**: one action at a time, up to 100 waiting, rule time to live and
  cooldown, stacking of waiting gifts (same rule, viewer and gift, bounded by
  `min`/`max`, overflow becomes another action), `cancel` when Studio gives up an
  action, pause through `state` (queued actions are held up to 60 s and get a fresh
  expiry window on resume).
- **Raw events** for the codes in `manifest.events`.
- **Requests**: `leaderboard.submit`, `leaderboard.top` and `bindings.list` with
  Studio's limits (4 in flight, one submit per 2 s, error codes) and fake data,
  plus `notify` after the gift rules change.
- **Leaderboard pictures** (feature `leaderboard-avatars`): `leaderboard.top`
  entries and `self` carry `avatarUrl`. The mock serves generated 128×128 PNGs
  from its own loopback server (`http://127.0.0.1:<port>/avatars/<name>.png`;
  real Studio sends AnimStream CDN URLs instead). The sample list mixes valid
  pictures, `null` for anonymous entries, a URL that answers 404 and one that
  returns bytes that are not a PNG. Without the feature (`--legacy` or
  `--features` without it) `avatarUrl` is omitted.
- **Strictness**: like Studio, a frame with unknown keys, wrong types, another
  session ID or an unknown message type ends the session.

It also checks that the game never prints the launch token, exits on `stop`, on
heartbeat loss and on lease expiry, and (macOS/Linux) that no process of the
game's process group outlives the game.

It does **not** emulate TikTok, the cloud license, the real leaderboard, Studio
Flows, the Gift Wall or the game control window (DE "Spielsteuerung", EN "Game
control"). Gift rules come from the manifest's `defaultBindings` or from the
scenario. Like Studio, the first gift of a burst is sent at once when nothing is
queued and later gifts merge while it runs; real TikTok streak timing varies.
Studio discards a game's stdout and stderr; the mock prints them for debugging.

## Install

Node.js 20 or newer. Install the one dependency (`ws`) once:

```sh
npm ci --prefix tools/mock-studio
```

`validate` and `scenarios` work without it.

## Quick start

```sh
# Check the manifest (exit 0 valid, 2 invalid) and read the advice
node tools/mock-studio/mock-studio.mjs validate manifest.json

# Godot 4 project in the current folder; "godot" is the editor binary on PATH
# or its full path. --headless runs without a window.
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json -- godot --path .
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json -- godot --headless --path .

# Exported builds (what Studio launches)
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json -- build/linux/MyGame.x86_64
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json -- build/windows/MyGame.exe
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json -- build/macos/MyGame.app/Contents/MacOS/MyGame
```

Keep a `.gdignore` file in `tools/` (this folder ships one) so Godot neither
imports nor exports the tool and its `node_modules`.

Unity: run the exported player executable (Windows `MyGame.exe`, macOS
`MyGame.app/Contents/MacOS/MyGame`, Linux `MyGame.x86_64`). Unreal: run the
packaged game process, for example `MyGame/Binaries/Win64/MyGame-Win64-Shipping.exe`,
not the bootstrap launcher in the package root, or the project from the editor
binaries without packaging:

```sh
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json -- "C:/Program Files/Epic Games/UE_5.4/Engine/Binaries/Win64/UnrealEditor.exe" "C:/Games/MyGame/MyGame.uproject" -game -windowed -log
```

`-game` starts the game without the editor UI; the first start compiles shaders
(raise `--connect-timeout`). The Unreal template shortens its rounds with
`-LobbySeconds=2 -RoundSeconds=10 -BreakSeconds=2` for the `leaderboard`
scenario.

## Commands

```text
node mock-studio.mjs validate <manifest.json>
node mock-studio.mjs run --manifest <manifest.json> [options] -- <game executable> [game args...]
node mock-studio.mjs scenarios
node mock-studio.mjs help
```

| Option | Meaning |
|--------|---------|
| `--scenario <name\|file>` | Built-in scenario (default `smoke`) or a JSON scenario file. |
| `--legacy` | Behave like Studio 0.1.285 and older: no `features`, no `session`, base manifest without `stackable`, `defaultBindings`, `presets`, action `image`, `leaderboard`, `giftWall` and action `effect`, no `action.source`, no stacking, and a `state` or `request` frame ends the session. |
| `--features <list>` | Comma-separated subset of `source,stack,state,leaderboard,bindings,leaderboard-avatars` (default: all). |
| `--language <de\|en>` | `ready.session.language` (default `en`). |
| `--streamer-handle <name>` | `ready.session.streamerHandle`, as if the streamer agreed to share it. Default: not shared. |
| `--leaderboard-offline` | Leaderboard requests fail with `unavailable` (offline or signed out). |
| `--ttl <ms>` | Time to live of gift rules, 1000–10000 (default 3000, Studio's default). |
| `--cooldown <ms>` | Cooldown of gift rules, 0–60000 (default 1000, Studio's default). |
| `--connect-timeout <s>` | Seconds to wait for the game's connection (default 60). |
| `--cwd <dir>` | Working directory of the game. Default: for an executable path without arguments its own folder (like Studio); otherwise the current directory, so `godot --path .` works. |
| `--env NAME=VALUE` | Extra environment variable for development switches, repeatable. Studio never passes such variables, so release behavior stays the default. |
| `--inherit-env` | Pass the whole environment instead of Studio's allowlist. |
| `--interactive` | After the scenario, keep the session open and read commands from stdin. |
| `--report <file.json>` | Write a machine-readable report. |
| `--transcript <file.jsonl>` | Write every frame, one JSON line each, with the launch token redacted. |
| `--quiet` | Do not echo the game's output. |

Exit codes: `0` no failed check (warnings allowed), `1` at least one failed check,
`2` usage, manifest or scenario error.

`validate` also lists the presets with their coin range and checks every local
action image (`media/actions/…` next to the manifest: PNG or WebP with alpha,
square, 256–1024 px, at most 300 KB; generated placeholders are flagged). An
invalid image exits with 1. Its `ADVICE` lines cover the Originals checklist:
missing descriptions or images, descriptions over 120 characters, missing
presets, presets outside the coin tiers (≤ 30, 99–299, ≥ 500) and missing
`defaultBindings` next to presets.

Action effects (extension `action-effects`): every action line shows its
`effect` (`[help]`, `[sabotage]`, `[neutral]` or `[no effect]`), every preset its
balance ("2 help · 2 sabotage") and the `split wall` line how Studio would split
the Gift Wall (`giftWall.split` with its defaults: help left, sabotage right,
neutral below, headers on). An unknown `effect` or a broken `giftWall.split` is a
manifest error naming the path (exit 2). `ADVICE` warns when no action or only
some actions have an `effect` (naming the unclassified ones), when the manifest
has no help or no sabotage action, when a preset has no help or no sabotage
action or one side has more than three times the other, when `giftWall.split` is
set without any classified action, and when actions are classified but
`giftWall` has no `split` (optional, recommended for Originals). The `presets`
scenario prints the balance per preset and, with a split wall, the cells of
each side.

## Built-in scenarios

| Name | What it does |
|------|--------------|
| `smoke` | Dry run of every action with default parameters (expects `simulated`, proving a handler is registered), one real run of every action (expects `completed`), raw robustness frames the game must reject (out-of-range value, unknown parameter, unknown action, expiry more than 15 s ahead), a burst of 20 Roses on the first stackable action, one raw event per `manifest.events` code (a comment contains markup), a repeated action ID, `stop`. |
| `stacking` | For every stackable action: 99 single Roses in a row, one streak event of 99 Roses, and 40 Roses at 3 per gift. Reports the merged counts and checks that no gift is lost. |
| `pause` | Waits until the game accepts actions, then until it reports `acceptingActions: false`, queues an action and checks that Studio holds it and delivers it after the game resumes. |
| `leaderboard` | Waits up to 180 s for `leaderboard.submit` and answers it. Play a round in the meantime or shorten rounds with a development switch. Then waits up to 30 s for an optional `leaderboard.top` and checks that the game keeps its session alive for 5 s with the missing and broken sample pictures; the report lists which pictures the game loaded (`avatarFetches`). |
| `presets` | Shows the manifest presets like Studio's first-start picker (gifts, coins from the mock's gift list, action labels), then applies each preset in turn: its bindings become the gift rules (`notify` for a game that listed bindings, Gift Wall order per `giftWall.sort`) and every gift is sent once; each action must complete. Fails when the manifest has no presets. With `--legacy` it checks `defaultBindings` instead (older Studios receive no presets). |
| `lobby` | Originals checklist: the first reported state must be phase `lobby` with `acceptingActions: true`; an action sent in the lobby must complete (and count in round 1); a non-lobby phase must begin by itself within 20 s (recommended about 15 s) and should accept actions. Notes the score 1.5 s into the round. Needs feature `state`. |
| `heartbeat` | Stops sending pings; the game must exit by itself within 10 s. |
| `lease` | Sends a lease that expires in 2 s and is never renewed; the game must exit. |

Run `smoke` with and without `--legacy`, `stacking`, `pause`, `leaderboard`,
`presets` and `lobby` for every build (the Originals checklist). If the game starts in a
menu with `acceptingActions: false`, queued actions wait up to 60 s like in
Studio; a game that never accepts actions fails.

## Scenario files

A scenario is a JSON object. `scenarios/example.json` uses every step type
against `scenarios/zombie-prank.manifest.json` (the example manifest from
`PROTOCOL.md`).

```json
{
  "name": "my-scenario",
  "settings": { "language": "de", "streamerHandle": "test_streamer", "features": ["source", "stack", "state", "leaderboard", "bindings", "leaderboard-avatars"], "ttlMs": 3000, "cooldownMs": 1000 },
  "rules": [{ "giftName": "Rose", "actionId": "spawn-zombies", "params": { "count": 1 }, "ttlMs": 3000, "cooldownMs": 1000 }],
  "steps": [
    { "type": "waitForState", "phase": "playing", "timeoutMs": 30000 },
    { "type": "gift", "giftName": "Rose", "repeat": 50, "viewer": { "name": "Anna" } },
    { "type": "stop" }
  ]
}
```

`settings` and `rules` are optional; command line options win over `settings`.
Without `rules` the manifest's `defaultBindings` act as gift rules, as if the
streamer accepted the default rules. Every step may have a `label` (shown in the
output) and a `comment`.

| Step | Fields | Behavior |
|------|--------|----------|
| `wait` | `ms` | Pause the scenario. |
| `note` | `text` | Print a line. |
| `waitForState` | `phase?`, `acceptingActions?`, `timeoutMs?` (30000) | Wait for a matching `state` report. Needs feature `state`. |
| `waitForRequest` | `op`, `timeoutMs?` (60000), `optional?` | Wait for the next request with this `op`; fails if Studio had to answer it with an error. With `optional: true` a missing request is only noted, a failed one only warned, and a successful answer is preferred. |
| `action` | `actionId`, `params?`, `dryRun?`, `viewer?`, `source?`, `ttlMs?`, `expect?`, `expectError?`, `async?`, `raw?`, `expiresInMs?` | Send an action like a test button in the game control window (source `HOTKEY`). `expect` is `completed` (default), `simulated` (default for dry runs), `rejected`, `expired` or `any`. `async: true` continues without waiting. `raw: true` skips Studio's validation to test the game's own checks; `expiresInMs` sets its expiry. |
| `gift` | `giftName`, `giftCount?` (1), `repeat?` (1), `intervalMs?` (0), `viewer?`, `rule?`, `expect?`, `expectActions?` | Viewer sends gifts. Each repeat is one gift event with `giftCount` gifts (a streak); every matching gift rule runs, and the raw GIFT event is forwarded if the manifest lists GIFT. `rule` is an inline rule used only by this step. `expectActions` checks how many action frames Studio sent. |
| `event` | `event` (`code`, `user?`, `handle?`, `giftName?`, `giftId?`, `giftCount?`, `giftCoins?`, `comment?`), `expect?` | Forward one raw event. Codes not in `manifest.events` are not sent, as in Studio. |
| `cancel` | | Studio gives up the running action and sends `cancel`. Warns if the game still reports it completed. |
| `bindingsChanged` | `rules?` | Replace the gift rules and send `notify` if the game has listed them. |
| `duplicate` | | Repeat the last action frame with the same ID; the game must not run it twice. |
| `raw` | `frame`, `waitMs?` (500) | Send any frame (`sessionId` is filled in unless given). |
| `stop` | `reason?`, `expectExit?` (true), `withinMs?` (5000) | End the session and check that the game exits by itself. |
| `silence` | `ms?` (10000), `expectExit?` (true) | Stop sending pings; the game must exit. |
| `lease` | `expiresInMs?` (2000), `expectExit?` (true) | Send a lease that is never renewed; the game must exit. |

`stop`, `silence` and `lease` end the session and must be the last step; without
one of them the mock appends `stop`.

## Reading the output

```text
-> action #3 spawn-zombies {"count":99} source=GIFT Rose x99 viewer=Ben
<- action-result #3 completed 41 ms
PASS run spawn-zombies with default parameters - completed after 21 ms
WARN double triggering - the game accepted the raw GIFT event and completed ...
SUMMARY 14 passed, 1 warning, 0 failed
```

`->` is Studio to game, `<-` game to Studio, `..` a note, `[game]` the game's own
output. Fix every FAIL. Read every WARN: it marks behavior that works but is
risky, for example double triggering or requests Studio had to refuse.

The report (`--report`) contains `result`, `mode`, `features`, `checks`, every
sent action with its final parameters, `source` and outcome, events, states,
requests with their answers, the leaderboard pictures the game loaded
(`avatarFetches`: path and HTTP status) and how the game exited. The transcript
(`--transcript`) holds every frame in both directions.

## Interactive mode

With `--interactive` the session stays open after the scenario:

```text
action spawn-zombies count=25
dry invert-controls seconds=10
gift Rose 99 Anna
gift "Finger Heart" 3
event COMMENT user=Anna comment=hello
bindings
state
stop
```

Use it to watch effects in the game window while you trigger them.

## How Studio launches a game

- The reviewed entrypoint runs without arguments, with its own folder as working
  directory and only these environment variables: `PATH`, `SystemRoot`, `WINDIR`,
  `TEMP`, `TMP`, `HOME`, `USERPROFILE`, `APPDATA`, `LOCALAPPDATA`, `LANG`,
  `LC_ALL`, `DISPLAY`, `WAYLAND_DISPLAY`, `XDG_RUNTIME_DIR`,
  `DBUS_SESSION_BUS_ADDRESS`, `LD_LIBRARY_PATH`, `DYLD_LIBRARY_PATH`, plus the
  five `ANIMSTREAM_*` variables.
- stdout and stderr are discarded. Write diagnostics to a log file in the user's
  game data folder, never the launch token.
- Exactly one WebSocket connection is accepted per launch.
- After `stop`, Studio ends the process tree immediately (Windows
  `taskkill /T /F`, macOS and Linux the process group). Do not rely on shutdown
  work after `stop`; save at the end of a round.

## Tests

```sh
npm test --prefix tools/mock-studio
```

The suite starts the real CLI against `test/fake-game.mjs`, a protocol client
with switchable mistakes, and covers handshake, legacy mode, strict frames,
stacking arithmetic, pause, leaderboard limits, heartbeat and lease handling.

[HTML](https://animstream.com/de/developers/games) · [AnimStream Docs Index](https://animstream.com/llms.txt)

