@plupin/cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ # Plupin game SDK — docs
2
+
3
+ Everything a creator needs to put an existing game into a Plupin room. No engine assumptions: the
4
+ same three calls work for a Three.js world, a canvas 2D game, Phaser, or plain DOM.
5
+
6
+ | Doc | Read it when |
7
+ |---|---|
8
+ | [recipes.md](recipes.md) | you want per-task recipes (≤ 40 lines) for multiplayer, the payment boundary, leaderboard, deploy |
9
+ | [prompt.md](prompt.md) | you want the owner template prompt and Definition of Done for building a game |
10
+ | [quickstart.md](quickstart.md) | you want your game multiplayer today |
11
+ | [api.md](api.md) | you need the exact surface: every option, method, event |
12
+ | [netcode.md](netcode.md) | you must choose between host-relayed world and server-authoritative play |
13
+ | [leaderboards.md](leaderboards.md) | your game should keep a ranking, and you want the top list plus each player's own place |
14
+ | [randomness.md](randomness.md) | your game rolls for a cosmetic: one platform source, and why a paid outcome never uses yours |
15
+ | [integration.md](integration.md) | you have a game on your laptop and want it online |
16
+ | [cli.md](cli.md) | you want `plupin dev` / `plupin deploy` (**planned**) |
17
+ | [checks.md](checks.md) | `plupin up` refused your build, or you want to know what it measures: MB, page load, time-to-first-input |
18
+ | [mcp.md](mcp.md) | an agent should drive the loop (**planned**) |
19
+
20
+ ## The 40-line adapter
21
+
22
+ `packages/game-sdk/examples/net.ts` is the whole client integration in one file: room, peers, join,
23
+ publish, sample, leave — with the authority choice and the clock rule written down where you need
24
+ them. Its test (`packages/game-sdk/tests/net.test.ts`) boots a real `plupin dev` server for a game that
25
+ has nothing but a bundle and a `plupin.json`, connects two clients, and asserts that the observer's
26
+ scene hooks receive an interpolated pose and a despawn.
27
+
28
+ One trap that file documents: `frame.ts` is the **room's** clock. Comparing it with your browser's
29
+ `performance.now()` makes remote peers never time out. Push with arrival time, or map the room clock
30
+ onto yours once you maintain a measured offset.
31
+
32
+ ## The whole API
33
+
34
+ ```ts
35
+ import { Peers, Room } from "@plupin/game-sdk"
36
+
37
+ const room = new Room({ gameId: "my-game", name: "guest", authority: "host" })
38
+ await room.connect()
39
+
40
+ room.on("relay", ({ frame }) => peers.push(frame.from, performance.now(), frame.data))
41
+ room.broadcast("pose", { x, y, z })
42
+
43
+ const peers = new Peers({
44
+ blend: (a, b, t) => ({ ...a, x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }),
45
+ create: (seat) => scene.add(seat),
46
+ update: (seat, at) => scene.move(seat, at),
47
+ remove: (seat) => scene.remove(seat),
48
+ })
49
+ ```
50
+
51
+ Three concepts, that is the entire SDK: **Room** (the connection), **Peers** (the other players),
52
+ **Interpolator** (smoothing, used by Peers, exposed for custom cases).
53
+
54
+ ## Status
55
+
56
+ | Piece | State |
57
+ |---|---|
58
+ | `Room` client | shipped |
59
+ | `Peers` / `Interpolator` | shipped |
60
+ | Server relay room (`authority: "host"`) | shipped and routed: `plupin.json` `authority: "host"` admits a room with kind `l`, no document needed |
61
+ | Referee (`room.claim`) | in progress |
62
+ | Leaderboards (`plupin.json` `leaderboards[]`, `GET /api/games/:gameId/leaderboards/:boardId`) | implemented, not deployed yet: declared in the manifest, written by the room, read with the caller's own rank. A `host`-authority game has no server result, so its boards stay empty |
63
+ | Randomness: `rollPlatformRandom` + gacha pools (`gacha.*`) | shipped in source: one CSPRNG, moderated pools, ledger-mediated draws, SDK roll. Not deployed yet |
64
+ | `plupin dev`, `plupin deploy`, `plupin mcp` | planned — contracts written, not implemented |
65
+
66
+ Docs marked **planned** describe a contract that exists so the implementation can be checked against
67
+ it. They never describe something you can run today.
@@ -0,0 +1,354 @@
1
+ # API
2
+
3
+ The complete public surface. If something is not on this page it is not stable.
4
+
5
+ ## `new Room(options)`
6
+
7
+ | option | type | default | meaning |
8
+ |---|---|---|---|
9
+ | `gameId` | `string` | — | the game id from `plupin.json` |
10
+ | `name` | `string` | — | display name for the seat |
11
+ | `authority` | `"server" \| "host"` | `"server"` | who produces world state; `"host"` enables `broadcast()` |
12
+ | `url` | `string` | same origin | API origin. Omit when served from `<game>.plupin.com` |
13
+ | `storage` | `CapabilityStore` | `sessionStorage` | where the seat capability is remembered |
14
+ | `fetch` | `FetchLike` | global `fetch` | injection point for tests |
15
+ | `WebSocket` | `SocketCtor` | global `WebSocket` | injection point for tests |
16
+ | `maxQueue` | `number` | `32` | intents buffered while one is in flight |
17
+ | `maxReconnects` | `number` | `6` | reconnect attempts before the room gives up |
18
+
19
+ ### Methods
20
+
21
+ | call | returns | notes |
22
+ |---|---|---|
23
+ | `await connect()` | `Promise<void>` | admits, opens the socket, resolves on the first snapshot |
24
+ | `send(intent)` | `boolean` | queued; `false` when not connected, finished, or the queue is full |
25
+ | `broadcast(kind, data)` | `boolean` | throws unless `authority: "host"` |
26
+ | `claim(claim)` | `boolean` | tier P: `{ kind: "reach", target }` or `{ kind: "ray", target, dir, from? }`; the room answers with `damage` / `down` / `error` |
27
+ | `on(kind, handler)` | `() => void` | unsubscribe function |
28
+ | `close()` | `void` | stops reconnecting and closes the socket |
29
+
30
+ ### Getters
31
+
32
+ | getter | type | meaning |
33
+ |---|---|---|
34
+ | `state` | `RoomStatus` | `idle \| connecting \| joined \| reconnecting \| finished \| closed` |
35
+ | `view` | `TView \| null` | last authoritative state |
36
+ | `token` | `string \| null` | state token; intents carry it |
37
+ | `finished` | `boolean` | the room ended |
38
+ | `seatId` | `string \| null` | your seat |
39
+ | `leader` | `string | null` | seat the room elected to produce world state |
40
+ | `isLeader` | `boolean` | `leader === seatId` (Perhatian: `connect()` resolve sebelum pemilihan host; jangan baca `isLeader` tepat setelah `await connect()`, dengarkan event `host`) |
41
+
42
+ ### Events
43
+
44
+ | event | payload |
45
+ |---|---|
46
+ | `snapshot` | `{ snapshot: { token, seq, view, you, characters, deadline, finished } }` |
47
+ | `relay` | `{ frame: { from, kind, data, ts } }` |
48
+ | `host` | `{ seat }` |
49
+ | `seat` | `{ seatId }` |
50
+ | `status` | `{ status }` |
51
+ | `damage` | `{ target, amount, by, hp, at }` — the room's answer to your claim |
52
+ | `down` | `{ seat }` — once per seat, when its hp reaches zero |
53
+ | `error` | `{ code }` — `invalid_capability`, `room_unavailable`, `room_mismatch`, `reconnect_exhausted`, `frame_too_large`, or a refused claim: `stale_claim`, `rate_limited`, `cooldown`, `out_of_range`, `missed`, `blocked`, `invalid_origin`, `unknown_target`, `target_down`, `down`, `invalid_claim`, `no_pose` |
54
+
55
+ ## `new Peers(options)`
56
+
57
+ | option | type | default | meaning |
58
+ |---|---|---|---|
59
+ | `blend` | `(a, b, t) => T` | — | your interpolation |
60
+ | `create` | `(seat) => void` | — | spawn a remote entity |
61
+ | `update` | `(seat, value, latest) => void` | — | per rendered frame |
62
+ | `remove` | `(seat) => void` | — | leave or timeout |
63
+ | `delayMs` | `number` | `120` | render behind the newest frame |
64
+ | `timeoutMs` | `number` | `3000` | silence before a peer is dropped |
65
+ | `maxPeers` | `number` | `64` | hard cap |
66
+
67
+ Methods: `push(seat, at, value)`, `sample(now)`, `latest(seat)`, `seats()`, `drop(seat)`, `clear()`.
68
+
69
+ ## `new Interpolator(blend, delayMs?, limit?)`
70
+
71
+ Methods: `push(at, value)`, `sample(now)`, `latest()`, `clear()`. Used by `Peers`; use it directly
72
+ only when you need your own buffer policy (for example, a camera target that must not lag).
73
+
74
+ ## `new Leaderboard(options)`
75
+
76
+ ## In-app purchases
77
+
78
+ A game asks; the player confirms on the platform's own page; the platform moves the Sigma. A static game with no server just reads what the player holds; a game with a server can take a signed receipt instead. A game never holds spending authority ([ADR-0018](../architecture/adr/0018-game-address-and-identity.md)).
79
+ The creator keeps 85% and the platform 15% (`GAME_CREATOR_SHARE_BPS`). The paid-Sigma part of that share becomes Creator Earnings, cashable at Rp80 per Sigma after a 30-day hold ([payouts](../product/payouts.md)). A creator cannot buy from their own game (`SELF_PURCHASE`).
80
+
81
+ ### 1. Declare what you sell
82
+
83
+ In `plupin.json`. A deploy writes this to the platform, and it is the only source of a price.
84
+
85
+ ```json
86
+ {
87
+ "products": [
88
+ { "sku": "gems-100", "title": "100 gems", "price": 50, "kind": "consumable" },
89
+ { "sku": "gold-skin", "title": "Gold skin", "price": 200, "kind": "permanent" }
90
+ ]
91
+ }
92
+ ```
93
+
94
+ | field | type | meaning |
95
+ |---|---|---|
96
+ | `sku` | `string` | 1–64 letters, digits, `.`, `_`, `-` |
97
+ | `title` | `string` | 1–60 chars, shown on the confirmation page |
98
+ | `price` | `number` | Sigma, 2–100000. Fixed here: no call can name a price |
99
+ | `kind` | `"consumable" \| "permanent"` | default `consumable`. Permanent is owned once. Fixed once the SKU exists |
100
+
101
+ That is all a static game needs. Add `receiptUrl` only if you run a server (step 4).
102
+
103
+ ### 2. Ask, from a click
104
+
105
+ ```ts
106
+ import { requestPurchase } from "@plupin/game-sdk"
107
+
108
+ button.onclick = async () => {
109
+ const result = await requestPurchase("gems-100", { tag: myPlayerId })
110
+ if (result.status === "completed") refreshItems() // a hint: read what the player really holds
111
+ }
112
+ ```
113
+
114
+ | option | meaning |
115
+ |---|---|
116
+ | `tag` | receipt servers only: how your server names this player, echoed in the receipt. Optional, up to 128 of `A-Za-z0-9:._-`. The player's browser carries it, so it can only choose who gets what that player paid for |
117
+ | `gameId` | defaults to the first label of the current host |
118
+
119
+ Returns `{ status: "completed", purchaseId, sku }`, `{ status: "canceled" }` or `{ status: "failed", code }`, with `code` such as `popup_blocked`. Call it from a user gesture, or the browser blocks the window. **Grant nothing on this result**: a page's own scripts can fake it.
120
+
121
+ ### 3. Read and use what the player holds
122
+
123
+ With no `receiptUrl`, the platform holds the items, and a sale delivers them in the same transaction. Permanent items and consumable counts live in Plupin's database, for this player and this game.
124
+
125
+ ```ts
126
+ import { connectPlayer, consume, getEntitlements } from "@plupin/game-sdk"
127
+
128
+ const held = await getEntitlements()
129
+ if (held.status === "signin_required") showConnectButton() // onclick: await connectPlayer()
130
+ if (held.status === "ok") render(held.items) // [{ sku, kind, quantity }]
131
+
132
+ const used = await consume("gems-100", { key: useId }) // { status: "ok", remaining, replayed }
133
+ ```
134
+
135
+ | call | notes |
136
+ |---|---|
137
+ | `getEntitlements()` | `{ status: "ok", items }`, `{ status: "signin_required" }` or `{ status: "failed", code }` |
138
+ | `consume(sku, { key })` | takes one. The same `key` never takes twice, so send it again when you retry. `failed` with `NOTHING_TO_CONSUME` or `NOT_CONSUMABLE` |
139
+ | `connectPlayer()` | one click on the platform's page, from a user gesture. A purchase already connects the player |
140
+
141
+ The page holds a token for one player in one game, kept in `localStorage` for up to 7 days. It can read and consume those items and nothing else: no Sigma, no other game.
142
+
143
+ **Tradeoff:** platform-held ownership cannot be forged, but your rules run in the browser, so a modified client can apply an effect without calling `consume`.
144
+ A receipt server is the stronger option for a competitive game, because your own server decides what each item does.
145
+
146
+ ### 4. Or grant on a receipt
147
+
148
+ Declare your server, and issue the key it uses. The key is shown once and replaces any earlier one. A `receiptUrl` with no key is not on sale, since nothing could verify a receipt.
149
+
150
+ ```json
151
+ { "receiptUrl": "https://api.example.com/plupin/receipts" }
152
+ ```
153
+
154
+ ```bash
155
+ plupin purchases key
156
+ ```
157
+
158
+ The game's own server is now the source of truth, so `getEntitlements` and `consume` have nothing for these sales. The platform posts each sale to `receiptUrl`, signed with your key, and sends it again until you acknowledge it: right after the sale, then at growing intervals up to six hours apart. Like Roblox's `ProcessReceipt`, it can arrive more than once, so grant once per `id`.
159
+
160
+ ```ts
161
+ import { receiptAck, verifyReceipt } from "@plupin/game-sdk"
162
+
163
+ export async function POST(request: Request) {
164
+ const receipt = await verifyReceipt({
165
+ body: await request.text(), // the raw body, before any parsing
166
+ signature: request.headers.get("plupin-signature"),
167
+ serverKey: process.env.PLUPIN_SERVER_KEY,
168
+ })
169
+ if (!receipt) return new Response("bad signature", { status: 401 })
170
+ await grantOnce(receipt.id, receipt.tag, receipt.sku) // idempotent on receipt.id
171
+ return Response.json(receiptAck(receipt))
172
+ }
173
+ ```
174
+
175
+ `verifyReceipt` returns the receipt, or `null` for a bad signature or one over five minutes old (`toleranceMs`). Only status 200 with `receiptAck(receipt)` as the body acknowledges; anything else means "try again later", and redirects are not followed.
176
+
177
+ | receipt field | meaning |
178
+ |---|---|
179
+ | `id` | the purchase id: your idempotency key |
180
+ | `gameId`, `sku`, `kind`, `price` | what was sold |
181
+ | `playerId` | this player in this game: stable, and useless on any other game. Never an account id |
182
+ | `tag` | what you passed to `requestPurchase`, or `null` |
183
+ | `createdAt` | ISO time of the sale |
184
+
185
+ **A purchase nobody acknowledges within 72 hours refunds itself**, and so does one whose game is removed. The player gets the full price, and the creator's share, which is held and unspendable until the acknowledgement, is reversed. An acknowledged purchase is final.
186
+
187
+ ### Game-server routes
188
+
189
+ For your server only, with `Authorization: Bearer <server key>`. Each one sees this game's purchases and nothing else, and none can take Sigma from a player.
190
+
191
+ | route | answer |
192
+ |---|---|
193
+ | `GET /api/games/<game>/purchases/<id>` | `{ purchase }`, the authoritative record, including `status`: `paid`, `delivered` or `refunded` |
194
+ | `POST /api/games/<game>/purchases/<id>/ack` | acknowledge outside a receipt. Safe to repeat. `409 PURCHASE_REFUNDED` if it was refunded |
195
+ | `POST /api/games/<game>/purchases/<id>/refund` | you cannot grant it: refund now. Safe to repeat. `409 PURCHASE_DELIVERED` once acknowledged |
196
+ | `GET /api/games/<game>/entitlements?player=<playerId>&cursor=&limit=` | what this player holds, newest first, for restoring permanent items. `{ items, cursor }` |
197
+
198
+ ### Test mode
199
+
200
+ `plupin dev` runs the same flow with no money and no database: `requestPurchase` opens a test confirmation page on the dev origin, and the wallet is the test wallet. With no `receiptUrl`, `getEntitlements` and `consume` work as in production. To test a receipt server:
201
+
202
+ ```bash
203
+ plupin dev --receipt-url http://127.0.0.1:9000/receipts
204
+ ```
205
+
206
+ Receipts go to that URL, signed with the fixed key `plupin_gsk_dev`, retried every 5 seconds; `verifyReceipt` and the game-server routes work unchanged with that key. `POST /_dev/purchases/expire` stands in for the window running out and refunds whatever is unacknowledged. On the dev origin a game's scripts share the page's test wallet, so test mode proves your flow, not the origin boundary.
207
+
208
+ ## Randomness
209
+
210
+ Plupin has **one** source of randomness: the Workers runtime CSPRNG (`crypto.getRandomValues`) behind one weighted-draw implementation (`packages/api/src/domains/random`). The invariant is not a suggestion:
211
+
212
+ > A game never rolls its own RNG for anything a player pays for. A paid random outcome (gacha, mystery item, loot draw) is a platform draw: Sigma leaves the wallet and the item arrives in one transaction, so the game cannot see or influence the roll. A free in-game roll may ask the platform for the number instead of generating its own.
213
+
214
+ Use that call for cosmetics, emote drops, chest contents — anything a player might later trade or care about. Writing your own generator means a player can argue the outcome was yours to choose, and the platform has no record to answer with.
215
+
216
+ ```ts
217
+ import { rollPlatformRandom } from "@plupin/game-sdk"
218
+
219
+ // one weight per outcome, in your own order: a fair die, then a 1-in-6 / 2-in-6 / 3-in-6 table
220
+ const die = await rollPlatformRandom([1, 1, 1, 1, 1, 1])
221
+ const drop = await rollPlatformRandom([1, 2, 3])
222
+
223
+ if (drop.status === "ok") grantCosmetic(drop.index) // 0 | 1 | 2
224
+ else showRetry(drop.code) // "busy" | "network" | "invalid_weights" | "unknown_platform"
225
+ ```
226
+
227
+ | field | type | meaning |
228
+ |---|---|---|
229
+ | `weights` | `number[]` | 2–64 relative weights, each an integer 1–10 000. Only the ratio matters |
230
+ | `options.url` | `string` | API origin; omit when the game is served from `<game>.plupin.com` or `plupin dev` |
231
+ | `options.fetch` | `Function` | injection point for tests |
232
+
233
+ The answer is `{ status: "ok", index, roll, total }`: `index` is into the array you passed, `roll` is the uniform offset in `[0, total)` and `total` is the weight sum. Store them if you want to prove a roll later — a paid draw stores the same two numbers on its row. The call never throws: a spent budget is `status: "failed", code: "busy"`.
234
+
235
+ What the platform does with a paid draw (visible to players through the shop, moderated like any listing): a creator publishes a pool of live listing ids with weights and a Sigma price per draw; the pool is reviewed before it goes live; the pool owner cannot draw from their own pool; an item the player already owns or authored is not in the roll, and when nothing is left the draw is refused rather than charged. Every draw keeps its request key, so a retried request returns the recorded outcome instead of a second roll.
236
+
237
+ ## `plupin.json`
238
+
239
+ The ranking your `plupin.json` declares, read from the game. Read-only on purpose: a score is produced
240
+ by the room that finished the match, so there is no method here that accepts a number from the client
241
+ ([leaderboards.md](./leaderboards.md)).
242
+
243
+ ```ts
244
+ import { Leaderboard } from "@plupin/game-sdk"
245
+
246
+ const board = new Leaderboard({ gameId: "dino", board: "score" })
247
+ const page = await board.top(10)
248
+ for (const entry of page.entries) hud.rank(entry.rank, entry.name, entry.score)
249
+ if (page.me) hud.you(page.me.rank)
250
+ ```
251
+
252
+ | option | type | default | meaning |
253
+ |---|---|---|---|
254
+ | `gameId` | `string` | — | the id from `plupin.json` |
255
+ | `board` | `string` | — | a board id declared in `plupin.json`'s `leaderboards` |
256
+ | `url` | `string` | same origin | API origin; omit on `<game>.plupin.com`. `plupin dev` does not serve this route: its test board is `/_dev/leaderboard/<id>` |
257
+ | `fetch` | `FetchLike` | global `fetch` | injection point for tests |
258
+
259
+ `top(n = 10, { window?, around? })` returns `{ gameId, revision, board, window, total, entries, me,
260
+ around }`. `entries` is the top `n` (1–100); `me` is your own row even when it is outside that slice;
261
+ `around: 3` adds three neighbours above and below. `window` is a key the board's own calendar
262
+ produces (`2026-10-31` for `daily`, `2026-W44` for `weekly`); omit it for the current window.
263
+
264
+ ## `new PlatformClient(options)`
265
+
266
+ The one place the SDK calls `fetch`. `Leaderboard` is built on it; reach for it directly only to read
267
+ a platform `/api/*` route the SDK has no class for yet, so the path, the status mapping and the error
268
+ shape are not yours to invent.
269
+
270
+ ```ts
271
+ import { PlatformClient } from "@plupin/game-sdk"
272
+
273
+ const platform = new PlatformClient({ gameId: "dino" })
274
+ const board = await platform.get<{ total: number }>("/api/games/dino/leaderboards/score", { limit: 10 })
275
+ ```
276
+
277
+ | option | type | default | meaning |
278
+ |---|---|---|---|
279
+ | `gameId` | `string` | — | the id from `plupin.json`, read back as `platform.gameId` |
280
+ | `url` | `string` | same origin | API origin, read back as `platform.origin`; required where there is no `location` |
281
+ | `fetch` | `FetchLike` | global `fetch` | injection point for tests |
282
+
283
+ `get<T>(path, query?)` is the only method. `path` must start with `/api/`, `query` values that are
284
+ `undefined` are left out, and it answers the parsed JSON typed as `T` without validating it, so check
285
+ the shape as `Leaderboard` does. Credentials are omitted: a game page holds no session cookie. Every
286
+ failure rejects with an `AppError`.
287
+
288
+ ## Errors
289
+
290
+ Every failure of `Leaderboard` and `PlatformClient` is one object, `AppError` from this package:
291
+
292
+ ```ts
293
+ import { AppError } from "@plupin/game-sdk"
294
+
295
+ try {
296
+ await board.top(10)
297
+ } catch (error) {
298
+ if (error instanceof AppError) {
299
+ hud.say(error.message) // what happened
300
+ if (error.retryable) setTimeout(retry, (error.retryAfterSeconds ?? 5) * 1000)
301
+ console.warn(error.code, error.fix) // what to change
302
+ }
303
+ }
304
+ ```
305
+
306
+ `code` is typed and exhaustive (`ErrorCode`, with every value in `ERROR_CODES`), `fix` is one sentence
307
+ about what to change, `retryable` is true only for `TOO_MANY_REQUESTS`, `SERVER_UNAVAILABLE` and
308
+ `NETWORK_UNREACHABLE`, `retryAfterSeconds` is the wait the platform named when it named one, and
309
+ `JSON.stringify(error)` carries no stack trace. The full table: [errors.md](./errors.md).
310
+
311
+ ## `plupin.json`
312
+
313
+ Validated by `@plupin/game-manifest`; run `parseManifest(json)` to get the same errors the platform
314
+ would, with defaults filled in.
315
+
316
+ | field | type | default | meaning |
317
+ |---|---|---|---|
318
+ | `id` | `string` | — | hostname label: lowercase letters, digits, dashes, 3–63 chars |
319
+ | `name` | `string` | — | display name, 1–60 chars |
320
+ | `entry` | `string` | `"index.html"` | file served for `/` and extension-less paths; must stay inside the bundle |
321
+ | `authority` | `"server" \| "host"` | `"server"` | who produces world state; `host` routes the room to RelayRoom |
322
+ | `maxPlayers` | `number` | `8` | 1–64 |
323
+ | `referee` | `object` | none | optional PvP validation; see below |
324
+ | `products` | `array` | `[]` | what the game sells; see [In-app purchases](#in-app-purchases) |
325
+ | `receiptUrl` | `string` | none | optional: your server, for signed receipts; see [In-app purchases](#in-app-purchases) |
326
+
327
+ `referee` fields: `defaultHp` (100), `weapons` (map of `{ damage, range, cooldownMs }`), `body`
328
+ (`{ radius: 0.4, height: 1.8 }`), and an optional `losGrid` (`{ cell, width, height, bits }`, base64
329
+ bitmap, row-major, 1 = wall) for line-of-sight checks. `cell` is metres per bitmap cell, so the map
330
+ covers `width × height` cells starting at the world origin, and it is capped at 262144 cells (a
331
+ 512×512 map is 1 km at 2 m cells) because the room keeps the bitmap in its own record. A weapon is
332
+ named by `claim.weapon` and falls back to the claim kind (`reach`, `ray`); a manifest with no
333
+ referee block still referees range and rate with the defaults above, and one the room cannot read is
334
+ refused at room start with `invalid_referee`.
335
+
336
+ ## Wire protocol
337
+
338
+ Both client and server speak JSON over one WebSocket. You never write these by hand — `Room` does —
339
+ but they are the contract if you write a client in another language.
340
+
341
+ Client → server: `join { name, capability? }`, `intent { token, seq, intent }`,
342
+ `relay { kind, data }` (host authority only), `claim { claim }` (host authority only: the room
343
+ answers it instead of forwarding it).
344
+
345
+ Server → client: `seat { seatId, capability }`, `snapshot { token, seq, view, you, characters,
346
+ deadline, finished }`, `relay { from, kind, data, ts }`, `host { seat }`,
347
+ `damage { target, amount, by, hp, at }`, `down { seat }`, `error { code }`.
348
+
349
+ Two rules the client must follow, both already implemented:
350
+
351
+ 1. one intent in flight — the next goes out only after a snapshot with `seq >= inFlight.seq`;
352
+ 2. replay an uncommitted intent only when the state token is unchanged.
353
+
354
+ Full protocol, cost model and authority tiers: [../architecture/game-sdk.md](../architecture/game-sdk.md).
@@ -0,0 +1,130 @@
1
+ # Characters
2
+
3
+ > Authoritative for: the character API a game uses.
4
+
5
+ `@plupin/character` gives a game one character in 2D or 3D. Every rig answers to the same six names (`head`, `torso`, `armL`, `armR`, `legL`, `legR`), so a pose or clip written once drives every body.
6
+
7
+ | Rig | Body |
8
+ | --- | --- |
9
+ | `plup` | Plup: a round body on stubby limbs |
10
+ | `r6` | Roblox R6 proportions, six parts |
11
+ | `r15` | Roblox R15 proportions, fifteen parts with elbows and knees |
12
+
13
+ ## 3D, with three.js
14
+
15
+ ```ts
16
+ import { createCharacter } from "@plupin/character/three"
17
+
18
+ const player = createCharacter("r15", { bodyColor: "#3d7bff", shirt, pants })
19
+ scene.add(player.object)
20
+
21
+ player.play("run") // idle, walk, run, jump, wave, dance
22
+ player.pose({ armR: { x: -1.2 } }) // hold a joint on top of the clip
23
+ player.bone("armR")?.add(sword) // attach anything to a joint
24
+
25
+ // every frame
26
+ player.update(deltaSeconds)
27
+ ```
28
+
29
+ ## 2D, with canvas
30
+
31
+ ```ts
32
+ import { drawCharacter2D } from "@plupin/character/canvas"
33
+
34
+ drawCharacter2D(context, {
35
+ rig: "r6",
36
+ look: { bodyColor: "#3d7bff", shirt, pants },
37
+ x: 200,
38
+ y: 300,
39
+ scale: 24,
40
+ view: "side",
41
+ clip: "walk",
42
+ seconds: time,
43
+ })
44
+ ```
45
+
46
+ ## Roblox clothing
47
+
48
+ `shirt` and `pants` take a Roblox classic template, a 585×559 PNG, unchanged. `validateClassicTemplate(width, height)` rejects any other size. T-shirts (512×512) and 3D layered clothing are not supported yet.
49
+
50
+ ## Emotes
51
+
52
+ An emote is a name, a face and a clip the rig already has. The faces are the named faces of the Plupin films (`cool`, `dead`, `stars`, ...), so an emote reads the same in a video, in the app and in your game. The same list is the shop's: the first eight are free, the rest are bought with Σ.
53
+
54
+ ```ts
55
+ import { EMOTES, emoteOf, NAMED_FACE_STAMPS } from "@plupin/character"
56
+ import { faceCanvas } from "@plupin/character/canvas"
57
+
58
+ const emote = player.emote("ngakak") // plays its clip; undefined for an unknown name
59
+ if (emote) {
60
+ emote.glyph // "(≧▽≦)", the kaomoji to float over the character
61
+ emote.face // "teriak", a key of NAMED_FACE_STAMPS (8 x 4 pixels)
62
+ const face = faceCanvas(emote.face) // a 64 x 64 canvas, usable as `look.face`
63
+ }
64
+ ```
65
+
66
+ `emoteOf("emote-tewas")` and `emoteOf("tewas")` are the same lookup. Paid emotes are for players who own them: the platform decides that, the SDK only plays what it is asked to.
67
+
68
+ ## Making an emote
69
+
70
+ An emote you sell is a composition, not a video: `{ glyph, face, clip }` plus a name, an id and a
71
+ price. The gallery seeds are the same shape, so a creator emote is not a second format.
72
+
73
+ ```json
74
+ {
75
+ "id": "emote-ngakak",
76
+ "slot": "emote",
77
+ "name": "Ngakak",
78
+ "sigmaPrice": 25,
79
+ "assetConfig": { "glyph": "(≧▽≦)", "face": "teriak", "clip": "jump" }
80
+ }
81
+ ```
82
+
83
+ `slot` is `emote` (played) or `outfit` / `hair` / `accessory` (worn, where `assetConfig` is
84
+ `{ "color": "#8a5ad8" }`). A face is either a named one from `NAMED_FACES` or your own drawn stamp:
85
+ `faceStamp` is four rows of eight palette keys (`FACE_STAMP_PALETTE`, `.` for transparent).
86
+
87
+ ```bash
88
+ plupin emote new my-emote --id emote-ngakak --name Ngakak --glyph "(≧▽≦)" --face teriak --clip jump --price 25
89
+ plupin emote preview my-emote # writes my-emote/.plupin/emote-preview.svg
90
+ plupin emote push my-emote # the listing id, state `pending`
91
+ ```
92
+
93
+ `@plupin/character/listing` is the module behind all three: `checkListingManifest` validates a
94
+ composition against these tables and `renderListingPreview` draws the headshot. The platform calls
95
+ the same two functions, so the SVG in `.plupin/` is byte-for-byte the picture the moderator decides
96
+ on and the shop shows, and `plupin emote push` fails rather than report success if they ever differ.
97
+ An agent can run the same loop through the hosted MCP tools `emote_new`, `emote_preview` and
98
+ `emote_push`.
99
+
100
+ ### Badges
101
+
102
+ A creator's name carries a tick when the platform vouches for it: gold for the official Plupin account,
103
+ blue for a creator whose identity check passed. You do not set it; it follows the account. See
104
+ `docs/ops/official-account.md`.
105
+
106
+ ### Animated emotes
107
+
108
+ An emote can ship its own animation instead of naming one the rig already has. `assetConfig.anim`
109
+ is keyframes for some of the six bones (`head`, `torso`, `armL`, `armR`, `legL`, `legR`):
110
+
111
+ ```json
112
+ { "fps": 20, "loop": false, "bones": ["armR"], "frames": [[0, 0, 0, 0], [0, 0, 2.6, 0.1]] }
113
+ ```
114
+
115
+ A frame is `x, y, z` in radians for each listed bone, in order, then one `lift` in studs (never
116
+ negative: the legs are straight, so a crouch would sink them into the floor). The same limits apply
117
+ for every surface, with the sentence naming the path: at most 30 fps, 240 frames and 8 seconds, a
118
+ rotation within ±3.2 rad, lift within 0 to 3, and 32 KB as JSON. `clip` may be left out; it is then
119
+ `idle`, the fallback an older renderer plays.
120
+
121
+ You rarely write frames by hand. `plupin emote import clip.json my-emote` takes a baked motion clip
122
+ (the 18-joint format the CC0 libraries convert to, such as Quaternius's Universal Animation Library,
123
+ or one you keyed yourself), solves each limb into the rig's rotations, and writes `anim` for you.
124
+ Use motion you have the right to ship: CC0, or your own. Do not upload ripped game or dance-app
125
+ emotes; a moderator rejects them, and a rejected listing does not refund its fee.
126
+
127
+ A paid listing costs a listing fee (10 Σ) when it enters review, counts against 5 listings per 24
128
+ hours and 12 pending-or-live listings, and an identical manifest is refused as `DUPLICATE_CONTENT`.
129
+ A rejection does not refund the fee. The shop shows "sold by @username", and a sale pays the creator
130
+ through the existing 90/10 creator-earnings lane.
@@ -0,0 +1,102 @@
1
+ # What `plupin up` checks
2
+
3
+ `plupin up` measures a build the way a phone plays it before publishing, and refuses when the build
4
+ crosses the ceiling the creator wrote in `plupin.json` → `budget`. There is no separate command: a check
5
+ an agent has to remember to run is a check that does not run. `--skip-checks` publishes unmeasured, and
6
+ `--dry-run` measures without publishing.
7
+
8
+ ```
9
+ $ plupin up ./dist --dry-run
10
+ checks my-game (5 responses, 8420 ms)
11
+ device iPhone 13, 390x844 @3x, touch
12
+ network fast3g: 150 ms RTT, 1600/750 kbps
13
+ source local host, no production server, no credentials
14
+ wire 0.193 MB before input (0.193 MB total, 5 responses, heaviest /three.core.min.js 0.103 MB)
15
+ load 1204 ms
16
+ ttfi 2.22 s — input listener at 2.219 s, tap accepted at 3.807 s
17
+ listener 2.219 s, canvas 0.326 s, tap 3.807 s
18
+ errors 0 (console 0, unhandled 0, webgl lost 0)
19
+ budget mb 6, ttfi 6 s, errors 0
20
+ pass every budget met
21
+ ```
22
+
23
+ ## What it runs
24
+
25
+ | | |
26
+ |---|---|
27
+ | game | the folder you point at, served by the same local host `plupin dev` uses (`127.0.0.1`, random port) |
28
+ | device | Chromium headless, viewport `390x844`, DPR 3, touch, iPhone Safari UA |
29
+ | network | fast 3G through CDP: 150 ms RTT, 1600 kbps down, 750 kbps up |
30
+ | needs | nothing remote for this step: no API, no token, no production server. Playwright's Chromium must be installed (`bunx playwright install chromium`) |
31
+
32
+ ## The numbers
33
+
34
+ **wire** — bytes the page actually transferred, read from Chromium's own network stack
35
+ (`encodedDataLength`), not from file sizes on disk. Two things make it honest:
36
+
37
+ - the local host gzips text responses the way Cloudflare does in production, so a 365 KB script is
38
+ counted as the 87 KB a phone downloads;
39
+ - bytes are counted as they arrive, so a texture still downloading when the run ends is charged for
40
+ what it already cost, and `incomplete` says how many responses were cut off.
41
+
42
+ `initialMb` is the part that landed before the game accepted input (or before the `load` event,
43
+ whichever came later): what a player waits through. `mb` is everything the run transferred and is
44
+ what the budget is measured against. The five heaviest assets are listed with their own sizes.
45
+
46
+ **ttfi** — seconds until the page can accept the first input, read off the page's own clock:
47
+
48
+ 1. the first `pointerdown` / `touchstart` / `mousedown` / `keydown` listener the game registers
49
+ (Playwright's own hit-target interceptors and the probe itself are excluded by stack), and
50
+ 2. a real touch tap sent through the touch screen, which must reach the page after that listener.
51
+
52
+ A page that never registers a listener fails with `ttfi: no input`, because a canvas that draws
53
+ nothing you can press is not a game. One that listens but never receives the tap fails with `ttfi: no
54
+ tap accepted`.
55
+
56
+ **load** — the page reaches its `load` event inside 45 s on that throttled link.
57
+
58
+ **errors** — console errors, uncaught exceptions, unhandled rejections, and WebGL context losses
59
+ (the last one is invisible in the console: the canvas keeps its size and stops drawing, so it is
60
+ counted where the context is handed out).
61
+
62
+ ## The budget
63
+
64
+ `plupin.json`:
65
+
66
+ ```json
67
+ { "id": "my-game", "name": "My Game", "budget": { "mb": 4, "ttfi": 5 } }
68
+ ```
69
+
70
+ | key | default | what it means |
71
+ |---|---|---|
72
+ | `mb` | `6` | megabytes transferred during the run |
73
+ | `ttfi` | `6` | seconds until the first input is accepted |
74
+ | `errors` | `0` | tolerated console errors + unhandled rejections + lost WebGL contexts |
75
+
76
+ A partial block fills the rest from the defaults. No block means the defaults, which are written
77
+ for a phone on fast 3G at `390x844`, not for a laptop on loopback. Every key is validated by
78
+ `@plupin/game-manifest`, so a typo is a manifest error instead of a budget that silently does not
79
+ apply.
80
+
81
+ ## Exit codes and artifacts
82
+
83
+ - `5` — a check failed and nothing was published. The summary names every metric
84
+ (`FAIL mb: 7.42 MB > 6 MB`).
85
+ - `1` — the folder is not a valid build, or Playwright's browser is missing. Install it with
86
+ `bunx playwright install chromium`.
87
+
88
+ Two files land in `.plupin/` beside the build (`./.plupin/` for `./dist`), never inside it, because
89
+ everything inside the folder is the bundle: `checks.json` holds the measured result and `checks.png` is
90
+ a screenshot of the phone viewport at the end of the run.
91
+
92
+ ## What it does not prove
93
+
94
+ - **A document that is not the build is never measured.** Before the first metric, the checks hash what
95
+ the local host answers and compare it with `<dir>/<entry>`; a mismatch is exit 1. A catch-all `200`,
96
+ an SPA shell or a stale revision would otherwise be reported as a game.
97
+ - **Software rendering.** Headless Chromium rasterises with SwiftShader, so `ttfi` includes a
98
+ software-rendering cost a real phone GPU does not pay. Treat it as an upper bound; the network
99
+ half is faithful because it goes through CDP throttling.
100
+ - **Gameplay.** No match is played. A build that loads and takes a tap can still be broken after that.
101
+ - **Real devices.** This is a phone-shaped Chromium on a Mac, not a mid-range Android on a train.
102
+ It catches the 8 MB build and the six-second load, not a 200 ms jank.