@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.
- package/dist/cli.js +26636 -0
- package/dist/docs/README.md +67 -0
- package/dist/docs/api.md +354 -0
- package/dist/docs/character.md +130 -0
- package/dist/docs/checks.md +102 -0
- package/dist/docs/cli.md +334 -0
- package/dist/docs/errors.md +42 -0
- package/dist/docs/integration.md +120 -0
- package/dist/docs/leaderboards.md +135 -0
- package/dist/docs/mcp.md +165 -0
- package/dist/docs/netcode.md +50 -0
- package/dist/docs/prompt.md +55 -0
- package/dist/docs/quickstart.md +119 -0
- package/dist/docs/randomness.md +73 -0
- package/dist/docs/recipes.md +205 -0
- package/dist/relay-room.mjs +20195 -0
- package/package.json +23 -4
- package/README.md +0 -3
package/dist/docs/mcp.md
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# MCP surface
|
|
2
|
+
|
|
3
|
+
Status: **`plupin mcp` shipped** (stdio, newline-delimited JSON-RPC 2.0) with the local tools below.
|
|
4
|
+
`deploy` and `deploy_status` are still **planned** — they need R2, which is not enabled yet.
|
|
5
|
+
|
|
6
|
+
An AI coding assistant should be able to answer "does this manifest work?" and "start my game so I
|
|
7
|
+
can test multiplayer" without the creator leaving the editor. Nothing here reaches production.
|
|
8
|
+
|
|
9
|
+
## Shipped tools
|
|
10
|
+
|
|
11
|
+
| tool | args | returns |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| `manifest_check` | `{ dir? }` | `{ ok: true, dir, manifest }` or the exact field errors |
|
|
14
|
+
| `dev_start` | `{ dir?, port? }` | `{ url, game, authority, roomId, roomUrl, connectedSockets }` |
|
|
15
|
+
| `dev_status` | — | `{ running, url, game, sockets }` |
|
|
16
|
+
| `dev_stop` | — | `{ stopped: true }` — idempotent |
|
|
17
|
+
| `docs` | `{ topic }` | the real markdown of `quickstart`, `api`, `netcode`, `cli`, or `mcp` |
|
|
18
|
+
|
|
19
|
+
`dev_start` runs the same code path as `plupin dev`: one origin serves the build and hosts the room,
|
|
20
|
+
and the room is the production `RelayRoom` class. An assistant testing multiplayer gets the same
|
|
21
|
+
answer a terminal would.
|
|
22
|
+
|
|
23
|
+
## Planned (blocked on R2)
|
|
24
|
+
|
|
25
|
+
| tool | args | returns |
|
|
26
|
+
|---|---|---|
|
|
27
|
+
| `deploy` | `{ confirm: true, dryRun? }` | `{ bundleRef, url, bytes, files }` |
|
|
28
|
+
| `deploy_status` | — | `{ bundleRef, bytes, files, deployedAt }` |
|
|
29
|
+
|
|
30
|
+
Rule that will not change: `deploy` refuses unless `confirm: true`. An agent must never publish
|
|
31
|
+
because it inferred intent.
|
|
32
|
+
|
|
33
|
+
## Emotes over the hosted surface
|
|
34
|
+
|
|
35
|
+
The hosted server (`https://api.plupin.com/mcp`) carries the authoring loop as three tools, so an
|
|
36
|
+
assistant with no terminal can compose and publish a listing:
|
|
37
|
+
|
|
38
|
+
| tool | scope | what it does |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| `emote_new` | `mcp:read` | returns a validated manifest for an emote (`{ glyph, face, clip }`) or a wearable (`{ color }`) |
|
|
41
|
+
| `emote_preview` | `mcp:read` | renders the headshot the moderator decides on, as a data URL and an image block |
|
|
42
|
+
| `emote_push` | `mcp:deploy` | publishes it into the moderation queue and returns the listing id with `pending` |
|
|
43
|
+
|
|
44
|
+
All three call `@plupin/character/listing`, the module `plupin emote preview` writes to disk, so the
|
|
45
|
+
picture an agent approves is byte-for-byte the picture the server stores. A refusal is the service's
|
|
46
|
+
own sentence (`DAILY_LISTING_LIMIT`, `ACTIVE_LISTING_CAP`, `DUPLICATE_CONTENT`, or the exact field
|
|
47
|
+
and the allowed values), which is what makes it actionable.
|
|
48
|
+
|
|
49
|
+
The stdio server in this document stays local-only on purpose: it writes files and touches no
|
|
50
|
+
network, so it has no `emote_push`. Publish from a terminal (`plupin emote push`) or over the hosted
|
|
51
|
+
endpoint.
|
|
52
|
+
|
|
53
|
+
## Rules
|
|
54
|
+
|
|
55
|
+
1. Every tool returns JSON or a document, never prose.
|
|
56
|
+
2. A failure is `{ content: [...], isError: true }` with a readable message — no stack traces.
|
|
57
|
+
3. Unknown tool names name the tools that do exist.
|
|
58
|
+
4. Local tools never write to production.
|
|
59
|
+
|
|
60
|
+
## Connect your agent
|
|
61
|
+
|
|
62
|
+
Two commands, one per agent CLI. They write the config the CLI already reads, so nothing is
|
|
63
|
+
hand-edited and no token is pasted by hand:
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
plupin login # once: mints the OAuth access token the hosted surface verifies
|
|
67
|
+
plupin connect claude # -> ~/.claude.json
|
|
68
|
+
plupin connect codex # -> ~/.codex/config.toml
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Each writes two servers, because the platform has two surfaces and an agent needs both:
|
|
72
|
+
|
|
73
|
+
| server | transport | what an agent gets |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `plupin` | stdio, `bunx -y @plupin/cli mcp` | the local tools in this document: `manifest_check`, `dev_start`, `dev_status`, `dev_stop`, `docs` |
|
|
76
|
+
| `plupin-hosted` | streamable HTTP, `<api>/mcp` | the hosted tools, `emote_new` / `emote_preview` / `emote_push` among them |
|
|
77
|
+
|
|
78
|
+
**Why the user-level file and not a project one.** The hosted entry carries a bearer token, and a
|
|
79
|
+
project config (`.mcp.json` beside the game) is a file that gets committed: one `git add .` would put
|
|
80
|
+
a live account token in a repository, and in its history. The user-level file also works from any
|
|
81
|
+
directory, including a build folder that is not a repository. The token is written into that file,
|
|
82
|
+
mode 600, and `plupin connect` never prints it.
|
|
83
|
+
|
|
84
|
+
After writing, the command asks the hosted surface for `tools/list` with the token it just wrote and
|
|
85
|
+
prints the count, so the receipt is a measurement. A refusal is reported as the status the server
|
|
86
|
+
answered (401 means the token expired: `plupin login` again) and the config is still there.
|
|
87
|
+
|
|
88
|
+
Re-running is safe and idempotent. Only the platform's own entries are touched: another server you
|
|
89
|
+
added by hand and every unrelated key in `~/.claude.json` survive byte for byte, and Codex's
|
|
90
|
+
`[mcp_servers.plupin]` table is replaced in place, duplicates and a stale `[.env]` sub-table removed.
|
|
91
|
+
|
|
92
|
+
### Claude Code
|
|
93
|
+
|
|
94
|
+
`plupin connect claude` writes these two entries under `mcpServers` in `~/.claude.json`:
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"plupin": {
|
|
99
|
+
"type": "stdio",
|
|
100
|
+
"command": "bunx",
|
|
101
|
+
"args": ["-y", "@plupin/cli", "mcp"]
|
|
102
|
+
},
|
|
103
|
+
"plupin-hosted": {
|
|
104
|
+
"type": "http",
|
|
105
|
+
"url": "https://api.plupin.com/mcp",
|
|
106
|
+
"headers": { "Authorization": "Bearer <the token plupin login stored>" }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`CLAUDE_CONFIG_DIR` moves that file (a second profile, a container), which is also how the CLI's
|
|
112
|
+
tests drive it without touching a real one.
|
|
113
|
+
|
|
114
|
+
### Codex CLI
|
|
115
|
+
|
|
116
|
+
`plupin connect codex` writes these tables into `~/.codex/config.toml`. `CODEX_HOME` moves the file.
|
|
117
|
+
|
|
118
|
+
```toml
|
|
119
|
+
[mcp_servers.plupin]
|
|
120
|
+
command = "bunx"
|
|
121
|
+
args = ["-y", "@plupin/cli", "mcp"]
|
|
122
|
+
|
|
123
|
+
[mcp_servers.plupin-hosted]
|
|
124
|
+
url = "https://api.plupin.com/mcp"
|
|
125
|
+
http_headers = { Authorization = "Bearer <the token plupin login stored>" }
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`http_headers` is the field Codex reads for a streamable-HTTP server (the same one
|
|
129
|
+
`codex mcp add --url` writes), so the token lives in the 0600 config instead of an environment
|
|
130
|
+
variable every shell has to export. `bearer_token_env_var` is the alternative when the token should
|
|
131
|
+
stay in the environment instead.
|
|
132
|
+
|
|
133
|
+
### By hand
|
|
134
|
+
|
|
135
|
+
The published package keeps the snippet one line long:
|
|
136
|
+
|
|
137
|
+
```json
|
|
138
|
+
{
|
|
139
|
+
"mcpServers": {
|
|
140
|
+
"plupin": {
|
|
141
|
+
"command": "bunx",
|
|
142
|
+
"args": ["-y", "@plupin/cli", "mcp"],
|
|
143
|
+
"cwd": "/absolute/path/to/your-game"
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`cwd` is what `manifest_check` and `dev_start` resolve a relative `dir` against; a client that
|
|
150
|
+
starts the server in the project root can leave it out. To run from a checkout instead of the
|
|
151
|
+
published package:
|
|
152
|
+
|
|
153
|
+
```json
|
|
154
|
+
{ "command": "bun", "args": ["run", "/absolute/path/to/plupin/packages/cli/src/bin.ts", "mcp"] }
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Session
|
|
158
|
+
|
|
159
|
+
```json
|
|
160
|
+
{ "method": "tools/call", "params": { "name": "manifest_check", "arguments": { "dir": "./dist" } } }
|
|
161
|
+
{ "ok": true, "manifest": { "id": "dude-theft", "authority": "host", "entry": "index.html" } }
|
|
162
|
+
|
|
163
|
+
{ "method": "tools/call", "params": { "name": "dev_start", "arguments": { "port": 8787 } } }
|
|
164
|
+
{ "url": "http://127.0.0.1:8787", "roomId": "dude-theft~<uuid>~l0", "connectedSockets": 0 }
|
|
165
|
+
```
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# Choosing a netcode
|
|
2
|
+
|
|
3
|
+
One question: **can a player be trusted with the outcome?**
|
|
4
|
+
|
|
5
|
+
- Cosmetic or simulated locally, nobody pays for it → `"host"`.
|
|
6
|
+
- A result another player or the economy depends on → `"server"` for that result, `"host"` for the rest.
|
|
7
|
+
|
|
8
|
+
Most worlds need both at once. Authority is per channel, not per game.
|
|
9
|
+
|
|
10
|
+
## The three tiers
|
|
11
|
+
|
|
12
|
+
| tier | produced by | server does | use for |
|
|
13
|
+
|---|---|---|---|
|
|
14
|
+
| world | elected host | forwards, stores nothing | NPCs, traffic, props, weather |
|
|
15
|
+
| players | each client, own avatar | keeps 2 s of poses, validates claims | movement, shooting, damage |
|
|
16
|
+
| economy | platform | applies and records | Sigma, purchases, rewards |
|
|
17
|
+
|
|
18
|
+
A game that only calls `broadcast()` is host-only. A game that only calls `send()` is
|
|
19
|
+
server-simulated. Both can coexist in one room.
|
|
20
|
+
|
|
21
|
+
## Referee claims (planned)
|
|
22
|
+
|
|
23
|
+
Instead of "I hit you", a client submits a claim and the room decides:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
room.claim({ kind: "ray", from: [x, y, z], dir: [dx, dy, dz], at: Date.now() })
|
|
27
|
+
room.on("damage", ({ target, amount, by }) => applyDamage(target, amount, by))
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The room checks range, cooldown, rate, the target capsule at `at`, and — if the game ships a coarse
|
|
31
|
+
LOS grid in `plupin.json` — whether a wall was in the way. Only then does it apply damage and
|
|
32
|
+
broadcast it. Your client-side hit stays a prediction.
|
|
33
|
+
|
|
34
|
+
## Cost, in numbers
|
|
35
|
+
|
|
36
|
+
| setup | per hour, 4 players |
|
|
37
|
+
|---|---|
|
|
38
|
+
| host relay at 15 Hz | ~216k messages → over the free 100k/day in ~28 minutes |
|
|
39
|
+
| host relay at 10 Hz, one publisher | ~36k messages → ~2.8 hours/day free |
|
|
40
|
+
| claims | 10/s → negligible |
|
|
41
|
+
| server-simulated physics at 60 Hz | not possible in a 10 ms CPU budget |
|
|
42
|
+
|
|
43
|
+
Relay frame rate is a budget. Prefer one publisher sending world state over every client sending its
|
|
44
|
+
own; the exception is a game where each player must control a distinct object (then each client
|
|
45
|
+
publishes its own pose, which is the 4×15 Hz case).
|
|
46
|
+
|
|
47
|
+
## What stays unverifiable
|
|
48
|
+
|
|
49
|
+
Aim skill, clipping inside your own physics, anything only the host can see. Rewards tied to those
|
|
50
|
+
must be capped or withheld. Pay for what the room can see, not for what the client reports.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Playbook Agent Game SDK — Prompt Template & Definisi Selesai
|
|
2
|
+
|
|
3
|
+
Dokumen ini adalah panduan operasional satu pintu bagi owner dan coding agent untuk membangun game interaktif di platform Plupin dari nol hingga live.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Kalimat Template Owner
|
|
8
|
+
|
|
9
|
+
Owner cukup menyalin dan menempelkan satu kalimat ini ke agent (ganti `[NAMA_GAME]` dan deskripsi konsep game):
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
Gw mau buat game [NAMA_GAME], gunakan SDK Plupin untuk multiplayer, leaderboard, dan deploy.
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Contoh spesifik:
|
|
16
|
+
```text
|
|
17
|
+
Gw mau buat game arena pertarungan tank 2D top-down bernama 'tank-brawl', gunakan SDK Plupin untuk multiplayer, leaderboard, dan deploy.
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## 2. Daftar Wajib Baca Sebelum Menulis Kode
|
|
23
|
+
|
|
24
|
+
Sebelum agent menyentuh kode atau menghasilkan berkas proyek apa pun, agent **wajib** membaca dokumen referensi berikut secara berurutan:
|
|
25
|
+
|
|
26
|
+
1. **`docs/game-sdk/recipes.md`** — Resep siap pakai per-task (Mulai, Multiplayer, batas Payment, Leaderboard, Deploy, Error Handling). Setiap resep mandiri dan ≤ 40 baris kode.
|
|
27
|
+
2. **`docs/game-sdk/api.md`** — Spesifikasi lengkap permukaan SDK (`Room`, `Peers`, `Interpolator`, `Leaderboard`, options, method, events).
|
|
28
|
+
3. **`docs/game-sdk/errors.md`** — Kontrak kode error terketik (`code`) dan aksi perbaikan spesifik.
|
|
29
|
+
4. **`docs/game-sdk/cli.md`** — Perilaku CLI pengembang (`plupin dev`, `plupin up`, `plupin status`).
|
|
30
|
+
5. **`AGENTS.md` & `docs/PRD.md`** — Prinsip platform: netral engine (Three.js, Phaser, Canvas 2D, atau DOM adalah pilihan setara), nol runtime dependency di client SDK, dan arsitektur server-refereed.
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## 3. Definisi Selesai (Definition of Done)
|
|
35
|
+
|
|
36
|
+
Suatu tugas pembuatan game oleh agent dinyatakan **SELESAI** jika dan hanya jika ketiga kriteria berikut terpenuhi dan dibuktikan dengan log eksekusi nyata:
|
|
37
|
+
|
|
38
|
+
1. **2 Peer Satu Room:**
|
|
39
|
+
- Dua client/tab peramban berhasil bergabung ke dalam satu room yang sama (`state === "joined"`).
|
|
40
|
+
- Kedua seat dapat saling bertukar intent atau relay pose terinterpolasi melalui `Peers`.
|
|
41
|
+
- Event spawn dan despawn berjalan bersih tanpa kebocoran state.
|
|
42
|
+
|
|
43
|
+
2. **Tidak Membelanjakan Sigma:**
|
|
44
|
+
- Kode game tidak memanggil debit apa pun; SDK tidak mengekspor `wallet` dan ADR-0018 melarang game membelanjakan Sigma pemain.
|
|
45
|
+
- Jika game menjual sesuatu, alurnya dicoba di mode uji `plupin dev`: `POST /_dev/wallet/spend` dua kali dengan `idempotencyKey` yang sama menghasilkan satu debit di `/_dev/ledger`.
|
|
46
|
+
- Pembuktian rute uji ini tidak dianggap sebagai pembayaran produksi.
|
|
47
|
+
|
|
48
|
+
3. **Host Melayani Game:**
|
|
49
|
+
- Perintah publikasi berhasil dijalankan, tanpa `--skip-checks`:
|
|
50
|
+
```bash
|
|
51
|
+
plupin up ./dist
|
|
52
|
+
```
|
|
53
|
+
- Perintah ini mengukur build lebih dulu dan menolak yang melewati `budget` di `plupin.json` (bawaan 6 MB, 6 detik sampai tap pertama diterima, 0 error, halaman termuat), jadi tidak ada langkah pengecekan terpisah.
|
|
54
|
+
- Alamat game dicetak oleh perintah tersebut.
|
|
55
|
+
- Probe host mengembalikan status **HTTP 200** dengan berkas entry yang baru diunggah, yang memverifikasi bahwa bundle live dan dapat dimainkan publik.
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# Quickstart
|
|
2
|
+
|
|
3
|
+
From a game that runs on one machine to a game two people can play. Three steps, one file.
|
|
4
|
+
|
|
5
|
+
## 1. Describe the game
|
|
6
|
+
|
|
7
|
+
`plupin.json` at the root of your build folder:
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"id": "dude-theft",
|
|
12
|
+
"name": "Dude Theft",
|
|
13
|
+
"engine": "2d",
|
|
14
|
+
"entry": "index.html",
|
|
15
|
+
"authority": "host",
|
|
16
|
+
"maxPlayers": 8
|
|
17
|
+
}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`engine` is the badge the catalogue shows (`2d` or `3d`). It defaults to `3d`, so a 2D game has to
|
|
21
|
+
say so; `plupin create` and `plupin up` record it instead of guessing from a flag.
|
|
22
|
+
|
|
23
|
+
`authority` is the only choice you must make:
|
|
24
|
+
|
|
25
|
+
- `"host"` — your game keeps its own physics; one player's client simulates the world and Plupin
|
|
26
|
+
forwards it. Use this if the game already has gravity, vehicles, ragdolls.
|
|
27
|
+
- `"server"` — Plupin runs the rules and sends you the state. Use this for turn-based or ranked play
|
|
28
|
+
where nobody may cheat.
|
|
29
|
+
|
|
30
|
+
Unsure? Start with `"host"`. You can move a single game to `"server"` later without changing the
|
|
31
|
+
client code.
|
|
32
|
+
|
|
33
|
+
## 2. Connect
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { Room } from "@plupin/game-sdk"
|
|
37
|
+
|
|
38
|
+
const room = new Room({ gameId: "dude-theft", name: "guest", authority: "host" })
|
|
39
|
+
await room.connect() // resolves on the first state from the room
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The id is compiled into your bundle, not read from `plupin.json` at runtime. If you copy a project
|
|
43
|
+
folder and change `id`, rebuild before deploying: the SDK compares the address it is served from
|
|
44
|
+
(`<id>.plupin.com`) with the `gameId` it was built for, and refuses with one sentence naming both
|
|
45
|
+
instead of a bare `admission failed: 404`.
|
|
46
|
+
|
|
47
|
+
Then publish your own state a few times per second — 10 to 15 Hz is plenty:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
setInterval(() => {
|
|
51
|
+
room.broadcast("pose", {
|
|
52
|
+
p: [player.pos.x, player.y, player.pos.z],
|
|
53
|
+
ry: character.group.rotation.y,
|
|
54
|
+
})
|
|
55
|
+
}, 66)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## 3. Draw the others
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { Peers } from "@plupin/game-sdk"
|
|
62
|
+
|
|
63
|
+
const peers = new Peers<{ p: [number, number, number]; ry: number }>({
|
|
64
|
+
blend: (a, b, t) => ({
|
|
65
|
+
p: [
|
|
66
|
+
a.p[0] + (b.p[0] - a.p[0]) * t,
|
|
67
|
+
a.p[1] + (b.p[1] - a.p[1]) * t,
|
|
68
|
+
a.p[2] + (b.p[2] - a.p[2]) * t,
|
|
69
|
+
],
|
|
70
|
+
ry: a.ry + ((((b.ry - a.ry) % (Math.PI * 2)) + Math.PI * 3) % (Math.PI * 2) - Math.PI) * t,
|
|
71
|
+
}),
|
|
72
|
+
create: (seat) => world.spawnRemote(seat),
|
|
73
|
+
update: (seat, at) => world.moveRemote(seat, at),
|
|
74
|
+
remove: (seat) => world.despawnRemote(seat),
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
room.on("relay", ({ frame }) => {
|
|
78
|
+
if (frame.kind === "pose") peers.push(frame.from, performance.now(), frame.data)
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
const frame = () => { peers.sample(performance.now()); requestAnimationFrame(frame) }
|
|
82
|
+
frame()
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
**2D is the same code.** Swap the tuple for `{ x, y }`, blend two numbers, and point `create` /
|
|
86
|
+
`update` / `remove` at your sprites.
|
|
87
|
+
|
|
88
|
+
## Local play
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
bunx @plupin/cli dev ./dist --port 8787
|
|
92
|
+
# game http://127.0.0.1:8787
|
|
93
|
+
# rooms http://127.0.0.1:8787/api/play/dude-theft/rooms
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
One origin serves the build and hosts the room, exactly like `<game>.plupin.com`. The room is the
|
|
97
|
+
production `RelayRoom` class, so a frame you see locally is a frame the platform accepts. Open the
|
|
98
|
+
game twice and both tabs are in the same room; no `url` override needed because the game and the
|
|
99
|
+
API share an origin.
|
|
100
|
+
|
|
101
|
+
`plupin deploy` ships in the same package, so a build folder can be published from the CLI today.
|
|
102
|
+
|
|
103
|
+
## Live (planned)
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
npx @plupin/cli deploy ./dist
|
|
107
|
+
# → https://dude-theft.plupin.com
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
No build runs on the platform: you upload the folder your own toolchain produced.
|
|
111
|
+
|
|
112
|
+
## Checklist before you ship
|
|
113
|
+
|
|
114
|
+
- [ ] `plupin.json` exists in the build output, not only in the source tree.
|
|
115
|
+
- [ ] The game runs from a subpath (`/index.html` served by any static server), not only from `/`.
|
|
116
|
+
- [ ] Assets are relative paths — absolute `/fonts/x.woff` breaks on a game subdomain.
|
|
117
|
+
- [ ] No `localStorage` for anything that must follow the player between devices; that is what the
|
|
118
|
+
Plupin profile is for.
|
|
119
|
+
- [ ] Pointer lock, audio and WebGL are started from a user gesture (mobile browsers require it).
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Randomness
|
|
2
|
+
|
|
3
|
+
Plupin has one source of randomness, and this page is the rule that keeps it that way.
|
|
4
|
+
|
|
5
|
+
## The invariant
|
|
6
|
+
|
|
7
|
+
> Games never roll their own RNG for anything a player pays for. Paid random outcomes happen on the
|
|
8
|
+
> platform, in one transaction, from the platform's CSPRNG. Free random outcomes may ask the platform
|
|
9
|
+
> for the number, so a game that wants randomness has one place to get it.
|
|
10
|
+
|
|
11
|
+
Two halves, one reason. A player who pays Sigma for a random cosmetic must be able to trust the roll
|
|
12
|
+
and the money move together: they are charged once, they receive what the roll decided, and both are
|
|
13
|
+
recorded. A game cannot provide that — it runs creator code on a game address with no wallet
|
|
14
|
+
authority ([ADR-0018](../architecture/adr/0018-game-address-and-identity.md)) — so a game never
|
|
15
|
+
receives the ability to spend, and the platform never takes the roll from the game.
|
|
16
|
+
|
|
17
|
+
The second half is convenience with the same guarantee: a game that wants its own cosmetic
|
|
18
|
+
randomness asks the platform instead of carrying a generator, so the answer is the same CSPRNG and
|
|
19
|
+
the same arithmetic a paid draw uses.
|
|
20
|
+
|
|
21
|
+
## What the source is
|
|
22
|
+
|
|
23
|
+
`packages/api/src/domains/random` is the only implementation:
|
|
24
|
+
|
|
25
|
+
- `cryptoUint32()` reads one uint32 from the Workers runtime's WebCrypto
|
|
26
|
+
(`crypto.getRandomValues`). No seed, no counter, no clock, nothing a player can influence, and no
|
|
27
|
+
`Math.random`: a non-cryptographic generator's state can be recovered from its outputs, which is
|
|
28
|
+
exactly the property a paid outcome may not have.
|
|
29
|
+
- `uniformBelow(range)` turns that into an unbiased integer in a range, rejecting the tail values
|
|
30
|
+
that would otherwise make low outcomes slightly likelier.
|
|
31
|
+
- `pickWeighted(entries)` maps one offset onto a weight table. The offset is the audit trail: the
|
|
32
|
+
same table and the same offset always name the same entry.
|
|
33
|
+
|
|
34
|
+
A future external beacon (a lavaRand-style delayed seed) would replace the body of `cryptoUint32` and
|
|
35
|
+
nothing else. No beacon is a dependency today.
|
|
36
|
+
|
|
37
|
+
## Paid draws
|
|
38
|
+
|
|
39
|
+
A creator publishes a **pool**: 2–24 live listing ids, each with a relative weight, plus the Sigma one
|
|
40
|
+
draw costs. The pool is a listing, so it enters the same moderation queue (`pending` → `live` or
|
|
41
|
+
`rejected` with a reason) and only an admin decision makes it drawable. A pool whose listing was taken
|
|
42
|
+
down loses that entry; a pool with nothing left refuses the draw instead of charging for it.
|
|
43
|
+
|
|
44
|
+
A draw is one transaction in `@plupin/api/domains/gacha`:
|
|
45
|
+
|
|
46
|
+
1. the draw row, which owns the request key and the CSPRNG offset;
|
|
47
|
+
2. the Sigma debit (`gacha_draw` in the ledger) and the pool owner's 90% (`gacha_sale`, plus the
|
|
48
|
+
standard creator earning);
|
|
49
|
+
3. the cosmetic grant into the player's inventory.
|
|
50
|
+
|
|
51
|
+
Any failure rolls all three back, so an empty wallet leaves no row, no item and no ledger entry. A
|
|
52
|
+
repeated request key returns the recorded draw (`replayed: true`) and never re-rolls, including when
|
|
53
|
+
the pool was taken down in between.
|
|
54
|
+
|
|
55
|
+
Rules a player can rely on:
|
|
56
|
+
|
|
57
|
+
- the pool owner cannot draw from their own pool (`SELF_DEALING`);
|
|
58
|
+
- an entry the player authored or already owns is not in the roll;
|
|
59
|
+
- the odds a pool advertises are the live entries' weights, computed by the server;
|
|
60
|
+
- an admin can read every draw with the pool, the item, the price and the stored offset.
|
|
61
|
+
|
|
62
|
+
## Free rolls, from a game
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { rollPlatformRandom } from "@plupin/game-sdk"
|
|
66
|
+
|
|
67
|
+
const result = await rollPlatformRandom([1, 2, 3])
|
|
68
|
+
if (result.status === "ok") grant(result.index)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`POST /api/play/random` answers `{ index, roll, total }`. It takes no session and moves no money,
|
|
72
|
+
which is why it can live on the game origin; it is rate limited per address
|
|
73
|
+
(`LIMIT_RANDOM`, 120/minute). Full option table: [api.md](api.md#randomness).
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
# Playbook Game SDK — Resep per-Task
|
|
2
|
+
|
|
3
|
+
Resep siap pakai untuk mengintegrasikan game apa pun ke platform Plupin menggunakan `@plupin/game-sdk`.
|
|
4
|
+
|
|
5
|
+
SDK ini memiliki **nol runtime dependency** dan netral engine: kode yang sama bekerja identik untuk Three.js, Phaser, HTML5 2D Canvas, WebGL murni, maupun DOM.
|
|
6
|
+
|
|
7
|
+
Setiap resep di bawah ini berisi kode lengkap (≤ 40 baris), import mandiri, dan satu perintah verifikasi langsung. Resep hanya memakai ekspor SDK yang benar-benar ada: `Room`, `Peers`, `Interpolator`, `Leaderboard`, `PlatformClient`, `AppError`, `ERROR_CODES`; `packages/game-sdk/tests/recipes.test.ts` menjaganya, dan mengompilasi setiap resep dengan TypeScript strict.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Resep 1: Mulai (Game Kosong → SDK Init → Satu Room Hidup)
|
|
12
|
+
|
|
13
|
+
Inisialisasi room multiplayer untuk game baru.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Room } from "@plupin/game-sdk"
|
|
17
|
+
|
|
18
|
+
const room = new Room({
|
|
19
|
+
gameId: "arena-dash",
|
|
20
|
+
name: "player-alpha",
|
|
21
|
+
authority: "host", // "host" untuk simulasi lokal client relay, "server" untuk platform authoritative
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
await room.connect()
|
|
26
|
+
console.log(`Room aktif. Seat: ${room.seatId}, status: ${room.state}`)
|
|
27
|
+
} catch (error) {
|
|
28
|
+
console.error("Gagal inisialisasi room:", error)
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**Perintah verifikasi:**
|
|
33
|
+
```bash
|
|
34
|
+
plupin dev ./dist --port 8787
|
|
35
|
+
```
|
|
36
|
+
Buka `http://127.0.0.1:8787`, amati log konsol mencetak `Room aktif. Seat: ...`.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Resep 2: Multiplayer (Admission, Snapshot/Intent, Peers, Authority, Reconnect)
|
|
41
|
+
|
|
42
|
+
Sinkronisasi multiplayer: admission otomatis via `connect()`, snapshot & intent untuk state, `Peers` untuk interpolasi remote player, seleksi authority leader, dan reconnect saat jaringan putus.
|
|
43
|
+
|
|
44
|
+
> **Penting (host election):** `connect()` resolve sebelum pemilihan host; jangan baca `isLeader` tepat setelah `await`. Tunggu event `room.on("host", ...)` untuk mendeteksi apakah seat ini terpilih memegang authority simulasi.
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { Peers, Room } from "@plupin/game-sdk"
|
|
48
|
+
|
|
49
|
+
const peers = new Peers<{ x: number; y: number }>({
|
|
50
|
+
blend: (a, b, t) => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }),
|
|
51
|
+
create: (seat) => console.log(`[Spawn] Remote peer masuk: ${seat}`),
|
|
52
|
+
update: (seat, pos) => console.log(`[Move] Peer ${seat}:`, pos),
|
|
53
|
+
remove: (seat) => console.log(`[Despawn] Peer keluar: ${seat}`),
|
|
54
|
+
delayMs: 120,
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
const room = new Room<{ score: number }, { type: "move"; x: number; y: number }>({
|
|
58
|
+
gameId: "arena-dash",
|
|
59
|
+
name: "player-alpha",
|
|
60
|
+
authority: "host",
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
room.on("status", ({ status }) => console.log("Status room:", status))
|
|
64
|
+
room.on("host", ({ seat }) => {
|
|
65
|
+
// `seat` adalah hasil pemilihan. Bandingkan dengan seat milikmu — jangan baca
|
|
66
|
+
// `isLeader` di luar handler ini, karena `connect()` resolve sebelum pemilihan selesai.
|
|
67
|
+
if (seat === room.seatId) console.log("Seat ini memegang authority simulasi:", seat)
|
|
68
|
+
})
|
|
69
|
+
room.on("relay", ({ frame }) => {
|
|
70
|
+
// `data` milik pengirim, jadi SDK mengetiknya `unknown`: game yang menyatakan bentuknya.
|
|
71
|
+
if (frame.kind === "pose") peers.push(frame.from, performance.now(), frame.data as { x: number; y: number })
|
|
72
|
+
})
|
|
73
|
+
room.on("snapshot", ({ snapshot }) => console.log("Authoritative state update:", snapshot.view))
|
|
74
|
+
|
|
75
|
+
try {
|
|
76
|
+
await room.connect()
|
|
77
|
+
// PENTING: connect() resolve sebelum pemilihan host; jangan baca isLeader di sini.
|
|
78
|
+
room.send({ type: "move", x: 12, y: 34 })
|
|
79
|
+
room.broadcast("pose", { x: 12, y: 34 })
|
|
80
|
+
const frame = () => {
|
|
81
|
+
peers.sample(performance.now())
|
|
82
|
+
requestAnimationFrame(frame)
|
|
83
|
+
}
|
|
84
|
+
requestAnimationFrame(frame)
|
|
85
|
+
} catch (error) {
|
|
86
|
+
console.error("Multiplayer error:", error)
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
**Perintah verifikasi:**
|
|
91
|
+
```bash
|
|
92
|
+
plupin dev ./dist --port 8787
|
|
93
|
+
```
|
|
94
|
+
Buka 2 tab browser; amati log kedua tab mencetak event `[Spawn]` dan frame pertukaran pose.
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Resep 3: Payment (Game Tidak Membelanjakan Sigma)
|
|
99
|
+
|
|
100
|
+
SDK **tidak punya** `wallet`, dan memang tidak akan punya `wallet.spend`: ADR-0018 melarang game membelanjakan Sigma pemain. Debit dan pembelian terjadi di platform dengan sesi root pemain, bukan di halaman game. Token game yang di-scope (`docs/architecture/identity.md` §2) baru spesifikasi, jadi SDK belum punya permukaan `auth` atau `wallet`.
|
|
101
|
+
|
|
102
|
+
Yang ada hari ini hanya mode uji lokal: `plupin dev` menjalankan dompet palsu di `/_dev/*` tanpa payment gateway, supaya idempotensi alur belanja bisa dicoba. Rute ini hanya ada di proses `plupin dev`, tidak ada di game yang sudah dideploy, jadi jangan dipanggil dari kode game yang dirilis.
|
|
103
|
+
|
|
104
|
+
**Perintah verifikasi:**
|
|
105
|
+
```bash
|
|
106
|
+
TOKEN=$(curl -s -X POST http://127.0.0.1:8787/_dev/auth/sign-in -d '{"name":"alpha"}' | jq -r .token)
|
|
107
|
+
curl -s -X POST http://127.0.0.1:8787/_dev/wallet/spend -H "Authorization: Bearer $TOKEN" \
|
|
108
|
+
-d '{"sku":"skin-legendary","amount":25,"idempotencyKey":"buy-1"}'
|
|
109
|
+
curl -s http://127.0.0.1:8787/_dev/ledger -H "Authorization: Bearer $TOKEN"
|
|
110
|
+
```
|
|
111
|
+
Kirim ulang `idempotencyKey` yang sama: ledger tetap mencatat satu debit.
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## Resep 4: Leaderboard (Top Ranking & Server-Refereed Score)
|
|
116
|
+
|
|
117
|
+
Membaca top ranking dan posisi pemain sendiri. `Leaderboard` hanya membaca: skor dihasilkan oleh room yang menyelesaikan match, jadi tidak ada `submit()` dan tidak ada rute yang menerima angka dari client. Board harus dideklarasikan di `leaderboards` pada `plupin.json`.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { AppError, Leaderboard } from "@plupin/game-sdk"
|
|
121
|
+
|
|
122
|
+
const board = new Leaderboard({ gameId: "arena-dash", board: "high-score" })
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
const page = await board.top(10, { around: 3 })
|
|
126
|
+
for (const entry of page.entries) {
|
|
127
|
+
console.log(`#${entry.rank} ${entry.name}: ${entry.score}`)
|
|
128
|
+
}
|
|
129
|
+
if (page.me) console.log(`Posisi pemain: rank #${page.me.rank}`)
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (error instanceof AppError) console.error(`Gagal memuat ranking [${error.code}]: ${error.fix}`)
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
**Perintah verifikasi:** `Leaderboard` memanggil route platform, jadi uji pada game yang sudah dideploy dengan alamat yang dicetak `plupin up`:
|
|
136
|
+
```bash
|
|
137
|
+
curl -s https://<alamat-game>/api/games/arena-dash/leaderboards/high-score
|
|
138
|
+
```
|
|
139
|
+
Respons berupa JSON berisi `board`, `entries`, dan `me`. Di `plupin dev`, board uji ada di `/_dev/leaderboard/<id>`, bukan di route ini.
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## Resep 5: Deploy (plupin.json minimal, plupin up)
|
|
144
|
+
|
|
145
|
+
Konfigurasi berkas `plupin.json` minimal di direktori build (`dist/plupin.json`), lalu publikasikan. Tidak ada perintah pengecekan terpisah: `plupin up` mengukur build lebih dulu dan menolak mempublikasikan build yang gagal.
|
|
146
|
+
|
|
147
|
+
**Berkas `plupin.json` minimal:**
|
|
148
|
+
```json
|
|
149
|
+
{
|
|
150
|
+
"id": "arena-dash",
|
|
151
|
+
"name": "Arena Dash",
|
|
152
|
+
"entry": "index.html",
|
|
153
|
+
"authority": "host",
|
|
154
|
+
"maxPlayers": 8
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
**Perintah Publish Satu Langkah:**
|
|
159
|
+
```bash
|
|
160
|
+
plupin up ./dist
|
|
161
|
+
```
|
|
162
|
+
Perintah ini memvalidasi folder & manifest, mengukur build secara lokal, mendaftarkan game di registry jika baru, mengunggah aset, dan melakukan polling ke alamat game sampai host menyajikan berkas entry yang baru diunggah (timeout 15s). Alamatnya dicetak oleh perintah ini.
|
|
163
|
+
|
|
164
|
+
**Ukur tanpa publikasi:** `plupin up ./dist --dry-run` (tanpa login).
|
|
165
|
+
|
|
166
|
+
> **Peringatan tegas:** Opsi `--skip-checks` mematikan gerbang pengukuran kualitas build (`mb`, `load`, `ttfi`, `errors`). Dilarang keras menggunakan `--skip-checks` pada publikasi produksi atau penyelesaian tugas karena menonaktifkan validasi gerbang platform.
|
|
167
|
+
|
|
168
|
+
### Arti Tiap Angka
|
|
169
|
+
|
|
170
|
+
Build yang gagal berarti exit 5, metriknya disebut, dan belum ada request ke platform. Batasnya bisa diubah di `plupin.json` → `budget`. Rincian: [checks.md](checks.md).
|
|
171
|
+
|
|
172
|
+
| Metrik | Arti & Pengukuran | Nilai Default Budget | Solusi Jika Gagal |
|
|
173
|
+
|---|---|---|---|
|
|
174
|
+
| **`mb`** | Total ukuran transfer data selama pengujian, diukur via stack jaringan Chromium (Fast 3G: 1.6 Mbps download, 150 ms latency). Menampilkan aset terberat. | `mb ≤ 6` | Kompres tekstur/audio, muat aset besar belakangan. |
|
|
175
|
+
| **`load`** | Halaman mencapai event `load` dalam 45 detik. | wajib | Periksa aset yang menggantung saat halaman dimuat. |
|
|
176
|
+
| **`ttfi`** | *Time to First Input* (detik). Waktu sampai halaman memasang event listener (pointer/touch/key) dan sebuah tap benar-benar sampai. | `ttfi ≤ 6` | Hindari JS yang memblokir sebelum listener terpasang, dan overlay yang menutupi game. |
|
|
177
|
+
| **`errors`** | Console error, uncaught exception, unhandled rejection, dan WebGL context loss. | `errors: 0` | Periksa log konsol, shader, dan pemuatan aset. |
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
## Resep 6: Error → Aksi
|
|
182
|
+
|
|
183
|
+
Kegagalan dari method SDK yang memanggil platform adalah satu `AppError` dengan `code`, `message`, `fix`, `retryable`, dan `retryAfterSeconds` kalau platform menyebut waktu tunggu. Daftar kode dan kalimat perbaikannya ada di satu tempat: [errors.md](errors.md).
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
import { AppError, Leaderboard } from "@plupin/game-sdk"
|
|
187
|
+
|
|
188
|
+
const board = new Leaderboard({ gameId: "arena-dash", board: "high-score" })
|
|
189
|
+
|
|
190
|
+
try {
|
|
191
|
+
await board.top(10)
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (!(error instanceof AppError)) throw error
|
|
194
|
+
console.warn(error.code, error.fix)
|
|
195
|
+
if (error.retryable) setTimeout(() => board.top(10), (error.retryAfterSeconds ?? 5) * 1000)
|
|
196
|
+
else console.error(error.message)
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Penolakan di dalam room (`stale_claim`, `out_of_range`, `reconnect_exhausted`, dan seterusnya) bukan kode di atas: ia datang lewat `room.on("error", ({ code }) => ...)`, daftarnya ada di [api.md](api.md).
|
|
201
|
+
|
|
202
|
+
**Perintah verifikasi:**
|
|
203
|
+
```bash
|
|
204
|
+
plupin docs sdk | grep BOARD_NOT_FOUND
|
|
205
|
+
```
|