# partii: a game developer's guide

Partii gives a game four things:

- **Online play** that connects through any network: rooms with short codes, a relay that always works, WebRTC when it is faster.
- **Player accounts**: a guest account on first launch, upgradeable to email, Apple, Google, Discord or Steam later.
- **Saves and purchases** that follow the player to every device.
- **A store page** to sell the game, plus **phone controllers** (players scan a QR code and their phone becomes a gamepad).
- **Analytics**: players, sessions, retention, gameplay events and grouped crash reports, on a dashboard at partii.games/dev.

You drive all of it from the `partii` command line. At a terminal it answers in plain words; for agents and scripts (whenever its output is piped or captured) every command prints one JSON document. This guide takes a game from nothing to all of the above.

- Reference: [API.md](API.md) (every operation; generated) and `partii help --json` (every command).
- Wire details: [PROTOCOL.md](PROTOCOL.md) (live rooms) and [CONTROLLER.md](CONTROLLER.md) (phones).
- Lessons from shipping: [Build games on Partii](build/README.md) (netcode patterns, rooms and phone controllers, Steam and Partii accounts, shipping, analytics, the paywall, mobile), written from Tankii.
- A coding agent building a game: start with "Agent quick start" (section 0): its own sign-in, a role on the project, keys and deploys with no one in between. Several agents on one game: [AGENT-TEAMS.md](AGENT-TEAMS.md) (worktrees, merging, shared numbers, test rules, a brief template).

## 0. Get the CLI and an account

```sh
curl -fsSL https://partii.games/install.sh | sh     # macOS, Linux; Windows: irm https://partii.games/install.ps1 | iex
partii login --email you@example.com                # emails a 6-digit code
partii login --email you@example.com --code 123456  # saves the sign-in for every later command
partii whoami
```

New emails get a free developer account. Until Partii trusts the account, a game you publish goes to review first (usually under a day), only free games, and up to 5 projects and 20 games (`partii whoami` shows the limits). Building from source instead: `cargo build -p partii-cli` in `partii/platform`.

Which platform you use:

- **Production** (the default): https://api.partii.games.
- **Local** (everything on your machine): `partii dev up` (leave it running), then `export PARTII_API=http://127.0.0.1:8787`. It prints a ready-made publishable key for a built-in `demo` project, handy for a first multiplayer test; `partii dev key` mints more. Locally, purchases go through a fake store and logins are fake, so nothing needs Stripe or Apple, and you sign up as a developer with `partii login --email you@example.com` (there's no mail locally, so the code comes back in the reply).
- **Staging**: `export PARTII_API=https://api-staging.partii.games` (no email there: `partii login` returns the code).

What the CLI prints:

- **At a terminal**, a short message in plain words: `partii login --email you@example.com` says "We emailed a 6-digit code to you@example.com. Check your inbox (and the spam folder), then run: partii login --email you@example.com --code 123456". Errors are one line and what to do, on stderr. Token values are never printed this way (a masked hint at most); publishable keys are, since they ship in your game.
- **Anywhere else** (pipes, agents, scripts, CI), exactly one JSON document on stdout: `{"ok":true,...}` or `{"ok":false,"error":{"code","message","hint"}}`. Progress for long commands is JSON lines on stderr.
- `--json` forces JSON at a terminal (`--pretty` indents it), `--human` forces words when piped, and `PARTII_OUTPUT=json` or `PARTII_OUTPUT=human` sets either for a whole session. `NO_COLOR` turns colors off. Exit codes are the same either way: 0 ok, 1 error, 2 usage.
- Commands whose point is a secret (`partii tokens create`, `partii login … --print-token`) print JSON at a terminal too, unless you pass `--human`.

`partii login` saves the API and token to `~/.config/partii/cli.json` (`PARTII_CONFIG` moves it; `partii logout` revokes and forgets it). Anything in the environment wins over the saved sign-in:

| Variable | What |
|---|---|
| `PARTII_API` | Platform URL (default `https://api.partii.games`) |
| `PARTII_TOKEN` | Your developer token (CI; `partii login --print-token` shows one) |
| `PARTII_KEY` | A publishable key (games and web pages ship this) |
| `PARTII_PLAYER_TOKEN` | A player's token (for player commands and tests) |

### Agent quick start: a coding agent on a game's team

A coding agent builds a Partii game on its own developer account, never on a person's: it signs up with its own email, is invited to the game's project with a role, and from then on mints keys and deploys itself. Nothing goes through another agent, and no token or key is ever passed in a message.

**1. Sign in** (every command after this uses the saved sign-in; nothing is interactive):

```sh
partii login --email agent-name@example.com                  # emails a 6-digit code (staging and local: the reply has it)
partii login --email agent-name@example.com --code 123456
partii whoami                                                # your developer id and limits
```

**2. Join the project.** Someone with `manage` on it (its owner or an admin) invites the agent's email; the agent accepts:

```sh
partii members invite mystudio --email agent-name@example.com --role builder   # the owner or an admin
partii members invites                                                         # (the agent) open invites
partii members accept inv_...                                                  # (the agent)
partii roles list mystudio                                                     # every role, and in plain words what it can and can't do
```

Which role an agent needs ([the presets](#a-team-roles-on-a-project); a project may define its own):

| Role | Enough for |
|---|---|
| owner | everything, including transferring the project (only the person who made it) |
| admin | keys (`keys create`), publishing, prices, secrets, members and roles, and everything below |
| editor | the store page, patch notes, achievements, theme |
| builder | builds, web deploys, analytics and errors, test purchases: what a building agent needs day to day |
| tester | sees the game, installs unreleased channels |

An agent that also makes its keys and publishes needs admin. A builder asks an admin once for the key (it's publishable, so it can go in the game's source).

**3. Or make the project and game itself** (it is then the owner):

```sh
partii projects put mystudio --name "My Studio"            # project ids: 1-32 lowercase letters and digits
partii games put my-game --field project=mystudio --title "My Game" --platforms '["web"]'   # --project mystudio is the same
```

Game ids are 1-40 lowercase letters, digits and dashes.

**4. Keys.** Keys belong to the project; one per platform you run on (production and staging are separate platforms, so each has its own key):

```sh
partii keys create mystudio --key-id web                                         # key.key = pk_mystudio_web_...
PARTII_API=https://api-staging.partii.games partii keys create mystudio --key-id web
```

A web game ships both and picks by address: [Which key and API a site uses](#which-key-and-api-a-site-uses).

**5. Deploy the site:**

```sh
partii web deploy my-game ./dist                  # add --isolated for threads (SharedArrayBuffer); --spa for client-side routes
partii web deploy my-game ./dist --no-activate    # upload only; then partii web activate my-game <deploy id>
partii web list my-game                           # each deploy's preview_url, review status and which is live
```

A new developer's site goes live at `https://my-game.partii.games` once Partii's review approves the deploy (usually under a day; `partii web list` shows `review.status`). The reply's `preview_url` (`https://<deploy>--my-game.partii.games/`) works at once: test and share that meanwhile.

**6. Staging or production.** Every command talks to production unless `PARTII_API` says otherwise. Staging is a separate platform with its own accounts, projects, keys and sites (`https://my-game-staging.partii.games`); sign in there separately:

```sh
export PARTII_API=https://api-staging.partii.games   # this shell talks to staging
partii login --email agent-name@example.com          # the reply has the code
```

Work on staging, then repeat the same commands without `PARTII_API` for production. Local (`partii dev up`) is the third choice, for tests (section 2, "Test against the real room").

## 1. Project, key, game

```sh
partii projects put mystudio --name "My Studio"   # ids: lowercase letters and digits
partii keys create mystudio --key-id game         # reply: key.key = pk_mystudio_game_...
export PARTII_KEY=pk_mystudio_game_...
partii games put my-game --project mystudio --title "My Game" --platforms '["web"]'
```

When it's ready: `partii games publish my-game`. A new developer's game goes to review (`in_review: true`); `partii games get my-game` shows `review.status` (pending, approved, rejected) and `review.note` (what to fix). Approved, it's on https://partii.games and its site opens at https://my-game.partii.games; until then the site is reachable at its preview address (`partii web list my-game`).

Every create is safe to repeat: `put` updates, and `create` with the same id returns the same key. Add `--dry-run` to any change to see it without making it.

Ids: projects are lowercase letters and digits; games are 1–40 lowercase letters, digits and dashes (`my-game`).

### A team: roles on a project

A project's creator is its owner. Invite others by email with a role; the role covers every game in the project.

```sh
partii members invite mystudio --email sam@example.com --role builder   # they get an email
partii members invites                                                  # (as Sam) open invites
partii members accept inv_...                                           # (as Sam, signed in with that email)
partii members list mystudio
partii members set-role mystudio <developer-id> --role editor
partii members remove mystudio <developer-id>                           # your own id leaves
partii members transfer mystudio --developer <developer-id>             # owner only; you stay as admin
```

The owner is the only built-in role. Until you set your own (below), every project has these presets:

| Role | Can |
|---|---|
| owner | everything, including transferring the project |
| admin | everything else: prices and sales, publishing, keys, secrets, players' purchases, Steam keys, web go-live, members and roles |
| editor | the store page (title, tagline, description, media), patch notes, instructions, achievements, theme, leaderboard settings |
| builder | builds (`--dir`, the launch path), web deploys, analytics and errors, test purchases |
| tester | sees the game; installs unreleased channels in the launcher |

Every preset also has `full_game` (plays free) and `debug_menu`; owner and admin have `publish_official` and `edit_official`, editors `edit_official`. `partii roles list mystudio` shows them, each with what it can and can't do in plain words.

**Testers in the launcher:** builds on any channel other than `stable` (`partii builds upload ... --channel beta`) install only for the team (roles with `view`), and roles with `full_game` install without buying. Sign in to the launcher with your developer account's email; testers start the launcher with `PARTII_LAUNCHER_CHANNEL=beta`. `partii games list` and `partii projects list` show your role on each. The exact tables are in `edge/src/api/roles.ts`.

### Your own roles

Each project defines its own roles: a name, a description, and what the role can do (its capabilities, `caps`). Two kinds of capability:

| Capability | Lets the role |
|---|---|
| `view` | see the project, its games, their unreleased builds and test channels |
| `build` | builds, deploys, analytics, errors and player reports |
| `edit` | the store page, patch notes, instructions, achievements and theme |
| `manage` | members and roles, prices and sales, publishing, keys and secrets |
| `publish_official` | publish official content in the game |
| `edit_official` | edit official content in the game |
| `full_game` | own the project's games on every platform without buying |
| anything else | whatever your game says: Partii stores it and hands it back through `gamesMe` |

`own` (transferring the project) is the owner's alone and is never granted. `build`, `edit` and `manage` need `view`.

Write `roles.json`, highest role first:

```json
{
  "roles": [
    { "name": "admin", "description": "Runs the project", "caps": ["view", "build", "edit", "manage", "publish_official", "edit_official", "full_game", "debug_menu"] },
    { "name": "level-designer", "description": "Builds and ships official levels", "caps": ["view", "edit", "edit_official", "full_game", "level.edit", "place_props"] },
    { "name": "tester", "description": "Plays unreleased builds", "caps": ["view", "full_game", "debug_menu"] }
  ]
}
```

```sh
partii roles list mystudio                                   # the roles, who holds each, and what each can and can't do
partii roles set mystudio --body @roles.json --dry-run       # the diff: roles added, removed, changed, and who it touches
partii roles set mystudio --body @roles.json --field reassign=editor=level-designer,builder=level-designer
partii roles reset mystudio --reassign level-designer=editor # back to the presets
partii members list mystudio                                 # each member's role and caps
partii projects audit mystudio                               # who changed which role or member, when
```

`roles set` replaces every role but the owner. A role someone still holds (a member, or an open invite) goes only with `reassign` (`old=new`, comma-separated, or `{"old": "new"}`); without it the set is refused and nothing changes. Names and capabilities are lower case and start with a letter (`a-z`, `0-9`, `_ . -`, at most 40); `owner` is reserved. At most 50 roles, 100 caps each, 200-character descriptions. A refusal lists every problem at once in `error.problems`.

**Nobody climbs.** Changing roles and members takes `manage`. Nobody adds, changes, removes or hands out a role with a capability they don't have themselves (the owner has them all), and roles with `manage` are the owner's alone to create, change and hand out. Every change goes in the project's audit log (`partii projects audit`).

**Team-only features in your game:** `GET /v1/games/{game}/me` (`gamesMe`, your key plus the player's token, guests included) answers the signed-in player's own team role and its capabilities, Partii's and your game's together: `{"game": "mygame", "role": "level-designer", "capabilities": ["view", "edit", "edit_official", "full_game", "level.edit", "place_props"]}`. The owner has every capability any of your roles names; guests and everyone else get `role: null` and `[]`. With the presets: owners and admins get `view`, `build`, `edit`, `manage`, `publish_official`, `edit_official`, `full_game`, `debug_menu`; editors `view`, `edit`, `edit_official`, `full_game`, `debug_menu`; builders `view`, `build`, `full_game`, `debug_menu`; testers `view`, `full_game`, `debug_menu`. A player is on the team through a test player you made (`partii test players create`) or by signing in with a team member's developer email (several match: the highest role). **Capabilities are for your UI only** (show or hide a debug menu, an "edit official level" button): a player can change their own client, so never trust them on a server, yours or Partii's. Partii checks what each request may do itself.

## 2. Multiplayer in a Rust game

Add `partii-net` from the open-source Partii SDK (<https://github.com/PartiiGames/partii-sdk>; Bevy games: `bevy_partii`). It runs its own threads, and nothing blocks your frame:

```toml
[dependencies]
partii-net = { git = "https://github.com/PartiiGames/partii-sdk" }   # crates.io soon; feature `native` (default) = desktop/mobile
serde_json = "1"                                                      # member/room `meta` is a serde_json::Value
```

(`partii-net` was `partii-engine`; `use partii_net::{Config, Engine, Event}` replaces `use partii_engine::…`.)

For a web (wasm) build use `default-features = false`; the same `Engine` API runs on the browser's event loop.

```rust
use partii_engine::{Config, Engine, Event, BROADCAST};

let engine = Engine::start(Config {
    edge: std::env::var("PARTII_API").unwrap_or("https://<your platform>".into()),
    key: "pk_mystudio_game_...".into(),
    conn: Engine::new_conn_id(),          // fresh per launch
    client: "mygame/1.0".into(),
    player_token: None,                   // or the signed-in player's token
    no_webrtc: false,
});

// Any time, even on the first frame: a create/join made before the engine is
// online is held and sent the moment it connects (Event::Online); if partii
// can't be reached within 10 s it fails with code "offline".
let req: u32 = engine.create("mygame", Some(4), "game", "Alice", serde_json::json!({}));
// or: engine.join("KXQPT", "game", "Bob", serde_json::json!({}));

// Every frame:
for ev in engine.poll() {
    match ev {
        Event::Created { room, .. } => show_code(&room.code),   // 5 capital letters
        Event::Joined { room, .. } => { /* you are room.you; the host is room.host */ }
        Event::Failed { req, code, message } => show_error(&code, &message), // not_found, full, not_joinable, offline, …
        Event::PeerConnected { mid, .. } => { /* member `mid` can receive now */ }
        Event::MemberLeft { mid, .. } => { /* gone */ }
        Event::Message { from, reliable, bytes } => handle(from, reliable, &bytes),
        Event::RoomClosed { reason } => back_to_menu(),          // "host_left", "expired", "kicked", …
        _ => {}
    }
}
engine.send(mid, false, input_bytes);     // unreliable: positions, inputs
engine.send(mid, true, event_bytes);      // reliable and ordered: chat, joins, round results
engine.send(BROADCAST, true, bytes);      // everyone else in the room
```

`create` and `join` return a request id (`u32`); the matching `Created`/`Joined`/`Failed` carries it as `req`. Every event:

| Event | Fields | Meaning |
|---|---|---|
| `Online` | `resumed: bool, relay: String` | The session socket is up (first time or after a drop). |
| `Offline` | – | The socket dropped; the engine is reconnecting (rooms survive short drops). |
| `Created` / `Joined` | `req: u32, room: Room` | You are in the room. |
| `Failed` | `req: u32, code: String, message: String` | A create/join didn't happen. |
| `RateLimited` | `req: u32, retry_after_ms: u64` | Comes just before a `Failed` with code `rate_limited`: Partii is busy on this network; retry after this long. |
| `MemberJoined` | `member: Member` | Someone joined. |
| `MemberUpdated` | `member: Member` | A member changed its own name or meta (`engine.member_update(Some("Sam"), None)`). |
| `MemberLeft` | `mid: u16, reason: String` | Someone left (or their seat grace ran out). |
| `MemberSuspended` / `MemberResumed` | `mid: u16` | A member's connection dropped / came back (seat kept meanwhile). |
| `RoomUpdated` | `room: Room` | Room settings changed (joinable, meta, size). |
| `Resumed` | `room: Room` | A new engine on an old session (a reloaded web page that passed its previous `conn`) is back in its room, same seat. |
| `RoomClosed` | `reason: String` | The room is gone for you. When the host leaves, guests get `host_left`. |
| `PeerConnected` | `mid: u16, path: PathId` | You can send to `mid` now. |
| `PathChanged` | `mid: u16, from, to: PathId, rtt: Option<f64>` | The route to a member changed (ws relay ↔ TURN ↔ direct). Informational. |
| `Message` | `from: u16, reliable: bool, bytes: Vec<u8>` | Data from a member. |
| `Error` | `message: String` | Something to log; the engine recovers by itself. |

`Room { code: String, game: String, host: u16, you: u16, joinable: bool, max_members: u32, meta: Value, members: Vec<Member> }` and `Member { mid: u16, kind: String, name: String, meta: Value, status: String }`. Member ids (`mid`) are small integers, unique within the room; the host is `room.host`.

What the engine does for you:

- **Paths.** A member is reachable the moment you are both in the room (over the relay). The engine moves to WebRTC (TURN, or direct when faster) on its own, and back when a path fails. Your code never sees paths. `engine.stats()` shows them.
- **Reliability.** Reliable messages survive path switches, network changes and short drops (the session resumes). Members who drop briefly keep their seat for 20 s.
- **Network changes.** Phones changing networks, apps backgrounded for a few seconds, and hotel Wi-Fi that only allows port 443 all keep working.

**Away (phones in the background).** iOS freezes a backgrounded app within seconds and its socket drops; past the 20 s grace that is a leave. Rooms can hold such a member longer: an engine that sends `caps: ["away"]` in its hello keeps its seat for the room's `away_grace_ms` (default 30 s, 5 s to 5 min; set on create or `update`) whether it says `{"t":"away"}` as it goes to the background or its socket just drops, and comes back into the same seat with the same `conn`. Opted-in engines hear `member_away {mid, reason: "hint" | "dropped", until, grace_ms}` and `member_back {mid}` instead of `member_suspended` / `member_resumed`; `member_left {reason: "timeout"}` comes only once the grace has run out. The host role never moves: a host that's away is still the host, and a host not back in time closes the room as `host_lost` (reclaimable). Engines that don't opt in see exactly what they did before. Wire details and sequences: [PROTOCOL.md "Away"](PROTOCOL.md#away). On web pages, `sdk/ts/src/away.ts` sends the hint for you and reads every presence event the same way:

```ts
import { AWAY_CAP, watchAway, socketAway, presenceOf } from "./partii/away";   // sdk/ts/src/away.ts
const stop = watchAway(socketAway(ws));    // hidden / pagehide → {"t":"away"}; visible / pageshow → {"t":"back"}
// in your event handler: old and new events alike
const p = presenceOf(frame);               // {mid, state: "away", reason} | {mid, state: "back"} | {mid, state: "left", reason} | null
```

(`partii-net`, the Rust and wasm engine, sends `caps: ["away"]` and maps these to engine events once it supports them; until then the controller page and Rust games keep today's 20 s behaviour.)

Room settings from the start: `engine.create_with("mygame", "game", "Alice", meta, json!({"max_members": 32, "kinds": {"game": {"joinable": false}, "phone": {"max": 16}}}))`. Per-kind rules let a room take phones at any time but games only while you host (`engine.update(json!({"kinds": {"game": {"joinable": true}}}))`); a refused join gets a clean `not_joinable` or `full`. See [PROTOCOL.md](PROTOCOL.md).

If your session drops for longer than the grace window, the room closes. As host, keep `room.reclaim` and create again with `json!({"reclaim": {"code": old_code, "token": reclaim}})` in the settings: within 10 minutes you get the same code back, so the QR on screen still works, and phones that saw `RoomClosed { reason: "host_lost" }` can rejoin it. Watch for the right event on each side: phones and guests see `host_lost`, but **the host's own engine reports `RoomClosed { reason: "expired" }`** when it reconnects after the grace window (the edge has forgotten its session). So as host, reclaim on `expired` (and on `host_lost`, in case you were told while still connected); don't end the room on it.

Members have a `kind` you choose:

- `game`: a full game client.
- `phone`: a phone controller (section 6).

Put anything you need about a member (your own player id, a team) in `meta` when you create or join. Other members see it in `room.members`.

For web pages, the same engine is built for browsers (`scripts/build-engine-web.sh`, which makes `sdk/engine-web`). `new WebEngine(JSON.stringify(config))` has the same methods (`createWith`, `memberUpdate`, `update` and `kick` take JSON strings); `poll()` returns a JSON array.

### Test it without a second person

```sh
partii bot host --menu-ms 0          # creates a room and echoes everything (prints the code)
partii bot guest --code KXQPT        # joins, pings, prints timings and the path used
partii torture run --client engine   # every bad network, in Docker (see docs/DESIGN.md)
```

### Multiplayer facts

What the room does, each with the line that does it. These are the rules your game meets in production, in `partii dev up` and in the SDK's room simulator alike.

- **Frames: 64 KiB of payload.** A relayed binary frame is `[kind][to: u16 BE][payload]` with at most 64 KiB (65,536 bytes) of payload; a bigger one is **dropped without an error** (`edge/src/protocol.ts` `MAX_RELAY_BYTES`; `edge/src/session.ts` `relayOut`: `data.byteLength > MAX_RELAY_BYTES + 3`). Split big state (a world snapshot) into chunks.
- **2000 deliveries a second per session, burst 4000.** One frame to one member is one delivery; a broadcast to 7 others is 7. Past the budget, frames are dropped (counted in your usage as `relay`, never sent back as an error) (`edge/src/protocol.ts` `RELAY_RATE`, `RELAY_BURST`, `Bucket`; `edge/src/session.ts` `relayOut`). A host broadcasting 60 Hz to 31 guests is 1,860 a second: at the edge of the budget. Send less often, or bundle several messages into one frame (`RELAY_BUNDLE`).
- **The relay is in order and lossless, per sender and receiver,** while both sockets are up (`edge/test/protocol.test.ts` "keeps relayed order under a burst"). Frames to a member whose socket is down are dropped, not queued (`edge/src/session.ts` `relay`: no socket, no send); control events (joins, signals) are queued for it, up to 512 (`BUFFER_LIMIT`, `session.ts` `deliver`).
- **Who hears what.** A join is answered to the joiner with the whole room (`ok {room}`: every member so far, itself included); everyone else gets `member_joined` (`edge/src/room.ts` `join`: `tell(…, m.mid)` skips the joiner). `member_left`, `member_suspended`/`member_resumed` (`member_away`/`member_back` with `caps: ["away"]`) and `member_updated` go to everyone else; `room_updated` goes to every member but the host, whose own `update` reply has the room (`room.ts` `update`).
- **When a joiner becomes visible.** The joiner can send to every member the moment its join reply arrives (the reply carries their connections). The others reach it once the edge has told their sessions (`edge/src/session.ts` `deliver`, `member_joined` adds the conn), which is just before their own client sees `member_joined`. A broadcast the host sends in that gap goes to the members its session knew, so a joiner can miss the first frames: have a new member say hello and have the host answer with the full state, rather than relying on a broadcast landing.
- **The host is whoever created the room, and it never moves.** No migration: when the host leaves, the room closes for everyone (`room_closed {reason: "host_left"}`); when its session times out, `host_lost`, with the code held 10 minutes for a reclaim (`edge/src/room.ts` `leave`, `mid === s.host`; `RECLAIM_MS`).
- **A dropped socket keeps its seat for 20 s** (`GRACE_MS`), or the room's away grace with `caps: ["away"]` (30 s default); then `member_left {reason: "timeout"}` (`edge/src/session.ts` `alarm`).
- **The Partii runtime has no WebRTC,** so a game in it relays everything through the edge (the runtime's probe reports `rtcPeerConnection: false`: `partii-runtime harness/probe.js`; docs/APPLE-TV.md "No WebRTC in Servo"). Make the WebSocket relay your game's normal path, and start the engine with `no_webrtc: typeof RTCPeerConnection === "undefined"` so it doesn't wait on a path that can't come.
- **`navigator.hardwareConcurrency` in the runtime is real now:** the machine's cores, less those a software GL's rasterizer needs (at least 2; `PARTII_RUNTIME_CORES=N` sets it). Builds before a4b49a4 said 2 whatever the machine (`partii-runtime src/shell.rs` `software_gl_preferences`). Size worker pools from it, not from a constant.

### Room events: order and shapes

What your game hears, in the order it hears it, and the two traps that cost one game a day each. The engine's events (`poll()`; on the web a JSON array of `{ev: "<snake_case name>", …}`) and the raw protocol's frames (`{t: "<name>", …}`, [PROTOCOL.md](PROTOCOL.md)) use the same names and fields.

**The host, creating:**

1. `online {resumed: false, relay}`: the socket is up.
2. `created {req, room}`: you're in. `room.you === room.host`, `room.members` is just you, `room.code` is the code to show.
3. For each guest, as it joins: `member_joined {member: {mid, kind, name, meta, status, net_version?, player_id?}}` (`player_id` only to the host), then `peer_connected {mid, path}` once you can send to it.
4. Then any of: `message {from, reliable, bytes}`, `member_updated {member}`, `member_suspended {mid}` / `member_resumed {mid}` (`member_away {mid, reason, until, grace_ms}` / `member_back {mid}` with the away grace), `member_left {mid, reason}` (`left`, `kicked`, `timeout`, `version_mismatch`), `path_changed`, `offline` / `online {resumed: true}` (a short drop: the room survives it).

**A guest, joining:**

1. `online`, then `joined {req, room}`: `room.members` is everyone so far, you included (`room.you`); the host is `room.host`. You get **no** `member_joined` for yourself or for anyone already in the room: read them from `room.members`.
2. `peer_connected` for each member, then the same stream as the host's (others joining after you come as `member_joined`).
3. `room_closed {reason}` when it ends for you: `host_left`, `host_lost` (the host's connection timed out; it may reclaim the code), `kicked`, `ended`, `expired`, `timeout`, `version_mismatch`.

A failed create or join is `failed {req, code, message}` (after `rate_limited {req, retry_after_ms}` when Partii is busy). Member and room shapes: the `Room` and `Member` lines above, and PROTOCOL.md "Server to client".

**Trap 1: events before your handlers.** A page is in its room (`created` / `joined`) before it has built its world and set its handlers, often a second or more. A `member_joined` heard in that gap and handed to a no-op handler is gone for good: the guest is in the room, but your game never admits it. Keep polling from the start and hold what you can't handle yet. The SDK does this for you (`sdk/ts/src/room-events.ts`, at partii.games/docs/sdk-ts/room-events.ts):

```ts
import { roomEvents } from "./partii/room-events";          // sdk/ts/src/room-events.ts
const room = roomEvents();
setInterval(() => room.feed(engine.poll()), 4);             // from the first moment; poll()'s JSON as is (or raw protocol frames)
// …once the world is built: everything held so far, oldest first, then new events as they come
room.on({
  member_joined: (e) => admit(e.member),
  member_left: (e) => drop(e.mid),
  message: (e) => onPacket(e.from, new Uint8Array(e.bytes)),
});
room.members;        // the other members right now (mid → member), kept current whether or not a handler is set
room.knows(mid);     // is mid another member of the room?
```

The room, member, message and signal events are held (up to 4,096; past that the oldest message goes first, `room.dropped` counts them); `online`, `offline`, `peer_connected`, `path_changed` and `error` aren't (they're current state, not history). Set related handlers in one `on({...})`: set one by one, a member's held `member_left` would reach its handler before its `member_joined`.

**Trap 2: datagrams from a member you don't know yet.** A joiner can send the moment its `joined` arrives, but the host's engine links a member only when it processes that member's `member_joined`, and the two travel separately (the join reply and the relay versus the room's event). So the joiner's first datagrams can reach the host first, and **the engine drops a datagram from a member it has no link to** (partii-net `on_binary`; the same for a send to a member with no link). Your game's own code may drop more: a host that admits players only through its `member_joined` handler and ignores messages from unknown mids drops every message from a guest whose join it missed (trap 1). The rules that make it work:

- The joiner says hello and keeps repeating it (every 250 ms or so) until the host answers; the host answers a hello with the full state. Never rely on one broadcast landing.
- The host admits a member from `room.members` at `created`/`resumed` and from every `member_joined`, through the backlog above, and treats a message from a mid it doesn't know as a reason to look (`room.knows(mid)`), not to drop the player.

The room simulator (`sdk/ts/src/room-sim.ts`, below) sends the edge's frames in the edge's order, so a unit test can join guests during a slow start and check that none is lost.

### Test against the real room

**Never write your own room shim.** A shim agrees with your game, not with the platform: one game's tests passed against its own loopback room and the first real room failed, because the shim's `member_joined` wasn't the edge's. Use one of these two instead; both are the real protocol.

**In unit tests: the SDK's room simulator** (`sdk/ts/src/room-sim.ts` with `room-protocol.ts`; copy both). It is the edge's Session and Room in your test process, behind a WebSocket-shaped socket, so your game's own socket code runs unchanged and sees the edge's frames byte for byte. Its constants and parsers are generated from `edge/src/protocol.ts`, and `edge/test/room-sim-conformance.test.ts` replays scripted rooms against it and the real edge and compares every frame, so it can't drift.

```ts
import { RoomSim, VirtualClock } from "./partii/room-sim";     // sdk/ts/src/room-sim.ts
const clock = new VirtualClock();                              // or leave it out: real time
const sim = new RoomSim({ clock, latencyMs: 40, jitterMs: 10 });
globalThis.WebSocket = sim.WebSocket as any;                    // your game's connect code, unchanged
// … start a host and three guests the way your game does …
clock.advance(1000);                                            // everything due runs, in order
sim.setNet(guestConn, { relayLoss: 0.05, relayReorder: 0.02 }); // a bad link for one client
sim.drop(guestConn);                                            // its network goes: suspended, then back or left
sim.stats(guestConn);                                           // frames and bytes each way, relay_dropped (budget), relay_refused (> 64 KiB)
sim.close();                                                    // end every socket and timer (lets the test exit)
```

It has the real limits (64 KiB, 2000/s burst 4000), simultaneous joins, the host rule above, the 20 s and away graces, buffered events, kicks, kinds, passwords and `net_version`. The knobs are off by default because the edge's relay neither loses nor reorders; `relayLoss` and `relayReorder` touch relayed frames only, as a WebRTC path would. Not simulated: rate limits per network, open-lobby listings, WebRTC.

**End to end: `partii test room`.** It starts `partii dev up` (or uses a running platform: `--api` with `--key`), opens your game as a host and N guests in headless Chromium, and prints one JSON verdict per client. Non-interactive, headless, with a hard `--timeout`; every child runs in its own process group and is ended on the way out.

```sh
partii test room --guests 3 --secs 30 ./my-game        # a folder: served with the COOP/COEP headers threads need
partii test room --guests 3 --secs 30 http://127.0.0.1:5173/
partii test room --guests 4 --secs 20                   # no game: the room alone, with engine clients
```

Each page gets a query telling it where the room is and what to do: by default the host's URL gets `partii_api=<edge>&partii_key=<key>&partii_room=new` and each guest's `partii_room=<CODE>` (and `partii_test=host` / `guest<i>`). If your game reads other names, say so: `--host-query 'edge={api}&key={key}&room=new' --guest-query 'edge={api}&key={key}&room={code}'` (`{api}`, `{key}`, `{code}`, `{i}` are filled in). The room code is read from the host page's own room socket, so nothing else is needed.

**`window.__partiiTestReport`** is how your game says it's in step. Set it to a function (or an object) that returns JSON; it is read every second and the last answer goes into the client's verdict as `report`. `synced` is the one field the verdict uses: `false` fails the run.

```js
window.__partiiTestReport = () => ({
  synced: worldHash === hostHash && Date.now() - lastSnapshotAt < 2000,   // your rule
  room: roomCode,      // optional: the code, if the host page's socket isn't the edge's
  players: players.size, step: tick, mismatches,                          // anything else you want to see
});
```

A client's verdict: `joined`, `mid`, `players_seen` (from the room socket: the room view and `member_joined`/`member_left`), `synced` (from your report, or null without one), `report`, `msgs_in`/`msgs_out` (relayed binary frames), `bytes_in`/`bytes_out`, `down_kbps`/`up_kbps`, and `errors` (uncaught page errors, which fail the run, and `console.error` lines). The run passes (`ok: true`, exit 0) when every client joined, sees all `N + 1` players and none says `synced: false`; otherwise `ok: false`, exit 1, and `error.message` lists each reason. Browser runs need Playwright where Node can find it (the game's folder, `PARTII_PLAYWRIGHT`, or `platform/apps/store`). The fixture game in `crates/partii-cli/tests/fixtures/room-game/index.html` is the smallest page that passes.

### Open lobbies (matchmaking)

Players can find a room without being sent its code: a host **lists** its room, your game shows a **server browser** of the game's open lobbies, and a **Quick Play** button joins the best one. Nothing new on the wire: a room lists itself through its `meta`, so any `partii-net` build can do it.

**List a room.** Put `listing` in the room's meta when you create it, or later with `update`:

```jsonc
"meta": {
  "listing": {
    "visibility": "public",            // or "friends": only the host's friends see it (needs a signed-in host)
    "name": "Sam's room",              // 1–40 characters; no links, web addresses or @handles
    "mode": "ffa",                     // up to 32; lists and Quick Play filter by it
    "map": "Docks",                    // optional, up to 32
    "tags": { "demo": true, "skill": "casual" }  // optional: up to 8, [a-z0-9_] names, booleans or short strings
  }
}
```

```rust
// Rust (partii-net): list it as you host, or any time after.
let meta = json!({"listing": {"visibility": "public", "name": "Sam's room", "mode": "ffa", "map": "Docks"}});
engine.create_with("mygame", "game", "Sam", meta.clone(), json!({"net_version": NET_VERSION, "max_members": 8}));
engine.update(json!({"meta": meta}));                       // change it (the whole meta: it replaces the old one)
engine.update(json!({"meta": {"listing": null}}));          // unlist
engine.update(json!({"password": "hunter2"}));              // a password (null drops it); never in meta
// Joining a password room:
engine.join_with(&code, "game", "Bob", json!({}), json!({"net_version": NET_VERSION, "password": "hunter2"}));
```

The texts go through Partii's content standard: a listing that fails (a link, a rude name, too long) refuses that `create` or `update` with `Failed { code: "listing_rejected", .. }` (the err frame's `field` says which, e.g. `listing.name`) and changes nothing, so tell the host to pick another name. The host's member name shows as the room's host (a signed-in host shows with their Partii name and @name instead; a host name that fails shows as "Host"). A listing changes at most 10 times a minute per room (and 30 per network and per player); sending meta again with the same listing doesn't count.

The room is listed while it is joinable and its host is in it. It leaves the list **at once** when its host leaves, it empties, or `joinable` goes false; a full room drops out of the default list (`has_space`). While listed the room reports itself every 20 s, and a lobby not heard from for 60 s is gone. Reserved rooms and captures (`meta.capture`) never list. A **password** (`password` on create or update) is kept only as a salted hash, never shown to members or the list; the list shows `password: true` and a join must send it (`password_required`, `wrong_password`). Wire details: [PROTOCOL.md "Open lobbies and passwords"](PROTOCOL.md#open-lobbies-and-passwords).

**Count only your players (`count_kinds`).** A room with a big screen and phones (or spectators) usually wants the list to show players, not every member. Put `count_kinds` in the listing: the lobby's `players` is then the members of those kinds, and its `max` the sum of those kinds' caps (`kinds: {"game": {"max": 4}}`), or the room's `max_members` when one of them has no cap. "Has a free seat" (the default list and Quick Play) uses the same counts, and also needs the room itself not full. And when **every** counted kind is closed to joins (`kinds: {"game": {"joinable": false}}`, say when the match starts), the room leaves the list, while phones can still join by code; it comes back when you reopen one. Without `count_kinds` nothing changes: every member counts, `max` is `max_members`, and kind rules don't delist.

```rust
// 4 tanks, any number of phones: the list shows "1/4" until 4 tanks are in.
let meta = json!({"listing": {"name": "Sam's room", "mode": "ffa", "count_kinds": ["game"]}});
engine.create_with("mygame", "game", "Sam", meta, json!({"net_version": NET_VERSION, "max_members": 16,
    "kinds": {"game": {"max": 4}, "phone": {"max": 12}}}));
engine.update(json!({"kinds": {"game": {"joinable": false, "max": 4}}}));   // match on: off the list
engine.update(json!({"kinds": {"game": {"joinable": true, "max": 4}}}));    // back in the lobby: listed again
```

**Passwords for some kinds (`password_kinds`).** With a password, `password_kinds: ["game"]` on create or update makes only joins of those kinds need it: phones (or any other kind) join without it. `null` on update means every kind again (the default), and dropping the password drops `password_kinds` too. The list shows `password: true` and `password_kinds: ["game"]` (`null`: every kind). Quick Play still skips every room with a password.

```rust
engine.create_with("mygame", "game", "Sam", meta, json!({"net_version": NET_VERSION, "password": "hunter2", "password_kinds": ["game"]}));
engine.update(json!({"password_kinds": null}));   // now phones need it too
```

**Switch lobbies off without a build.** If lobbies misbehave (or you're not ready), turn them off for the whole game: `partii secrets set mygame lobbies.enabled --value false`. At once the list answers `{"lobbies": [], "enabled": false}` and Quick Play `404 no_lobby` with `"enabled": false`; rooms keep working by code. `--value true` (or `partii secrets delete mygame lobbies.enabled`) turns them back on; a game that never set it has them on. Your build can poll `GET /v1/games/{game}/lobbies/status` (`partii lobbies status <game>`; public, no key, cached for 60 s) for `{"enabled": true}` and hide its server browser and Quick Play button when it's false.

**The server browser.** `GET /v1/games/{game}/lobbies` with the game's publishable key (`X-Partii-Key`), and the player's token when signed in (optional): `partii lobbies list <game>`.

| Query | Meaning |
|---|---|
| `net_version` | Only lobbies on exactly this build. Always pass yours: a room on another build refuses the join with `version_mismatch`. |
| `mode` | Only this mode. |
| `region` | Only this region: `na-west`, `na-east`, `eu`, `asia`, `oceania`, `sa`, `af`. |
| `has_space` | Default `true`: only lobbies with a free seat. `false` also lists full ones. |
| `sort` | `region` (default: your region first, then the same area, then the rest; most players first within each), `players`, `newest`. |
| `limit` | 1–100, default 50. |

```json
{"ok": true, "enabled": true, "your_region": "na-west", "your_colo": "SJC",
 "lobbies": [{"code": "KXQPT", "name": "Sam's room", "mode": "ffa", "map": "Docks", "tags": {"demo": true},
   "players": 3, "max": 8, "region": "na-west", "colo": "SJC", "net_version": "a1b2c3",
   "friends_only": false, "password": false, "password_kinds": null, "host": {"name": "Sam", "handle": "sam"},
   "friends": ["Ann"], "created_at": 1794499796727, "updated_at": 1794499816727}]}
```

Join one with its `code`, as you would a typed code. `friends` names the viewer's friends in that lobby (friends: you follow each other); `friends_only` lobbies show only to signed-in viewers who are the host's friends. Player ids never appear. **Region** is where the host's connection reached Partii (its Cloudflare location, `colo`), boiled down to a coarse area; `your_region` is the caller's. It's a hint for sorting, not a measured ping.

**Quick Play.** `POST /v1/games/{game}/lobbies/quick-join` with `{"net_version": "...", "mode": "ffa", "region"?: "eu"}` (`partii lobbies quick-join <game>`) answers `{code, name, mode, map, players, max, region, net_version}`: a public lobby with a free seat and no password, on your build and mode, in your region first (the body's `region`, else where the request came from), then the fullest that still has a seat (games start sooner), then the oldest. Join it at once; the seat isn't held, so a join that meets `full` asks again. None: `404` `no_lobby` with hint `host one` (and `"enabled": true`): create a listed room and wait for players. `"enabled": false` instead means the game's lobbies are switched off (above).

**Web games (TypeScript).** `sdk/ts/src/lobbies.ts` wraps both with the generated client:

```ts
import { createClient } from "./partii/client";
import { listLobbies, quickPlay, withListing } from "./partii/lobbies";
const client = createClient({ base: PARTII_API, key: PARTII_KEY, playerToken });    // token optional
engine.update(JSON.stringify({ meta: withListing(meta, { name: "Sam's room", mode: "ffa" }) }));
const { lobbies, your_region } = await listLobbies(client, "mygame", { net_version: NET_VERSION });
const hit = await quickPlay(client, "mygame", { net_version: NET_VERSION, mode: "ffa" });  // null: host one
```

**Cross-play.** There is one list per game for everyone: players signed in through Steam, through Partii, or not at all see and join the same lobbies. **Steam friends** don't count as friends yet (friends are mutual follows on Partii); a later version may add them through Steam's `GetFriendList` with the game's publisher key.

Limits: the list 60 a minute per player and 600 per IP; Quick Play 20 per player and 120 per IP (`429 rate_limited` with `retry_after_ms`). Refresh a browser every few seconds at most.

## 3. Players and saves

Add `partii-account` (`partii-account = { git = "https://github.com/PartiiGames/partii-sdk" }`, from the open-source SDK). One `Account` per launch does it all on a background thread (native builds):

```rust
use partii_account::{Account, AccountConfig, merge_objects};

let acct = Account::start(AccountConfig {
    edge: "https://<your platform>".into(),
    key: Some("pk_mystudio_game_...".into()),
    game: "mygame".into(),
    data_dir: save_folder.clone(),       // keeps this install's device id + offline entitlement cache
    display_name: "Player".into(),
    slots: vec!["progress".into()],      // fetched at sign-in
    merge: Some(merge_objects),          // or your own fn(slot, mine, theirs) -> Option<merged>
    ..AccountConfig::default()
});

// Any frame (never blocks):
acct.ready();                            // signed in + first fetch done
acct.player_id();                        // Some("p_...")
acct.owns("full");                       // Some(true/false); None while unknown (fresh install offline)
acct.read_save("progress");              // Some(json text) once fetched
acct.write_save("progress", r#"{"level":3}"#);  // queued; conflicts merge and retry
acct.pending_writes();                   // writes not stored yet; wait for 0 before quitting if it matters
```

The API, in types:

| Item | Type |
|---|---|
| `AccountConfig { edge, game, display_name }` | `String` |
| `AccountConfig { key, player_token }` | `Option<String>` |
| `AccountConfig { data_dir }` | `PathBuf` |
| `AccountConfig { slots }` | `Vec<String>` |
| `AccountConfig { merge }` | `Option<fn(slot: &str, mine: &str, theirs: &str) -> Option<String>>` (JSON texts in, merged JSON text out; `None` keeps yours) |
| `merge_objects` | a ready-made `merge`: unions two JSON objects, your keys win |
| `ready()` | `bool`: signed in, entitlements and the listed slots fetched |
| `player_id()` | `Option<String>` |
| `owns(sku)` | `Option<bool>` |
| `read_save(slot)` | `Option<String>`: JSON text; `None` if empty or not fetched |
| `save_rev(slot)` | `i64`: 0 = never written |
| `write_save(slot, json_text)` | `bool`: queued; the text is stored as parsed JSON |
| `pending_writes()` | `usize` |
| `refresh()`, `start_checkout()` | `()` |
| `take_checkout()` | `Option<Result<String, String>>` |
| `error()` | `Option<String>` |
| `player_token()`, `client()` | `Option<String>`, `Option<partii_api::Client>`: call any player operation (e.g. `ugcPublish`) as this player; calls block, so make them off the frame; ask again after `login` |
| `is_guest()`, `providers()` | `Option<bool>` (None until known), `Vec<String>` |
| `login(provider, fields)`, `take_login()` | `()`, `Option<Result<(), String>>`: link a provider; the guest becomes or merges into that account |
| `steam_browser_login()`, `take_browser_url()` | `()`, `Option<String>`: "Sign in through Steam" in the browser (no Steam key needed); open the URL, the outcome arrives via `take_login` |
| `submit_receipt(store, fields)`, `take_receipt()` | `()`, `Option<Result<(), (code, message)>>`: a platform-store purchase (App Store `{"transaction": Transaction.id}`, Play `{"purchase_token", "product_id"}`), verified and unlocked on every platform; also for restores. A purchase belongs to one Partii account: a guest's moves to whoever restores it, a signed-in account's gives `claimed_by_another_account` |

**When `owns` is fresh.** Before `ready()`, `owns` returns last week's cached answer (or `None` on a fresh install). Once `ready()` is true it reflects the platform at sign-in. After a purchase made elsewhere (the browser, another device), call `refresh()`; `owns` updates when the answer arrives.

- **Sign-in.** On first launch the install becomes a guest player (a random device id kept in `data_dir`), with no form. Later `acct.login(provider, fields)` links Steam (`{"ticket": hex}`; add `"identity"` if you made the ticket with `GetAuthTicketForWebApi(identity)`), email (`{"email", "code"}`, after `playersEmailStart`), Apple or Google (`{"id_token"}`; Apple's `identity_token` works too), Game Center (`{"team_player_id", "bundle_id", "timestamp", "salt", "signature", "public_key_url"}` from `fetchItemsForIdentityVerificationSignature`, with salt and signature in base64, plus an optional `"alias"` as the display name. Silent on iOS: it's the same player on every device signed in to that Game Center account. In dev and staging, `{"team_player_id", "test": true}` signs in without a device.) or Discord (`{"code"}`). The guest becomes, or merges into, that account, so saves, purchases and votes follow the player to every device, and this device signs in to that account from then on. Show "Sign in to publish" while `is_guest()` is `Some(true)`.
- **Steam.** Two ways in, both reaching the same player. *Ticket:* `acct.login("steam", json!({"ticket": hex, "identity": "partii"}))` with a ticket from `GetAuthTicketForWebApi("partii")`. It is checked with **your game's own** Steamworks key, which you store once:
  ```sh
  partii secrets set <game> steam.web_api_key --value -     # paste the key, then Ctrl-D (stdin keeps it out of shell history)
  partii secrets set <game> steam.app_ids --value 4971410,4971420   # full game, demo, …
  ```
  Secrets are encrypted, tied to the game, and never shown again (`partii secrets list <game>` shows the last 4 characters). *Browser:* if the game has no key, `login` fails with `steam_not_set_up`. Call `acct.steam_browser_login()` instead and open the URL from `take_browser_url()`; the player signs in at steamcommunity.com and the game picks it up. This needs no key, so it works for any game.
- **Saves.** Named JSON slots per game. If another device wrote first, your `merge` function gets both copies and the merged result is written. Every write keeps a backup (`savesHistory`, `savesRestore`).
- **Offline.** The last entitlement answer is cached for a week, so a paid game stays unlocked without a network.
- **Tests.** Set `AccountConfig::player_token` (e.g. from `partii test players create`) to act as a specific player.

Under the hood these are plain API calls (`POST /v1/players/guest`, `PUT /v1/saves/{game}/{slot}` with `base_rev`, `GET /v1/players/me/entitlements?game=`), listed in [API.md](API.md); `partii-client` (in the SDK) is a client for all of them if you need more.

### Sign in through partii.games, show who's signed in, sign out

Let partii.games sign the player in (no credentials typed into the game; creating an account works there too):

1. `POST /v1/players/web/start {game, return_to?}` with your key (and the guest's token) → `{url, poll, expires_at}`. Open `url` in a browser sheet (SFSafariViewController / ASWebAuthenticationSession on iOS, the system browser on desktop). It's good for 30 minutes.
2. The page says "Sign in to play <your game>": an email code, or one tap "Continue as <email>" when the browser is already signed in. It approves the sign-in for you.
3. Poll `POST /v1/players/web/poll {poll}` every couple of seconds until `status` is `done` (or `expired`).
4. Exchange it once: `playersLogin {provider: "partii", poll}` with the guest's token → the usual `{player, player_token, merged}`; the guest's saves and purchases join the account.

**Send the player back to your game (optional).** Register a return link once, and the page opens it as soon as the player has signed in. It also shows a big "Back to <your game>" button, since browsers want a click before they open an app link the first time:

```
partii secrets set mygame web.return_url --value mygame://signed-in
```

Use an app link your game registers (a custom scheme on Mac, Windows and Linux, or a link that closes an ASWebAuthenticationSession on iOS), or an https page on your own site. Without one, the page just says the player can close it.

A start call can name a different `return_to`, for example per platform. It must be the registered `web.return_url` itself, or use a scheme listed in `web.return_schemes` (`--value mygame`). An https one also needs its host in `web.return_hosts` (`--value mygame.com`), and http is never allowed. The link always comes from your game's config or its start call, never from the page's address.

The Partii app signs in the same way, with its own key (project `partii`). Its start call names `partii://signed-in`. On Mac, Windows and Linux that link brings the app back to the front. On iPhone the page opens in an ASWebAuthenticationSession with callback scheme `partii`, and the sheet closes when the page goes there. Either way, the app's poll finishes the sign-in. The edge allows `partii://signed-in` and `https://partii.games/app/signed-in` (a universal link, used by iPhone builds up to 0.2.15) for project `partii`, and nothing else. That universal link never worked from Safari: iOS doesn't open a universal link that its own site navigates to.

### Sign in automatically (web games on partii.games)

A web game hosted on partii.games can sign the player in with no tap at all, inside the Partii app and in a browser:

```ts
// The TypeScript SDK's files (sdk/ts/src): client.ts, generated.ts, autosignin.ts
import { createClient } from "./partii/client";
import { autoSignIn } from "./partii/autosignin";
const api = createClient({ base: "https://api.partii.games", key: "pk_..." });
// ...after your guest sign-in (playersGuest), so the guest's progress is merged:
const r = await autoSignIn(api);   // {player, player_token, merged} | {need: "tap" | "sign_in"} | null
```

How it works, without ever putting a session token in a URL:

- **In the Partii app** (the phone app plays your site full screen): the game asks the app's window with `postMessage({partii: "signin", op: "ticket"})`. The app answers only your own site's frame, only for a signed-in account, with a one-time launch ticket for your game (10 minutes, works once, only with your project's key).
- **In a browser:** a hidden frame of `https://partii.games/signin-bridge.html` (`staging.partii.games` for `-staging` sites) answers the same question with the player's partii.games session, but only to `https://<your game>.partii.games`, only for your game, and only once the player has opened the game from partii.games while signed in, or owns it. Otherwise it says `need: "tap"`: use the web sign-in above, whose page is one tap.
- Either way the game exchanges the ticket itself: `playersLogin {provider: "launch", ticket}` with the guest's token, the same exchange the desktop launcher's `PARTII_LAUNCH_TICKET` uses.

Sites elsewhere (your own domain, deploy previews, jam hosts) get no answer.

### Safe-area insets in the Partii app (web games and phone controllers)

The Partii phone app opens your game's site (`https://<game>.partii.games`: a web game's Play, or a phone-controller game's Join) full screen and **full bleed**, under the notch and home indicator too. It's a frame, and inside a frame iOS's `env(safe-area-inset-*)` can't be trusted: it's 0, or it stays on the rotation the frame's page was made in (an upright phone's 47–59 px on top and 34 px below, on a sideways screen: Sandii and Cosmos, 2026-11-14). **Don't lay out from `env()` alone in the app.** The app tells your site its insets, in CSS px:

- **At first load**, in the address: `?safe=T,R,B,L` (whole numbers, merged with any query of yours), e.g. `https://tankii.partii.games/?safe=0,47,21,47` in landscape. They're for the rotation your game is shown in: a game whose store page says `"orientation": "landscape"` gets the sideways ones even when it's tapped on a phone held upright, and its frame is made only once the app has turned.
- **As messages** from the app's window: `{t: "partii:insets", top, right, bottom, left}`, posted to your site's exact origin when the frame loads, on every resize or rotation, and again at about 0.1, 0.3, 0.7 and 1.5 s as a rotation settles (iOS has the new insets late: the first ones after a rotation can be the old rotation's, so lay out from the latest). Check `event.source === window.parent`.

Keep text and touch controls (a move stick, buttons) inside them; draw the rest edge to edge. They're the phone's notch or Dynamic Island and home bar only: in landscape nothing on top, the notch's depth on both sides (the notch's and the rounded corners'), and the home bar's 21 px below. The app's close × floats in the top-right corner over your game: you don't make room for it. (In a jam there's no ×: Partii's own capsule, Lindii and the Menu, floats against the right edge with its centre at 60% of the height, its background reaching the edge and its buttons inside the right inset; it takes no room either, and a jam game finds its box as `what: "corner"` in `app.screen.partii.rects`. See JAM.md.) The TypeScript SDK does both for you:

```ts
import { onSafeArea } from "./partii/safearea";   // sdk/ts/src/safearea.ts
onSafeArea(({ top, right, bottom, left }) => layoutControls({ top, right, bottom, left }));
// also sets --partii-safe-top/-right/-bottom/-left on <html>:
//   .stick { left: calc(var(--partii-safe-left, env(safe-area-inset-left)) + 16px); }
```

In a plain browser neither comes, and `env()` works as usual, so fall back to it. A page that keeps its own CSS variables from `env()` (`--sat: env(safe-area-inset-top)`) puts Partii's first: `--sat: var(--partii-safe-top, env(safe-area-inset-top, 0px))`.

### Starting up in the Partii app: the loading card

When a player taps Play (or Join), the app grows your game's cover to the full screen and shows a loading card over it (your game's name, a spinner, "Starting…") while your site loads underneath, hidden. Your site fades in when its frame fires `load`. Nothing by 8 s: the player sees "Couldn't start" with Retry.

If your page loads before it can draw (a big WebAssembly download, say, behind your own loading bar), you can keep the app's card up instead, optionally:

- `parent.postMessage({ t: "partii:loading" }, "*")` early (in `<head>`): the app waits for the next message instead of `load`, and doesn't give up at 8 s.
- `parent.postMessage({ t: "partii:ready" }, "*")` once your first frame is on screen: the app fades your game in. It also shows it at 20 s whatever happens.

Only the frame the app opened is listened to. In a plain browser nobody listens, so it's safe to send anyway.

The player's own view (`playersMe`, every sign-in answer) has `email`: the address they signed in with, or `null`. It's never in public views.

**Sign out** on this device: `playersLogin {provider: "device", device_id, sign_out: true}` with the signed-in token. The device moves to a new guest (its `{player, player_token}` come back); the account keeps its purchases and saves, and signing in again returns to it.

### Steam and Partii accounts: link, unlink, never lose one

The full case table (what to show, what changes) is in [ACCOUNTS.md](ACCOUNTS.md). The rules a client relies on:

- **A sign-in never swallows a real account.** With a player token, `playersLogin` (and the website and launcher sign-ins, and the Steam browser poll) merges the caller into the identity's owner only when the caller is *soft*: its sign-ins are all device, steam or gamecenter. A real caller (email, apple, google, discord) gets `409 identity_in_use` with `error.other {id, display_name, avatar_url, providers, soft}`, and nothing changes. The Steam browser poll answers `status: "conflict"` with `other` instead.
- **Link and unlink:** `POST /v1/players/me/identities {provider, ..., move?}` (steam, steam_openid, email, partii, gamecenter, apple, google, discord) and `DELETE /v1/players/me/identities/{provider}`. With `move: true`, a soft other account is merged in; a real one gives up only that sign-in, never its last.
- **Names:** a Steam persona (or Game Center alias) names the player, cut to 12 characters, and follows renames at each sign-in until the player picks a name (`name_custom`). A rename your game makes for the player is `PATCH /v1/players/me {display_name, auto: true}`.
- **Steam ownership** is checked at every Steam sign-in and link (bounded; `entitlements {granted, revoked}` in the reply) and daily from `playersEntitlements`.
- `player.features` lists what the edge supports; gate new flows on it.

### Manage a player's profile for them

An agent can set up someone's Partii profile (partii.games/@name) with the CLI, with their permission:

1. `partii player email-start --email <their email>` emails them a 6-digit code; ask them for it.
2. `partii player login --provider email --email <their email> --code <code> --save` signs in as them and keeps the sign-in in `~/.config/partii/cli.json` (mode 600); the token isn't printed. Player commands use Partii's own key, so no `PARTII_KEY` is needed.
3. Then:
   - `partii player me`: their profile as they see it: name, @handle, bio, picture, links with their status.
   - `partii player update --display-name "Sam" --handle sam --bio "Building games with friends"`: the bio is the short description, 160 characters at most.
   - `partii player link-add --kind instagram --url https://instagram.com/sam` (kinds: linkedin, instagram, facebook, youtube, tiktok, bluesky, x, twitch, discord, github, threads, steam, mastodon, website; 10 at most). `partii player links` lists them with ids, and `partii player link-remove <id>` removes one. `partii player update --field 'links=[{"kind":"github","url":"https://github.com/sam"}]'` replaces the whole list.
   - `partii player avatar --file picture.png`: PNG, JPEG, WebP or GIF, 2 MB at most.
   - `partii profiles get <handle>` shows the public page; `partii profiles follow <handle>` and `partii profiles unfollow <handle>` follow people.
4. `partii player forget` drops the saved sign-in when you're done.

Social links are checked to be a profile on that site and show at once. A picture, a website or a Mastodon link shows only after Partii's moderator approves it. Until then `partii player me` marks it pending, and a denied one shows as `denied`; remove it.

### Leaderboards

Submit once per run, with a player token (guests count). Each board keeps every player's best for today, this week and all time. Days and weeks are UTC, and weeks start on Monday.

```ts
await api.leaderboardSubmit("rocket-to-heaven", "altitude", { score: 4200, meta: { play_time_seconds: 81.5, cause: "lava" } });
const top = await api.leaderboardGet("rocket-to-heaven", "altitude", { period: "daily", limit: 10 });
// top.entries: [{rank, player_id, display_name, score, meta, achieved_at}]
// top.me: your best and rank (with a player token), or null
// top.resets_at, top.players, top.total_plays
```

- **New boards** are created on the first submit, and higher scores win. For times, run `partii leaderboards config <game> <board> --higher-is-better false` before anyone submits.
- **Worse scores** count as a play but don't replace the player's best. `meta` (flat, 1 KB) is kept with the best score.
- **Signing in:** a guest's scores join the account it signs in to.
- **Cheaters:** `partii leaderboards remove <game> <board> <player>` removes a player's scores. Deleted players drop off.
- **Top scores on your store page** (off until you turn it on): `partii leaderboards store-page <game> --field board=score`, or Top scores on the game's page in Make. The page shows the board's all-time top 10 and each visitor's own best ("You: #12"): under the buy card on a computer, below the description on a phone. Kids' accounts and profiles taken down show as "A player". `--field board=` turns it off.

### Achievements

Define them once per game with the CLI (re-running updates; fields you leave out keep their value):

```sh
partii achievements set mygame first_win --field name="First win" --field description="Win a round" --field points=10
partii achievements set mygame centurion --field name="Centurion" --field description="Win 100 rounds" --field goal=100 --field order=2
partii achievements set mygame secret_room --field name="Secret room" --field hidden=true   # shown as "Hidden achievement" until unlocked
partii achievements icon mygame first_win --file first_win.png   # JPEG, PNG or WebP, at most 512 KB; 256x256 works best (or --field icon=https://…)
partii achievements list mygame      # with unlocks and percent of players
partii achievements delete mygame secret_room
```

Unlock from the game with `partii-account`, as often as you like: each is sent once, queued on disk while offline, and recorded with the time it happened.

```rust
acct.unlock_achievement("first_win");
acct.achievement_progress("centurion", rounds_won); // unlocks at the goal; progress only goes up
if acct.achieved("first_win") { /* … */ }
for id in acct.take_unlocked() { /* show a toast: partii just confirmed it */ }
```

Without `partii-account`, call `achievementsUnlock` with the game's key and the player token. Its answer's `newly` is true when that call unlocked it. A game's key can only unlock its own game's achievements.

**Where players see them:**
- **Public:** `storeAchievements` (`partii store achievements <game>`) lists each achievement with the percent of players who have it. "Players" means anyone who owns the game, saved in it, or made progress.
- **A player's own:** `playersAchievements` adds their progress and unlock times, plus a summary of how many are unlocked and points earned.
- **Display:** both the launcher and partii.games show them on the game's page.
- **Signing in:** a guest's achievements join the account it signs in to (the furthest progress and the earliest unlock win).

### Player content: levels, worlds, replays, game modes

Players can publish what they make so that other players can browse and download it. Only the author can change or unpublish it. Every call is in [API.md](API.md) under `ugc*`.

Players' content is **for signed-in players only**: publishing, browsing, lookups, downloads, votes, plays and reports all take your key plus the token of a player who signed in some way (Steam ticket, Game Center, Apple, Google, Discord or email). The exception is your project's **official publisher** (`author.official`): signed out (no token, or a device guest's), browse and search show only official items, and their lookups and files download. Anything else answers `403 sign_in_required` (one code for both cases, so the game shows one "sign in to see community content" state). Votes, plays and reports need a sign-in even on official items. An invalid or expired token is `401`. When a guest signs in, its progress merges into the account.

1. **Upload by hash.** `POST /v1/games/{game}/ugc/uploads` with `{kind: "file" | "thumbnail", size, sha256}` (hex). If that hash is already stored you get `exists: true`; skip to step 2. Otherwise PUT the bytes to `upload.url` with exactly `upload.headers` and no auth headers; the URL is good for an hour. The platform checks the hash, so other bytes are refused.
2. **Publish.** `POST /v1/games/{game}/ugc` with `{kind: "level" | "world" | "replay" | "mode", title, description, tags, visibility: "public" | "unlisted", sha256, client_version, thumbnail_sha256?, refs?}`. A World lists the exact Level file hashes it uses in `refs`. Each of those hashes must already be uploaded to this game. A World needs a picture: publishing one without `thumbnail_sha256`, or clearing it later with `PATCH /v1/ugc/{id}`, is refused with 400 `no_picture`.
3. **New versions.** `POST /v1/ugc/{id}/versions` with `{sha256, client_version, notes?, refs?}`. Old versions stay downloadable by hash, so a World that pins one keeps working.
4. **Browse.** `GET /v1/games/{game}/ugc?sort=new|top|played&kind=&tags=a,b&q=&author=&limit=&cursor=`. Pass `next_cursor` back as `cursor` to get the next page. Unlisted items never appear here; find them with `GET /v1/games/{game}/ugc/code/{share_code}` (every item has a six-character code). To fetch one item use `GET /v1/ugc/{id}`, which includes every version. Every item includes `my_vote` (0 when the viewer hasn't voted).
5. **Download** from `download_url` or `thumbnail_url` with the player's token (`Authorization: Bearer pt_…`). Cache them forever, since they are addressed by hash. `GET /v1/games/{game}/ugc/hash/{sha256}` says which items and versions a hash belongs to.
6. **Votes and plays.** `PUT /v1/ugc/{id}/vote {value: 1 | -1 | 0}` (one vote per player). `POST /v1/ugc/{id}/plays` is fire and forget; `plays` counts players, not launches.
7. **Unpublish, reports, moderation.** The author calls `DELETE /v1/ugc/{id}`. The item leaves browse and lookups, but its files stay downloadable by hash while Worlds pin them. Players report with `POST /v1/ugc/{id}/report {reason}`. You review reports with `partii ugc reports <game>` and hide or restore an item with `partii ugc moderate <id> --action hide --reason "…"`. Hiding removes the item's files too.

Rules: only signed-in players can publish; guests can browse, download, vote and play, and their votes follow them when they sign in. Files are capped at 5 MB, thumbnails are PNG up to 256 KB, and each player gets 300 items per game. Per player per hour: 30 publishes or versions, 60 uploads, 300 votes and 20 reports. Deleting an account unpublishes its items.

A player's report hides an item at once, until the moderator decides, and its author gets a notice saying why.

### Game modes: players share their own rules

A game mode is player content of kind `mode`: a small JSON file a player makes in your game and shares by link. It uses the same calls as levels, with the gate of official content: a mode is a **private draft** until its author publishes it, and publishing passes Partii's automatic content check first (nothing sexual or suggestive is ever public).

**The file** is a JSON object of at most 50 KB: `{v?, name, description, version, needs: {…}, author?, picture?, …your fields}`. `v` is `1` (or left out) or `2`; anything else is `400 bad_mode`. `name`, `description` and `version` (letters, digits, `. _ + -`) are required, and `needs` is an object (what the mode needs from the game). `author` is display text only; credit comes from the player's account. `picture` is optional; when it's there, it is the sha256 of the mode's PNG picture, uploaded as a thumbnail. Links and inline images are refused, because every picture passes the check. A bad file is `400 bad_mode`, a big one `400 mode_too_large`, and a picture that differs from `thumbnail_sha256` is `400 picture_mismatch`.

**A mode with player art is `v: 2`** and adds two fields (a v1 mode carries neither):

- `art`: at most 16 entries `{id, w, h, px}`, the pixels of pixel art (below, "Pixel art") inline. Each entry passes the same checks as an art file (16 or 32 square, `w*h/2` bytes of `px`, `id` the canonical hash), with no other fields, and each `id` appears once. A bad entry is `400 bad_art`, naming it (`art[2]: …`).
- `looks`: an object of at most 64 slots (`^[A-Za-z0-9_.-]{1,40}$`), each mapped to the `id` of an entry in `art`, e.g. `{"tank": "3f9c…", "flag.red": "a01b…"}`. Otherwise `400 bad_mode`.

**Inline art goes live only as moderated art.** Pin each piece's art file sha256 in the mode's `refs` (as for embedded art). Publishing requires every inline entry to be, byte for byte, the pixels of a live art item of the game that the mode pins. Matching the id alone isn't enough. Otherwise it's `409 art_not_live`: `error.ids` names the inline entries, and `error.hashes` names pinned art that isn't live. A draft may hold art that isn't live yet. Because every piece is pinned, `refs_state` reports each one later: when art is hidden or removed, the mode stays up, and you draw the default look for that slot.

1. **Save a draft.** Upload the file (and picture) as for any player content, then `POST /v1/games/{game}/ugc` with `{kind: "mode", sha256, client_version, draft: true, thumbnail_sha256?, title?, description?, tags?, remix_of?}`. `title` and `description` default to the file's `name` and `description`. It answers `{item, version: 1, status: "draft"}`. Save again with `POST /v1/ugc/{id}/versions {sha256, client_version, draft: true}`: that overwrites the newest draft (its `version` stays the same) rather than piling up versions. Only the author sees a draft, by any route (others get `404`).
2. **Publish** (an explicit action by the player): `POST /v1/ugc/{id}/versions/{n}/publish`. Or skip the draft: `ugcPublish` or `ugcVersion` without `draft`. The answers are those of official content: `200 {item, version, status: "published"}`; `422 content_refused` (`error.reasons`; it stays a draft, with `check_reason`); `202 content_pending`; `202 content_waiting` while a person looks.
3. **Share and install.** Every mode is `unlisted`: `GET /v1/games/{game}/ugc/code/{share_code}` (or `GET /v1/ugc/{id}`) answers `{item: {…, versions}}`, and `download_url` has the file. A live mode works for anyone with the link, signed out too, because it was checked before it went live.
4. **Mine.** `GET /v1/players/me/ugc?game={game}` lists the player's items. Each mode has `status` (its newest version's state: `draft`, `checking`, `waiting`, `published`, `refused`), `latest_version` and `check_reason`. A mode with nothing live yet is `hidden: true`, with `hidden_reason: "draft: nothing published yet"`. Its author also gets these on `ugcGet` and `ugcByCode`, with every version and its `state`.
5. **Change or delete.** `PATCH /v1/ugc/{id}` changes the title, description, tags or picture (author only; a mode stays unlisted). Once the mode is live, the changed words or picture pass the check first. `DELETE /v1/ugc/{id}` unpublishes it.
6. **Remix.** Publish with `remix_of: <id>`, the id of a mode of this game the player can open. The new mode carries `remix_of: {id, author: {id, display_name}}` and `original_author: {id, display_name}`, the first author in the chain, so credit survives remixes of remixes. Every other item has `null` there.

There is no browse and no voting for modes yet. They never appear in `GET /v1/games/{game}/ugc` (`?kind=mode` is `400`), and a vote is `409 votes_off`. Reports, the per-player item cap and the hourly publish rate work as for levels.

### Pixel art: players' icons, pickups and decals

Pixel art is player content of kind `art`: a tiny picture a player draws in your game, shared inside the modes and worlds that use it. It takes the game mode path (private draft, explicit publish, unlisted, no browse, no votes), with one difference: **no person ever looks**. Partii decides everything automatically.

**The file** is JSON of at most 4 KB: `{format: "tankii.art", v: 1, id, w, h, px, name, author?}`. `w` = `h`, 16 or 32. `px` is base64 of 4-bit pixels, row by row from the top-left, high nibble first (`w*h/2` bytes: 128 or 512). Index 0 is transparent; 1-15 are v1's fixed palette: `f75f4f ff8c42 f2b234 53c45e 3fc9c9 4f8ef7 ae6cf0 f06cab 8b6f47 e8eef8 6d5536 1a1a1a 8a8f99 3b2a1e f6ecd2`. `id` is the first 16 hex characters of the sha256 of `"TA" | v | w | h | px` (one byte each for v, w and h). No other fields. Anything else is `400 bad_art`. Art takes no thumbnail, refs or remix_of.

1. **Save and publish** as for modes, with `kind: "art"`: `POST /v1/games/{game}/ugc {kind: "art", sha256, client_version, draft?}`, then `POST /v1/ugc/{id}/versions/{n}/publish`. Partii renders the pixels itself (it never takes a client's picture) and checks that picture with `name` and `author`. `200 published`; `202 content_pending` (it goes live or is refused on its own); `422 content_refused` with `error.reasons`, also when the reviewer isn't sure. Art never answers `content_waiting`. A new version changes it; `PATCH` doesn't.
2. **Embed.** A mode or world lists the art it uses by its file's sha256 in `refs`, as a world lists its Levels. It goes live only when every piece is live: otherwise `409 art_not_live`, with `error.hashes`. A draft may pin art that isn't live yet. A v2 mode can also carry the pixels inline (`art` and `looks`, see "Game modes"): each inline piece must be the exact pixels of live art it pins, or `error.ids` names it.
3. **Before you show art to a stranger**, ask `POST /v1/games/{game}/ugc/status {sha256s: [...]}` (at most 64; the game key alone works, so guests can call it). It answers `{states: {sha256: "live" | "hidden" | "removed" | "unknown"}}` and may be cached for a minute. Draw only `live` art; for the rest, draw your default look.
4. **When art is taken down,** the modes and worlds that use it stay up. `ugcGet`, `ugcByCode` and `officialCampaign` carry `refs_state: {sha256: state}` for the art they pin.
5. **Reports.** `POST /v1/ugc/{id}/report {reason}` hides the art for everyone at once, and its author gets a notice. A stricter automatic check then runs. The art comes back only if that check passes and fewer than 3 players have reported it. Otherwise it's removed for good, and 3 distinct reporters remove it at once. A failed check counts as a strike against the author.

Art counts toward the 300-item cap. It has its own hourly allowance of 60 versions, apart from the 30 publishes other kinds share. Deleting the author's account (or the item) removes their art (`removed`).

### Official content: your team edits the game's own levels and worlds

Your team can build the game's own content (the campaign, seed levels) inside the normal game and publish it to every player. Official items are authored by your project's **official publisher** player (made for you the first time; it shows as the game, `author.official: true`), never by the person who pressed Publish. Two capabilities decide who may do what (§1 "Your own roles"):

| Capability | Lets a team member |
|---|---|
| `edit_official` | save drafts of official content, and load them to playtest |
| `publish_official` | make official content live: publish, publish a draft, roll back, change its title, description, tags, thumbnail or visibility, delete it, set the game's campaign |

With the presets, owners and admins have both and editors have `edit_official`. The player is on the team the usual way: a test player of a member, or signed in with a member's developer email. Missing the capability is `403 missing_capability` with `error.need` (`"publish_official"` or `"edit_official"`).

**Nothing goes live unchecked.** Every official publish passes Partii's automatic content check first ([CONTENT-POLICY.md](CONTENT-POLICY.md): nothing sexual or suggestive, ever): the item's title, description, tags and version notes, its thumbnail, and the text of its file and of every file it pins in `refs` (names, signs, dialogue). It passes and is live at once, or it's refused (`422 content_refused`, `error.reasons` says what was seen) and nothing changes for players. When the check can't answer at once, the call returns `202 content_pending` with `{item, version, status: "pending"}`, and the version goes live the moment it passes. A long file is checked whole, in parts. When the reviewer isn't sure, nothing is refused for that alone: the version waits for a person to look (`202 content_waiting`, `status: "waiting"`, and the version's `state: "waiting"` and `check_reason` in `GET /v1/ugc/{id}?drafts=1`), and goes live once they pass it, or is refused with their reason. A suspended player or developer can't publish (`403 suspended`). Official items don't count toward a player's item cap or hourly publish rate. Every official action is in the project's audit log (`partii projects audit`): who (their developer account and their player), what, and the check's verdict.

**Players only ever get published versions.** A draft never reaches a player by any route: not the campaign, not `ugcGet`, not by hash (`404`). An official item that only has drafts is invisible to players until it's published.

**The campaign.** The game's first official world becomes its official campaign (the game setting `official_campaign`), unless the setting already points elsewhere. Change it with `partii games put <game> --field official_campaign=<item id>` (a role with `edit` or `publish_official`). Players load it with your key alone, no sign-in: `GET /v1/games/{game}/official/campaign` answers `{id, version, sha256, size, client_version, refs, download, updated_at}`, where `download` is the path of the file and `refs` the Levels it pins (all readable signed out). It's always the newest published version; players never pick one. Nothing set: `404 no_official_campaign`.

Example: tankii's admin edits the campaign in the game.

1. **Set roles.** The presets already work (admins publish, editors draft). Your own split: a `roles.json` with, say, `{"name": "lead", "caps": ["view", "publish_official", "edit_official", "full_game"]}` and `{"name": "level-designer", "caps": ["view", "edit_official", "full_game"]}`, then `partii roles set tankii --body @roles.json`. In the game, `GET /v1/games/tankii/me` tells it whether to show the editor's Save and Publish buttons.
2. **Save a draft from the game.** Upload the world and each Level it pins as for any player content (`ugcUploadStart`, then PUT). The first time, `POST /v1/games/tankii/ugc` with `{as: "official", kind: "world", title: "Campaign", sha256, client_version, refs: [level hashes], draft: true}`; it answers `{item, version: 1, status: "draft"}`. Keep `item.id`: it's the one campaign item, and every later version goes on it. After that, `POST /v1/ugc/{id}/versions` with `{sha256, client_version, refs, notes, draft: true}` saves version N+1 as a draft.
3. **Playtest the draft.** With a team member's player token, `GET /v1/games/tankii/official/campaign?draft=1` answers the newest draft (`draft: true`), or the live version when there's no newer draft. Download `download` and each of `refs` with the same token. `GET /v1/ugc/{id}?drafts=1` lists every version with its `state` (`published`, `draft`, `checking`, `refused`).
4. **Publish.** `POST /v1/ugc/{id}/versions/{n}/publish` makes draft `n` live (`publish_official`), through the content check: `{item, version: n, status: "published"}`. Or publish straight from the game: `POST /v1/ugc/{id}/versions` without `draft` (or the first `ugcPublish` with `as: "official"` and no `draft`).
5. **Players load it.** At start, `GET /v1/games/tankii/official/campaign` with the key; compare `sha256` with the cached file, and download `download` and any `refs` it doesn't have. Signed out works.
6. **Roll back.** `POST /v1/player/ugc/{id}/rollback` with `{}` republishes the previous live version's file as a new version N+1, so history only moves forward and players simply get the newest; `{to_version: n}` picks an earlier live version. It answers `{item, version, status}` and is audited.

Changing an official item's title, description, tags, thumbnail or visibility (`PATCH /v1/ugc/{id}`) and deleting it (`DELETE /v1/ugc/{id}`, which also clears the campaign setting if it pointed there) need `publish_official`; changed words and pictures pass the content check too.

### Partii's content standard and reports

Everything public on Partii keeps to [Partii's content standard](CONTENT-POLICY.md) (partii.games/content-policy): modest dress, no sexual themes or innuendo, clean language, and violence that serves the game (realistic shooters are fine; gore for its own sake, torture, sadistic violence and attacks on real people or groups are not). Your game, its store page, screenshots and site are yours to keep to it; Partii trusts developers and doesn't hold your game for an automatic review.

Anyone signed in can report a public game (`POST /v1/reports {kind: "game", id, reason}`; jams and profiles the same way). A report takes the game off the store and its site at once, and you get a notice naming the rule and what was seen: in your Partii notifications, by email, in `partii takedowns list` (`GET /v1/takedowns`) and on the game itself (`partii games get <id>` shows `status: "taken_down"` and `takedown`). Publishing and unpublishing wait while it's down. Change what breaks the standard, then ask for another look with `partii takedowns rereview game:<id>`; a person restores it when it's fine. A confirmed break is a strike: the second pauses publishing for 7 days, the third for 30, the fourth until Partii lifts it.

## 4. Sell it

```sh
partii games put mygame --project mystudio --title "My Game" --tagline "One line" \
  --description "What it is." --price-cents 499 \
  --field 'platforms=["macos","windows","ios","android"]' \
  --field 'demo={"free_levels":20}'                   # a free part; `demo=null` = no free part (the whole game is paid)
partii builds upload mygame --platform macos --version 1.0.0 --file MyGame.dmg   # optional for publishing; any size
partii builds upload mygame --platform windows --version 1.0.0 --dir dist/windows   # the build FOLDER: for the partii launcher (only changed chunks upload) plus the website zip
partii games publish mygame                           # now on the store (needs nothing else)
partii games sale mygame --percent 25                 # a week-long sale (or --starts-at/--ends-at, ms)
partii codes create mygame --count 10 --note press    # redeemable keys
```

**Every new version is reviewed.** Each stable build and web deploy waits for Partii's review before players get it (usually within a day), updates to approved games too; players keep the last approved version meanwhile. `partii builds list <game>` and `partii web list <game>` show each one's `review` (`pending` = In review, `approved`, `rejected` with a `note`, `team` for beta channels, which only your team installs and which aren't reviewed, `held` for a release you haven't released yet). Sign and notarize Mac builds: the Partii app marks installed games as downloaded, so macOS Gatekeeper refuses unsigned ones (details: docs/PATCHING.md "Review" and "Gatekeeper and SmartScreen").

**Release trains: upload now, go live when you say.** Add `--hold` to `partii builds upload` (each platform, `--dir` or `--file`): the version is reviewed as usual but doesn't go live, even once approved; `partii builds list` shows it `held`. Then:

```bash
partii builds release mygame --version 1.0.122                                   # every platform of 1.0.122, now
partii builds release mygame --version 1.0.122 --at 2026-11-14T07:00:00-07:00    # at 07:00 MST (Partii's 5-minute clock: on time at :00, :05, …)
partii builds release mygame --version 1.0.122 --platform windows                # one platform
```

It needs the `manage` capability (owners and admins). A version still in Partii's review answers 409 `waiting_for_review` and nothing goes live; release it once it's approved. Running it again is safe (`already_live`). For a web site: `partii web deploy mygame ./dist --hold` (same as `--no-activate`), then `partii web activate mygame <deploy>`.

**Platforms: what you say, and what players see.** `platforms` is what the game runs on, as you say it (macos, windows, linux, ios, android, web). Players never see that list. The store's badges and the launcher's "On …" line show `available`, which Partii works out from what's actually out:

- **macos, windows, linux:** a current stable build for that platform that Partii approved (`partii builds upload`, a file or a launcher folder). Beta channels, server builds and builds still in review don't count.
- **ios, android:** an App Store or Google Play listing, set as links in the store page: `--field 'store={"appstore_url":"https://apps.apple.com/…","play_url":"https://play.google.com/…"}'`. TestFlight and phone files uploaded as builds don't count.
- **web:** a live site that is the game (`partii web deploy`, and `web` in `platforms`). A site that's only a phone controller page isn't.
- **steam, epic, playstation, xbox, switch:** your game's page on that store, set as a link in the store page like the phone listings:

  ```sh
  partii games put mygame --field 'store={"cover":"…","steam_url":"https://store.steampowered.com/app/123/My_Game/","xbox_url":"https://www.xbox.com/games/store/my-game/9ABC","switch_url":"https://www.nintendo.com/us/store/products/my-game-switch/"}'
  ```

  | Field | Platform | Must be https on |
  | --- | --- | --- |
  | `appstore_url` | ios | `apps.apple.com` (or `itunes.apple.com`) |
  | `play_url` | android | `play.google.com` |
  | `steam_url` | steam | `store.steampowered.com` |
  | `epic_url` | epic | `store.epicgames.com` |
  | `playstation_url` | playstation | `store.playstation.com` |
  | `xbox_url` | xbox | `xbox.com` or `microsoft.com` (or a subdomain, e.g. `www.xbox.com`, `apps.microsoft.com`) |
  | `switch_url` | switch | `nintendo.com` (or a subdomain, e.g. `www.nintendo.com`) |

  Any other host, `http:`, or a link with a user name or port is refused with a 400 that names the field. `null` or `""` removes one. Remember that `store` is replaced as a whole: send your cover, screenshots and other links along with it.

**Store links on your game's page.** Partii's game page (partii.games and the Partii app) shows each platform in `available` as an icon. The App Store, Google Play, Steam, Epic, PlayStation, Xbox and Switch icons link straight to your page on that store ("Get Mygame on Steam"): partii.games opens it in a new tab, the Partii app in the player's browser. Mac, Windows, Linux and Browser stay plain icons, since the page's own Play or Download button covers them.

With nothing out yet, the page shows no platforms at all. **Phones that join a game on a screen** are a separate setting: `--field phone_controller=true` if phones join your game's rooms (docs/CONTROLLER.md). The store's game shape then carries your game's own site as `controller_url` (`https://<game>.partii.games`, deployed with `partii web deploy`; null until the site is live). In the Partii phone app your game's button is **Play**, and it opens the app's QR scanner: the player scans the QR code your game shows on its screen, and the app opens what it encodes full screen. It has nothing to do with iOS or Android builds.

**On a phone: one button per game.** The Partii phone app (its Home's "Play on your phone" list and the game's page) and partii.games in a phone's browser give every game one button, picked in this order. A Home row is your game's art, its title and that button: no tag, and Partii never says "controller" or "big screen" or asks the player how they want to play. Your game decides that (§6, "Your game decides what a phone is").

| Your game | The button | What a tap does |
| --- | --- | --- |
| Has its own app for this phone (`store.appstore_url` on iPhone, `store.play_url` on Android) | **Get the app** (**Open** once Partii has opened your app on that phone) | Tries `store.app_link` first: your app opens if it's installed. If it isn't, or you set no `app_link`, the App Store or Google Play listing opens (it shows Open itself when the app is installed) |
| A web game they can play (free, a demo, or theirs) | **Play** | Plays full screen right in the Partii app |
| Plays on a screen and takes phones (`phone_controller`, with a live site: `controller_url`) | **Play** (with a QR mark) | Opens the QR scanner. Scanning the code on your game's screen opens it full screen right in the Partii app (signed in automatically, told the safe-area insets) |

**What a scanned QR code opens** (the app's Home has the same scanner as **Scan to join**, with "Type a code instead" for a jam's code). Only what Partii's own screens show, nothing else: a jam's invite (`https://partii.games/j/<code>`, from the jam's Invite) joins that jam; an address on your game's own site (`https://<game>.partii.games/…` for a game in the store, or the same origin as your `controller_url`; for example `https://<game>.partii.games/c/<ROOM>?k=…&e=…&g=<game>`) opens your site in the app; a jam's own phone controller (the link `jam.phone()` gives, on the jam's `j-<id>.partii.games`) opens in the app too. Partii has no generic controller page: every game brings its own controller if it takes phones. Any other code opens nothing, and a toast says "That QR code isn't a Partii game". So put your room's QR on your screen as an address on your own site. The camera's frames never leave the phone; only the code's text is read.

A listing only for the other phone isn't a button: an iPhone skips a game that's only on Google Play and goes on to the next row of the table. Nothing matches: no button, just where it plays. On partii.games in a phone's browser, a game with a listing for that phone shows **Get it on the App Store** (or Google Play) first, linking straight to the listing, and its other buttons step down to secondary; the scanner row doesn't apply there (a phone's own camera app scans your QR code).

To have Partii open your app when it's installed, set `store.app_link` beside the listings:

```sh
partii games put mygame --field 'store={"appstore_url":"https://apps.apple.com/app/id123","play_url":"https://play.google.com/store/apps/details?id=com.me.mygame","app_link":"https://mygame.example/open"}'
```

- **Best: an https universal link** (iOS) / **App Link** (Android), on a domain your app claims (`apple-app-site-association`, `assetlinks.json`). On an iPhone Partii opens it only as a universal link, so it never lands in Safari: your app opens, or the App Store listing does.
- **Or your app's own scheme**, like `mygame://play`. The scheme is letters, digits, `+ . -`. iPhone opens your app or reports that nothing could, and then the listing opens.
- Never `http:`, `javascript:`, `data:`, `file:` or `partii:`; those are refused. `"app_link": null` removes it. Remember that `store` is replaced as a whole: send your cover and screenshots along with it.
- Partii can't ask a phone which apps are installed (iOS only lets an app check schemes it lists in advance), so the button says **Get the app** until your app has opened from Partii on that phone once. On Android Partii can't tell either, so a tap opens the Google Play listing, which shows **Open** when your game is installed.

**Regional prices, as on Steam.** You set one base price, in US dollars. Every pricing region (the euro countries, the UK, Japan, Brazil, India, Steam's lower-priced USD regions for Latin America, MENA, the CIS and South Asia, and about 30 more) then gets its own price in its own currency, automatically: Steam's recommended regional price for your base (the "multi-variable conversion" in Steam's pricing explorer, which weighs local spending power, what games cost there and the exchange rate), rounded the way prices look there: $19.99 is €19.49, £15.99, ¥2,800, R$63.99, ₹1,099, and $10.49 in Latin America. You don't have to do anything: a paid game is priced everywhere the moment it has a base price, and the regional prices move with the base when you change it. A sale's percent applies everywhere. Free stays free.

Buyers see and pay their region's price; Partii decides the region from where they are, never from what the client says. Russia and Kuwait aren't regions (Stripe takes no Russian payments, and a US Stripe account can't charge Kuwaiti dinars), so buyers there pay the base price, like any country that isn't listed.

You can override any of it:

- **Your own price for a region.** It wins over the recommendation and never changes by itself, even when the base does.
- **The base price for a region.** That region pays the USD base instead.
- **Regional pricing off.** Every region pays the base price. Your own prices are kept, and come back when you turn it on again.

```sh
partii games prices mygame                                       # every region: what it pays, set by (auto, manual or base), recommended, ≈ USD, % of base
partii games prices-set mygame --field 'prices=[{"region":"jp","amount":2500}]'  # your own price for a region
partii games prices-set mygame --field 'prices=[{"region":"eu","base":true}]'    # this region pays the base price
partii games prices-set mygame --field 'prices=[{"region":"jp","amount_minor":null}]'  # back to the recommended price
partii games prices-set mygame --field regional_pricing=off      # the base price everywhere (auto turns it back on)
partii games prices-recommend mygame                             # the recommended prices, and what going back to them would change
partii games prices-recommend mygame --field apply=true --field keep_manual=false  # every region back on the recommendation
```

Prices are in each currency's smallest unit (`amount_minor`: 1949 is €19.49, 2800 is ¥2,800) or, with `amount`, in the currency itself. The dashboard's **Pricing** tab (partii.games/dev) shows every region with its recommended price and who set it, and does all of this with buttons. Partii refreshes the recommendations from Steam's table now and then; recommended prices follow it, and yours stay put. Every sale is recorded in US dollars at what Stripe settled, so earnings and payouts stay in one currency.

**Sales.** Put a game on sale with a percent off and a start and end (`partii games sale mygame --percent 25`, or **Start a sale** on the dashboard's Pricing tab). The store and the launcher show the normal price struck through next to the sale price, in each buyer's own currency, with when the sale ends. Schedule one ahead with `--field starts_at=<ms>`; Hypers get one email when it starts. EU and UK law says a struck-through price must be the lowest price of the 30 days before the sale, so Partii keeps a few rules:

- A sale lasts at most 30 days, and can be scheduled up to 90 days ahead.
- The next sale starts at least 30 days after the last one ended. A sale ended early counts from when it ended; a scheduled one you cancel doesn't count.
- No sale starts within 30 days of a price rise, in any region.
- Prices are locked while a sale is on or scheduled. End the sale (`partii games sale-end mygame`) to change them.
- While a sale is on, `games sale` changes its percent or end, not its start.

`partii games prices mygame` shows `sale_rules`, with `earliest_start_at` for the next sale.

In the game, the player owns it if their entitlements say so:

```
GET /v1/players/me/entitlements?game=mygame
   → {entitlements: [{game, sku: "full", source}], signed}
```

Keep `signed` (it is valid for a week) so the game stays unlocked offline. While the player doesn't own the game, play only the free part.

**The free part, the same in every Partii game:** joining is always free (a player without the game can join a friend who owns it, on a phone or a second screen); hosting is paid (the demo shows HOST locked, with Buy); story and campaign games give the first 10–20% free. Describe it in `demo`, which the store page shows and the game reads:

```json
{"join_free": true, "free": ["Kids Mode", "Story chapter 1"], "story_chapters": 1, "kids_mode": true}
```

`join_free` and `free` (names of what's free) are shown on the store; `free_levels` shows as "The first N levels are free", and `unit` renames what it counts (`{"free_levels": 3, "unit": "missions"}` shows "The first 3 missions are free"; 1–20 letters and spaces, a plural; default `levels`); any other keys are the game's own. A game with a `demo` can be installed by anyone through the Partii app (the binary is the demo); the full game unlocks with `owns("full")`. `demo: null` means nothing is free and only owners install.

To unlock from inside the game:

- `acct.start_checkout()`, then `acct.take_checkout()` gives the URL to open in the browser (`Err("completed")` means the local fake store finished at once). Call `acct.refresh()` when the player is back; `acct.owns("full")` turns true.
- **Hear about the purchase right away** (a buy screen with a QR code, or a checkout in the browser): call `acct.watch_purchase(Duration::from_secs(15 * 60))` when the buy screen opens. Partii tells the game within about a second of the payment landing: `acct.take_purchased()` returns true once and `acct.owns("full")` is true, with no polling. Without partii-account, hold `GET /v1/players/me/entitlements/wait?game=mygame&timeout=25` open in a loop; it answers `{owned: true, entitlements, signed}` as soon as the player owns the game, or `owned: false` after the timeout.
- In the App Store or Google Play (Apple requires it for unlocking inside an iPhone app): buy with StoreKit 2 / Play Billing, then `acct.submit_receipt("appstore", json!({"transaction": id}))` and wait for `acct.take_receipt()`; finish the store transaction only after `Ok`. For restores, submit each of StoreKit's current entitlements the same way. TestFlight and App Review buy in Apple's sandbox; those purchases unlock too (marked as test purchases).
- Purchases made in the App Store, Google Play or Steam: send them to `playersReceipt`. Partii verifies them with the store.
- **Google Play:** set your app and the one-time product that unlocks the game on the store page: `--field 'store={…,"play_package_name":"com.me.mygame","play_product_id":"com.me.mygame.full"}'` (`store` is replaced whole, so send the keys you already have too; `partii games get mygame` shows them). Buy with Play Billing, then `acct.submit_receipt("play", json!({"purchase_token": token, "product_id": "com.me.mygame.full"}))`. Partii looks the token up as your app and product only (a `product_id` that isn't the game's is refused, never trusted), records the price Play lists for the buyer's region, and acknowledges the purchase if your app hasn't yet (acknowledge in the app too: Play refunds what nobody acknowledges within 3 days). Refunds, chargebacks and revoked purchases are picked up within an hour (Play's voided purchases) and the game goes back, as with any refund. In the Play Console, invite Partii's Play service account (ask support@partii.games for its address) to your app with "View app information", "View financial data, orders, and cancellation survey responses" and "Manage orders and subscriptions".

Test without paying:

```sh
partii test players create --name Tester            # → player id + player_token
partii test purchase --game mygame --player p_...   # Stripe test mode, or the fake store locally
partii sales mygame                                  # purchases and totals (gross_cents counts real sales only; test purchases are test_count)
```

Uploads go straight to storage: the CLI gets a signed URL (`buildsUploadStart`), PUTs the file with its sha256 (storage refuses bytes that don't match), then records it (`buildsUploadFinish`). Locally, `partii dev` takes the file through the API instead; the command is the same.

Body fields are also flags: `--price-cents 500` and `--field price_cents=500` are the same; use `--field` for JSON values (lists, objects, `null`).

### Privacy policy and account deletion for app stores

Every game needs its own privacy policy. Google Play rejects an app whose policy "does not clearly identify the app, developer name, or legal entity" of its listing, so don't give it the generic partii.games/privacy. Partii makes one for each game, as plain HTML that reads fine with no JavaScript:

- `https://<game>.partii.games/privacy`: the privacy policy. It names the app (its title), the developer, the legal entity and the privacy contact, says what the game sends to its own servers (`store.data` plus your own section) and how to delete an account, then gives Partii's privacy policy in full (what Partii keeps for the game as its platform and processor, Partii Games LLC).
- `https://<game>.partii.games/delete-account`: how to delete an account (in the app: **Settings > Delete account**; on the web: partii.games/delete-account; or by email, also for guests), and what's deleted and what's kept.

Set the names to match your store listings exactly, then paste the two addresses into Google Play (App content > Privacy policy, and Data safety > Delete account URL) and App Store Connect (Privacy Policy URL):

```sh
partii games privacy-set mygame --legal-entity "Mystudio LLC" --developer-name "Mystudio" --contact-email privacy@mystudio.com
partii games privacy-set mygame --publisher "Mystudio, a brand of Mystudio Holdings LLC"   # optional: a free-text publisher line, shown as is
partii games privacy-set mygame --extra @privacy-extra.md     # optional: markdown about data your own servers keep
partii games privacy mygame     # privacy_url, delete_account_url, what the pages show, and todo
```

- Until `legal_entity` is set the pages say it hasn't been provided yet, and `partii games get`, `partii games privacy` and `partii games publish` list `privacy policy: set your legal entity`. The developer defaults to your project's name and the contact to support@partii.games.
- `partii games get`, `partii games list` and the store page (`storeGame`) report `privacy_url` and `delete_account_url`.
- Your own pages win: a `privacy` or `delete-account` page on your site (`privacy.html`, or `privacy/index.html`; section 7) is served instead of Partii's (`partii games privacy` shows `served: site`). Make sure yours names the same app, developer and legal entity.
- The pages go live with your game: once it may be public (a trusted developer, or approved by Partii's review), like its site.

### Store page media: trailer, screenshots, GIFs

A game's page on partii.games works like a Steam page: the trailer in a big player at the top, a strip of thumbnails under it (the trailer's, then every screenshot in your order; click one, or use ‹ ›, the arrow keys, or a swipe on a phone), and the description below with your GIFs in it.

**Upload each file.** The type comes from the bytes: PNG, JPEG or WebP pictures and GIFs (or animated WebP/PNG) up to 10 MB each, MP4 or WebM video up to 500 MB. `media-upload` sends a video straight to storage (signed upload, sha256 checked), so a big trailer is fine; anything else goes in one request (at most 95 MB). `--name` becomes the alt text.

```sh
partii games media-upload mygame --file trailer.mp4 --name "Trailer"          # {media: {id, kind: "video", url, review}}
partii games media-upload mygame --file shots/01-desert.png --name "Desert"   # kind "image"
partii games media-upload mygame --file bankshot.gif --name "Bank shots"      # kind "animated"; media.markdown is ![Bank shots](url)
partii games media mygame                                                      # everything uploaded, with url, markdown and review.status
partii games media-delete mygame <id>                                          # also takes it off the page
```

**Every upload is reviewed** against [Partii's content standard](CONTENT-POLICY.md) before anyone sees it, like a jam's store pictures: a picture as itself, a GIF or video by frames from across all of it. `review.status` is `pending` (usually a few minutes), `ok` (public), `held` (a person looks first) or `removed`. Until it's `ok`, Partii serves nothing and the store leaves it out wherever your page uses it, so you can set the page right away.

**Then point the page at the URLs** (`store` is replaced as a whole: send all of it):

```sh
partii games put mygame --description @description.md \
  --field 'store={"cover":"<header url>","trailer":"<trailer url>","screenshots":["<url 1>","<url 2>","<url 3>"],"background":"<page background url>"}'
```

- `store.trailer`: first in the gallery, played with sound and controls, never by itself (it streams; its poster is `store.trailer_poster`, else the first screenshot). A YouTube link works too (YouTube's privacy-enhanced player).
- `store.screenshots`: in the order the strip shows them. 1920x1080 is best; the page shows resized copies, never your originals.
- `store.cover`: the header image on cards and the top of the page. `store.background` (optional): the dimmed picture behind the page, else the cover.
- `store.icon` (optional): the game's square app icon, for the buy sheet, purchase emails and small square tiles (cards and the top of the page keep the cover). It must be one of the game's own uploads, a still PNG, JPEG or WebP, square and at least 256x256 (1024x1024 is best); `games put` refuses anything else. Without one, those places use the cover. `null` removes it.

**The cover in one step.** `games cover` uploads the picture and sets `store.cover`; `games background` does the same for `store.background`, and `games icon` for `store.icon` (it checks the picture is square, at least 256x256, before uploading). Each reads your game's current `store` and writes it back with only that one field changed, so screenshots, the trailer and store links stay as they are. `--dry-run` shows what `store` would become without uploading anything.

```sh
partii games cover mygame --file art/cover.png          # PNG, JPEG or WebP, up to 10 MB; 16:9, about 1920x1080
partii games background mygame --file art/backdrop.jpg  # the dimmed picture behind the page
partii games icon mygame --file art/icon.png            # the square app icon: 1024x1024 is best, at least 256x256
```

It's reviewed like any upload, so it shows on the store once its review is `ok` (`partii games media mygame`). The buy sheet shows an item's own picture, else the game's icon, else its cover.
- **The description is markdown:** paragraphs, lists, `**bold**`, links, and pictures with `![alt](url)`. Pictures show only when they're this game's own uploads (the `markdown` from `media-upload`), at their own size up to the column width. Any other image is left out, and `games put` answers with `warnings` saying so (and naming uploads still in review).

With the API: `PUT /v1/games/{game}/media?name=…` (the body is the file), or for a big video `POST /v1/games/{game}/media/uploads {type, size, sha256}` → PUT the bytes to `upload.url` with `upload.headers` → `POST /v1/games/{game}/media/uploads/{id} {type, size, sha256, name}`. `GET /v1/games/{game}/media`, `DELETE /v1/games/{game}/media/{id}`.

### Builds for the Partii launcher

Upload the unzipped build folder with `--dir`. The launcher installs and patches from it, downloading only what changed between versions. The same command also uploads a zip of the folder as a plain `file` build (`--no-zip` skips that): Partii's release review and your team can open it, but players never download it from the website.

- The CLI splits files into chunks and only uploads chunks Partii doesn't have yet. A small patch to a big game uploads a few MB.
- **What to run** is guessed (the only `.app` on macOS, the only `.exe` on Windows, the only executable on Linux, at the top level or one folder down). Say it with `--launch <path inside the folder>` when there's more than one.
- Partii signs every build's manifest, and the launcher checks every file's hash. How it works: [PATCHING.md](PATCHING.md).
- **Script injection:** Partii scans every build you upload (launcher builds, files, web deploys) for code that injects script into web pages. A game must never run its own script inside Partii's pages: open the buy sheet (`partii.games/buy/…`) in the system browser (what `account.buy()` does), or in a plain webview that adds no scripts to partii.games pages (no `WKUserScript` / `evaluateJavaScript`, WebView2 `AddScriptToExecuteOnDocumentCreated` / `ExecuteScript`, Android `evaluateJavascript` / `addJavascriptInterface`, Tauri initialization scripts or `eval`, Electron preload or `executeJavaScript` on those pages). A game that buys for a player without their permission is removed and its developer banned.
- **Storage:** chunks stay as long as some build listed in `partii builds list` uses them. Delete builds you no longer need (`partii builds delete <game> <build>`); Partii's operators then collect their unused chunks, never touching anything uploaded or reused in the last 24 hours.

### How players install

Players install games only through the Partii app (since 2026-11-09 the website never offers a game's files). A game's store page shows one big **OPEN IN PARTII** button, a `partii://game/<game id>` link that opens the app at that game's page, where Install or Play does the rest. When the app doesn't open (it isn't installed), the page offers Partii for their computer, then the same button again. On an iPhone the button opens the Partii app; on other phones the page says the game plays on Mac or Windows. Games that play in the browser keep **Play in your browser**. The store page has no install steps of its own: put what players should know (controls, system requirements, phones joining) in the description.

Under the button a line says what the app does: "Install with the Partii app. It keeps the game up to date." On Linux, where Partii isn't out yet, the page says the game installs with the Partii app on a Mac or Windows PC.

**No website downloads.** `storeDownload` and `storeDownloadLink` answer players `410 launcher_only` ("Games install through the Partii app: https://partii.games/download"). Only your project's team (your test players, or a player signed in with a team member's developer email) still gets the latest approved stable `file` build with `partii store download` or `partii store download-link`, to check what was approved. To get exactly what a player's app installs, headlessly (agents, QA), use `partii store install <game> --out <dir> [--platform macos|windows|linux] [--channel <channel>]`: the signed launcher build, checked like the app checks it ([PATCHING.md](PATCHING.md), "Installing headlessly"). `partii instructions` still stores per-platform install steps, but the store no longer shows them.

### Your game's output: launch logs

The launcher writes everything your game prints (stdout and stderr, in one file) to a log per launch, since 2026-11-12:

| OS | Folder |
|---|---|
| macOS | `~/Library/Logs/games.partii.launcher/games/<game>/` |
| Windows | `%LOCALAPPDATA%\games.partii.launcher\logs\games\<game>\` |
| Linux | `~/.local/share/games.partii.launcher/logs/games/<game>/` |

Each file is named for the launch's start in UTC (`2026-11-12T01-30-05Z.log`), opens with a `[partii]` line (game, version, platform, pid) and ends with one saying how it exited (code or signal) and after how long. The last 10 launches per game are kept; each file stops at 20 MB (a `[partii]` line says the rest was dropped; the game is never slowed or blocked by its logging). In the app: the game's gear menu, **Show logs**. Logs stay on the player's machine: ask a tester to send you the file. Print what helps you debug (connection state, room codes, errors), never tokens: `PARTII_LAUNCH_TICKET` and player tokens must not reach stdout.

### Steam keys for Partii buyers

If the game is also on Steam, people who buy it on Partii can get it on Steam too. Request keys in Steamworks (Users & Permissions › Request Steam Product Keys), then load them:

```sh
partii steam-keys add mygame --keys @keys.txt --batch "2026-10 request"   # one key per line; duplicates are skipped
partii steam-keys list mygame                                            # counts, and who has which key
partii steam-keys list mygame --status revoked                           # refunded: ban these in Steamworks
partii steam-keys remove mygame --keys @unused.txt                       # take unassigned keys back out (they never come back)
partii steam-keys settings mygame --low-water 30                         # alert level (default 50; 0: never alert)
```

Each player who owns the game through Partii (a purchase, a grant or a code, but not an App Store or Steam purchase) gets one key, once: buying again, a retried payment notice or a resent email always gives the same key, and two buyers never get the same one. The key comes **by email**: in the purchase receipt for a card purchase, or in its own "Your Steam key" email for a grant or a code. It also shows in their Partii library and on the game's page with an **Activate on Steam** button (`https://store.steampowered.com/account/registerkey?key=…`). A game can show it too: `GET /v1/store/games/{game}/steam-key` with the player's token. A refund, or `partii entitlements revoke`, marks that player's key revoked; ban it in Steamworks. A revoked or removed key is never given to anyone again. Keys are encrypted at rest, never logged, and shown only to their player and to you.

**Running low.** When fewer keys than the game's alert level are free (default 50; set it with `partii steam-keys settings`), you and your team members who manage the game get a notification and an email, once each time the pool drops below the level (it re-arms when you're back at or above it). **Running out** never stops a sale: the buyer gets the game, their receipt says the key is on its way, and they wait in line. When you add keys, the line gets them first, oldest first, each by email (`steam-keys add` answers `delivered` and `waiting`; Partii's hourly sweep finishes a line longer than 100). `partii steam-keys list mygame` shows the counts (available, assigned, revoked, removed, waiting), the alert level and whether the alert is out. Follow Valve's Steam Keys rules: don't sell keys for less than the Steam price for long.

### Steam owners get it on Partii

People who own the game on Steam can get it on Partii free: they link Steam once (in the launcher's Library, or on partii.games/library) and Partii asks Steam whether that account owns the game. Set it up with your Steamworks publisher Web API key and the app ids that count (the full game: not the demo or playtest):

```sh
partii secrets set mygame steam.web_api_key --value -          # paste the key on stdin
partii secrets set mygame steam.owned_app_ids --value 4485010
```

- Owners get an entitlement with `owned_via: steam` (`partii entitlements list mygame` shows `source: steam`). Family Sharing borrowers don't count.
- Partii checks at each Steam sign-in and link, rechecks at most once a day when the player's library loads or the game asks for entitlements, and when they press "Check Steam" (`partii store steam-sync` with a player token). If Steam stops reporting ownership (a refund), only the Steam-granted copy goes away; a purchase on Partii is never touched. When Steam doesn't answer, nothing changes.
- Steam-granted copies don't get a Steam key (they already have the game there).

### Patch notes

Post each version's player-facing notes (markdown) right after you upload its builds. Publishing a version again updates it, so a pipeline can run this every time:

```sh
partii notes publish mygame 1.2.0 --markdown @notes.md            # title: "<Game> 1.2.0"; --title, --date YYYY-MM-DD optional
# → {"url": "https://partii.games/games/mygame/updates/1.2.0", "index_url": "https://partii.games/games/mygame/updates", …}
partii notes list mygame                                          # newest first: version, title, excerpt, url
partii notes delete mygame 1.2.0
```

Give each post its own picture (a screenshot of the headline feature): it's the hero at the top of the page, the thumbnail in the list, and the image in link previews (Discord, Slack, …). Without one, the game's cover is used.

```sh
partii notes image mygame 1.2.0 --file shot.jpg      # JPEG, PNG or WebP, at most 2 MB; 16:9 works best. Uploading again replaces it.
partii notes publish mygame 1.2.0 --markdown @notes.md --image https://cdn.example.com/shot.jpg   # or link one; publishing again without --image keeps it
```

Staging notes for a release train: `--hold` saves them without showing them to players; they go public with the version's build (`partii builds release`, now or at its `--at` time), with `notes release`, or when you publish them again without `--hold`. `--at` makes them public at a set time instead (the store shows them within about 15 seconds of it, or sooner if the build is released first).

```sh
partii notes publish mygame 1.2.0 --markdown @notes.md --hold                          # staged
partii notes publish mygame 1.2.0 --markdown @notes.md --at 2026-11-14T07:00:00-07:00  # public then
partii builds release mygame --version 1.2.0     # the build and its staged notes go live together (notes_released: true)
partii notes release mygame 1.2.0                # or release the notes on their own
partii notes get mygame 1.2.0                    # with your developer token: staged notes too, with held, release_at and public
```

Without a token (or for someone else's game) staged notes are 404 and missing from `notes list`, as for players.

`url` is a public page (no sign-in needed) to link from Discord or a launcher. The game's store page shows the latest one and links to all of them. The notes render headings, bullet and numbered lists (nested), **bold**, *italic*, `code`, links and images (https URLs only). One `## <version>` section of a CHANGELOG.md, without its heading line, is a good body. In the CLI, any text flag's `@path` reads a file (`@@` for a literal @).

### Hype (the wishlist)

Players Hype a published game on partii.games or in the launcher. The count shows on the game's page (`hype` in `storeGames` and `storeGame`). Everyone Hyping it gets one email when it launches and one per sale, so a game can go on the store before its first build and collect Hype:

- **Launch:** the first stable build of any kind (`builds upload`, `--dir`, or the direct upload), when Partii approves it.
- **Sale:** `partii games sale <game>`, when the sale starts (a scheduled one within the hour of its start). One email per sale: changing it doesn't send another.

```sh
partii games hype mygame --days 30     # {hype, daily: [{day, new}], notices: [{event, sent}]}: the count, new Hypes per day, emails sent
partii store hype mygame               # as a player (key + player token): Hype; `store unhype` stops; `store hyped` lists yours
```

### Who's playing: live counts and gameplay clips

Every store card shows Hype and how many people are playing right now. `playing_now` is in `storeGames` and `storeGame`: the people in your game's live rooms (`room` connections under your project, with that game) and hosted matches. Jams count the distinct people in the jam (`jamsLive`). The numbers come from one aggregate refreshed about every 20 s, so they lag a little and never cost your rooms anything.

- **Order:** `GET /v1/store/games?sort=playing` puts the most played first (ties by Hype); the default stays `recent`. `jamsLive` is `playing` by default (`?sort=recent` for the old order). partii.games and the launcher show the most played first.
- **Who:** `GET /v1/store/games/{game}/live` (`partii store live <game>`) gives `{playing_now, people, more, you_playing}`. Without a player token it's the count only. With one, `people` lists up to 4 of the player's friends (mutual follows) in the game by name and avatar, and `more` is everyone else. Strangers are never named; ids never leave Partii. Public jams also name their owner.
- **Single-player and offline play:** a game played on its own (no Partii room) counts too, with a heartbeat from the player's account. While the player is actually playing, send `POST /v1/player/playing` (player token + publishable key, as every player call) every 60 s, and `stopped` when play ends:

  ```sh
  curl -X POST https://api.partii.games/v1/player/playing \
    -H "authorization: Bearer $PLAYER_TOKEN" -H "x-partii-key: $PARTII_KEY" -H "content-type: application/json" \
    -d '{"game":"mygame","state":"playing"}'     # every 60 s while playing; "stopped" when they stop
  partii player playing --field game=mygame --field state=playing
  ```

  - **Cadence:** one `playing` every 60 s. Each lasts 150 s, so a player whose game quit or lost the network drops out within two and a half minutes; `stopped` removes them at once (the store's count catches up within about 30 s, like every count). At most one `playing` per 20 s per player: more get `429 rate_limited` with `retry_after_ms`. A `stopped` lets the next `playing` through right away (a new run).
  - **Only while playing:** never for a paused game, the title or home screen, menus, or a player who has gone idle. Stop when the window loses focus for long, and start again when they're back in play.
  - **Only with consent:** send only while the player's **Share anonymous stats** switch is on (on by default; the same switch as analytics). Off means no heartbeats at all.
  - **Counted once:** `game` must be a game in your key's project (anything else is `404`). A player in one of the game's rooms who also sends heartbeats counts once.
  - **Privacy:** heartbeat players are counts like everyone else; only their friends (mutual follows) see them by name in `storeGameLive`. Ids never leave Partii.
  - **Cost:** most heartbeats are answered at the edge; Partii writes a session only when it starts, stops or is about to lapse.
- **Clips:** a store card and the game page's media viewer loop a short muted clip of your game. Set `store.clip` to an https WebM, MP4 or animated WebP (a few seconds, small: under 2 MB is best), or `store.trailer` if it's a video file. The cover is the poster. Clips play while on screen (at most 6 at once) and stay still with reduced motion. A game page with a trailer and screenshots shows its media gallery instead (Store page media).
- **Jam clips:** while the owner or a builder has a jam open, the launcher records about 4 s of its game every few minutes and sends it with `PUT /v1/player/jams/{jam}/clip` (multipart `clip` + `poster`, up to 1.5 MB and 256 KB, 6 an hour; no CLI command, `curl -F clip=@c.webm -F poster=@p.jpg`). `partii player jam-clip-remove <jam>` removes it. Members always see their jam's clip; a public card shows it only after its poster passes review.

### Earnings: your share, referrals and payouts

**Status:** this runs on staging. Production turns it on after Stripe Connect is set up there; until then these commands answer `not_available`. [PAYOUTS.md](PAYOUTS.md) has the whole money flow.

**How a sale splits.** For each Partii sale (Stripe), the ledger records:
- **Stripe's card fee:** the real one, from Stripe. You pay it.
- **Partii's 10%** of the price.
- **The referral commission,** when a referrer brought the buyer. It comes out of your share.
- **The rest is yours.** A $5 sale with no referral: Stripe about $0.45, Partii $0.50, you $4.05.

**When you're paid.** Earnings wait **14 days** (the refund window). After that, Partii transfers them to your Stripe account once they reach **$50**.

**Refunds.** A refund reverses the sale: Partii returns its 10% and the referrer loses the commission. Stripe keeps its fee, so you carry it.

Players can refund a game they bought on Partii themselves (**Request refund** on its page and in their library) while both are true: they bought it less than 14 days ago, and they've played it for less than 2 hours. Each player can do this once per game; a copy bought again after a refund can't be refunded this way. App Store, Google Play and Steam purchases refund through that store; grants, codes and test purchases can't be refunded. Play time is what the Partii launcher reports while your game runs, plus your game's own `POST /v1/player/playing` heartbeats. `partii store refund-status <game>` shows a player's answer and why not (reason codes in [API.md](API.md), `storeRefundStatus`).

**Referrals.** Any signed-in player can share a game's link. A buyer who follows it belongs to that referrer for 30 days; the first referrer wins. Their purchase pays the referrer your game's referral percent, also after the 14 days. Your own team's links and buying through your own link pay nothing. Referrals are off until you set a percent.

```sh
partii games referral mygame --percent 10      # referrers earn 10% of each sale they bring (0 turns it off; max 40)
partii payouts onboard myproject               # project owner: a Stripe link to set up where your money goes
partii payouts status myproject                # account, balance (pending / available / paid), per-game split, payouts
partii referrals link mygame                   # as a player: your link (partii.games/games/mygame?ref=<code>)
partii referrals stats                         # as a player: links, buyers you hold, earnings, payout account
partii referrals onboard                       # as a player: set up how you're paid (Stripe)
```

Players also find all of this on partii.games under **Earnings**, and **Share** on every game page copies their link.

## 5. Live content

```sh
partii content push mygame --version 2026.10.12 --field 'files={"levels/1.json":"<base64>"}'
```

Games read `GET /v1/content/{game}/manifest` at launch and fetch changed files by hash (`contentFile`). Levels, tuning and scripts update without a store release.

## 6. Phone controllers

**Your game decides what a phone is.** Partii never asks a player "controller or player": people just join (on a phone, by scanning the QR code on the screen), and your game, or Lindii building it, picks what happens next:

1. **A controller.** A party game in front of one screen makes every phone a gamepad (this section).
2. **A player.** The game plays on the phone itself, and works that out on its own.
3. **The player's choice.** If you want to offer both, ask in your own game's UI.

**Which bucket is your game in?** Where people look (one shared screen, each their own, or either) and what the phone is (a pad, a private screen, or the whole game) sort every game into five buckets; a game made in a room says its bucket in partii.json `"screens"`, and a shared-screen game's PLAY on a phone opens its pad with how to join. See [docs/GAME-BUCKETS.md](GAME-BUCKETS.md).

Partii provides the pieces (rooms, the QR join, the controller page, input frames, seats), not the decision.

When the game hosts a room, show a QR code for:

```
<controller page>/c/<ROOM CODE>?k=<publishable key>&e=<platform URL>&g=<game id>
```

Each game builds its own controller page: controllers need the game's own states, layouts and art. Start from `platform/apps/controller` (sticks, buttons, joining, sign-in; React + the engine's wasm) and host yours with `partii web deploy <game> ./dist --spa` (§7), so the QR code points at `https://<game>.partii.games/c/<CODE>?…`. The phone joins as a member of kind `phone` and streams input frames (10 bytes, about 30 times a second; [CONTROLLER.md](CONTROLLER.md)):

```rust
// In Event::Message from a phone member:
if bytes.len() >= 9 && bytes[0] == 0x50 {
    let lx = bytes[3] as i8 as f32 / 127.0;          // left stick, -1..1 (+y down)
    let ly = bytes[4] as i8 as f32 / 127.0;
    let rx = bytes[5] as i8 as f32 / 127.0;          // right stick
    let ry = bytes[6] as i8 as f32 / 127.0;
    let buttons = u16::from_le_bytes([bytes[7], bytes[8]]); // 1 primary, 2 secondary, 4 start
}
```

**Reloads.** Keep the page's `conn` per room code in `sessionStorage` and pass it in the engine config (`connFor` in `apps/controller/src/engine.ts`): a reload within 20 s comes back as the same member (`Resumed`, and a `join` of the same code returns the same seat). With the away grace (`caps: ["away"]`, §2 "Away"), the same resume works for the room's `away_grace_ms` (30 s by default) after the phone went to the background. On `room_closed` with reason `host_lost`, keep retrying the join every few seconds for up to 10 minutes: the game may be taking its code back.

Tell the phone its seat so it can colour itself: `engine.send(mid, true, br#"{"t":"seat","label":"P2","color":"#3B82F6"}"#.to_vec())`. Rename its buttons with `{"t":"layout","buttons":["JUMP","GRAB"]}`, and add a Start (bit 2) with a button of `"kind":"start"`: Partii's controller page draws only the player pill and the leave × itself.

Make the page look like your game with a theme (colours, fonts, button lips, logo): `partii theme set <game> --body @theme.json` after uploading its files with `partii theme file`. The format is in [CONTROLLER.md](CONTROLLER.md#looking-like-the-game).

## 7. Host a site: browser games and controllers

Any static folder (a browser build of the game, a phone controller, a page) goes online at `https://<game>.partii.games`:

```sh
partii web deploy hexii ./dist                    # live at https://hexii.partii.games once Partii approves it
partii web deploy tankii ./controller/dist --spa  # client-side routes (/c/CODE) serve index.html
partii web deploy hexii ./dist --no-activate      # upload, preview at the preview_url, then:
partii web activate hexii <deploy id>             # go live (an approved deploy at once: also how you roll back; one in review when approved)
partii web list hexii                             # deploys, which is live, preview links
partii web take-down hexii
```

- The folder needs `index.html` at its top. Dotfiles are skipped, except a top-level `.well-known` (iOS universal links, Android app links). Up to 10,000 files, 100 MB each, 1 GB per deploy.
- Only changed files upload (files are stored by their hash), straight to storage.
- `--spa`: a path with no file serves the nearest `index.html` above it, so `/controller/c/ABCD` gets `/controller/index.html`.
- `--isolated`, or `"threads": true` in the site's `partii.json`: cross-origin isolation headers on every file (COOP, COEP, Document-Isolation-Policy and CORP cross-origin: docs/THREADS.md), which `SharedArrayBuffer` and threaded wasm need (Godot 4, Unity with threads, Emscripten pthreads). Everything on the site must then be same-origin or CORS-enabled. It then has shared memory in Partii's frame in Chrome and Edge on a computer, in the Mac and iPhone apps (1.2.4 and later play it at the top of a view of its own), and as its own top page in any browser. Older apps and Android don't isolate it framed ([THREADS.md](THREADS.md#site-games-partii-web-deploy-and-the-desktop-apps-game-window)); check any surface with https://partii.games/probe/threads.html.
- `/privacy` and `/delete-account` are your game's privacy policy and account deletion pages ("Privacy policy and account deletion for app stores" in section 4): Partii's generated ones unless the folder has its own (`privacy.html` or `privacy/index.html`, likewise for `delete-account`), which then win, even with `--spa`.
- `404.html` at the top is served for missing pages. Unity's `.br`/`.gz` build files are served with the right encoding.
- HTML is revalidated on every load; other files are cached for a minute, so a new deploy shows up within a minute.
- Each game's site is its own origin. Call the Partii API from it with your publishable key like any web app (`https://api.partii.games`).
- Staging: `https://<game>-staging.partii.games` (with `PARTII_API=https://api-staging.partii.games`).

### Which key and API a site uses

A site game runs at several addresses: `https://my-game.partii.games` (production), `https://my-game-staging.partii.games` (staging), each deploy's preview (`https://<deploy>--my-game.partii.games`), and your machine during tests. Each platform has its own publishable key, so build both keys into the game (they aren't secrets: they only name the project) and let the address pick. The SDK does it (`sdk/ts/src/site.ts`, at partii.games/docs/sdk-ts/site.ts; no imports, copy it beside `client.ts`):

```ts
import { siteConfig } from "./partii/site";              // sdk/ts/src/site.ts
import { createClient } from "./partii/client";
const cfg = siteConfig({
  "my-game.partii.games": "pk_mystudio_web_...",         // partii keys create mystudio --key-id web
  "my-game-staging.partii.games": "pk_mystudio_web_...", // the same, with PARTII_API=https://api-staging.partii.games
});
// cfg: {game: "my-game", api, key, env: "prod" | "staging" | "local", preview, host} | null
const api = cfg ? createClient({ base: cfg.api, key: cfg.key }) : null;   // null: no key for this address, Partii stays off
// the room engine: new WebEngine(JSON.stringify({ edge: cfg.api, key: cfg.key }))
```

- **Previews:** a `<deploy>--` prefix is stripped before the lookup, so a preview uses its site's key (`cfg.preview` is the deploy id).
- **The API:** `https://api-staging.partii.games` for any address ending in `staging.partii.games`, `https://api.partii.games` otherwise.
- **The game:** from the address (`my-game` from `my-game.partii.games` or `my-game-staging.partii.games`). On your own domain, map that address too and pass `{game: "my-game"}`.
- **On your machine** (`localhost`, `127.0.0.1`, `*.localhost`) the address says nothing, so the page's query does, and only there: `?partii=staging` or `?partii=prod` uses that address's key and API; `?partii_key=…&partii_api=…` (what `partii test room` adds) uses those; `<game>.localhost:8787` (a `partii dev up` site) looks up its own address and talks to `http://127.0.0.1:8787`. With nothing in the query it's null.
- **Tests:** `siteConfig(keys, {override: {api, key, game}})` wins over everything; `{location: {hostname, search}}` stands in for the page's address.

Godot games do the same by hand (Smashii's `Util/PartiiBoot.gd`: the same map, the same preview rule, `?partii=staging` on localhost).

## 8. Analytics: players, events, errors

The account crate sends events and error reports; partii.games/dev shows them (sign in with a developer token, `partii tokens create`).

```rust
partii_account::install_panic_hook(&save_dir);   // first thing in main
let acct = Account::start(AccountConfig {
    version: env!("CARGO_PKG_VERSION").into(),
    build: "steam".into(),                        // or "demo", "appstore", …; platform is filled in
    analytics: settings.share_stats,              // the player's "Share anonymous stats" switch (on by default)
    ..cfg
});
acct.set_owned(acct.owns("full") == Some(true)); // the dashboard's demo/full filter
acct.track("level_complete", json!({ "mission": 12, "secs": 81.5, "players": 2 }));
acct.report_error("error", "save failed", None, json!({ "screen": "pause" }));
acct.end_session(Duration::from_secs(2));         // on quit: session_end {secs}, then send
```

| Call | |
|---|---|
| `track(name, props)` | Queue an event. Names are `[a-z][a-z0-9_.]*`, at most 48 characters. Props are flat: keys of `[A-Za-z0-9_]` (1-40), values strings up to 200 characters, numbers and bools, 1 KB in all. An event that breaks a rule is dropped without an error (the reply only counts it): see API.md, "What the server silently drops". Sent every 30 s. |
| `report_error(kind, message, backtrace, context)` | `kind` is `panic`, `error` or `warning`. Sent at once. Reports of the same bug group together, even when the numbers in the message differ. |
| `install_panic_hook(dir)` | Writes panics to `dir`. A panic is reported straight away if the game survives it, otherwise at the next launch. |
| `set_analytics(on)`, `set_owned(full)` | The player's switch (off drops what's queued). Demo or full game. |
| `end_session(wait)` | Sends `session_end` and the queue, waiting at most `wait`. Returns `true` when everything went. Whatever is left (for example while offline) is kept on disk and sent next launch. |
| `session_id()` | This launch's id; every event and report carries it. |

The dashboard and the CLI show the same numbers. The CLI takes the same filters: `--days`, `--platform`, `--version` and `--owned true|false`.

```sh
partii analytics summary tankii                      # players today, last 7 and last 30 days; new vs returning; sessions and median length; D1/D7/D30 retention; by platform, version and country
partii analytics events tankii                       # every event name, with counts and players
partii analytics events tankii --name level_complete --by mission   # the funnel: players per mission
partii errors list tankii                            # open error groups: count, players, versions, last seen
partii errors get tankii <fingerprint>               # the latest reports, with backtraces and context
partii errors mark tankii <fingerprint> --status fixed   # reopens by itself if it comes back
```

- **Sessions** are one launch each. Their length comes from `session_end` (from the first to the last event if the game was killed).
- **Retention:** of the players first seen in the range, the share who played again exactly 1, 7 or 30 days later.
- **Privacy:** no IP addresses are stored, only the country. Raw events are kept 90 days. A device is the game's random install id. If the player deleted their account, their events stay but no longer link to them. What's collected is listed at partii.games/privacy; link to it from your game's settings next to the switch.
- **Limits:** 100 events and 20 errors per call, and 60 calls a minute per device. The crate stays well under these.
- **Dropped, not refused:** a bad event name or prop drops that event with a 200 answer (`dropped` counts it), and a bad `session`, `version`, `build` or `platform` is stored blank. The full list, with leaderboards and errors, is API.md "What the server silently drops". Web games: [partii-examples](https://github.com/PartiiGames/partii-examples) `06-analytics` checks events before sending them.

## 9. Errors

Every failure is `{"ok": false, "error": {"code", "message", "hint"}}`, and the hint says what to do. CLI exit codes:

| Exit | Meaning |
|---|---|
| 0 | ok |
| 1 | the platform said no |
| 2 | a bad command line |

## 10. Hosted servers

Partii can run your game's server for you: an authoritative match on Partii's game hosts, placed near your players, moved to another host if its host dies. Your server is a **WASM module** on partii-host's ABI: write it with the SDK's `partii-server` crate (`Game` trait, `export_game!`; test it natively with `partii_server::testing::Sim`), or any language that compiles to `wasm32` and uses the imports and exports in the ABI (`env.now_ms`, `send`, `broadcast`, `log`, `random_u32`, `max_datagram`; export `memory`, `alloc`, `tick`, and `on_join`, `on_leave`, `on_input`, `init` as you need them).

```sh
partii builds upload mygame --kind server --version 1.0.0 --file target/wasm32-unknown-unknown/release/mygame_server.wasm
partii builds list mygame          # server: {runtime, abi, problems, bench: {status, tier, cpu_us, usd_per_player_hour, …}}
```

Uploading checks the module (wrong imports or missing exports are listed under `server.problems`) and runs a short **benchmark**: 8 synthetic players sending 32-byte inputs every tick for 15 s (`--bench-players`, `--input-bytes`, `--input-hz`, `--bench-secs`; `--tick-hz` sets your match's tick rate, default 60). The result gives your server a **CPU tier** (light, standard, heavy) and an **estimated cost per player-hour**, so you know what hosting it costs before your players arrive. Synthetic inputs are random bytes, so a server that ignores what it can't parse looks lighter than with real players: treat the numbers as a first estimate.

Starting a match and seating players:

```sh
partii servers start mygame                       # {match, build, gen}
partii servers seat mygame <match> --field seat=player-42 --field name=Sam
#   {endpoint: {udp, quic, webtransport, ws, ticket, …}}: the player connects there with the ticket
partii servers list mygame
partii servers stop mygame <match>
```

A seat id is the player's stable id: if their connection drops, ask `servers seat` again with the same seat and they keep their place. If a match's host dies, Partii starts it on another host (from its last `checkpoint()` if your module exports `checkpoint` and `restore`, ABI v0.2) and the next `servers seat` hands out tickets for the new host. Native Linux servers (`--kind server` with an ELF binary) are accepted and stored, but don't run yet: they need Partii's bare-metal hosts.

## 11. Free assets: the Partii Asset Library

Thousands of free models, textures, HDRI skies, sounds and fonts (CC0, and OFL for fonts) that any game may ship. No key needed:

```sh
partii assets search --q "pirate ship" --kind model --limit 10   # id, title, dims, tris, animations, thumb, license
partii assets get kenney/pirate-kit/ship-pirate-large             # the full record, with its lock entry
partii assets add kenney/pirate-kit/ship-pirate-large             # into the jam's assets.lock (sorted, safe to repeat)
partii assets check                                               # loadAsset ids vs assets.lock; --fix adds the missing ones
```

`add` and `check` run in a jam folder (one with `partii.json` or `AGENTS.md`; `--dir` points at another). `add` takes several ids, refuses ids the library doesn't have and licenses a game can't use (only CC0 and CC BY, and OFL or Apache 2.0 for fonts), and prints each asset's `loadAsset("…")` line and its `dims`. `check` reads every `loadAsset("…")` and `loadAsset('…')` in the jam's code (template strings aren't ids) and reports `missing` (loaded, not locked), `unused` (locked, not loaded) and `unknown` (not in the library); it exits 1 when anything is missing or unknown. Both use the jam's own Partii host (from its `.claude/settings.json`) unless `--api` or `PARTII_API` says otherwise.

## Checklist for a new game

1. Project and key (section 1).
2. Engine in the game: host and join with a code (section 2). Check with `partii bot guest`.
3. `partii-account` at launch: guest sign-in, saves, `owns("full")` (section 3); `install_panic_hook`, a few `track` events and `end_session` on quit (section 8).
4. Store page, price and demo gate; the game checks entitlements (section 4). For app stores: your legal entity and the game's own privacy policy and account deletion URLs (`partii games privacy-set`, section 4).
5. Optional: phone controllers (section 6) and live content (section 5).
