@irtio/cli 0.5.2 → 0.7.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.
Files changed (39) hide show
  1. package/dist/api-keys-UTLYMZYN.js +222 -0
  2. package/dist/api.d.ts +52 -0
  3. package/dist/api.js +15 -0
  4. package/dist/bundle.js +1 -1
  5. package/dist/{chunk-GBNHBWES.js → chunk-BQBOBFBO.js} +10 -6
  6. package/dist/chunk-IDF46P7R.js +98 -0
  7. package/dist/{chunk-32QTPKVT.js → chunk-JL235KIE.js} +1 -1
  8. package/dist/chunk-OCVALOGK.js +31 -0
  9. package/dist/{chunk-KRQUAEN2.js → chunk-OTSFRVJN.js} +12 -6
  10. package/dist/chunk-UPHQM6NZ.js +72 -0
  11. package/dist/chunk-WFMRNGO5.js +481 -0
  12. package/dist/chunk-ZK5JLUD4.js +94 -0
  13. package/dist/credentials.d.ts +61 -0
  14. package/dist/credentials.js +20 -0
  15. package/dist/delete-project-MXUYNGAO.js +118 -0
  16. package/dist/deploy.d.ts +151 -0
  17. package/dist/{deploy-3SABPL3T.js → deploy.js} +324 -44
  18. package/dist/{dev-QJOGXLKM.js → dev-AUZ4OLA3.js} +3066 -211
  19. package/dist/index.js +121 -25
  20. package/dist/init.d.ts +1 -1
  21. package/dist/init.js +20 -4
  22. package/dist/{keys-XBORZAPI.js → keys-NXRIBJZP.js} +8 -4
  23. package/dist/leaderboard-ZBJBKETM.js +406 -0
  24. package/dist/{login-3EXB4CGX.js → login-3RVN5PPN.js} +12 -5
  25. package/dist/{logs-2EOXLNWF.js → logs-AT7G6YRH.js} +9 -5
  26. package/dist/{migrate-WUO2GBMX.js → migrate-FMXTRVUV.js} +12 -8
  27. package/dist/ratings-XBLX2MUW.js +297 -0
  28. package/dist/{rollback-GA6UY772.js → rollback-LI4TDLQA.js} +9 -5
  29. package/dist/rooms-52Q5KBUS.js +411 -0
  30. package/dist/simulate.d.ts +254 -6
  31. package/dist/simulate.js +925 -64
  32. package/dist/{static-deploy-5TBH4VNA.js → static-deploy-7UCYINJB.js} +6 -4
  33. package/dist/status-JZGKH2P6.js +219 -0
  34. package/dist/usage-7S447INI.js +213 -0
  35. package/dist/{whoami-CI5D5RCC.js → whoami-UFSWPWK6.js} +8 -4
  36. package/package.json +23 -7
  37. package/dist/chunk-BPE452KF.js +0 -180
  38. package/dist/chunk-TV66QHFP.js +0 -167
  39. package/dist/rooms-B66LQIIF.js +0 -226
package/dist/index.js CHANGED
@@ -1,27 +1,45 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- var [, , command, ...args] = process.argv;
4
+ var [, , command, ...rawArgs] = process.argv;
5
+ var args = [];
6
+ for (let i = 0; i < rawArgs.length; i++) {
7
+ const arg = rawArgs[i];
8
+ if (arg === "--token-file") {
9
+ const value = rawArgs[++i];
10
+ if (value === void 0) {
11
+ console.error("irtio: --token-file needs a value");
12
+ process.exit(1);
13
+ }
14
+ process.env.IRT_CREDENTIALS_FILE = value;
15
+ } else {
16
+ args.push(arg);
17
+ }
18
+ }
5
19
  var HELP = `irtio \u2014 multiplayer rooms for web games
6
20
 
7
21
  usage: irtio <command>
8
22
 
9
23
  commands:
10
- init [dir] [--tick|--event] scaffold irtio/schema.ts, rpc.ts, room.ts,
11
- [--name <name>] room.test.ts and irtio.json (--tick/--event
12
- skip the one question it otherwise asks;
13
- --name is the project name a first deploy
14
- registers, default the directory)
24
+ init [dir] [--tick|--event] [--physics] scaffold irtio/schema.ts, rpc.ts, room.ts,
25
+ [--name <name>] room.test.ts, AGENT.md and irtio.json
26
+ (--tick/--event skip the one question it
27
+ otherwise asks; --physics adds a shared world
28
+ builder; --name is the project name a first
29
+ deploy registers, default the directory)
15
30
  dev [--room <file>] [--port <n>] [--no-watch] bundle the room file and run it locally
16
31
  simulate [--bots <n>] [--seconds <n>] drive N real clients at a running room and
17
- [--room <code>] [--url <ws://\u2026>] check the built-in invariants
18
- [--cheat] [--key <projectKey>] --cheat sends illegal writes and expects
19
- [--trace <path>] corrections; --trace dumps every frame
20
- [--misprediction-max <units>] fail the run if one correction snaps a
21
- [--snaps-max <n>] prediction further than this, if more than
22
- [--corrections-max <perSec>] <n> corrections fall outside the resim
23
- [--overruns-max <n>] window, above this correction rate/bot, or
24
- above this many server tick overruns.
32
+ [--scenario <file>] check the built-in invariants. --scenario runs
33
+ [--room <code>] [--url <ws://\u2026>] your own assertions against the server's
34
+ [--cheat] [--cheat-bot <n>] recorded timeline; --cheat and --conditions
35
+ [--conditions <json>] make the run adversarial; --truth diffs a room
36
+ [--conditions-bot <n>:<json>] save against what the clients received;
37
+ [--truth] [--key <projectKey>] --trace dumps every frame
38
+ [--trace <path>] fail the run if one correction snaps a
39
+ [--misprediction-max <units>] prediction further than this, if more than
40
+ [--snaps-max <n>] <n> corrections fall outside the resim
41
+ [--corrections-max <perSec>] window, above this correction rate/bot, or
42
+ [--overruns-max <n>] above this many server tick overruns.
25
43
  exits 0 clean, 1 violation, 2 not performed
26
44
 
27
45
  login [--url <control>] sign in to a control plane via the browser
@@ -53,19 +71,61 @@ commands:
53
71
  rooms [--project <id>] [--url <control>] list a project's rooms (rows not reported for
54
72
  longer than the control plane's retention
55
73
  window, 30 days by default, are pruned)
74
+ status [--room <id>] [--project <id>] show a project's metrics: the latest tenant-wide
75
+ [--url <control>] rollups, then a per-room table of connections and
76
+ tick health. --room shows one room's recent
77
+ history instead
78
+ usage [--windows] [--project <id>] show what a project used this billing period,
79
+ [--url <control>] per meter. --windows adds the hourly rows behind
80
+ the totals. Card plans see allowances, rates
81
+ and estimated overage; free plans see no dollars
82
+ delete-project <id> --yes [--url <control>] delete a project and every record the control
83
+ plane holds about it. Without --yes it only
84
+ prints what would happen. Refused while the
85
+ project's tenant is live
86
+ leaderboard <board> [--limit <n>] print a project's leaderboard. Reads are public,
87
+ [--around <player>] so no login is needed. There is no submit
88
+ [--project <id>] [--url <control>] command: scores reach a board only from room
89
+ code, which is what makes them
90
+ server-authoritative
91
+ ratings <queue> [--limit <n>] [--all] print a project's skill ratings for one queue,
92
+ [--project <id>] [--url <control>] best first. Needs your login: a rating is what
93
+ the matchmaker uses, not a public scoreboard.
94
+ There is no submit command
95
+ ratings list [--project <id>] every queue with ratings, and its row count
96
+ ratings delete <queue> --player <id> --yes remove one player's rating. Without --yes it
97
+ prints what would go and changes nothing
56
98
  keys jwt-secret [--project <id>] mint a JWT signing secret (printed ONCE);
57
99
  [retire] [--url <control>] retire finishes a rotation
58
100
  keys jwt-mint --secret <s> --sub <player> sign a test token locally with the documented
59
101
  [--room <id>] [--role <r>] [--ttl <sec>] recipe \u2014 the secret never leaves this machine
102
+ rooms [--active|--idle] list a project's rooms, with the retention
103
+ [--idle-longer-than <d>] window in force and when each will be deleted
104
+ rooms get <room> one room in full: type, size class, how many
105
+ saves it holds, how big its state is, deadline
106
+ rooms set <room> --retention <d|forever|clear> override the retention window for THIS room
60
107
  rooms saves <room> list a room's save generations, newest first
61
108
  rooms restore <room> --save <id> bring a room back from a save \u2014 DISCARDS its
62
109
  current state; stops the tenant if it is live
110
+ rooms delete <room> [--force] delete a room's stored state. Refused while it
111
+ is awake unless --force, which disconnects its
112
+ clients first
113
+ api-keys mint --scopes <list> [--label <t>] create a scoped API key for this project and
114
+ print it once. Scopes: rooms:read, rooms:write
115
+ api-keys list this project's keys, revoked ones included
116
+ api-keys revoke <id> stop a key working; the row stays as a record
63
117
 
64
118
  every command takes --help (or -h) and prints its own usage, which is the authority: the lines
65
119
  above are a map, and the command's own help is generated next to the code that parses it.
66
120
 
121
+ every command takes --token-file <file> to read and write credentials there instead of the
122
+ default location (same as setting IRT_CREDENTIALS_FILE). Sign in once with
123
+ \`irtio login --token-file ./.claude/irtio-token.json\`, then pass the same flag on later
124
+ commands \u2014 the pattern for agents and sandboxes that cannot reach the home directory.
125
+
67
126
  every command that reads the project file takes -c/--config <file> to read a different one
68
- (dev, deploy, deploy --static, migrate create, rollback, logs, rooms, keys). Default irtio.json;
127
+ (dev, deploy, deploy --static, migrate create, rollback, logs, rooms, status, keys, api-keys).
128
+ Default irtio.json;
69
129
  the named file must exist. That is the test.irtio.json / prod.irtio.json pattern.
70
130
  `;
71
131
  switch (command) {
@@ -75,7 +135,7 @@ switch (command) {
75
135
  break;
76
136
  }
77
137
  case "dev": {
78
- const { dev } = await import("./dev-QJOGXLKM.js");
138
+ const { dev } = await import("./dev-AUZ4OLA3.js");
79
139
  await dev(args);
80
140
  break;
81
141
  }
@@ -85,50 +145,86 @@ switch (command) {
85
145
  break;
86
146
  }
87
147
  case "login": {
88
- const { login } = await import("./login-3EXB4CGX.js");
148
+ const { login } = await import("./login-3RVN5PPN.js");
89
149
  await login(args);
90
150
  break;
91
151
  }
92
152
  case "whoami": {
93
- const { whoami } = await import("./whoami-CI5D5RCC.js");
153
+ const { whoami } = await import("./whoami-UFSWPWK6.js");
94
154
  await whoami(args);
95
155
  break;
96
156
  }
97
157
  case "deploy": {
98
158
  if (args.includes("--static")) {
99
- const { staticDeploy } = await import("./static-deploy-5TBH4VNA.js");
159
+ const { staticDeploy } = await import("./static-deploy-7UCYINJB.js");
100
160
  await staticDeploy(args);
101
161
  break;
102
162
  }
103
- const { deploy } = await import("./deploy-3SABPL3T.js");
163
+ const { deploy } = await import("./deploy.js");
104
164
  await deploy(args);
105
165
  break;
106
166
  }
107
167
  case "migrate": {
108
- const { migrate } = await import("./migrate-WUO2GBMX.js");
168
+ const { migrate } = await import("./migrate-FMXTRVUV.js");
109
169
  await migrate(args);
110
170
  break;
111
171
  }
112
172
  case "rollback": {
113
- const { rollback } = await import("./rollback-GA6UY772.js");
173
+ const { rollback } = await import("./rollback-LI4TDLQA.js");
114
174
  await rollback(args);
115
175
  break;
116
176
  }
117
177
  case "keys": {
118
- const { keys } = await import("./keys-XBORZAPI.js");
178
+ const { keys } = await import("./keys-NXRIBJZP.js");
119
179
  await keys(args);
120
180
  break;
121
181
  }
182
+ // ---- M6 lane A: rooms API ----
183
+ // Deliberately not folded into `keys` above: that one manages the HMAC secret a game signs its
184
+ // own player tokens with, and this one manages a credential a developer's backend authenticates
185
+ // to irtio with. Two ideas, two names, so "rotate my signing secret" is never one typo away
186
+ // from "revoke my cron job's key".
187
+ case "api-keys": {
188
+ const { apiKeys } = await import("./api-keys-UTLYMZYN.js");
189
+ await apiKeys(args);
190
+ break;
191
+ }
192
+ // ---- end M6 lane A ----
122
193
  case "logs": {
123
- const { logs } = await import("./logs-2EOXLNWF.js");
194
+ const { logs } = await import("./logs-AT7G6YRH.js");
124
195
  await logs(args);
125
196
  break;
126
197
  }
127
198
  case "rooms": {
128
- const { rooms } = await import("./rooms-B66LQIIF.js");
199
+ const { rooms } = await import("./rooms-52Q5KBUS.js");
129
200
  await rooms(args);
130
201
  break;
131
202
  }
203
+ case "status": {
204
+ const { status } = await import("./status-JZGKH2P6.js");
205
+ await status(args);
206
+ break;
207
+ }
208
+ case "delete-project": {
209
+ const { deleteProject } = await import("./delete-project-MXUYNGAO.js");
210
+ await deleteProject(args);
211
+ break;
212
+ }
213
+ case "usage": {
214
+ const { usage } = await import("./usage-7S447INI.js");
215
+ await usage(args);
216
+ break;
217
+ }
218
+ case "ratings": {
219
+ const { ratings } = await import("./ratings-XBLX2MUW.js");
220
+ await ratings(args);
221
+ break;
222
+ }
223
+ case "leaderboard": {
224
+ const { leaderboard } = await import("./leaderboard-ZBJBKETM.js");
225
+ await leaderboard(args);
226
+ break;
227
+ }
132
228
  case void 0:
133
229
  case "help":
134
230
  case "--help":
package/dist/init.d.ts CHANGED
@@ -59,7 +59,7 @@ interface InitResult {
59
59
  * `irtio init [dir] [--tick|--event]`. Hand-rolled like `parseDevArgs`: the CLI has no
60
60
  * argument-parsing dependency and four flags do not earn one.
61
61
  */
62
- declare const USAGE = "usage: irtio init [dir] [options]\n\nScaffolds irtio/schema.ts, irtio/rpc.ts, irtio/room.ts, irtio/room.test.ts and irtio.json.\nNothing that already exists is ever overwritten.\n\noptions:\n [dir] where to scaffold (default: here)\n --tick a tick room, without asking\n --event an event room, without asking\n --physics scaffold a physics room and its shared world builder\n --name <name> the project name a first deploy registers (default: the directory)\n -h, --help print this\n";
62
+ declare const USAGE = "usage: irtio init [dir] [options]\n\nScaffolds irtio/schema.ts, irtio/rpc.ts, irtio/room.ts, irtio/room.test.ts, irtio/AGENT.md\nand irtio.json. Nothing that already exists is ever overwritten.\n\noptions:\n [dir] where to scaffold (default: here)\n --tick a tick room, without asking\n --event an event room, without asking\n --physics scaffold a physics room and its shared world builder\n --name <name> the project name a first deploy registers (default: the directory)\n -h, --help print this\n";
63
63
  declare function parseInitArgs(args: readonly string[]): InitArgs;
64
64
  /** `p_` + 16 hex characters: the project id *is* the public key, so it is not a secret. */
65
65
  declare function generateProjectId(): string;
package/dist/init.js CHANGED
@@ -2,7 +2,9 @@ import {
2
2
  HelpRequested,
3
3
  helpFor,
4
4
  helpRequested
5
- } from "./chunk-TV66QHFP.js";
5
+ } from "./chunk-OCVALOGK.js";
6
+ import "./chunk-IDF46P7R.js";
7
+ import "./chunk-UPHQM6NZ.js";
6
8
 
7
9
  // src/init.ts
8
10
  import { randomBytes } from "crypto";
@@ -11,6 +13,11 @@ import { mkdir, readFile, writeFile } from "fs/promises";
11
13
  import * as path from "path";
12
14
  import { createInterface } from "readline/promises";
13
15
  import pc from "picocolors";
16
+
17
+ // src/agent-guide.generated.ts
18
+ var AGENT_GUIDE = "# irt.io integration guide\n\nThe whole product in one page, written for a context window. Everything below is enough to take a\nsingle-player web game to a deployed, verified multiplayer room without opening a dashboard.\n\n## The mental model\n\nA **room** is a server-side TypeScript file. It owns a small typed **schema**: the state two\nplayers have to agree on, and nothing else about your game. Each client owns its own instances and\nwrites them like local objects. The room's `validate` decides what a write may be. Everything else\nin your game stays where it was. You verify a room the way you verify code. Bots drive real\nsockets, a **scenario** asserts against the server's own recorded timeline, and the same seed gives\nthe same verdict.\n\n## The skeleton\n\nThe smallest project that deploys. Four files, and `irtio init` writes all of them.\n\n```ts\n// irtio/schema.ts\nimport { defineSchema, entity, f32, str, u8 } from '@irtio/schema';\n\nimport { rpc } from './rpc.js';\n\nexport const schema = defineSchema(\n {\n // One instance per connected client, owned by that client. Owned means writable on that\n // client and read-only everywhere else.\n players: entity({ x: f32, y: f32, name: str(24), color: u8 }),\n },\n {\n project: 'p_c0ffee1234abcd56', // written by `irtio init`; public, domain-locked, not a secret\n roles: ['player'] as const,\n rpc,\n },\n);\n```\n\n```ts\n// irtio/rpc.ts\nimport { server, u8 } from '@irtio/schema';\n\n// Typed calls in both directions. `server(...)` is client to server. Names and signatures are\n// part of the schema hash, so skew is caught as a version error instead of at runtime.\nexport const rpc = {\n cheer: server({ params: { volume: u8 } }),\n};\n```\n\n```ts\n// irtio/room.ts\nimport { defineRoom } from '@irtio/server';\n\nimport { schema } from './schema.js';\n\nconst WIDTH = 800;\nconst HEIGHT = 500;\n\nexport default defineRoom(schema, {\n mode: 'tick', // 'event' if nothing moves without a player doing something\n tickRate: 20,\n\n onJoin(state, ctx) {\n if (ctx.reconnecting) return;\n state.players.add(\n ctx.clientId,\n { x: 0, y: 0, name: ctx.name || 'anon', color: (ctx.tick * 37) % 256 },\n { owner: ctx.clientId }, // the line the whole client-side write model rests on\n );\n },\n\n onLeave(state, ctx) {\n state.players.remove(ctx.clientId);\n },\n\n // Owner writes pass through here before they are accepted. Return `next` to accept, `prev` to\n // reject, or a clamped object. This is where cheating stops. Delete it and anything that fits\n // the declared types is accepted.\n validate: {\n players(prev, next) {\n // Refuse what could never be a real value, lock the fields the room assigned at join,\n // and clamp the rest into the world.\n if (!Number.isFinite(next.x) || !Number.isFinite(next.y)) return prev;\n if (next.name !== prev.name || next.color !== prev.color) return prev;\n return {\n ...next,\n x: Math.min(WIDTH, Math.max(0, next.x)),\n y: Math.min(HEIGHT, Math.max(0, next.y)),\n };\n },\n },\n\n rpc: {\n cheer(state, params, ctx) {\n if (params.volume > 10) throw new Error('too loud'); // the normal way a room says no\n state.players.get(ctx.clientId)!.color = params.volume;\n },\n },\n\n tick() {}, // tick mode needs one, even empty\n});\n```\n\n```ts\n// your game, three lines added\nimport { joinRoom } from '@irtio/client';\n\nimport { schema } from './irtio/schema.js';\n\nconst room = await joinRoom(schema, { name: 'you' }); // reads ?room=, or creates one\nconst me = room.state.players[room.me]; // yours: write it like a local object\nif (me) me.x = 10;\n\nfor (const [, p] of room.render.players) draw(p); // `render` interpolates everyone else\n```\n\n`room.state` is the authoritative read path for game logic and tests. `room.render` has the same\nshapes and reads non-owned entities a beat behind arrival, interpolated, which is what you draw\nfrom. Writes are batched once per animation frame, and `room.flush()` forces one out now.\n`room.leave()` closes the session. A page rarely needs it; a test with several sessions always\ndoes. `joinRoom`'s options are `{ name, role, url, key, token, physics, transport }`; see\nthe client reference.\n\n`@irtio/client` is a module, so the page that imports it needs whatever bundler your game already\nuses. There is no `irtio build`.\n\n### Write the validate rule your game actually has\n\n`validate` is the one part of the skeleton you cannot copy without thinking. The wrong rule here\nis worse than no rule, because it refuses honest play silently. The server sends a correction, and\nthe thing does not go where the player put it.\n\nA **speed limit** (`if (Math.hypot(next.x - prev.x, next.y - prev.y) > MAX_STEP) return prev;`) is\nright when the thing being moved has a movement speed the game defines: a character, a vehicle, a\ndragged token. It is wrong for a **mouse cursor**. A cursor legitimately teleports when the pointer moves fast,\nor when it leaves the window and comes back. A player gains nothing by putting their cursor\nsomewhere.\n\nAsk what a cheat would actually win. Position, for a cursor, wins nothing, so clamp it and stop.\nPosition for a character wins map knowledge and reach, so limit the step. Score, turn order, hit\ndetection and inventory win the game outright, so they should not be client-owned at all: make\nthem `serverOwned` and change them through an RPC.\n\n## The four commands\n\n```bash\nnpx irtio init # scaffold the four files above plus irtio.json\nnpx irtio dev # bundle irtio/room.ts and run it locally\nnpx irtio simulate --scenario irtio/scenario.ts # real bots, your assertions, exit code\nnpx irtio deploy # create the project if new, classify, upload\n```\n\n`simulate` drives real clients at a room that is **already running**, so `dev` stays up in another\nterminal while you run it. The four are a loop, not a pipeline.\n\nEvery subcommand takes `--help`, and the per-command help is the complete list; the top-level\nsummary is a map.\n\n`dev` is the whole server, locally: it bundles the room file and runs it the way the hosted\nserver does, so it is what you develop and test against. It does not build or serve your\n**client**. That stays your own bundler's job, the same one your game already uses.\n\n`deploy` is the hosted path and needs `irtio login`. There is no offline `deploy`. Without an\naccount, `dev` plus your own bundler is as far as you get, and that runs everything below.\n\n`deploy` creates the project on first use and classifies the schema change against the last\ndeployment. It refuses breaking changes unless a migration covers them, then prints where the room\nis playable. `simulate` exits non-zero on a violation, so both belong in CI.\n\nWhen the question is \"why is this room using so much bandwidth\", both commands take `--profile`.\n`dev --profile` prints a per-room breakdown by collection and field once a second.\n`simulate --profile` prints one for the whole run as the bots saw it. The answer is usually a\nsingle wide field, or `overhead` telling you the updates are too small and too frequent. See\n[the profiler](/docs/guides/profiler).\n\n**Restart `dev` after editing the room.** With `--no-watch`, a `dev` you forgot to kill keeps\nserving the old bundle. `simulate` connects to it and reports a clean run against code you have\nreplaced. The report header names the bundle hash and how long the server has been up. Compare\nthose two lines between runs: an edit that changed nothing in the header changed nothing in the\ncode under test.\n\nAn agent driving this through MCP calls `project_create`, `origin_add`, `deploy`, `scenario_run`,\nthen `logs` or `metrics`. Sign in once with `npx irtio login`; the MCP config snippet is a command\nand carries no secret.\n\n## Verify a room with a scenario\n\nA scenario is a TypeScript module next to the room file. Assertions run against the recorded\nauthoritative timeline, one frame per server tick. A scenario can prove something about a race no\nclient could observe, and it replays: same seed, same verdict.\n\n```ts\n// irtio/scenario.ts\nimport { defineScenario } from '@irtio/bots';\n\nimport type { schema } from './schema.js';\n\nexport default defineScenario<typeof schema>({\n bots: 2,\n seconds: 4,\n seed: 41,\n\n // Adversarial in two words: bot 0 lags, and every bot tries illegal writes. `validate` above\n // is what has to refuse them.\n conditions: (index) => (index === 0 ? { rttMs: 200 } : undefined),\n cheat: true,\n\n script: async (bot) => {\n await bot.wait(200);\n await bot.room.call.cheer({ volume: 3 });\n await bot.wait(500);\n },\n\n assert: (timeline) => {\n timeline.check('nobody left the arena', () => {\n for (const tick of timeline.ticks) {\n for (const id of timeline.at(tick).players!.ids()) {\n const p = timeline.at(tick).players!.get(id)!;\n if (p.x < 0 || p.x > 800) throw new Error(`player ${id} at x=${p.x} on tick ${tick}`);\n }\n }\n });\n },\n});\n```\n\n`cheat: true` makes the bots write play-illegal values. If the run reports\n`HOLE bot <n> cheated and drew 0 corrections`, your `validate` accepted them, and that is the\nfinding. `truth: true` additionally saves the room at the end and diffs it against what each client\nactually received.\n\nTwo things to know before you read a result.\n\n**A cheat run that works fails the run by default.** Every refused write is a correction, and the\nbuilt-in `correction-storm` invariant fails above 5 corrections per second per bot. A deliberate\ncheater passes that immediately. Raise it for the run with `--corrections-max 25`, and read the\n`HOLE` line rather than the exit code as the verdict on `validate`.\n\n**The built-in invariants alone prove nothing about `validate`.** They are protocol invariants:\nframes decoded, nobody saw what they should not, bandwidth inside budget, no tick overruns. A room\nthat accepts every illegal write there is passes all of them. Only `cheat` and your own scenario\nassertions test server authority, so a run with neither says nothing about whether your game can be\ncheated.\n\n## One retrofit diff\n\nThe canvas case, the shortest one. The cursors canvas example is this diff as running code; see\n[the retrofit guide](/docs/guides/retrofit).\n\n```diff\n+import { joinRoom } from '@irtio/client';\n+\n+import { schema } from './irtio/schema.js';\n+\n+const room = await joinRoom(schema, { name: 'you' });\n-const player = { x: canvas.width / 2, y: canvas.height / 2, name: 'you', color: 200 };\n-\n canvas.addEventListener('pointermove', (event) => {\n const bounds = canvas.getBoundingClientRect();\n+ const player = room.state.players[room.me];\n+ if (!player) return;\n player.x = event.clientX - bounds.left;\n player.y = event.clientY - bounds.top;\n });\n\n function frame() {\n- const entries = [['me', player]];\n+ const entries = [...room.render.players];\n for (const [, p] of entries) draw(p);\n }\n```\n\nThe whole shape is an import, a join, an entity lookup instead of a local object, and one changed\niteration. The camera, particles, input handling, HUD, draw code and level geometry do not\nmove. If your retrofit touches those, it is doing more than a retrofit. Three.js and Phaser follow\nthe same four steps against their own loops; see the retrofit guide.\n\nYour entity does not exist for the first frame or two after the page loads, which is what\n`if (!player) return;` is for. Writing an instance you do not own is a compile error and a\nwarn-once no-op at runtime.\n\n## When it goes wrong\n\nThe codes you will actually meet, with the fix. The full catalogue is at `/docs/reference/errors`.\n\n| Code | Fix |\n|---|---|\n| `E_AUTH` | The project key was rejected. Check `project` in `irtio/schema.ts` matches the project you are deploying to. On localhost with no `irtio init` the client uses the key `dev`, which only `irtio dev` accepts |\n| `E_SCHEMA_MISMATCH` | The client was built with a different schema than the room is running. The hash covers every field, type, order, role and RPC signature. Rebuild the client, or deploy the schema the client has |\n| `E_ORIGIN` | The page's origin is not in the project's origin list. Register it. `localhost` is always allowed, so this only bites on a deployed page |\n| `E_ROOM_FULL` | The room is at `maxClients`, 64 by default. Raise it in `irtio/room.ts`, or join with no `?room=` to get a new room |\n| `E_ROOM_NOT_FOUND` | No such room, or an id that cannot be one. Do not construct ids yourself: let `joinRoom` create one and read `room.link` |\n| `E_WRITE_REJECTED` | Your `validate` refused the write, or the value did not fit its declared type. If this is a legitimate move, `validate` is too strict or the field too narrow |\n| `E_NOT_OWNER` | Something wrote an instance it does not own. `await room.requestOwnership(entity, id)` first, and re-read the instance after a grant |\n| `E_RPC_BAD_PARAMS` | Parameters did not match the declared shape. Types normally prevent this, so it means client and server were built from different `rpc.ts` files |\n| `E_RATE_LIMITED` | Read the message. `rate limited` is too many frames: batch instead of calling `room.flush()` in a loop. `too many connections from this address` is the per-IP cap (`connectionsPerIpPerMin`, default 120), which a load run from one machine has to raise |\n| `E_STARTING` | Not an error. The server was asleep and is waking. `room.status === 'starting'`; show a spinner and keep waiting |\n| `E_SLOW_CONSUMER` | The client was not draining its stream and was dropped; it reconnects itself. If it recurs, the room produces more per tick than the connection carries: lower `tickRate`, narrow field types, or use role visibility |\n| `E_CONNECT_FAILED` | Not a protocol code. The socket failed before the join. Read the URL in the message: `ws://localhost:7070` means `irtio dev` is not running |\n| `deploy refused: N breaking changes` | Snapshots cannot be read under the new schema. `irtio migrate create <name>`, write the transform, then `irtio deploy --allow-breaking`. Additive changes (a new field with `.default(...)` or `.opt`) need none of this |\n| `not logged in` | `deploy`, `logs`, `rooms`, `whoami` and `migrate create` need credentials. Run `irtio login` |\n| `HOLE bot <n> cheated and drew 0 corrections` | Not a failure, and the most important warning here. Illegal writes were accepted. Add rules to `validate` |\n\n## Past the skeleton\n\nThe skeleton above is the smallest thing that deploys. Each of these is one docs page\nand none of them changes the model.\n\n- Server-authoritative physics with client prediction: `irtio init --physics`, a shared\n `irtio/world.ts` both sides import, Rapier in 3D (`/docs/physics/overview`) or matter.js in 2D\n (`/docs/physics/matter2d`, `tickRate: 60`). Both predict, and `room.prediction` reads the same\n either way (`/docs/physics/prediction`).\n- Scripted NPCs that are ordinary client sessions at the protocol level: `room.spawnNPC(...)`\n (`/docs/guides/npcs`).\n- Player storage that outlives a room (`room.kv`), room saves and restores, hibernation, and the\n `retention` option that sets how long a room's state survives\n (`/docs/persistence/player-storage`, `/docs/persistence/saves`, `/docs/concepts/hibernation`).\n- Signed player tokens, roles, and per-role visibility (`/docs/concepts/auth`,\n `/docs/concepts/visibility`).\n- A player identity that survives reconnects, hibernation and a closed tab\n (`/docs/concepts/identity`).\n- Ranked boards per project, written only by your room code\n (`/docs/persistence/leaderboards`).\n- Two strangers matched into a room without either knowing a room code\n (`/docs/concepts/quick-match`).\n- Voice chat in a room, on its own meter (`/docs/concepts/voice`).\n- One of your rooms sending a message to another (`/docs/concepts/room-bus`).\n- A project split across more than one server when a single one is full\n (`/docs/deploy/sharding`).\n\n**Starting from an engine.** Build against the engine's own loop from the first line: React and\nreact-three-fiber (`/docs/integrations/react`), Three.js (`/docs/integrations/threejs`), Phaser\n(`/docs/integrations/phaser`), PixiJS (`/docs/integrations/pixijs`), Babylon.js\n(`/docs/integrations/babylonjs`).\n\n**Moving a game that already exists.** Single-player, which is the diff above at full length:\ncanvas (`/docs/guides/retrofit`), Three.js (`/docs/guides/retrofit-threejs`), Phaser\n(`/docs/guides/retrofit-phaser`). Already multiplayer on something else: Colyseus\n(`/docs/migrate/colyseus`), Playroom (`/docs/migrate/playroom`), Socket.IO\n(`/docs/migrate/socket-io`).\n\nEvery term these pages use is defined once in the glossary (`/docs/reference/glossary`).\n\n## Rules of thumb\n\n- Sync the smallest set of facts two players must agree on. Everything else stays local.\n- A player reporting a fact about themselves is an owned write. Anything a player could gain by\n lying about (scores, deals, turn order, hit detection) is `serverOwned` plus an RPC.\n- Types are budgets, not hints. `f32`, `u8`, `str(24)` are what make an update a handful of bytes.\n- Never import `room.ts` from client code. Shared geometry and constants go in their own module\n that both sides import.\n- Do not paste a credential into a config file. `irtio login` writes one; MCP and the CLI find it.\n- Believe a room when a scenario with an adversarial pass says so, not when it looks right in two\n tabs.\n";
19
+
20
+ // src/init.ts
14
21
  var INIT_DEPENDENCIES = [
15
22
  "@irtio/schema",
16
23
  "@irtio/server",
@@ -21,8 +28,8 @@ var DEFAULT_TICK_RATE = 20;
21
28
  var DEFAULT_IDLE_MS = 3e4;
22
29
  var USAGE = `usage: irtio init [dir] [options]
23
30
 
24
- Scaffolds irtio/schema.ts, irtio/rpc.ts, irtio/room.ts, irtio/room.test.ts and irtio.json.
25
- Nothing that already exists is ever overwritten.
31
+ Scaffolds irtio/schema.ts, irtio/rpc.ts, irtio/room.ts, irtio/room.test.ts, irtio/AGENT.md
32
+ and irtio.json. Nothing that already exists is ever overwritten.
26
33
 
27
34
  options:
28
35
  [dir] where to scaffold (default: here)
@@ -377,7 +384,11 @@ var ROOM_TEST_TEMPLATE = `/**
377
384
  * view agrees with the server. \`testRoom\` runs the real room and real client semantics in
378
385
  * process \u2014 no sockets, no server, fake clock \u2014 so this is a unit test in every way that matters.
379
386
  *
380
- * Extend it: that is what it is for.
387
+ * Extend it: that is what it is for. One thing to know when you do. The write below jumps from the
388
+ * spawn position straight to x=10, and the scaffolded \`validate\` accepts it because it accepts
389
+ * everything. The moment you write a real \`validate\` with a step limit, the room will refuse this
390
+ * write and this test will fail against a room that is working correctly. Make the write a legal
391
+ * move from where \`onJoin\` spawns the player, and add a test that an illegal one is refused.
381
392
  */
382
393
 
383
394
  import { expect, test } from 'vitest';
@@ -433,6 +444,9 @@ function nextSteps(installCommand) {
433
444
  "",
434
445
  " 5. check it under load before you believe it",
435
446
  pc.cyan(" npx irtio simulate --bots 5 --seconds 10"),
447
+ "",
448
+ " irtio/AGENT.md is the whole product on one page: the model, this skeleton, the four",
449
+ " commands, a retrofit diff and every error worth knowing. Point your coding agent at it.",
436
450
  ""
437
451
  ];
438
452
  }
@@ -500,6 +514,7 @@ async function runInit(options = {}) {
500
514
  ["irtio/world.ts", WORLD_TEMPLATE],
501
515
  ["irtio/room.ts", physicsRoomTemplate()],
502
516
  ["irtio/room.test.ts", PHYSICS_ROOM_TEST_TEMPLATE],
517
+ ["irtio/AGENT.md", AGENT_GUIDE],
503
518
  ["irtio.json", `${JSON.stringify({ project, name }, null, 2)}
504
519
  `]
505
520
  ] : [
@@ -507,6 +522,7 @@ async function runInit(options = {}) {
507
522
  ["irtio/rpc.ts", RPC_TEMPLATE],
508
523
  ["irtio/room.ts", roomTemplate(mode)],
509
524
  ["irtio/room.test.ts", ROOM_TEST_TEMPLATE],
525
+ ["irtio/AGENT.md", AGENT_GUIDE],
510
526
  ["irtio.json", `${JSON.stringify({ project, name }, null, 2)}
511
527
  `]
512
528
  ];
@@ -1,12 +1,16 @@
1
1
  import {
2
2
  readProjectConfig
3
- } from "./chunk-32QTPKVT.js";
3
+ } from "./chunk-JL235KIE.js";
4
+ import {
5
+ helpRequested
6
+ } from "./chunk-OCVALOGK.js";
4
7
  import {
5
8
  createApiClient,
6
- helpRequested,
7
- isLoginRequired,
9
+ isLoginRequired
10
+ } from "./chunk-IDF46P7R.js";
11
+ import {
8
12
  resolveControlUrlForUser
9
- } from "./chunk-TV66QHFP.js";
13
+ } from "./chunk-UPHQM6NZ.js";
10
14
 
11
15
  // src/keys.ts
12
16
  import "fs";