Developers

Character Play SDK

Make games for Character App: fans play them beside a creator's Episodes, on phones, desktop and X. You write the game; the platform draws everything around it.

Full guide as plain text

Everything here is true in play 1.18, the newest minor. Kit play-kit-1.18.1.tgz.

Start

mkdir play-games && cd play-games
npm install https://character.app/_play/kit/play-kit-1.18.1.tgz
npx playwright install chromium webkit
npx play doctor
npx play new game-my-game --genre arcade   # canvas template + the arcade playbook in game-my-game/AGENTS.md
cd game-my-game && npx play dev             # checks play.json in seconds, prints http://127.0.0.1:<port>

play new with no --genre writes the arcade playbook. --template canvas is the default and the one to start from.

The loop: fast first, full check last

  1. play dev after every play.json edit. Seconds. It refuses a bad manifest with the path and the fix.
  2. play shots after every game edit. About 10 seconds. It writes poster, first-input, mid-round and result PNGs for phone, landscape and desktop. Look at them.
  3. play check once, at the end, with nothing else running. About 11 minutes alone on a laptop, 20 to 40 minutes when other checks share the machine. It runs your game in Chromium and WebKit at every size, with an idle bot and a random bot, and writes .play/check.json (findings block, quality warnings do not) and .play/sheet.png.
  4. play pack writes the ZIP you hand to Publishing.

Codex's sandbox cannot start a browser: run new, the static part of check and pack inside it, and dev, shots and the full check outside.

What are you making?

You wantMake it asStart
Catch, dodge, tap, a score that climbsa Play bundleplay new <id> --genre arcade. Playbook: docs/playbooks/arcade.md, example examples/game-fish-dash
A rhythm gamea Play bundle--genre arcade and change the loop: schedule notes on host.clock.frame from the song's time, play the song on host.audio.music, and keep count-in + song + outro under 50 s of play time (all of it counts, PLAY-Q002)
A puzzle, turn or move baseda Play bundle--genre arcade and change the loop: seed each level from run.seed, let idle lose on a move or time limit, store progress at each cleared level with host.save
A game with choices and a scorea Play bundle--template dom. Each ending is an outcome with its own id and title; the idle bot only reads win, won, victory, success as a win and notes other ids as unclassified, so give the ending an idle player reaches the id loss (titled as you like). A choice is a button on your stage; endings found go in a records set. A bundle has no choice nodes (choices and kind: "story" are refused)
A branching story (scenes and choices, no score)the story format tale@1, not a bundleConnect the Character App MCP, call get_publishing_workspace, then get_tale_format and stage_tale_episode. Needs Publishing access and a role on the Story
Levels on a grid, simple scenes, or a simple arcade game, with no codethe JSON game format (levels, scenes or arcade)get_game_format on the Character App MCP returns it with examples
A remix of a house game (slicer, rhythm)not open yetBuild your own on canvas

A finished bundle goes live through Publishing: the "Import a bundle you built" screen, or stage_creator_game then publish_creator_game on the MCP. The creator approves it in Publishing.

What the platform draws, and what you draw

The platform draws every screen and control around your stage: the Front with Play, the mode row, the score chips, pause, sound, Settings, the result card, sharing, the store, prices, Buy, sign-in, and every way out. You draw only your stage: the world, the player, the hazards, feedback.

Never use these (refused by `play check`)

RefusedUseCode
requestAnimationFrame, setTimeout, setInterval; listening for visibilitychange, blur, pagehide, fullscreenchangehost.clock.frame, host.clock.after, host.on('pause' | 'resume'). They stop while the platform pausesPLAY-S106
Math.random, Date.now, crypto.getRandomValues (once "seeded": true)a generator seeded from run.seedPLAY-S112
localStorage, sessionStorage, indexedDB, cacheshost.save (progress, 16 KiB of JSON) and host.records (collections)PLAY-S105
fetch or XMLHttpRequest off your bundle, WebSocket, EventSourcefiles in your bundle, loaded with new URL('./x.png', import.meta.url)PLAY-S103
parent, top, opener, document.body, document.querySelectorelements under the stage you are given, queried from your own rootPLAY-S104
new Audio, new AudioContexthost.audio.context, effects into host.audio.output, songs into host.audio.musicPLAY-S107
eval, Function, Worker, SharedArrayBufferplain ES modules on the stage threadPLAY-S108
location, alert, confirm, prompt, opennothing: the platform owns navigationPLAY-S109
keys Escape, KeyP, KeyM, KeyF in input.actionsother keys; those four are the platform's pause, mute and full screenPLAY-M001

Gotchas (each one cost a tester time)

  1. run.finish({ stats }) takes only ids listed in result. A hud-only id fails the run with PLAY-R001, and the L005, L007, Q001, Q002 after it are echoes.
  2. Keys are KeyboardEvent.code values: ArrowLeft, KeyA, Space, Digit1. Not "a" or "1".
  3. A bundle is always "kind": "game", with an id starting game-, "x": { "card": false }, "verifier": { "kind": "none" } and no ranked mode.
  4. A bundle cannot award an earn: earns need a registered verifier, and only house games have one. A prize is stars (scoring.stars), a verdict, and optionally a records set kept on the fan's device. See docs/concepts/scoring-and-prizes.md.
  5. run.variant can be null. Never build an id from it.
  6. hud shows the first 3 stats that have a value, although hud may list 4.
  7. Idle must lose: the checker's idle bot must not win or reach the clock cap (PLAY-Q001), and must not earn a star (PLAY-Q011).
  8. Accept the first input within 3 s of Play (PLAY-Q003) and change pixels within 150 ms of a press (PLAY-Q004). Focus your canvas on start.
  9. Keep a round under 50 s of play time, counting any count-in and outro (PLAY-Q002, a warning).
  10. Settings rows are toggle or choice (2 to 6 options of up to 16 characters), at most 6. Difficulty goes here, never in a screen before play.
  11. The pad: "pad": true on up to 3 actions draws 64 px buttons over the foot of your stage. viewport.safe does not count them, so keep 80 / viewport.scale stage px clear above safe.bottom while the pad shows.
  12. Map pointer positions through canvas.getBoundingClientRect(): the stage is scaled. Touch targets are at least 44 CSS px (32 with a mouse); divide by viewport.scale for stage px.
  13. The end of a round (1.18): call run.finish(result, { linger: true }), play your closing moment on host.clock, then run.showResult() within 3000 ms (PLAY-Q028 if the card has to rise without it). When the card rises the platform hides your stage and shows your cover under it; nothing you draw after that is seen. See docs/concepts/run-and-end.md.
  14. A locked level (variants[].unlock) can be declared, but a creator cannot sell one yet: its files ship to every viewer. Only wearables are sellable.
  15. play dev listens on 127.0.0.1 only, on a new port each time; use the origin it prints. Use 127.0.0.1, not localhost.

Boundaries

The members you will use

export function mount(stage, host) { // game.js's one export, called after the Play tap
  /* build under stage */ host.ready() // once, within 3 s, when your first frame is drawn; a 15 s stall fails PLAY-L001
  return () => {}                    // cleanup: remove DOM, listeners and audio; a remount must start fresh
}
host.on('start', run => {})          // every run: reset, seed from run.seed, read settings, focus
host.clock.frame((dt, now) => {})    // your loop; stops while paused
host.clock.after(ms, fn)             // play-time timer; holds across pauses
host.hud.set({ score: 0 })           // the platform's score chips
host.input.actions((id, down) => {}) // declared keys and pad buttons
host.input.pad.show(viewport.pointer === 'coarse')
host.settings.get('speed')           // a declared setting's value
host.audio.output / host.audio.music // effects / songs
host.save.store(data) / run.resume   // progress and Continue
host.records.add('endings', 'truth') // a collection kept on the device
host.store.worn / host.on('worn')    // the wearable she has on
run.finish({ outcome, verdict, score, stats }, { linger: true }) // once; stats from `result` only
host.on('resultArea', area => {})   // 1.18: where the card will rest (area.safe)
run.showResult()                     // 1.18: your closing moment is done; the card rises
host.report(error)                   // errors; play goes on

Full types: kit.d.ts and types/. Your ids: play.gen.d.ts (regenerated by play new and play check).

The bundle: play.json at the root, one ES module entry, relative imports, lowercase file names. At most 400 files, 32 MiB, and 1.5 MiB gzipped for the first load (lazy-import the rest). A cover of at least 1200 px on its short side and at most 500 KiB, untitled (titled: false). Details: docs/concepts/manifest.md.

Pages

Paths are inside the kit: node_modules/@charactr/play/ in your project.

Web copies: this page at https://character.app/_play/kit/AGENTS.md, each page at https://character.app/_play/kit/docs/<page>.md, and everything in one file at https://character.app/_play/kit/llms-full.txt.

What the platform draws, and what you draw

Every Play game shares one platform shell. A fan who learns a control in one game finds it in the same place, doing the same thing, in every other game, Episode and story.

The three layers

  1. Set in stone (platform-owned): the top bar, sheets, sign-in, money, navigation and keys. A game cannot restyle, cover or redraw them.
  2. Platform-drawn, game-filled: the Front, mode row, HUD chips, Settings rows, Store, result card and share copy. You declare them in play.json; the shell draws them.
  3. The game's own: everything inside your stage element and within viewport.safe — your world, gameplay, effects, sound and stage controls.

The bar (one meaning per slot)

SlotOutside a round (Front, result, lobby)PlayingPaused
LeftThe world (picture + name → Home; Character App mark beside it on Front)Empty (game owns the screen)The world
R1 (outer right)YouPauseResume
R2SoundSoundSound
R3ShareNoneNone
R4 (wide screens)FullscreenNoneFullscreen

While paused, the account lives inside the pause menu ("You" opens as a step and Back returns to Pause). Only Resume resumes the round. Draw nothing in the bar strip above viewport.safe.top.

What the platform draws (never draw these)

Surface or controlWho owns itEnforced by
Top bar (world, You, Pause/Resume, Sound, Share, Fullscreen)Platform; keep clear of viewport.safe.topPLAY-V002 (safe area)
Front, pause/More, Settings, Leaderboard, result/All stats, sharePlatform (calm card from play.json)PLAY-Q022 (dialogs, h2, button overlays while playing)
Score and timer chipsPlatform (stats + hud + host.hud.set)not checked
Shell keys: Escape, KeyP, KeyM, KeyF (plus R on pause, Enter on result)PlatformPLAY-M001 (manifest), PLAY-Q020 (swallowed Escape/P/M/F); R/Enter not checked
Navigation: home, Episodes, profile, Back, links outPlatform (from episodes and the page)PLAY-S104, PLAY-S109 (blocking); PLAY-Q024, PLAY-Q017 (warnings)
Sign-in, account status, save-status linePlatformPLAY-S105 (storage, blocking); PLAY-Q026 (sign-in copy/inputs, warning); save-status copy not checked
Store, Buy sheet, checkout, coins and pricesPlatform (store, unlocks, host.store)PLAY-Q025 (prices), PLAY-Q027 (store/payment, warnings); PLAY-R013 (store.open during play)
Clock, pause/resume, audio construction and networkPlatform (host.clock, host.audio, bundle files)PLAY-S103, PLAY-S106, PLAY-S107, PLAY-S108, PLAY-L004, PLAY-L008
End of a round (the result card, your cover under it)Platform (see below)PLAY-L005, PLAY-R001, PLAY-R002, PLAY-R003; PLAY-Q028 (a linger that hits its ceiling, warning)

Money: the never-list

The server decides what a fan owns, her coin balance, every price, membership and media access — never the browser or game code.

What you supply

Game, story or Episode?

Pick the format that fits what you are making before writing any code.

FormatBest forEntry point
Play bundle (play@1)Custom interactive games (arcade, rhythm, puzzle, action, choice game with a score)play new <id> (kit play-kit-1.18.1.tgz)
Story Episode (tale@1)Branching picture and sound stories with choices and endings (no score)Character App MCP (get_tale_format, stage_tale_episode)
JSON game (character-game-v1)No-code grid puzzles, simple branching scenes, or tiny 160×120 arcade gamesCharacter App MCP (get_game_format, stage_creator_game)
House-game remix (engine pack)Reskinning a house engine (slicer, rhythm) with art, copy and tuningNot open yet; build on --template canvas

Play bundle (`play@1`, up to 1.18)

A ZIP with play.json, an ES module exporting mount(stage, host) and local assets. Bundle mode enforces (PLAY-M001):

Story Episode (`tale@1`)

Interactive branching Episodes played inside the Episode player with pictures, captions, voice, cues, flags and shareable choice splits.

JSON game (`character-game-v1`)

Data-only games hosted by first-party platform code (no custom JS). Call get_game_format on the Character App MCP for the strict schema and examples. Overall limits: ≤24 KiB JSON, up to 8 games per Story. Pick exactly one shape:

House-game remix (not open yet)

The engine registry on main is empty, so no engine pack id can be staged by creators yet. Start from play new <id> --template canvas instead.

Manifest and bundle files

Put play.json at the ZIP root beside an ES module entry exporting mount(stage, host) and declared relative assets. Every object in play.json is closed (unknown keys fail PLAY-M001), and text fields must be nonempty without a URL.

Bundle rules and refusals (`PLAY-M001`)

File names, assets and budgets (`PLAY-S001`–`PLAY-S010`, `PLAY-S102`–`S103`)

Attribution, Episodes, sharing and telemetry (`PLAY-M001`)

Expanded field shapes (`PLAY-M001`)

`setting` (up to 6, 1.17)

{ id, label (≤24), note? (≤60), kind: "toggle", default: boolean } or { ..., kind: "choice", options: [{ id, label (≤16) }] (2–6), default: optionId }. No audience or board words.

{ "id": "speed", "label": "Speed", "note": "Next run.", "kind": "choice",
  "options": [{ "id": "calm", "label": "Calm" }, { "id": "fast", "label": "Fast" }], "default": "calm" }

`idKey` (keys inside `input.actions[].keys`)

A KeyboardEvent.code string matching /^[A-Z][A-Za-z0-9]{1,19}$/. Never Escape, KeyP, KeyM or KeyF.

{ "id": "jump", "label": "Jump", "keys": ["Space", "ArrowUp", "KeyW"], "pad": true }

`cell` (sprite-sheet crop on wearable `still`, 1.17)

Four integers [x, y, w, h] with x, y >= 0 and w, h >= 1, in pixels inside still (must fit image bounds).

{ "id": "gold", "title": "Gold Cat", "wear": true, "still": "art/sheet.png", "cell": [0, 0, 256, 320] }

`earn` (up to 16, 1.10+ — registered house verifiers only, refused in bundles)

{ id, kind: "keepsake" | "achievement", title (≤40), line (≤90), art? (required for keepsake), wear?, wearLabel?, moves?, type?, still?, cell?, layer?, section?, when: { variant?, score?, outcome?, stats?: { [statId]: { min?, max? } } } }.

{ "id": "crown", "kind": "keepsake", "wear": true, "title": "Crown", "line": "Hit 500.",
  "art": "art/crown.png", "when": { "variant": "ranked", "score": 500 } }

Publishing

Run play pack to build .play/<id>.zip and print bundle_sha. Bind the show in Studio Publishing (or stage_creator_game on the Publishing MCP), play the preview, and approve that exact bundle_sha.

Mount, run and end

Every Play experience exports mount(stage, host) and follows one lifecycle so pause, remount, saves and result cards work cleanly.

Mount, ready and cleanup (`PLAY-L001`, `PLAY-L002`, `PLAY-L003`, `PLAY-L006`)

export function mount(stage, host) {
  const canvas = document.createElement('canvas')
  canvas.tabIndex = 0
  stage.append(canvas)
  const offStart = host.on('start', run => {
    reset(run.seed, run.variant ?? 'classic', run.resume)
    canvas.focus({ preventScroll: true })
  })
  host.ready()
  return () => { offStart(); canvas.remove() }
}

Start, seed and variant (`PLAY-Q006`, `PLAY-S112`, `PLAY-L009`, `PLAY-L007`)

Clock and pause (`PLAY-S106`, `PLAY-L004`, `PLAY-R007`)

Finishing a run (`PLAY-R001`, `PLAY-R002`, `PLAY-R003`, `PLAY-L005`)

The end of a round (play 1.18: `linger`, `resultArea`, `showResult`, `PLAY-Q028`)

The new end follows the minor your play.json declares, not the kit you build with.

function end(run, outcome, verdict, score, stats) {
  if (ended) return
  ended = true; endRun = run; endAt = host.clock.now()
  host.input.pad.show(false)
  playEndCue()
  run.finish({ outcome, verdict, score, stats }, { linger: true })
    .then(() => { shown = true }).catch(err => host.report(err))
}
host.clock.frame(() => {   // keeps running during the linger
  if (ended && !shown && !called && host.clock.now() - endAt >= 600) { called = true; endRun.showResult() }
  draw()
})

What a fan sees at the end

Stage, layout and input

Draw only inside the stage element you are given. Never draw exit, home, profile, Episode or save-status controls; the platform draws them.

Scaled stage and size classes (`PLAY-V001`, `PLAY-Q008`)

Safe area, geometry and CSS (`PLAY-V002`, `PLAY-V003`, `PLAY-S110`, `PLAY-Q019`)

let view = host.viewport
host.on('viewport', v => { view = v; host.input.pad.show(v.pointer === 'coarse') })
const padGap = () => (view.pointer === 'coarse' ? 80 : 0) / view.scale
canvas.addEventListener('pointerdown', e => {
  e.preventDefault()
  const r = canvas.getBoundingClientRect()
  const x = (e.clientX - r.left) * (view.width / r.width)
  const y = (e.clientY - r.top) * (view.height / r.height)
  handleTap(x, y, view.safe.bottom + padGap())
})

Actions, pad, stick and press (`PLAY-M001`, `PLAY-Q020`)

"input": { "stick": false, "actions": [
  { "id": "left",  "label": "Left",  "keys": ["ArrowLeft", "KeyA"],  "pad": true },
  { "id": "right", "label": "Right", "keys": ["ArrowRight", "KeyD"], "pad": true }
] }

Stage consumer kit (`fk-*` and `--fk-*`)

Class / tokenWhat it looks likeWhen to use it
.fk-pill + variant52 px (44 px .sm) rounded pill; pair with .tonal, .her, .ours or .soft (bare has no fill)Primary or secondary stage buttons
.fk-chip (+ .tonal)24 px rounded badge on dark glassCompact state tags or labels
.fk-disc (+ .raised)44×44 px circular icon button on glassCompact icon controls
.fk-row (.lead, .tx, .val)≥60 px hairline row with lead slot, copy and tabular valueStage lists, non-wearable pickers
.fk-kv3-column bordered stat strip (small label over tabular b)Compact multi-stat stage strips
.fk-t-<role>Archivo type scale (display, title, heading, label, body, meta, micro, figure)Consistent stage typography
--fk-* tokensTheme-mapped ground, sheet, ink, accent fill, hit size and radii (--fk-ground, --fk-ink, --fk-fill, --fk-hit, --fk-r-*)Custom stage DOM matching the show

Testing on a phone

play dev binds 127.0.0.1 only on a fresh port each run — open the exact 127.0.0.1 origin it prints (localhost is refused). Use play shots to check pp, pl and dt PNGs in ~10 s; X in-app phone sizes are checked in play check (docs/concepts/quality-and-testing.md).

Next (play 1.19): the platform draws more on-stage UI pieces and the safe area covers the touch pad.

Modes, start and settings

One press on the Front plays the first free mode. Declare modes and settings in play.json so the platform draws the mode row and Settings sheet instead of a pre-play menu.

Modes (`variants`, `PLAY-M001`, `PLAY-Q007`)

Start and home (`start`, `PLAY-M001`)

"start": { "label": "Play", "howTo": ["Tap or use Left/Right to catch fish.", "Dodge falling pots."] },
"variants": [
  { "id": "classic", "title": "Classic", "blurb": "40 s timed run" },
  { "id": "rush",    "title": "Rush",    "blurb": "25 s, faster drops" }
]

Settings (`settings`, 1.17, `PLAY-M001`, `PLAY-R001`, `PLAY-Q022`)

"settings": [
  { "id": "speed", "kind": "choice", "label": "Pace", "note": "Applies next run.",
    "options": [{ "id": "calm", "label": "Calm" }, { "id": "quick", "label": "Quick" }], "default": "calm" },
  { "id": "hints", "kind": "toggle", "label": "Show cues", "default": true }
]
let pace = host.settings.get('speed')
let hints = host.settings.get('hints')
host.on('settings', values => { pace = values.speed; hints = values.hints })
host.on('start', run => {
  const mode = run.variant ?? 'classic'
  startRound(mode, pace === 'quick' ? 1.25 : 1, Boolean(hints))
})

Scoring, stats and prizes

Declare scores, chips, result stats, outcomes and verdicts in play.json so the shell draws the HUD and result card consistently.

Scoring (`PLAY-M001`, `PLAY-R003`)

Stats, HUD and result (`PLAY-M001`, `PLAY-R001`, `PLAY-Q007`, `PLAY-Q009`)

"scoring": { "unit": "fish", "order": "desc", "min": 0, "max": 999, "rules": 1,
  "stars": [8, 18, 30], "verifier": { "kind": "none" } },
"stats": [
  { "id": "score", "label": "Fish" },
  { "id": "hits", "label": "Pots", "of": 3 },
  { "id": "best-streak", "label": "Best streak" },
  { "id": "time", "label": "Time", "format": "seconds" }
],
"hud": ["score", "hits"],
"result": ["best-streak", "time"]

Outcomes, verdicts and stars (`PLAY-M001`, `PLAY-R010`, `PLAY-Q001`, `PLAY-Q007`, `PLAY-Q011`)

Prizes in a creator bundle (`PLAY-M001`, `PLAY-R001`)

host.hud.set({ score: caught, hits: pots }, { tone: { hits: pots >= 2 ? 'warn' : null } })
if (caught >= 20) host.records.add('trophies', 'master-angler')
run.finish({
  outcome: pots >= 3 ? 'loss' : 'win',
  verdict: pots >= 3 ? 'bonked' : 'feast',
  score: caught,
  stats: { 'best-streak': bestStreak, time: Math.round(elapsed / 1000) },
}).catch(err => host.report(err))

Store and unlocks (play 1.17 and later)

Declare store and unlocks in play.json so the platform draws the store, rows, Buy handoff and reveal. Never draw a store, price or Buy button (PLAY-Q025, PLAY-Q027).

Declaring the store and unlocks (`PLAY-M001`, `PLAY-S002`)

"store": {
  "title": "Wardrobe", "base": { "title": "Classic", "art": "art/base.png" },
  "figure": { "art": "art/figure.png", "size": [320, 400] },
  "sections": [{ "id": "looks", "title": "Looks" }]
},
"unlocks": [{
  "id": "star-cape", "title": "Star Cape", "type": "Outfit", "line": "A bright cape.",
  "wear": true, "section": "looks", "art": "art/cape-card.png", "layer": "art/cape-layer.png"
}]

Runtime store API (`PLAY-R001`, `PLAY-R013`)

let worn = host.store.worn
host.on('worn', id => { worn = id; draw() })
const hasNightMap = () => host.unlocks.get('night-map')?.state === 'owned'
// The platform draws the store's doors (Front, pause, result). To open it yourself: between rounds only (PLAY-R013 while playing)
host.store.open({ section: 'looks' })

Picture budgets (`PLAY-Q023`) and art without an artist

Locked levels, legacy unlocks and sales (`PLAY-M001`, `PLAY-R011`)

Next (play 1.19): store layouts. Levels locked on the server, so creators can sell them, come later.

Saves, records and sound

Use the host for progress, collections and audio so saves carry across sessions and sound obeys mute, volume sliders and pause.

Saves and Continue (`PLAY-R004`, `PLAY-R005`, `PLAY-R009`, `PLAY-L006`, `PLAY-L010`, `PLAY-Q012`, `PLAY-Q013`)

function loadSave() {
  const raw = host.save.read()
  return raw && raw.v === 1 && Number.isInteger(raw.level) ? raw : { v: 1, level: 1 }
}
function checkpoint(level, variant) {
  host.save.store({ v: 1, level }, { place: 'level-' + level, continue: { variant, step: level } })
}
host.on('pause', why => {
  if (why === 'hidden' || why === 'leaving') checkpoint(currentLevel, currentVariant)
})

Records (`PLAY-R001`)

"records": [{ "id": "trophies", "kind": "set", "label": "Catches", "items": ["gold-koi", "eel"] }]

Sound (`PLAY-S107`, `PLAY-L008`, `PLAY-R012`, `PLAY-Q005`, `PLAY-Q021`)

function beep(freq, dur = 0.08) {
  const ctx = host.audio.context
  if (!ctx || host.audio.state === 'muted') return
  const osc = ctx.createOscillator(), gain = ctx.createGain()
  osc.frequency.value = freq
  gain.gain.setValueAtTime(0.18, ctx.currentTime)
  gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + dur)
  osc.connect(gain).connect(host.audio.output)
  osc.start(); osc.stop(ctx.currentTime + dur)
}
canvas.addEventListener('pointerdown', () => {
  if (host.audio.state === 'locked') void host.audio.request(true)
  beep(520)
})

Quality, checks and testing

Run fast checks while iterating and save the full play check for the end.

Tooling, templates and loop

What `play check` verifies

X windows (`PLAY-Q014`–`Q018`)

Phones open the full page in X's in-app browser (390×664 iPhone, 412×780 Android); desktop uses link cards (564×564, 504×504, registered games only). Read host.surface and host.window (1.14) instead of user-agent strings; fit the stage, honor pause, never draw links out (PLAY-Q017) or debug readouts like fps or 390x664 (PLAY-Q018).

Theme, performance and accessibility

import type { Mount } from '@charactr/play'
import type { Ids } from './play.gen.js'
export const mount: Mount<Ids> = (stage, host) => {
  let calm = host.theme.reducedMotion, compact = host.window.fit === 'window'
  const offTheme = host.on('theme', t => { calm = t.reducedMotion })
  const offWin = host.on('window', w => { compact = w.fit === 'window' })
  host.ready()
  return () => { offTheme(); offWin() }
}

Arcade playbook (play 1.18)

Catch, dodge, tap: one verb, a short round, a score that climbs. Everything on this page is true in play 1.18, the newest minor. A Next line names a coming minor and is never something you can use yet.

The feel

Start here

npm install https://character.app/_play/kit/play-kit-1.18.1.tgz
npx play new game-my-arcade --genre arcade      # canvas template (Starfall) + this page in AGENTS.md
cd game-my-arcade && npx play dev                # validates play.json in seconds and prints http://127.0.0.1:<port>

The manifest for an arcade game

FieldWhat to declareWhy
variants2 or 3 modes: classic (a timed round) and rush (shorter and denser). The first one is free and never lockedThe platform draws the mode row, and Play starts the first mode with one press. Fewer than 2 modes raises PLAY-Q007
statsscore; a lives or misses stat with of: 3; best-streak; time with format: "seconds"of makes the chip read "Pots 1/3"
hud["score", "hits"]The platform draws these as chips in the bar while she plays. It shows the first 3 that have a value, although hud allows 4. Never draw a score on your stage
result["best-streak", "time"]. The score is shown anywayfinish({ stats }) accepts only ids listed in result. A hud-only id there fails the run (PLAY-R001)
outcomeswin and loss. Your own titles go in titleThe idle bot reads these ids: other ids land "unclassified"
verdicts2 to 4 short headlines with a line each (feast, bonked, short)The result card's words. Missing verdicts raise PLAY-Q007
scoringunit, order: "desc", min, max, rules: 1, stars: [a, b, c], verifier: { "kind": "none" }Bundle scores are personal: no ranked mode and no public board (only registered house games rank)
input.actionsleft and right, each with keys and pad: trueKeys are KeyboardEvent.code values: ArrowLeft, KeyA, Space, Digit1. Escape, KeyP, KeyM and KeyF are the platform's pause, mute and full screen, and are refused (PLAY-M001)
settingsUp to 6 rows. Use choice (2 to 6 options of up to 16 chars) or toggleThe platform draws them in Settings. Difficulty and controls go here and are never asked before play
startlabel (up to 24 chars) and howTo (up to 3 lines of up to 80)The Front and the pause sheet's How to play
x{ "card": false }Bundles do not run inside the X card
"input": { "actions": [
  { "id": "left",  "label": "Left",  "keys": ["ArrowLeft", "KeyA"],  "pad": true },
  { "id": "right", "label": "Right", "keys": ["ArrowRight", "KeyD"], "pad": true } ] },
"settings": [ { "id": "speed", "kind": "choice", "label": "Cat speed", "note": "Applies from your next run.",
  "options": [ { "id": "calm", "label": "Calm" }, { "id": "quick", "label": "Quick" } ], "default": "calm" } ]

Prizes

A creator game cannot award an earn. Earns need a registered score verifier, and only house games have one (play dev says "Earned things need a registered verifier"). An arcade prize is three things:

Goods and the store

The round

Start (host.on('start', run => …), every run, Play again included): - Reset all state. - Seed your chance with run.seed. Never use Math.random. PLAY-Q006 warns when no read of the seed is found, and with "seeded": true in play.json, Math.random, Date.now and crypto.getRandomValues are refused (PLAY-S112). - Read settings with host.settings.get(id). - Set the chips with host.hud.set({ score: 0, hits: 0 }). - Show the pad on touch: host.input.pad.show(viewport.pointer === 'coarse'). - Focus your canvas so keys reach it. - Arm the round's end on play time: host.clock.after(ms, end).

The first ten seconds: - The first input must be accepted within 3 s of Play (PLAY-Q003). Paint feedback within 150 ms of a press (PLAY-Q004). - Something worth catching arrives in the first second or two, and the danger ramps slowly. - Teach by playing. howTo holds the words, so draw no tutorial screen.

Pause: do nothing. - host.clock.frame and host.clock.after stop while the platform pauses. - requestAnimationFrame, setTimeout and setInterval are refused (PLAY-S106), so nothing of yours keeps running.

The end: - Call run.finish exactly once, with outcome, verdict, score and only result stats. Catch its promise and pass errors to host.report. - Make sure idle loses: let some hazards fall on the player, or use a miss fuse, or PLAY-Q001 fires. - Keep the round under 50 s of play time, counting any count-in or outro (PLAY-Q002). - The closing moment (1.18): play one end sound, hide the pad, then call run.finish(result, { linger: true }). The card waits and host.clock keeps running, so play a short closing beat (Fish Dash flashes a ring round the cat for 600 ms), then call run.showResult(). Call it within 3000 ms, or the card rises anyway and play check warns PLAY-Q028. A pause or a hidden page ends the linger early; that is fine. - Where the card will rest: host.on('resultArea', area => …) gives area.safe. Compose the closing shot inside the stage minus area.safe, or keep your play shot when the free space is smaller than your subject. viewport.safe never grows for the card, so nothing in your layout needs to move. - What a fan sees: a published bundle runs in its own frame. During the linger she sees your stage; when the card rises, the platform hides your frame and shows your cover art under the card. So design the cover and the closing beat; nothing you draw after the rise is seen. - In play dev and play check the game runs in the same page, so the stage stays visible under the card and host.clock runs until the card rests. The canvas template settles its figure into the free space with resultArea.

Input on touch and keyboard

The three most common mistakes

  1. A hud-only stat in finish. You get PLAY-R001 "The manifest does not declare this id" at finish. The PLAY-L005, PLAY-L007, Q001 and Q002 that follow are only echoes. Send only ids from result.
  2. Timers and chance from the browser. PLAY-S106 (requestAnimationFrame, setTimeout, setInterval, always refused). PLAY-Q006 warns when the seed is never read, and PLAY-S112 refuses Math.random, Date.now and crypto.getRandomValues once you declare "seeded": true. Use host.clock and a generator seeded from run.seed, as in the example.
  3. An idle player who survives. PLAY-Q001, or Q011 when idle earns a star. Aim some hazards at the player, end on loss, and set stars[0] above idle luck.

The loop: 1. Run play dev after each play.json edit (seconds). 2. Run play shots after each game edit (about 10 s). It writes poster, first-input, mid-round and result PNGs for phone, landscape and desktop. 3. Run play check once at the end, alone: about 11 to 13 minutes on a laptop (Fish Dash: 628, 670, 753 and 776 s), 20 to 40 minutes while other checks run.

The warnings an arcade game will see

CodeWhat it meansThe answer
PLAY-Q001The idle player won or reached the clock capAim hazards at the player, or use a miss fuse, and end on loss
PLAY-Q002The round ran past 50 s of play timeShorten the round. A count-in counts
PLAY-Q003 / Q004No accepted input in 3 s; no pixels changed within 150 ms of a pressFocus on start, preventDefault() the press, and paint at once
PLAY-Q005No sound reached host.audio.output in a roundPlay cues for input, hit, miss and the end through host.audio.output
PLAY-Q006No read of run.seed was foundSeed your generator from run.seed
PLAY-Q007Fewer than 2 modes, or no verdicts or statsDeclare them
PLAY-Q011The idle bot earned a star, or the random bot earned threeRaise the stars thresholds

Warnings never block, but a passing check with none is the bar for a playbook example.

What standout means here

The example and its check

examples/game-fish-dash (node_modules/@charactr/play/examples/game-fish-dash in a project) is a 150-line canvas game with: - two modes and four stats, of which two are HUD chips; - win and loss, and three verdicts; - stars, keys and the touch pad; - a choice setting; - "seeded": true, a seeded spawn, idle that loses, and a lingering finish with a 600 ms closing flash.

It has no store: add one from the canvas template. Its cover is the template's Starfall placeholder.

Its last check: on play 1.18 with the lingering end, play check from the kit 1.18.1 source on the production shell, alone on a laptop (Nov 27): passed 26 runs in Chromium and WebKit, 0 findings, 0 warnings in 776 s. The seeded replay matched in both modes in both browsers, so S112 and the replay are exercised, and no PLAY-Q028. On kit 1.17.0 it had passed the same way (628 s, then 753 s once seeded).

Next

Play codes

Generated from CODES in packages/play/src/check/codes.ts (ERROR_CODES blocking findings plus PLAY-Q001–PLAY-Q027 quality warnings).

PLAY-M001

PLAY-M002

PLAY-R001

PLAY-R002

PLAY-R003

PLAY-R004

PLAY-R005

PLAY-R006

PLAY-R007

PLAY-R008

PLAY-L001

PLAY-L002

PLAY-S001

PLAY-S002

PLAY-S003

PLAY-S004

PLAY-S005

PLAY-S006

PLAY-S007

PLAY-S008

PLAY-S009

PLAY-S010

PLAY-S011

PLAY-S012

PLAY-S101

PLAY-S102

PLAY-S103

PLAY-S104

PLAY-S105

PLAY-S106

PLAY-S107

PLAY-S108

PLAY-S109

PLAY-S110

PLAY-S111

PLAY-V001

PLAY-V002

PLAY-V003

PLAY-L003

PLAY-L004

PLAY-L005

PLAY-L006

PLAY-L007

PLAY-L008

PLAY-R009

PLAY-R010

PLAY-R011

PLAY-R012

PLAY-R013

PLAY-S112

PLAY-L009

PLAY-L010

PLAY-C001

PLAY-Q001

PLAY-Q002

PLAY-Q003

PLAY-Q004

PLAY-Q005

PLAY-Q006

PLAY-Q007

PLAY-Q008

PLAY-Q009

PLAY-Q010

PLAY-Q011

PLAY-Q012

PLAY-Q013

PLAY-Q014

PLAY-Q015

PLAY-Q016

PLAY-Q017

PLAY-Q018

PLAY-Q019

PLAY-Q020

PLAY-Q021

PLAY-Q022

PLAY-Q023

PLAY-Q024

PLAY-Q025

PLAY-Q026

PLAY-Q027

PLAY-Q028

Host API reference (`@charactr/play`)

Generated from the emitted types/host.d.ts declarations, comments in packages/play/src/host.ts, arrival minors from packages/play/lock/*.json and packages/play/src/capabilities.ts, and finishStatIds in packages/play/src/manifest.ts.

Finish rule (`finishStatIds`)

`PlayHost`

MemberTypeSinceNotes (from host.ts)
host.playreadonly { … }≤1.3—
host.play.majorreadonly major: 1≤1.3—
host.play.minorreadonly minor: number≤1.3—
host.contentreadonly content: C≤1.3engines only: what the engine's route released for this experience; frozen
host.viewportreadonly viewport: Viewport≤1.3—
host.themereadonly theme: Theme≤1.3—
host.surfacereadonly surface: HostSurface1.141.14; surface is fixed, 'window' fires on a change
host.windowreadonly window: HostWindow1.141.14; surface is fixed, 'window' fires on a change
host.readyready(): void≤1.3your first frame is drawn; the Poster lifts. Exactly once
host.requestPauserequestPause(): void≤1.3ask for a pause (a lost GL context); answered by 'pause'
host.requestStartrequestStart(options: { variant: I["variant"]; step?: number; }): void≤1.3 (widened 1.5)—
host.on('lobby', …)on(e: "lobby", fn: (selection: { variant: I["variant"] | null; locked: boolean; focus?: I["unlock"]; }) => void): Off≤1.3 (widened 1.7)—
host.on('start', …)on(e: "start", fn: (run: Run<I>) => void): Off≤1.3—
host.on('pause', …)on(e: "pause", fn: (why: PauseReason) => void): Off≤1.3—
host.on('resume', …)on(e: "resume", fn: () => void): Off≤1.3—
host.on('viewport', …)on(e: "viewport", fn: (v: Viewport) => void): Off≤1.3—
host.on('window', …)on(e: "window", fn: (w: HostWindow) => void): Off1.141.14
host.on('theme', …)on(e: "theme", fn: (t: Theme) => void): Off≤1.3—
host.on('audio', …)on(e: "audio", fn: (s: AudioState) => void): Off≤1.3—
host.on('unlocks', …)on(e: "unlocks", fn: (all: readonly Unlock<I>[]) => void): Off1.5—
host.on('earned', …)on(e: "earned", fn: (ids: readonly I["earn"][]) => void): Off1.10—
host.on('worn', …)on(e: "worn", fn: (id: I["unlock"] | I["earn"] | I["base"]) => void): Off1.17—
host.on('settings', …)on(e: "settings", fn: (values: Readonly<Record<I["setting"], string | boolean>>) => void): Off1.17—
host.on('resultArea', …)on(e: "resultArea", fn: (area: ResultArea) => void): Off1.18—
host.inputreadonly { … }≤1.3—
host.input.actionsactions(fn: (id: string, down: boolean) => void): Off≤1.3—
host.input.actact(el: HTMLElement, words: { busy: string; fail?: string; }, run: (io: { signal: AbortSignal; }) => Promise<unknown>): Promise<boolean>1.151.15 busy; abort at 10 s
host.input.padreadonly { … }≤1.3—
host.input.pad.showshow(visible: boolean): void≤1.3—
host.input.pad.stickreadonly { … }≤1.3—
host.input.pad.stick.xreadonly x: number≤1.3—
host.input.pad.stick.yreadonly y: number≤1.3—
host.input.pad.cooldowncooldown(id: string, remaining: number, duration: number): void≤1.3—
host.clockreadonly clock: Clock≤1.3—
host.lobbyClockreadonly lobbyClock: Clock1.12Play 1.12. Animates the hero only while the shell's lobby is open and visible.
host.audioreadonly audio: Audio<I>≤1.3—
host.hudreadonly { … }≤1.3null clears a chip
host.hud.setset(values: Partial<Record<I["stat"], number | null>>, options?: { readonly tone?: Partial<Record<I["stat"], Tone | null>>; }): void≤1.3 (widened 1.4)—
host.haptichaptic(kind: "tick" | "hit" | "bad"): void≤1.3—
host.choicesreadonly { … }≤1.3—
host.choices.askask(node: I["node"]): void≤1.3a choice is on screen
host.choices.choosechoose(node: I["node"], option: I["option"]): void≤1.3the fan picked
host.recordsreadonly { … }≤1.3a set: "Endings found"
host.records.addadd(record: I["record"], item: I["item"]): void≤1.3—
host.records.hashas(record: I["record"], item: I["item"]): boolean1.4—
host.savereadonly { … }≤1.316 KiB of JSON; null clears
host.save.storestore(data: Json, options?: string | SaveOptions<I>): void≤1.3 (widened 1.4)—
host.save.readread(): Json | null1.4—
host.save.durablereadonly durable: boolean1.4—
host.resultreadonly { … }1.7—
host.result.actionaction(a: { label: string; focus: I["unlock"]; }): void1.7—
host.unlocksreadonly { … }1.5—
host.unlocks.signedInreadonly signedIn: boolean1.7—
host.unlocks.listlist(): readonly Unlock<I>[]1.5Read from mount, in manifest order.
host.unlocks.getget(id: I["unlock"]): Unlock<I>1.5An undeclared id throws PLAY-R001.
host.unlocks.buybuy(id: I["unlock"]): Promise<UnlockState>1.5Home only (PLAY-R011); store first, checkout leaves the page.
host.unlocks.arrivalreadonly arrival: I["unlock"] | null1.5Which unlock this visit came back to wear.
host.earnedreadonly { … }1.10—
host.earned.signedInreadonly signedIn: boolean1.10—
host.earned.listlist(): readonly Earned<I>[]1.10—
host.earned.hashas(id: I["earn"]): boolean1.10An undeclared id throws PLAY-R001.
host.earned.keepkeep(): Promise<boolean>1.111.11. Home only (PLAY-R011): the host's sign-in sheet; true once earns are on her account.
host.earned.arrivalreadonly arrival: I["earn"] | null1.111.11. The earn this home entry came to give (the result card's wear button).
host.storereadonly { … }1.17Play 1.17. Platform store (prices, ownership and counts are the host's) and declared settings rows.
host.store.wornreadonly worn: I["unlock"] | I["earn"] | I["base"]1.17—
host.store.openopen(options?: { section?: I["section"]; item?: I["unlock"] | I["earn"]; note?: string; }): void1.17—
host.store.wearwear(id: I["unlock"] | I["earn"] | I["base"]): boolean1.17—
host.settingsreadonly { … }1.17—
host.settings.getget(id: I["setting"]): string | boolean1.17—
host.tracktrack<K extends keyof T & string>(...args: keyof T[K] extends never ? [ name: K ] : [ name: K, fields?: { readonly [P in keyof T[K]]?: T[K][P]; } ]): void1.161.16
host.reportreport(error: unknown): void≤1.3the error beacon; play goes on
host.failfail(reason: "unsupported" | "broken"): void≤1.3fatal: the platform shows its card and removes you

`Run`

MemberTypeSinceNotes (from host.ts)
run.idreadonly id: string≤1.3minted by the host
run.nreadonly n: number≤1.31 for the first run of this visit
run.variantreadonly variant: I["variant"] | null≤1.3—
run.bestreadonly best: number | null1.4—
run.viareadonly via: Via1.4—
run.stepreadonly step: number | null1.4—
run.armreadonly arm: string≤1.3'off' unless the surface drew a trial arm for this visit
run.seedreadonly seed: number≤1.3uint32: derive all chance from it
run.rankedreadonly ranked: boolean≤1.3a verified result is possible for this run
run.resumereadonly resume: Json | null≤1.3exactly what you last gave save.store, or null
run.arrivalreadonly arrival: string | null≤1.3a place string a link carried here, untouched; first run only; it wins over resume
run.finishfinish(result: Result<I>, options?: FinishOptions): Promise<void>≤1.3 (widened 1.18)—
run.showResultshowResult(): void1.18—

`Result`

MemberTypeSinceNotes (from host.ts)
result.outcomereadonly outcome: I["outcome"]≤1.3—
result.scorereadonly score?: number≤1.3an integer inside scoring.min..max; required when play.json has scoring
result.variantreadonly variant?: I["variant"]≤1.3a personal renderer fallback can finish under its own declared rules
result.verdictreadonly verdict?: I["verdict"]≤1.3which declared headline and line the result card shows
result.statsreadonly stats?: Partial<Record<I["stat"], number | null>>≤1.3 (widened 1.4)The stat ids run.finish({ stats }) accepts: only the ids listed in play.json result (never hud-only ids).
result.starsreadonly stars?: 0 | 1 | 2 | 31.4—
result.toNextStarreadonly toNextStar?: number1.4—
result.nextreadonly next?: { readonly variant: I["variant"]; readonly step?: number; } | { readonly episode: number; }1.4—
result.wornreadonly worn?: I["unlock"] | I["earn"]1.7 (widened 1.10, 1.12)—
result.earnedreadonly earned?: I["earn"][]1.10A hint while the host awaits the verified finish.
result.proofreadonly proof?: Json≤1.3registered verifiers only (the four live games)

`Clock`

LOCAL. Play time: it stops for every pause. play check runs it in real time; a seeded game is also replayed in fixed 1000/60 ms steps.

MemberTypeSinceNotes (from host.ts)
clock.nownow(): number≤1.3ms of play time since mount
clock.frameframe(fn: (dt: number, now: number) => void): Off≤1.3once per display frame while playing; dt in ms, at most 100
clock.afterafter(ms: number, fn: () => void): Off≤1.3once, after ms of play time; holds across pauses

`Audio`

LOCAL. One context and two buses, made by the host inside the Play tap. The fan's Settings level each.

MemberTypeSinceNotes (from host.ts)
audio.statereadonly state: AudioState≤1.3—
audio.contextreadonly context: AudioContext≤1.3—
audio.outputreadonly output: AudioNode≤1.3effects: connect sources here, never to destination
audio.musicreadonly music: AudioNode1.131.13. Songs, beds and declared channels
audio.requestrequest(on: boolean): Promise<AudioState>1.9Play 1.9. From a fan's tap in your stage, request(true) lifts a browser lock; request(false) needs audio.toggle (else PLAY-R012). Resolves to the resulting state (unchanged on refusal or without activation); disposal rejects.
audio.channelchannel(name: I["channel"]): { readonly element: HTMLAudioElement; readonly gain: AudioParam; }≤1.3One blessed media element per channel declared in play.json audio.channels, routed through its own gain.

`Viewport`

STATE. Logical CSS px of the stage element you were given. Mirrored on it as data-size and --play-safe-*.

MemberTypeSinceNotes (from host.ts)
viewport.widthreadonly width: number≤1.3the whole stage box: art may fill all of it
viewport.heightreadonly height: number≤1.3—
viewport.safereadonly safe: Insets≤1.3text and controls stay inside; covers device insets and the platform's control band
viewport.scalereadonly scale: number≤1.30.6 to 1: under 1 when the frame is smaller than your design size
viewport.dprreadonly dpr: number≤1.3device px per logical px, capped at 2 and including scale: size canvases with it
viewport.sizeClassreadonly sizeClass: Exclude<SizeClass, "tiny">≤1.3nothing is mounted in a tiny frame
viewport.orientationreadonly orientation: "portrait" | "landscape" | "square"≤1.3—
viewport.pointerreadonly pointer: "coarse" | "fine"≤1.3—

Supporting types

TypeDefinitionSinceNotes (from host.ts)
Offtype Off = () => void≤1.3—
Jsontype Json = null | boolean | number | string | readonly Json[] | { readonly [key: string]: Json; }≤1.3—
Idsinterface Ids { variant: string; outcome: string; verdict: string; stat: string; record: string; item: string; channel: string; node: string; option: string; unlock: string; earn: string; base: string; section: string; setting: string; }≤1.3Literal ids, generated from play.json into play.gen.d.ts, so a typo fails to compile.
TrackFieldValuetype TrackFieldValue = string | number | boolean1.16—
TrackEventstype TrackEvents = Record<string, Record<string, TrackFieldValue>>1.16—
Mounttype Mount<I extends Ids = Ids, C = unknown, T extends TrackEvents = TrackEvents> = (stage: HTMLElement, host: PlayHost<I, C, T>) => void | Off | Promise<void | Off>≤1.3 (widened 1.16)The required export of an experience. Called once, after the fan's Play tap. Return your cleanup.
PrepareFronttype PrepareFront = (stage: HTMLElement, viewport: Viewport, reducedMotion: boolean, signal: AbortSignal, report: (error: unknown) => void) => void | Promise<void>1.8Play 1.8. Optional direct-game entry export, after the Front paints and before mount.
SizeClasstype SizeClass = "tiny" | "short" | "compact" | "portrait" | "regular"≤1.3—
Insetsinterface Insets { readonly top: number; readonly right: number; readonly bottom: number; readonly left: number; }≤1.3—
ResultAreainterface ResultArea { readonly safe: Insets; }1.18Where the result card will rest, as stage insets: the same shape as viewport.safe, each side >= it.
FinishOptionsinterface FinishOptions { readonly linger?: boolean; }1.18true: the card waits for run.showResult()
HostSurfacetype HostSurface = "page" | "card" | "inapp"1.14Play 1.14. Where the host shows the game: its own page, an X post's card or an in-app browser. Never read the UA.
HostWindowinterface HostWindow { readonly width: number; readonly height: number; readonly fit: "window" | "full"; }1.14STATE. Play 1.14. The whole play window in CSS px. fit is 'window' under 600 px high: keep your chrome compact.
Themeinterface Theme { readonly scheme: "dark" | "light"; readonly ground: string; readonly ink: string; readonly accent: string; readonly reducedMotion: boolean; }≤1.3STATE. The show's look, read-only. Mirrored on the stage as --play-ground, --play-ink, --play-accent.
AudioStatetype AudioState = "locked" | "muted" | "on"≤1.3—
PauseReasontype PauseReason = "fan" | "hidden" | "sheet" | "resize" | "leaving"≤1.3'resize' is deprecated and never sent: a resize arrives as 'viewport'. It leaves the type at play@2.
Tonetype Tone = "warn"1.4—
Viatype Via = "start" | "continue" | "again" | "next" | "challenge"1.4—
UnlockStatetype UnlockState = "owned" | "available" | "pending" | "unavailable"1.5Owned belongs to this account; available is on sale even to a guest. Never wear pending (awaiting confirmation) or unavailable (not sold here).
Unlockinterface Unlock<I extends Ids = Ids> { readonly id: I["unlock"]; readonly state: UnlockState; readonly reason?: "closed" | "not-here"; readonly revoked?: "refunded" | "disputed" | "account"; readonly price: string | null; readonly edition?: { readonly number: number; readonly of: number; } | null; readonly limited?: { readonly of: number; readonly soldOut: boolean; }; }1.5—
Earnedinterface Earned<I extends Ids = Ids> { readonly id: I["earn"]; readonly at: number; readonly verified: true; readonly until?: number; }1.10Play 1.10. A keepsake or achievement confirmed by server replay.
SaveOptionsinterface SaveOptions<I extends Ids = Ids> { readonly place?: string; readonly continue?: { readonly variant?: I["variant"]; readonly step?: number; }; }1.4—
PlayError`interface PlayError extends Error { readonly code: PLAY-${string}; readonly fix: string; readonly doc: string; }`≤1.3What the host throws and rejects with. The class itself lives in errors.ts.

Limits reference

Generated from the exported constants that both the Play SDK checks and the documentation read.

ConstantValueSource
LIMITS.hostMinor18packages/play/src/manifest.ts
LIMITS.idMin2packages/play/src/manifest.ts
LIMITS.idMax48packages/play/src/manifest.ts
LIMITS.title80packages/play/src/manifest.ts
LIMITS.tagline90packages/play/src/manifest.ts
LIMITS.designMin240packages/play/src/manifest.ts
LIMITS.designMax1280packages/play/src/manifest.ts
LIMITS.aspectMin0.4packages/play/src/manifest.ts
LIMITS.aspectMax2.4packages/play/src/manifest.ts
LIMITS.startLabel24packages/play/src/manifest.ts
LIMITS.howToLines3packages/play/src/manifest.ts
LIMITS.howToLine80packages/play/src/manifest.ts
LIMITS.channels8packages/play/src/manifest.ts
LIMITS.variants8packages/play/src/manifest.ts
LIMITS.outcomesMin1packages/play/src/manifest.ts
LIMITS.outcomes24packages/play/src/manifest.ts
LIMITS.outcomeTitle40packages/play/src/manifest.ts
LIMITS.verdicts16packages/play/src/manifest.ts
LIMITS.headline40packages/play/src/manifest.ts
LIMITS.verdictLine90packages/play/src/manifest.ts
LIMITS.stats8packages/play/src/manifest.ts
LIMITS.statLabel16packages/play/src/manifest.ts
LIMITS.hud4packages/play/src/manifest.ts
LIMITS.result8packages/play/src/manifest.ts
LIMITS.nodes24packages/play/src/manifest.ts
LIMITS.optionsMin2packages/play/src/manifest.ts
LIMITS.options6packages/play/src/manifest.ts
LIMITS.optionLabel60packages/play/src/manifest.ts
LIMITS.blurb48packages/play/src/manifest.ts
LIMITS.tip80packages/play/src/manifest.ts
LIMITS.stepNoun16packages/play/src/manifest.ts
LIMITS.stepMax9999packages/play/src/manifest.ts
LIMITS.recordItems64packages/play/src/manifest.ts
LIMITS.itemId48packages/play/src/manifest.ts
LIMITS.unlocks16packages/play/src/manifest.ts
LIMITS.unlockTitle40packages/play/src/manifest.ts
LIMITS.unlockType16packages/play/src/manifest.ts
LIMITS.unlockLine90packages/play/src/manifest.ts
LIMITS.storeSections6packages/play/src/manifest.ts
LIMITS.sectionTitle24packages/play/src/manifest.ts
LIMITS.settings6packages/play/src/manifest.ts
LIMITS.settingLabel24packages/play/src/manifest.ts
LIMITS.settingNote60packages/play/src/manifest.ts
LIMITS.settingOptionLabel16packages/play/src/manifest.ts
LIMITS.records4packages/play/src/manifest.ts
LIMITS.episodes3packages/play/src/manifest.ts
LIMITS.sources64packages/play/src/manifest.ts
LIMITS.sharePost120packages/play/src/manifest.ts
LIMITS.earns16packages/play/src/manifest.ts
LIMITS.earnTitle40packages/play/src/manifest.ts
LIMITS.earnLine90packages/play/src/manifest.ts
LIMITS.moves24packages/play/src/manifest.ts
LIMITS.moveTitle40packages/play/src/manifest.ts
LIMITS.itemMoves4packages/play/src/manifest.ts
LIMITS.telemetryEvents16packages/play/src/manifest.ts
LIMITS.telemetryFields4packages/play/src/manifest.ts
LIMITS.lingerMs3000packages/play/src/manifest.ts
INPUT_LIMITS.actions12packages/play/src/manifest.ts
INPUT_LIMITS.actionLabel16packages/play/src/manifest.ts
INPUT_LIMITS.keys4packages/play/src/manifest.ts
INPUT_LIMITS.pad3packages/play/src/manifest.ts
HUD_SHOWN3packages/play/src/manifest.ts
BUNDLE_LIMITS.zipBytes33554432 (32 MiB)packages/play/src/bundle.ts
BUNDLE_LIMITS.bytes33554432 (32 MiB)packages/play/src/bundle.ts
BUNDLE_LIMITS.files400packages/play/src/bundle.ts
BUNDLE_LIMITS.fileBytes16777216 (16 MiB)packages/play/src/bundle.ts
BUNDLE_LIMITS.ratio200packages/play/src/bundle.ts
BUNDLE_LIMITS.firstLoadGzip1572864 (1.5 MiB)packages/play/src/bundle.ts
BUNDLE_LIMITS.coverBytes512000 (500 KiB)packages/play/src/bundle.ts
BUNDLE_LIMITS.coverShortSide1200 pxpackages/play/src/bundle.ts
BUNDLE_LIMITS.pathMax200packages/play/src/bundle.ts
BUNDLE_LIMITS.depthMax8packages/play/src/bundle.ts
WIRE.message16384 (16 KiB)packages/play/src/wire.ts
WIRE.save24576 (24 KiB)packages/play/src/wire.ts
WIRE.savesPerSecond2packages/play/src/wire.ts
WIRE.recordsPerSecond10packages/play/src/wire.ts
WIRE.buysPerSecond1packages/play/src/wire.ts
WIRE.storeOpensPerSecond1packages/play/src/wire.ts
WIRE.wearsPerSecond4packages/play/src/wire.ts
WIRE.tracksPerSecond2packages/play/src/wire.ts
WIRE.tracksPerRun30packages/play/src/wire.ts
WIRE.tracksPerVisit100packages/play/src/wire.ts
WIRE.trackBytes256 (256 B)packages/play/src/wire.ts
STORE_PICTURE_BUDGETS.spriteSheet400 KiB, max 2048×2048 pxpackages/play/src/check/quality.ts
STORE_PICTURE_BUDGETS.still40 KiB, max 512×640 pxpackages/play/src/check/quality.ts
STORE_PICTURE_BUDGETS.layer80 KiB, max 768×960 pxpackages/play/src/check/quality.ts
STORE_PICTURE_BUDGETS.figure120 KiB, max 768×960 pxpackages/play/src/check/quality.ts
STORE_PICTURE_BUDGETS.totalBytes1572864 (1.5 MiB)packages/play/src/check/quality.ts
MUSIC_BUS_LIMIT_MS8000 ms (8 s)packages/play/src/check/quality.ts
LAYOUT_RULES.touchTarget44 CSS pxpackages/play/src/check/layout.ts
LAYOUT_RULES.mouseTarget32 CSS pxpackages/play/src/check/layout.ts
LAYOUT_RULES.minText11 CSS pxpackages/play/src/check/layout.ts
LAYOUT_RULES.gap8 CSS pxpackages/play/src/check/layout.ts
BOT_RULES.firstInputMs3000 ms (3 s)packages/play/src/check/bots.ts
BOT_RULES.feedbackMs150 mspackages/play/src/check/bots.ts
BOT_RULES.roundMs50000 ms (50 s)packages/play/src/check/bots.ts
BOT_RULES.capMs60000 ms (60 s)packages/play/src/check/bots.ts
BOT_RULES.winOutcomeswin, won, victory, successpackages/play/src/check/bots.ts
BOT_RULES.lossOutcomesloss, lose, lost, defeat, failed, failurepackages/play/src/check/bots.ts
READY_BUDGET_MS3000 ms (3 s)packages/play/src/check/budget.ts
LOAD_STALL_MS15000 ms (15 s)apps/character-app/playables/shell/load.ts
TELEMETRY_ENUM_MIN2packages/play/src/telemetry.ts
TELEMETRY_ENUM_MAX16packages/play/src/telemetry.ts
TELEMETRY_INT_MIN-1000000packages/play/src/telemetry.ts
TELEMETRY_INT_MAX1000000packages/play/src/telemetry.ts
RESERVED_SHELL_KEYSEscape, KeyP, KeyM, KeyFpackages/play/src/check/lifecycle.ts

Manifest reference (`play.json`)

Generated from the emitted PlayManifest declaration (types/manifest.d.ts), LIMITS, INPUT_LIMITS, HUD_SHOWN, BUNDLE_LIMITS, TELEMETRY_*, and BUNDLE_REFUSED. All named shapes (setting, idKey, earn, cell, figureSize, moves, telemetry, choices) are expanded in place by the TypeScript compiler. Hand-written JSON examples live in the linked concept pages.

Bundle and kind refusals (`BUNDLE_REFUSED`)

FieldScopeRuleFix
art.scenebundleBundles use the cover in play 1.4.Remove art.scene.
kindbundleStudio bundles are games.Use kind game.
idbundleCreator ids use the game namespace.Prefix the slug with game-.
x.cardbundleBundles have no X card in play@1.Set x.card to false.
scoring.verifierbundleBundle scores are personal.Set verifier.kind to none.
variants[].rankedbundleBundles cannot declare ranked variants.Omit ranked.
choicesschemaChoices belong to stories.Remove choices from this game.
share.postschemaA post template belongs to games.Remove share.post from this story.

Field index

FieldRequiredBundleExample page
playyesAllowed[concepts/manifest.md](../concepts/manifest.md)
idyesRefused in a bundle (Creator ids use the game namespace.)[concepts/manifest.md](../concepts/manifest.md)
titleyesAllowed[concepts/manifest.md](../concepts/manifest.md)
taglinenoAllowed[concepts/manifest.md](../concepts/manifest.md)
genrenoAllowed[concepts/manifest.md](../concepts/manifest.md)
worldnoAllowed[concepts/manifest.md](../concepts/manifest.md)
seedednoAllowed[concepts/run-and-end.md](../concepts/run-and-end.md)
artyesart.scene refused in a bundle (Bundles use the cover in play 1.4.)[concepts/manifest.md](../concepts/manifest.md)
stageyesAllowed[concepts/stage-and-input.md](../concepts/stage-and-input.md)
xyesx.card refused in a bundle (Bundles have no X card in play@1.)[concepts/quality-and-testing.md](../concepts/quality-and-testing.md)
themenoAllowed[concepts/quality-and-testing.md](../concepts/quality-and-testing.md)
inputnoAllowed[concepts/stage-and-input.md](../concepts/stage-and-input.md)
startnoAllowed[concepts/modes-and-settings.md](../concepts/modes-and-settings.md)
audioyesAllowed[concepts/saves-records-sound.md](../concepts/saves-records-sound.md)
variantsnovariants[].ranked refused in a bundle (Bundles cannot declare ranked variants.)[concepts/modes-and-settings.md](../concepts/modes-and-settings.md)
outcomesyesAllowed[concepts/scoring-and-prizes.md](../concepts/scoring-and-prizes.md)
verdictsnoAllowed[concepts/scoring-and-prizes.md](../concepts/scoring-and-prizes.md)
statsnoAllowed[concepts/scoring-and-prizes.md](../concepts/scoring-and-prizes.md)
hudnoAllowed[concepts/scoring-and-prizes.md](../concepts/scoring-and-prizes.md)
resultnoAllowed[concepts/scoring-and-prizes.md](../concepts/scoring-and-prizes.md)
storenoAllowed[concepts/store-and-unlocks.md](../concepts/store-and-unlocks.md)
settingsnoAllowed[concepts/modes-and-settings.md](../concepts/modes-and-settings.md)
unlocksnoAllowed[concepts/store-and-unlocks.md](../concepts/store-and-unlocks.md)
earnsnoAllowed[concepts/scoring-and-prizes.md](../concepts/scoring-and-prizes.md)
movesnoAllowed[concepts/store-and-unlocks.md](../concepts/store-and-unlocks.md)
recordsnoAllowed[concepts/saves-records-sound.md](../concepts/saves-records-sound.md)
episodesnoAllowed[concepts/manifest.md](../concepts/manifest.md)
sourcesnoAllowed[concepts/manifest.md](../concepts/manifest.md)
sharenoAllowed in a bundle (share.post refused on stories: A post template belongs to games.)[concepts/manifest.md](../concepts/manifest.md)
telemetrynoAllowed[concepts/manifest.md](../concepts/manifest.md)
entryone of entry or engineAllowed[concepts/manifest.md](../concepts/manifest.md)
engineone of entry or engineAllowed[formats.md](../formats.md)
kindyesRefused in a bundle (Studio bundles are games.)[concepts/manifest.md](../concepts/manifest.md)
scoringno (kind: "game" only)scoring.verifier refused in a bundle (Bundle scores are personal.)[concepts/scoring-and-prizes.md](../concepts/scoring-and-prizes.md)
choicesno (kind: "story" only)Refused in a bundle (Choices belong to stories.)[concepts/manifest.md](../concepts/manifest.md)

Field definitions

`play`

play: `1.${number}`

`id`

id: string

`title`

title: string

`tagline`

tagline?: string

`genre`

genre?: string

`world`

world?: string

`seeded`

seeded?: boolean

`art`

art: {
  cover: string;
  scene?: string;
  focus?: readonly [number, number];
  titled?: boolean;
}

`stage`

stage: {
  design: readonly [number, number];
  aspect?: readonly [number, number];
  orientation?: "portrait" | "landscape" | "any";
}

`x`

x: { card: boolean }

`theme`

theme?: { accent: string }

`input`

input?: {
  actions: readonly { id: string; label: string; keys: readonly string[]; pad?: boolean }[];
  stick?: boolean;
}

`start`

start?: {
  mode?: "lobby" | "direct";
  label?: string;
  homeLabel?: string;
  returnHome?: boolean;
  howTo?: readonly string[];
}

`audio`

audio: { essential: boolean; channels: readonly string[]; toggle?: boolean }

`variants`

variants?: readonly {
  id: string;
  title: string;
  ranked?: boolean;
  rules?: number;
  blurb?: string;
  step?: string;
  stars?: readonly [number, number, number];
  previous?: readonly number[];
  episode?: number;
  unlock?: string;
}[]

`outcomes`

outcomes: readonly { id: string; title: string }[]

`verdicts`

verdicts?: readonly { id: string; headline: string; line: string; tip?: string }[]

`stats`

stats?: readonly {
  id: string;
  label: string;
  format?: "label" | "int" | "seconds";
  labels?: readonly string[];
  of?: number;
}[]

`hud`

hud?: readonly string[]

`result`

result?: readonly string[]

`store`

store?: {
  title?: string;
  sale?: string;
  featured?: string;
  base?: { title: string; art: string; id?: string };
  default?: "base" | "earned";
  figure?: { art: string; size: readonly [number, number] };
  sections?: readonly { id: string; title: string }[];
}

`settings`

settings?: readonly (
  | {
      id: string;
      label: string;
      kind: "choice";
      options: readonly { id: string; label: string }[];
      default: string;
      note?: string;
    }
  | { id: string; label: string; kind: "toggle"; default: boolean; note?: string }
)[]

`unlocks`

unlocks?: readonly {
  id: string;
  title: string;
  art?: string;
  moves?: readonly string[];
  veil?: { title: string; art?: string };
  type?: string;
  line?: string;
  wear?: boolean;
  still?: string;
  cell?: readonly [number, number, number, number];
  layer?: string;
  section?: string;
}[]

`earns`

earns?: readonly {
  id: string;
  kind: "keepsake" | "achievement";
  title: string;
  line: string;
  when: {
    variant?: string;
    score?: number;
    outcome?: string;
    stats?: Record<string, { min?: number; max?: number }>;
  };
  wear?: boolean;
  wearLabel?: string;
  art?: string;
  moves?: readonly string[];
  type?: string;
  still?: string;
  cell?: readonly [number, number, number, number];
  layer?: string;
  section?: string;
}[]

`moves`

moves?: readonly { id: string; title: string; art?: string }[]

`records`

records?: readonly { id: string; kind: "set"; label: string; items: readonly string[] }[]

`episodes`

episodes?: readonly { part: number; why: "continue" | "origin" }[]

`sources`

sources?: readonly {
  file: string;
  asset_id: string;
  source_sha256: string;
  source: "studio" | "publishing" | "upload";
}[]

`share`

share?: { post?: string; keepsake?: { id: string; title: string } }

`telemetry`

telemetry?: {
  events: Record<string, Record<string, { type: "enum"; values: readonly string[] } | { type: "int"; min: number; max: number } | { type: "bool" }>>;
}

`entry`

entry?: string

`engine`

engine?: `${string}@${number}`

`kind`

kind: "game" | "story"

`scoring`

scoring?: {
  unit: string;
  order: "asc" | "desc";
  min: number;
  max: number;
  rules: number;
  verifier:
    | { kind: "registered"; id: "loft" | "rhythm" | "court" | "descent" | "keynote" }
    | { kind: "none" };
  stars?: readonly [number, number, number];
  compatible?: readonly { rules: number; max?: number }[];
}

`choices`

choices?: Record<string, { options: readonly { id: string; label: string }[] }>

Play minor history

Generated from PLAY_CAPABILITIES (packages/play/src/capabilities.ts) and diffs across packages/play/lock/1.*.json.

MinorCapabilitiesAdded / widened typesAdded / raised limitsAdded codes
1.3—Baseline lock (95 host types)Baseline lock (41 values)Baseline lock (45 codes)
1.4recordsTone, Via, SaveOptions.place, SaveOptions.continue, SaveOptions.continue.variant, SaveOptions.continue.step, PlayHost.records.has, PlayHost.save.read, PlayHost.save.durable, Run.best, Run.via, Run.step, Result.stars, Result.toNextStar, Result.next, PlayHost.hud.set (widened), PlayHost.save.store (widened), Result.stats (widened)LIMITS.blurb, LIMITS.tip, LIMITS.stepNoun, LIMITS.stepMax, LIMITS.recordItems, LIMITS.itemId, LIMITS.sharePost, WIRE.message, WIRE.save, WIRE.savesPerSecond, WIRE.recordsPerSecond, LIMITS.result (3 → 8)PLAY-L009, PLAY-L010, PLAY-R009, PLAY-R010, PLAY-S112
1.5—Ids.unlock, UnlockState, Unlock.id, Unlock.state, Unlock.price, PlayHost.on:unlocks, PlayHost.unlocks, PlayHost.unlocks.list, PlayHost.unlocks.get, PlayHost.unlocks.buy, PlayHost.unlocks.arrival, PlayHost.requestStart (widened)LIMITS.unlocks, LIMITS.unlockTitle, WIRE.buysPerSecondPLAY-R011
1.6————
1.7storeUnlock.reason, Unlock.revoked, PlayHost.result, PlayHost.result.action, PlayHost.unlocks.signedIn, Result.worn, PlayHost.on:lobby (widened)——
1.8resumeInputPrepareFront——
1.9soundRequestAudio.request—PLAY-R012
1.10earnsIds.earn, Unlock.edition, Unlock.limited, Unlock.limited.of, Unlock.limited.soldOut, Earned.id, Earned.at, Earned.verified, PlayHost.on:earned, PlayHost.earned, PlayHost.earned.signedIn, PlayHost.earned.list, PlayHost.earned.has, Result.earned, Result.worn (widened)LIMITS.earns, LIMITS.earnTitle, LIMITS.earnLine—
1.11keepEarnsEarned.until, PlayHost.earned.keep, PlayHost.earned.arrivalLIMITS.moves, LIMITS.moveTitle, LIMITS.itemMoves—
1.12lobbyClock, unlockEdition, declaredWornPlayHost.lobbyClock, Result.worn (widened)——
1.13musicBusAudio.music——
1.14hostWindowHostSurface, HostWindow.width, HostWindow.height, HostWindow.fit, PlayHost.surface, PlayHost.window, PlayHost.on:window——
1.15pressActPlayHost.input.act——
1.16telemetryTrackFieldValue, TrackEvents, PlayHost.track, Mount (widened)LIMITS.telemetryEvents, LIMITS.telemetryFields, WIRE.tracksPerSecond, WIRE.tracksPerRun, WIRE.tracksPerVisit, WIRE.trackBytes—
1.17storeScreen, statLabels, gameSettingsIds.base, Ids.section, Ids.setting, PlayHost.on:worn, PlayHost.on:settings, PlayHost.store, PlayHost.store.worn, PlayHost.store.open, PlayHost.store.wear, PlayHost.settings, PlayHost.settings.getLIMITS.unlockType, LIMITS.unlockLine, LIMITS.storeSections, LIMITS.sectionTitle, LIMITS.settings, LIMITS.settingLabel, LIMITS.settingNote, LIMITS.settingOptionLabel, WIRE.storeOpensPerSecond, WIRE.wearsPerSecondPLAY-R013
1.18resultAreaResultArea.safe, FinishOptions.linger, PlayHost.on:resultArea, Run.showResult, Run.finish (widened)LIMITS.lingerMs—

Play check checklist

Generated from CODES in packages/play/src/check/codes.ts. Every MUST item is a blocking finding; every SHOULD item is a quality warning.

MUST (blocking findings)

SHOULD (quality warnings)

Working example

{
  "play": "1.18",
  "kind": "game",
  "id": "game-starfall",
  "title": "Starfall",
  "tagline": "Catch the falling stars before they land.",
  "entry": "game.js",
  "art": {
    "cover": "cover.png",
    "focus": [
      0.5,
      0.45
    ],
    "titled": false
  },
  "stage": {
    "design": [
      300,
      400
    ],
    "aspect": [
      0.5625,
      1.0
    ],
    "orientation": "any"
  },
  "x": {
    "card": false
  },
  "start": {
    "label": "Catch stars",
    "howTo": [
      "Tap a star, or press Space or Enter for the lowest one.",
      "A round lasts 30 seconds. Three misses end it early."
    ]
  },
  "audio": {
    "essential": false,
    "channels": []
  },
  "scoring": {
    "unit": "stars",
    "order": "desc",
    "min": 0,
    "max": 9999,
    "rules": 1,
    "stars": [
      5,
      15,
      25
    ],
    "verifier": {
      "kind": "none"
    }
  },
  "outcomes": [
    {
      "id": "stargazer",
      "title": "Stargazer"
    },
    {
      "id": "star-keeper",
      "title": "Star keeper"
    }
  ],
  "verdicts": [
    {
      "id": "steady",
      "headline": "Steady hands.",
      "line": "The sky ran out before you did."
    },
    {
      "id": "missed",
      "headline": "Three got away.",
      "line": "They always fall faster at the end."
    }
  ],
  "stats": [
    {
      "id": "score",
      "label": "Stars"
    },
    {
      "id": "misses",
      "label": "Misses",
      "of": 3
    },
    {
      "id": "best-streak",
      "label": "Best streak"
    },
    {
      "id": "time",
      "label": "Time",
      "format": "seconds"
    }
  ],
  "hud": [
    "score",
    "misses"
  ],
  "result": [
    "best-streak",
    "time"
  ],
  "variants": [
    {
      "id": "classic",
      "title": "Classic",
      "blurb": "30 seconds. Stars speed up as you score."
    },
    {
      "id": "storm",
      "title": "Storm",
      "blurb": "30 seconds. Faster falls from the start."
    },
    {
      "id": "midnight",
      "title": "Midnight",
      "blurb": "Faster stars in a darker sky.",
      "unlock": "midnight-level"
    }
  ],
  "store": {
    "title": "Store",
    "base": {
      "id": "star-base",
      "title": "Stargazer",
      "art": "figure.png"
    },
    "figure": {
      "art": "figure.png",
      "size": [
        480,
        600
      ]
    },
    "sections": [
      {
        "id": "looks",
        "title": "Looks"
      },
      {
        "id": "levels",
        "title": "Levels"
      }
    ]
  },
  "unlocks": [
    {
      "id": "comet-cape",
      "title": "Comet cape",
      "type": "Look",
      "line": "A trailing stardust cape.",
      "wear": true,
      "section": "looks",
      "art": "cape-art.png",
      "layer": "cape.png"
    },
    {
      "id": "moon-hat",
      "title": "Moon hat",
      "type": "Look",
      "line": "A crescent brim for late skies.",
      "wear": true,
      "section": "looks",
      "art": "hat-art.png",
      "layer": "hat.png"
    },
    {
      "id": "midnight-level",
      "title": "Midnight",
      "type": "Level",
      "line": "Faster stars in a darker sky.",
      "section": "levels",
      "art": "level.png"
    }
  ],
  "settings": [
    {
      "id": "trails",
      "kind": "toggle",
      "label": "Star trails",
      "note": "Soft streaks behind falling stars.",
      "default": true
    }
  ],
  "share": {
    "post": "Caught {score} {unit} in {title}. {link}"
  },
  "episodes": []
}
// game.js: Starfall, a complete play@1.18 game. Tap the falling stars, or press Space or Enter for the lowest one.
// A round ends after 30 seconds of play time, or sooner at three misses.
// The platform draws the Front, pause, More, Settings (with Star trails), the Store (Looks + Levels), the result,
// You, share and sign-in from play.json: draw only the stage, never a menu, result, store, exit, sign-in, price or debug text.
// Fans open it from X links in X's in-app browser: keep input inside the stage box, honor pause and read host.window,
// never the user agent. Shelf Cat shows the rest of 1.14.
const ROUND_MS = 30000
const LAYER_FILES = { 'comet-cape': './cape.png', 'moon-hat': './hat.png' }

export function mount(stage, host) {
  const root = document.createElement('div')
  root.className = 'starfall'
  const style = document.createElement('style')           // CSS lives inside the stage, scoped to your root class
  style.textContent = '.starfall,.starfall canvas{display:block;width:100%;height:100%;touch-action:none;user-select:none}'
  const canvas = document.createElement('canvas')
  canvas.tabIndex = 0                                       // focusable, so keys reach the game without listening on document
  canvas.setAttribute('aria-label', 'Starfall: press Space or Enter to catch the lowest star')
  root.append(style, canvas)
  stage.append(root)
  const g = canvas.getContext('2d')
  const offs = []
  let v = host.viewport, run = null, rand = seeded(0), stars = [], spawnIn = 0
  let score = 0, misses = 0, streak = 0, best = 0, startedAt = 0, ended = false, roundOff = null
  let endSafe = null, endAt = 0, shown = false, endRun = null, showCalled = false, easeAt = 0, settled = false
  let worn = host.store.worn                                // 1.17: base id or an owned wearable id
  let trails = host.settings.get('trails')                  // 1.17: declared toggle setting from Settings sheet

  const pictures = new Map()
  const loadPic = (key, file) => {
    const img = new Image()
    img.decoding = 'async'
    img.onload = () => draw()
    img.src = new URL(file, import.meta.url).href
    pictures.set(key, img)
  }
  loadPic('figure', './figure.png')
  for (const [id, file] of Object.entries(LAYER_FILES)) loadPic(id, file)

  const resize = (next) => {                               // fires once on subscribe, then on every change
    v = next
    canvas.width = Math.round(v.width * v.dpr)
    canvas.height = Math.round(v.height * v.dpr)
    draw()
  }
  // Seeded chance: every random number comes from run.seed (mulberry32).
  function seeded(a) { return () => { a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a)
    t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296 } }

  const settle = () => {                                   // jump to final spot if the platform ended the linger early
    if (!showCalled) { settled = true; draw() }
  }
  const begin = (r) => {                                   // every run, including Play again
    run = r; rand = seeded(r.seed); stars = []; spawnIn = 0
    score = 0; misses = 0; streak = 0; best = 0; ended = false; startedAt = host.clock.now()
    endSafe = null; endAt = 0; shown = false; endRun = null; showCalled = false; easeAt = 0; settled = false
    host.hud.set({ score, misses })
    roundOff?.()
    roundOff = host.clock.after(ROUND_MS, end)             // play time: it holds while paused, so the finish is predictable
    canvas.focus({ preventScroll: true })
  }
  const blip = (freq) => {                                 // Web Audio through the host's bus, never to destination
    const ctx = host.audio.context, o = ctx.createOscillator(), a = ctx.createGain()
    o.frequency.value = freq; a.gain.setValueAtTime(0.2, ctx.currentTime)
    a.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15)
    o.connect(a).connect(host.audio.output); o.start(); o.stop(ctx.currentTime + 0.16)
    o.onended = () => { o.disconnect(); a.disconnect() }
  }
  const end = () => {
    if (!run || ended) return
    ended = true
    roundOff?.(); roundOff = null
    const r = run; run = null
    endRun = r; endAt = host.clock.now()
    r.finish({
      outcome: score >= 30 ? 'star-keeper' : 'stargazer',
      verdict: score >= 30 ? 'steady' : 'missed',
      score: Math.min(score, 9999),
      stats: { 'best-streak': best, time: Math.round((host.clock.now() - startedAt) / 1000) },
    }, { linger: true }).then(() => { shown = true; settle() }).catch((e) => host.report(e))
  }

  const step = (dt) => {
    if (!run || ended) return
    spawnIn -= dt
    if (spawnIn <= 0) {                                    // spawn inside the safe rect, clear of the bar strip
      const s = v.safe, x = s.left + 20 + rand() * Math.max(0, v.width - s.left - s.right - 40)
      const boost = run.variant === 'midnight' ? 1.25 : 1
      stars.push({ x, y: s.top + 16, speed: (0.08 + rand() * 0.06 + score * 0.002) * boost })
      const cadence = run.variant === 'midnight' ? 480 : run.variant === 'storm' ? 560 : 700
      spawnIn = cadence - Math.min(400, score * 10)
    }
    for (const st of stars) st.y += st.speed * dt
    const floor = v.height - v.safe.bottom
    const landed = stars.filter((st) => st.y > floor)
    if (landed.length) {
      stars = stars.filter((st) => st.y <= floor)
      misses += landed.length; streak = 0; host.haptic('bad'); blip(140)
      host.hud.set({ misses: Math.min(misses, 3) })
      if (misses >= 3) end()
    }
  }
  const draw = () => {
    g.setTransform(v.dpr, 0, 0, v.dpr, 0, 0)               // draw in logical px
    g.fillStyle = run?.variant === 'midnight' ? '#0b0e24' : host.theme.ground
    g.fillRect(0, 0, v.width, v.height)
    let flash = 0
    if (ended && !showCalled && !settled) {                     // 1.18: 600 ms linger flash; t = 1 calls showResult() once
      const t = Math.min(1, (host.clock.now() - endAt) / 600)
      flash = host.theme.reducedMotion ? 0 : Math.sin(t * Math.PI)
      if (t >= 1) { showCalled = true; easeAt = host.clock.now(); endRun?.showResult() }
    }
    const fig = pictures.get('figure')
    if (fig && fig.complete && fig.naturalWidth) {
      const h = Math.min(110, (v.height - v.safe.top - v.safe.bottom) * 0.32), w = h * (480 / 600)
      const playY = v.height - v.safe.bottom - h
      const top = endSafe ? endSafe.top : v.safe.top
      const freeH = endSafe ? v.height - top - endSafe.bottom : 0
      const targetY = endSafe && freeH >= h ? Math.max(top, v.height - endSafe.bottom - h) : playY
      let fy = playY
      if (ended && settled) fy = targetY
      else if (ended && showCalled) {
        const u = host.theme.reducedMotion ? 1 : Math.min(1, (host.clock.now() - easeAt) / 400)
        fy = playY + (targetY - playY) * (1 - (1 - u) ** 3)
        if (u >= 1) settled = true
      }
      const fx = (v.width - w) / 2
      if (flash > 0) {
        g.save(); g.globalAlpha = flash * 0.45; g.fillStyle = host.theme.accent
        g.beginPath(); g.arc(fx + w / 2, fy + h / 2, h * 0.65, 0, Math.PI * 2); g.fill(); g.restore()
      }
      g.drawImage(fig, fx, fy, w, h)
      const layer = pictures.get(worn)
      if (layer && layer.complete && layer.naturalWidth) g.drawImage(layer, fx, fy, w, h)
    }
    for (const st of stars) {
      if (trails) {
        g.save(); g.globalAlpha = 0.28; g.strokeStyle = host.theme.accent; g.lineWidth = 6; g.lineCap = 'round'
        g.beginPath(); g.moveTo(st.x, st.y); g.lineTo(st.x, st.y - 26); g.stroke(); g.restore()
      }
      g.fillStyle = host.theme.accent
      g.beginPath(); g.arc(st.x, st.y, 14, 0, Math.PI * 2); g.fill()
    }
  }
  const caught = (index) => {
    stars.splice(index, 1); score++; streak++; best = Math.max(best, streak)
    host.hud.set({ score }); host.haptic('tick'); blip(660 + streak * 20)
  }
  const tap = (e) => {
    if (!run || ended) return
    const r = canvas.getBoundingClientRect()               // the stage may be scaled: map through the rect
    const x = (e.clientX - r.left) * v.width / r.width, y = (e.clientY - r.top) * v.height / r.height
    // Hit sizes are CSS pixels after scaling: a 44 px touch target is a 22 px radius divided by the scale.
    const reach = Math.max(32, (v.pointer === 'coarse' ? 22 : 16) / v.scale)
    const hit = stars.findIndex((st) => Math.hypot(st.x - x, st.y - y) < reach)
    if (hit >= 0) caught(hit)
  }
  const key = (e) => {
    if (!run || ended || (e.key !== ' ' && e.key !== 'Enter')) return
    e.preventDefault()
    if (!stars.length) return
    caught(stars.reduce((low, st, i) => st.y > stars[low].y ? i : low, 0))   // the lowest star
  }

  canvas.addEventListener('pointerdown', tap)
  canvas.addEventListener('keydown', key)
  offs.push(host.on('viewport', resize))
  offs.push(host.on('start', begin))
  offs.push(host.on('resultArea', (area) => { endSafe = area.safe; if (shown) { settled = true; draw() } }))
  offs.push(host.on('worn', (id) => { worn = id; draw() }))
  offs.push(host.on('settings', (values) => { trails = values.trails; draw() }))
  offs.push(host.clock.frame((dt) => { step(dt); draw() }))   // runs while playing and until the result rests
  draw()
  host.ready()                                             // first frame is up: the Poster lifts

  return () => {
    offs.forEach((off) => off()); roundOff?.()
    canvas.removeEventListener('pointerdown', tap); canvas.removeEventListener('keydown', key); root.remove()
  }
}