@homie-rocks/studio 0.46.0 → 0.46.2

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,496 @@
1
+ /** Load clients live on worker threads; every snapshot is decoded, no per-frame diagnostic re-encoding. */
2
+ import { parentPort, workerData } from 'node:worker_threads';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { performance, monitorEventLoopDelay } from 'node:perf_hooks';
5
+ import WebSocket from 'ws';
6
+ import { snapshotDecoder } from '../rules/interest.mjs';
7
+
8
+ export class Histogram {
9
+ bins = new Uint32Array(60001);
10
+ count = 0;
11
+ max = 0;
12
+ add(ms) {
13
+ if (!Number.isFinite(ms) || ms < 0) return;
14
+ this.bins[Math.min(60000, Math.round(ms))]++;
15
+ this.count++;
16
+ this.max = Math.max(this.max, ms);
17
+ }
18
+ merge(h) {
19
+ for (let i = 0; i < this.bins.length; i++) this.bins[i] += h.bins[i];
20
+ this.count += h.count;
21
+ this.max = Math.max(this.max, h.max);
22
+ }
23
+ json() {
24
+ const p = (q) => {
25
+ let n = 0;
26
+ for (let i = 0; i < this.bins.length; i++) {
27
+ n += this.bins[i];
28
+ if (n >= Math.ceil(this.count * q)) return this.count ? i : null;
29
+ }
30
+ return null;
31
+ };
32
+ return {
33
+ count: this.count,
34
+ p50: p(0.5),
35
+ p95: p(0.95),
36
+ p99: p(0.99),
37
+ max: this.max
38
+ };
39
+ }
40
+ }
41
+ export function createLoad({
42
+ origin,
43
+ game,
44
+ room,
45
+ index = 0,
46
+ workers = 1,
47
+ lead = 3,
48
+ compress = true,
49
+ onProblem = () => {}
50
+ }) {
51
+ const clients = [],
52
+ errors = new Map(),
53
+ first = new Histogram(),
54
+ welcome = new Histogram(),
55
+ ack = new Histogram(),
56
+ gaps = new Histogram(),
57
+ // From the tick a player held when it stamped an input to the tick it
58
+ // reached the rules, ms: what the system took, whatever the lead.
59
+ loops = new Histogram();
60
+ // Snapshots that said how early this player's input was, and how many said late.
61
+ let lateAcks = 0,
62
+ onTime = 0;
63
+ const loop = monitorEventLoopDelay({ resolution: 10 });
64
+ loop.enable();
65
+ let measuring = false,
66
+ rampCancelled = false,
67
+ stopping = false,
68
+ epoch = null,
69
+ totalUp = 0,
70
+ totalDown = 0,
71
+ up = 0,
72
+ down = 0,
73
+ sent = 0,
74
+ inputFrames = 0,
75
+ received = 0,
76
+ skipped = 0,
77
+ expired = 0,
78
+ disconnects = 0,
79
+ peakLag = 0,
80
+ badLag = 0,
81
+ stopReason = null;
82
+ let timer,
83
+ expected = performance.now();
84
+ const problem = (type, value) => {
85
+ const key = `${type}: ${String(value).slice(0, 300)}`;
86
+ if (errors.has(key)) errors.set(key, errors.get(key) + 1);
87
+ else if (errors.size < 100) {
88
+ errors.set(key, 1);
89
+ onProblem(key);
90
+ }
91
+ };
92
+ function send(c, m) {
93
+ if (c.ws?.readyState !== 1) return;
94
+ if (c.ws.bufferedAmount > 262144) {
95
+ stopReason ??= 'driver send backlog';
96
+ return;
97
+ }
98
+ const text = JSON.stringify(m),
99
+ bytes = Buffer.byteLength(text);
100
+ c.ws.send(text);
101
+ totalUp += bytes;
102
+ if (measuring) {
103
+ up += bytes;
104
+ sent++;
105
+ if (m.t === 'in') inputFrames++;
106
+ c.up += bytes;
107
+ }
108
+ }
109
+ function snapshot(c, raw) {
110
+ c.rawSnapshots++;
111
+ c.rawTick = raw.k;
112
+ const snap = c.decoder.decode(raw);
113
+ if (!snap) {
114
+ c.decodeMiss++;
115
+ return;
116
+ }
117
+ const own = snap.d[1].find((e) => e[9] === c.seat && e[10] !== 1);
118
+ if (!own) {
119
+ c.ownMissing++;
120
+ return;
121
+ }
122
+ const now = performance.now();
123
+ epoch ??= snap.e;
124
+ if (epoch !== snap.e) stopReason ??= 'room restarted';
125
+ if (c.first === null) {
126
+ c.first = now;
127
+ first.add(now - c.began);
128
+ }
129
+ if (c.epoch !== snap.e) {
130
+ c.pending.clear();
131
+ c.lastSent = 0;
132
+ c.epoch = snap.e;
133
+ }
134
+ const gap = c.at ? now - c.at : 0;
135
+ c.maxStateGapMs = Math.max(c.maxStateGapMs, gap);
136
+ c.k = snap.k;
137
+ c.at = now;
138
+ c.own = own;
139
+ c.r = own[2];
140
+ c.snapshots++;
141
+ if (measuring) {
142
+ c.firstTick ??= snap.k;
143
+ c.firstAt ??= now;
144
+ c.lastTick = snap.k;
145
+ c.lastAt = now;
146
+ c.frames++;
147
+ gaps.add(gap);
148
+ }
149
+ const control = snap.c?.find((row) => row[0] === c.seat);
150
+ // The room says how early this player's inputs arrive, in sixteenths of a
151
+ // tick (the smallest since its last snapshot). The toolkit's client steers
152
+ // its clock by that, to be half a tick early but for its jitter; this probe
153
+ // moves its whole-tick lead the same way: every two seconds, one more when
154
+ // the earliest twentieth of its last forty reports was under half a tick
155
+ // early, one fewer when it was over a tick and a half.
156
+ if (control && control[3] !== -128 && control[3] !== undefined) {
157
+ const early = control[3] / 16;
158
+ if (measuring) { if (early <= 0) lateAcks++; onTime++; loops.add((c.lead - early) * 50); }
159
+ (c.early ??= []).push(early); if (c.early.length > 40) c.early.shift();
160
+ if (c.early.length >= 20 && now - (c.leadAt ?? 0) > 2000) {
161
+ const low = c.early.slice().sort((a, b) => a - b)[Math.floor(c.early.length / 20)];
162
+ if (low < 0.5 && c.lead < 12) c.lead++;
163
+ else if (low > 1.5 && c.lead > 1) c.lead--;
164
+ c.leadAt = now; c.early.length = 0;
165
+ }
166
+ }
167
+ if (control)
168
+ for (const [tick, at] of c.pending) {
169
+ if (tick > control[2]) break;
170
+ c.pending.delete(tick);
171
+ if (measuring) {
172
+ if (tick === control[2]) ack.add(now - at);
173
+ else skipped++;
174
+ }
175
+ }
176
+ }
177
+ async function connect(i, reused) {
178
+ const c = {
179
+ i,
180
+ key: reused?.key ?? randomBytes(18).toString('base64url'),
181
+ seat: null,
182
+ token: reused?.token ?? null,
183
+ priorSeat: reused?.seat ?? null,
184
+ first: null,
185
+ lead,
186
+ began: performance.now(),
187
+ decoder: snapshotDecoder(),
188
+ pending: new Map(),
189
+ epoch: null,
190
+ k: 0,
191
+ r: 0,
192
+ at: 0,
193
+ lastSent: 0,
194
+ firstTick: null,
195
+ firstAt: null,
196
+ lastTick: null,
197
+ lastAt: null,
198
+ frames: 0,
199
+ up: 0,
200
+ down: 0,
201
+ snapshots: 0,
202
+ rawSnapshots: 0,
203
+ decodeMiss: 0,
204
+ ownMissing: 0,
205
+ maxStateGapMs: 0,
206
+ own: null,
207
+ nextPing: performance.now() + (i % 20) * 100,
208
+ nextInput: performance.now() + (i % 10) * 10
209
+ };
210
+ clients.push(c);
211
+ try {
212
+ const response = await fetch(
213
+ `${origin}/${game}/__game/?room=${encodeURIComponent(room)}&device=desk&want=play&b=${c.key}`,
214
+ { signal: AbortSignal.timeout(15000) }
215
+ );
216
+ if (!response.ok) throw Error(`bootstrap HTTP ${response.status}`);
217
+ const match = (await response.text()).match(
218
+ /window\.HOMIE_NET=(\{[^<]+\})<\/script>/
219
+ );
220
+ if (!match) throw Error('No HOMIE_NET bootstrap');
221
+ const cfg = JSON.parse(match[1]);
222
+ if (cfg.room !== undefined && cfg.room !== room)
223
+ throw Error('bootstrap changed the requested room');
224
+ c.ws = new WebSocket(cfg.url, {
225
+ origin: 'null',
226
+ handshakeTimeout: 15000,
227
+ // A browser always offers compression; a driver that refuses it asks
228
+ // one uplink for several times the bytes real players would cost it.
229
+ perMessageDeflate: compress
230
+ });
231
+ c.ws.on('open', () => {
232
+ c.helloAt = performance.now();
233
+ c.compressed = /permessage-deflate/.test(c.ws.extensions ?? '');
234
+ send(c, {
235
+ t: 'hello',
236
+ rules: true,
237
+ v: 1,
238
+ rev: 12,
239
+ token: c.token,
240
+ name: `Load ${i}`,
241
+ device: 'desk',
242
+ want: 'play',
243
+ canHost: false,
244
+ // As the toolkit's client (0.46.2): this decoder coasts a body it was not sent.
245
+ coast: 1,
246
+ game,
247
+ max: 1000,
248
+ ...(cfg.ver ? { ver: cfg.ver } : {})
249
+ });
250
+ });
251
+ c.ws.on('message', (data) => {
252
+ totalDown += data.length;
253
+ if (measuring) {
254
+ down += data.length;
255
+ received++;
256
+ c.down += data.length;
257
+ }
258
+ let m;
259
+ try {
260
+ m = JSON.parse(data.toString());
261
+ } catch {
262
+ problem('decode', i);
263
+ return;
264
+ }
265
+ if (m.t === 'welcome') {
266
+ c.token = m.token;
267
+ c.seat = m.seat;
268
+ welcome.add(performance.now() - c.began);
269
+ if (m.full || c.seat === null) problem('unseated', i);
270
+ if (m.snap) snapshot(c, m.snap);
271
+ } else if (m.t === 'snap') snapshot(c, m);
272
+ else if (m.t === 'seat') c.seat = m.seat;
273
+ else if (m.t === 'err' || m.t === 'error') {
274
+ problem(m.code ?? m.t, m.message);
275
+ if (
276
+ ['room-over', 'host-fault', 'host-failed', 'closed'].includes(
277
+ m.code
278
+ )
279
+ )
280
+ stopReason ??= `server ${m.code}`;
281
+ }
282
+ });
283
+ c.ws.on('error', (e) => problem('socket', e.message));
284
+ c.ws.on('unexpected-response', (_req, res) => {
285
+ problem('upgrade', res.statusCode);
286
+ res.resume();
287
+ c.ws.terminate();
288
+ });
289
+ c.ws.on('close', (code, reason) => {
290
+ c.closeCode = code;
291
+ c.closeReason = String(reason);
292
+ c.closedAt = performance.now();
293
+ if (!stopping && !c.retired) {
294
+ disconnects++;
295
+ problem('close', `${code} ${reason}`);
296
+ }
297
+ });
298
+ } catch (e) {
299
+ problem('connect', e.message);
300
+ }
301
+ }
302
+ // Stagger sends into 10 ms slices. No catch-up burst after a held timer.
303
+ timer = setInterval(() => {
304
+ const now = performance.now(),
305
+ lag = Math.max(0, now - expected - 10);
306
+ expected = now;
307
+ peakLag = Math.max(peakLag, lag);
308
+ badLag = lag > 2000 ? badLag + 1 : 0;
309
+ if (badLag >= 3) stopReason ??= 'driver event loop stalled';
310
+ for (const c of clients) {
311
+ if (c.retired || c.ws?.readyState !== 1) continue;
312
+ if (now >= c.nextPing) {
313
+ send(c, { t: 'ping', c: Date.now(), hid: false });
314
+ c.nextPing = now + 2000;
315
+ }
316
+ if (c.own && now - c.at > 5000 && !c.staleReported) {
317
+ c.staleReported = true;
318
+ problem('stale snapshot', 'own state absent for more than 5 seconds');
319
+ }
320
+ if (!c.own || now - c.at > 2000 || now < c.nextInput) continue;
321
+ c.nextInput += 100;
322
+ if (c.nextInput <= now) c.nextInput = now + 100;
323
+ const k = Math.max(
324
+ c.lastSent + 1,
325
+ c.k + Math.min(10, Math.floor((now - c.at) / 50)) + c.lead
326
+ ),
327
+ y = c.own[3][1],
328
+ east = Boolean(c.own[7][1]);
329
+ send(c, {
330
+ t: 'in',
331
+ e: c.epoch,
332
+ k,
333
+ s: [
334
+ [
335
+ 0,
336
+ east ? 127 : -127,
337
+ y > 55
338
+ ? -35
339
+ : y < -55
340
+ ? 35
341
+ : Math.round(Math.sin(now / 3100 + c.i) * 35)
342
+ ]
343
+ ],
344
+ r: c.r,
345
+ // The newest tick this socket holds, as the toolkit's own client says it.
346
+ ...(c.rawTick !== undefined ? { g: c.rawTick } : {})
347
+ });
348
+ c.pending.set(k, now);
349
+ c.lastSent = k;
350
+ for (const [tick, at] of c.pending) {
351
+ if (now - at <= 5000) break;
352
+ c.pending.delete(tick);
353
+ if (measuring) expired++;
354
+ }
355
+ }
356
+ }, 10);
357
+ const summary = () => ({
358
+ worker: index,
359
+ attempted: clients.length,
360
+ connected: clients.filter((c) => c.ws?.readyState === 1).length,
361
+ joined: clients.filter((c) => !c.retired && c.first !== null).length,
362
+ fresh: clients.filter(
363
+ (c) =>
364
+ !c.retired &&
365
+ c.ws?.readyState === 1 &&
366
+ c.own &&
367
+ performance.now() - c.at < 2000
368
+ ).length,
369
+ stopReason,
370
+ epoch,
371
+ inputFrames,
372
+ disconnects,
373
+ loopP99Ms: loop.percentile(99) / 1e6,
374
+ peakTimerLagMs: peakLag,
375
+ upBytes: up,
376
+ downBytes: down,
377
+ upFrames: sent,
378
+ downFrames: received,
379
+ // Bytes off the wire (after TLS, before inflation) for sockets still open.
380
+ wireDownBytes: clients.reduce(
381
+ (a, c) =>
382
+ a + Math.max(0, (c.ws?._socket?.bytesRead ?? 0) - (c.wire0 ?? 0)),
383
+ 0
384
+ ),
385
+ compressed: clients.filter((c) => c.compressed).length
386
+ });
387
+ return {
388
+ connect,
389
+ summary,
390
+ cancelRamp() {
391
+ rampCancelled = true;
392
+ },
393
+ async ramp(n, rampMs) {
394
+ await new Promise((r) => setTimeout(r, index * rampMs));
395
+ const pending = new Set();
396
+ for (let i = index; i < n && !stopping && !rampCancelled; i += workers) {
397
+ while (pending.size >= Math.max(1, Math.floor(8 / workers)))
398
+ await Promise.race(pending);
399
+ if (rampCancelled || stopping) break;
400
+ const task = connect(i).finally(() => pending.delete(task));
401
+ pending.add(task);
402
+ await new Promise((r) => setTimeout(r, rampMs * workers));
403
+ }
404
+ await Promise.all(pending);
405
+ },
406
+ start() {
407
+ measuring = true;
408
+ for (const c of clients) {
409
+ c.wire0 = c.ws?._socket?.bytesRead ?? 0;
410
+ c.pending.clear();
411
+ c.firstTick = null;
412
+ c.firstAt = null;
413
+ c.frames = 0;
414
+ }
415
+ },
416
+ async churn(count) {
417
+ const leaving = clients.filter(
418
+ (c) =>
419
+ c.i < count &&
420
+ !c.retired &&
421
+ c.first !== null &&
422
+ c.ws?.readyState === 1
423
+ );
424
+ for (const c of leaving) {
425
+ c.retired = true;
426
+ c.ws.close(1000, 'churn');
427
+ }
428
+ await new Promise((r) => setTimeout(r, 1000));
429
+ await Promise.all(leaving.map((c) => connect(c.i, c)));
430
+ return leaving.length;
431
+ },
432
+ async finish() {
433
+ const end = summary();
434
+ measuring = false;
435
+ stopping = true;
436
+ clearInterval(timer);
437
+ loop.disable();
438
+ for (const c of clients) c.ws?.close(1000, 'load step complete');
439
+ await new Promise((r) => setTimeout(r, 250));
440
+ for (const c of clients) if (c.ws?.readyState !== 3) c.ws?.terminate();
441
+ return {
442
+ ...end,
443
+ errors: [...errors].map(([text, count]) => ({ text, count })),
444
+ histograms: { first, welcome, ack, gaps, loops },
445
+ inputReports: onTime,
446
+ inputReportsLate: lateAcks,
447
+ leadTicks: clients.filter((c) => !c.retired).map((c) => c.lead),
448
+ ackSkipped: skipped,
449
+ ackExpired: expired,
450
+ totalUp,
451
+ totalDown,
452
+ players: clients.map((c) => ({
453
+ i: c.i,
454
+ seat: c.seat,
455
+ epoch: c.epoch,
456
+ priorSeat: c.priorSeat,
457
+ sameSeat: c.priorSeat === null ? null : c.seat === c.priorSeat,
458
+ retired: Boolean(c.retired),
459
+ firstStateMs: c.first === null ? null : c.first - c.began,
460
+ helloAfterMs: c.helloAt ? c.helloAt - c.began : null,
461
+ closeCode: c.closeCode,
462
+ closeReason: c.closeReason,
463
+ maxStateGapMs: c.maxStateGapMs,
464
+ rawSnapshots: c.rawSnapshots,
465
+ decodeMiss: c.decodeMiss,
466
+ ownMissing: c.ownMissing,
467
+ frames: c.frames,
468
+ tickHz:
469
+ c.lastAt > c.firstAt
470
+ ? ((c.lastTick - c.firstTick) * 1000) / (c.lastAt - c.firstAt)
471
+ : null,
472
+ deliveredHz:
473
+ c.lastAt > c.firstAt
474
+ ? ((c.frames - 1) * 1000) / (c.lastAt - c.firstAt)
475
+ : null,
476
+ upBytes: c.up,
477
+ downBytes: c.down
478
+ }))
479
+ };
480
+ }
481
+ };
482
+ }
483
+ if (parentPort) {
484
+ const load = createLoad({
485
+ ...workerData,
486
+ onProblem: (text) => parentPort.postMessage({ event: 'error', text })
487
+ });
488
+ parentPort.on('message', async ({ id, op, args = [] }) => {
489
+ try {
490
+ const value = await load[op](...args);
491
+ parentPort.postMessage({ id, value });
492
+ } catch (e) {
493
+ parentPort.postMessage({ id, error: e.stack });
494
+ }
495
+ });
496
+ }
package/lib/scaffold.mjs CHANGED
@@ -105,7 +105,7 @@ export function wranglerConfig({ worker, name, d1, d1Id = null, r2 = null, layou
105
105
  previews: { vars: { STUDIO_NAME: name, HOMIE_PREVIEW: '1' }, durable_objects: { bindings: rooms } },
106
106
  };
107
107
  return `// This studio's site on its own Cloudflare account (written by homie-studio). Everything here runs on
108
- // Cloudflare's Workers Free plan. \`npm run deploy\` (on this computer, or in Workers Builds) puts it live;
108
+ // the studio's Cloudflare Workers account. \`npm run deploy\` (on this computer, or in Workers Builds) puts it live;
109
109
  // \`npx wrangler preview\` puts a branch on its own Preview URL with its own rooms. There is no R2 binding
110
110
  // until \`homie-studio storage add\` gives the studio storage for large media.
111
111
  ${JSON.stringify(config, null, 2)}
@@ -118,7 +118,7 @@ export function agentsMd({ name, slug }) {
118
118
  This folder is a studio: **${name}** (\`${slug}\`). It is one repository.
119
119
  Its games, music, videos and posts live here; its website and public game rooms
120
120
  run on the studio's **own Cloudflare account** (one Worker, one D1 database and
121
- the Table/Lobby Durable Objects, all on Cloudflare's free Workers plan), built
121
+ the Table/Lobby Durable Objects, on the studio's Cloudflare account), built
122
122
  from \`@homie-rocks/studio\`, pinned in \`package.json\`. The homie.rocks
123
123
  directory lists its games; homie.rocks does not host them.
124
124
 
@@ -217,7 +217,7 @@ studio's pinned copy, never a registry lookup of the bare name.
217
217
  - \`npx --no-install homie-studio deploy --plan\` — says what deploy will create on Cloudflare and what it
218
218
  costs, and changes nothing. Tell the person before the first deploy.
219
219
  - \`npm run deploy\` — the site on this studio's Cloudflare: one Worker, one D1 database, two
220
- SQLite-backed Durable Objects, all on the free Workers plan (no payment method needed).
220
+ SQLite-backed Durable Objects on the studio’s Cloudflare account; its subscription is not inferred.
221
221
  If Wrangler is not signed in, run \`npx wrangler login\`: the person approves once in
222
222
  their browser. It never overwrites a Worker or database this studio did not create.
223
223
  - **Workers Builds** (Cloudflare's own CI, set up by the "Deploy to Cloudflare" button or in the dashboard): on
@@ -553,9 +553,9 @@ chat's card follows the work from then on) and, for a studio still being set up,
553
553
  \`"games/*/game.json"\`) and \`"budget"\` (\`{ "usd": <n>, "credits": <n> }\`: the most the studio's media jobs spend
554
554
  in all). In Claude Code, the Homie plugin's mod holds an edit to a protected file, a deploy, and a paid call past
555
555
  the budget until the person says Proceed, and takes keys out of command output. In Codex the plugin's hooks hold
556
- the same calls until the person's own \`proceed <code>\`, once the person has trusted them, and in Grok Build once
556
+ unrequested deploys and the other held calls until the person's own \`proceed <code>\`, once the person has trusted them, and in Grok Build once
557
557
  the plugin is trusted. \`npx --no-install homie-studio setup status --client codex\` (or \`grok\`) says whether Homie's
558
- holds are on, and while they are off, ask before each of those yourself. When a call is refused, say what you
558
+ holds are on. A deploy the person requested in their own words is already approved for that task; do not ask again or demand a typed code. Stop an unrequested deploy and ask once. When a call is refused, say what you
559
559
  meant to do and why; do not retry it unless the person asks.
560
560
 
561
561
  ## Telling Homie
@@ -2733,6 +2733,48 @@
2733
2733
  }
2734
2734
  }
2735
2735
  }
2736
+ },
2737
+ "0.46.2": {
2738
+ "files": {
2739
+ "CLAUDE.md": "ddf2b2a0376202f6",
2740
+ "README.md": "684b3cca8001673c",
2741
+ "HANDOFF.md": "29337e2ace95b2e7",
2742
+ "games/README.md": "5ad32fe80c61f117",
2743
+ "music/README.md": "a3dc042dadd39df8",
2744
+ "videos/README.md": "16babc3437d5545b",
2745
+ "posts/README.md": "37841aae476bd540",
2746
+ "site/README.md": "732894273a32dc3f",
2747
+ "site/src/worker.mjs": "6cc5c6131eaf6fd0"
2748
+ },
2749
+ "sections": {
2750
+ "AGENTS.md": {
2751
+ "(intro)": "394cbbe934e80722",
2752
+ "## Version-matched authoring guides": "f6261a0e5801b96b",
2753
+ "## Layout": "f3a280b8c96cd068",
2754
+ "## Apps: one screen, roles and parts": "8596f2b25edda3e2",
2755
+ "## Commands (all through the pinned CLI in node_modules)": "5222e08ca55e326e",
2756
+ "## The site": "0cb8dd9a6f8a0096",
2757
+ "## Making games": "bb715272fd1a615b",
2758
+ "## The Game Codex and progress": "0738ef719cef3a4c",
2759
+ "## Art direction and models": "a48fff7bf0a5f2fc",
2760
+ "## Running live games (the back office)": "51ebf2ab756f6e4d",
2761
+ "## Servers and AI seats": "1ccfd549d2369a60",
2762
+ "## Selling things (the shop)": "9e020d69dd6a954e",
2763
+ "## Continuing a build from the Claude app": "0d68081e924ca419",
2764
+ "## Rules": "27881d11d3ff3803",
2765
+ "## Telling Homie": "80b46fdd9e578db8",
2766
+ "## Beta": "9d02638207a26e73"
2767
+ }
2768
+ },
2769
+ "named": {
2770
+ "Homie Arcade": {
2771
+ "sections": {
2772
+ "AGENTS.md": {
2773
+ "## Commands (all through the pinned CLI in node_modules)": "611b437f5b3303f0"
2774
+ }
2775
+ }
2776
+ }
2777
+ }
2736
2778
  }
2737
2779
  }
2738
2780
  }
@@ -529,6 +529,7 @@ export interface NetStats {
529
529
  offline: boolean;
530
530
  rtt: number | null;
531
531
  offset: number;
532
+ telemetrySource: 'server' | 'browser' | 'offline' | 'disconnected';
532
533
  snapHzIn: number;
533
534
  snapHzOut: number;
534
535
  inputHzIn: number;
@@ -550,6 +551,8 @@ export interface NetStats {
550
551
  stateKeys: number;
551
552
  peers: number;
552
553
  reconnects: number;
554
+ /** Most recent loss, retained after recovery so a brief reconnect is diagnosable. */
555
+ lastDisconnect?: { at: number; why: string; code: number | null; reason: string | null; silentMs: number };
553
556
  /** Revision 9: times a link that was up went down (a reconnect that worked on the first knock counts once). */
554
557
  drops?: number;
555
558
  /** Revision 9: where this browser stands with its room. */
@@ -1695,6 +1698,7 @@ export function createNetplay<S = unknown, A = unknown, C = unknown>(opts: Netpl
1695
1698
  let ws: WebSocketLike | null = null;
1696
1699
  let attempt = 0;
1697
1700
  let reconnects = 0;
1701
+ let lastDisconnect: NetStats['lastDisconnect'];
1698
1702
  let drops = 0;
1699
1703
  let heartbeats = 0;
1700
1704
  /** My welcome gave me back the seat my token named (the same player), and a newer build is live (section 23). */
@@ -1777,6 +1781,9 @@ export function createNetplay<S = unknown, A = unknown, C = unknown>(opts: Netpl
1777
1781
  let playableSent = false;
1778
1782
  let autoArmed = false;
1779
1783
  let snapSeen = false;
1784
+ /** The newest tick this socket has been sent (rules games): said on inputs and pings as `g`, so a Gate that
1785
+ * finds this player far behind the room sends it fewer, fresher frames instead of every one late. */
1786
+ let gotTick: number | null = null;
1780
1787
  let loadingAt = 0;
1781
1788
  const createdAt = (typeof performance !== 'undefined' ? performance.now() : Date.now());
1782
1789
  const arrived: ArrivalInfo = { mode: arrival, by: null, playableMs: null, explicitMs: null, lateMs: null };
@@ -2619,6 +2626,7 @@ export function createNetplay<S = unknown, A = unknown, C = unknown>(opts: Netpl
2619
2626
  if (wasOffline && rulesGame) rulesNotice('Connection restored. Joining the online round.');
2620
2627
  offline = false;
2621
2628
  connected = true;
2629
+ gotTick = null;
2622
2630
  downSince = 0;
2623
2631
  attempt = 0;
2624
2632
  if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
@@ -2764,6 +2772,7 @@ export function createNetplay<S = unknown, A = unknown, C = unknown>(opts: Netpl
2764
2772
  if (Array.isArray(m['c'])) s.c = m['c'] as ControlWire[];
2765
2773
  if (m['hb'] === 1) s.hb = 1;
2766
2774
  if (typeof m['e'] === 'number') s.e = m['e'];
2775
+ if (!local && rulesGame) gotTick = s.k;
2767
2776
  if (acceptSnap(s, bytes, true, local)) { emit('snapshot', s); if (!snapSeen) { snapSeen = true; autoPlayable(); } }
2768
2777
  }
2769
2778
 
@@ -2881,7 +2890,7 @@ export function createNetplay<S = unknown, A = unknown, C = unknown>(opts: Netpl
2881
2890
  pingsOut.set(c, c);
2882
2891
  if (pingsOut.size > 16) { const first = pingsOut.keys().next().value; if (first !== undefined) pingsOut.delete(first); }
2883
2892
  // A hidden host's yield is behind its checkpoint in the sender: the relay hears of the hidden tab after both.
2884
- raw({ t: 'ping', c, hid: hidden() && !rulesSender?.handing, ...(rulesGame ? { readySpeed } : {}) });
2893
+ raw({ t: 'ping', c, hid: hidden() && !rulesSender?.handing, ...(rulesGame ? { readySpeed } : {}), ...(gotTick !== null ? { g: gotTick } : {}) });
2885
2894
  }
2886
2895
 
2887
2896
  function sendCheckpoint(): void {
@@ -2939,12 +2948,13 @@ export function createNetplay<S = unknown, A = unknown, C = unknown>(opts: Netpl
2939
2948
  function statsNow(): NetStats {
2940
2949
  const t = wall();
2941
2950
  return {
2951
+ telemetrySource: offline ? 'offline' : !connected ? 'disconnected' : opts.rulesHost?.mode === 'server' ? 'server' : 'browser',
2942
2952
  role, seat, host, connected, offline, rtt, offset: Math.round(offset),
2943
2953
  snapHzIn: snapIn.hz(t), snapHzOut: snapOut.hz(t), inputHzIn: inputIn.hz(t), inputHzOut: inputOut.hz(t), idleInputsSkipped: idleSkipped,
2944
2954
  lastSnapBytes, maxSnapBytes, bytesInPerS: perSecond(bytesIn), bytesOutPerS: perSecond(bytesOut),
2945
2955
  interpDelay: Math.round(interpDelay()), snapAgeP90: Math.round(ageP90), starvedPct: +starvedPct.toFixed(3), rejectedSnaps,
2946
2956
  owned: api.owned, pending: sentHist.length, stateKeys: stateMap.size,
2947
- peers: peers.size, reconnects, drops, link, heartbeats, promotions, round: roundInfo ? roundInfo.n : null,
2957
+ peers: peers.size, reconnects, lastDisconnect, drops, link, heartbeats, promotions, round: roundInfo ? roundInfo.n : null,
2948
2958
  decides: { asked: decideStats.asked, ai: decideStats.ai, local: decideStats.local, floor: decideStats.floor, msP50: [...decideStats.ms].sort((x, y) => x - y)[Math.floor(decideStats.ms.length / 2)] ?? null },
2949
2959
  };
2950
2960
  }
@@ -2980,8 +2990,10 @@ export function createNetplay<S = unknown, A = unknown, C = unknown>(opts: Netpl
2980
2990
  else paintLink();
2981
2991
  }
2982
2992
 
2983
- function lost(sock: WebSocketLike, why: string): void {
2993
+ function lost(sock: WebSocketLike, why: string, event?: unknown): void {
2984
2994
  if (ws !== sock) return;
2995
+ const detail = event && typeof event === 'object' ? event as { code?: unknown; reason?: unknown } : null;
2996
+ lastDisconnect = { at: Date.now(), why, code: typeof detail?.code === 'number' ? detail.code : null, reason: typeof detail?.reason === 'string' ? detail.reason.slice(0, 160) : null, silentMs: Math.max(0, wall() - lastMsgAt) };
2985
2997
  ws = null;
2986
2998
  sock.onclose = null; sock.onmessage = null; sock.onerror = null; sock.onopen = null;
2987
2999
  if (why !== 'closed') { try { sock.close(4000, why); } catch { /* gone */ } }
@@ -3011,13 +3023,14 @@ export function createNetplay<S = unknown, A = unknown, C = unknown>(opts: Netpl
3011
3023
  lastMsgAt = wall();
3012
3024
  raw({
3013
3025
  t: 'hello', rules: rulesGame, v: NETPLAY_VERSION, rev: NETPLAY_REVISION, token, name: name || undefined, device, want, canHost: asAgent && asAgent.hands === 'host' ? false : canHost, game: opts.game, max: opts.maxPlayers,
3026
+ ...(rulesGame ? { coast: 1 } : {}),
3014
3027
  ...(watching ? { watch: true } : {}), ...(caps.size ? { caps: [...caps] } : {}), ...(asAgent ? { agent: asAgent } : {}),
3015
3028
  // Revision 9 (an older relay ignores both): the game's revision and what this build can do.
3016
3029
  ...(version ? { ver: version } : {}), ...(features.length ? { feat: features } : {}),
3017
3030
  });
3018
3031
  };
3019
3032
  sock.onmessage = (ev) => onMessage(ev.data);
3020
- sock.onclose = () => lost(sock, 'closed');
3033
+ sock.onclose = (event) => lost(sock, 'closed', event);
3021
3034
  // Browsers follow an error with close; Node's WebSocket, on a refused connection, never does.
3022
3035
  sock.onerror = () => lost(sock, 'error');
3023
3036
  }
@@ -3415,7 +3428,7 @@ export function createNetplay<S = unknown, A = unknown, C = unknown>(opts: Netpl
3415
3428
  if (seat === null || !entries.length) return false;
3416
3429
  if (rulesHost && offline) { rulesHost.frame({ t: 'in', from: seat, e, k, s: entries, r }); return true; }
3417
3430
  if ((!rulesGame && role === 'host') || offline || !connected) return false;
3418
- if (!raw({ t: 'in', e, k, s: entries, r })) return false;
3431
+ if (!raw({ t: 'in', e, k, s: entries, r, ...(gotTick !== null ? { g: gotTick } : {}) })) return false;
3419
3432
  inputOut.hit(wall());
3420
3433
  return true;
3421
3434
  },