1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956 | /**
* ardegazu-peer-kit — a headless Node peer for the ardegazu.ro suite.
*
* HAND-AUTHORED declarations for the package root. Until v1.3.0 these were
* tsc's own output of a TypeScript src/; the kit is ClojureScript now
* (dev/docs/CLJS.md), so this file IS the contract — it is not derived from
* anything, and `test/types/consumer.ts` compiles against it to keep it honest.
*
* The surface is deliberately identical to v1.3.0's, name for name and
* signature for signature, with two changes:
* - `FriendLink`, `SuiteAppDef`, `Friend`, `Receipt`, `PresenceInfo`,
* `InviteMsg`, `PubsubLike` and `GameLb` are re-exported from the REAL
* ardegazu-social-kit instead of the retired src/vendor/ copy, and
* `Identity`/`Profile` from ardegazu-id-kit;
* - `SocialOptions` grew `profileSync` and `appState`, the social-kit 1.2.0
* hooks the vendored copy never had.
*/
import type { Identity, Profile } from "ardegazu-id-kit";
import type {
Friend,
FriendLink,
GameLb,
InviteMsg,
PresenceInfo,
PubsubLike,
Receipt,
AppDef as SuiteAppDef,
} from "ardegazu-social-kit";
import type { Libp2p } from "libp2p";
import { EventEmitter } from "node:events";
export type { Identity, Profile, Friend, FriendLink, InviteMsg, PresenceInfo, PubsubLike, Receipt, SuiteAppDef };
export type { GameLb };
/* ------------------------------------------------------------------ apps --- */
/** One suite game app: its salt namespaces rooms, its prefix the protocol. */
export interface AppDef {
/** Catalog name (matches the hub). */
name: string;
host: string;
/** Namespaces rooms on the shared p2p app (v2 = libp2p stack). */
salt: string;
/** Room protocol prefix — the one line that differs between the games. */
protocolPrefix: string;
}
export declare const GAMES: {
readonly "neon-grid": AppDef;
readonly "valley-blocks": AppDef;
readonly tessera: AppDef;
readonly seance: AppDef;
readonly lampion: AppDef;
readonly odeon: AppDef;
};
export type GameName = keyof typeof GAMES;
/** Signaling endpoints shared by every app in the suite. */
export declare const SIGNAL: {
descriptorUrl: string;
turnUrl: string;
relayFallback: RelayInfo;
};
/** A default allowlisted Origin for the shims (any suite app origin works). */
export declare const DEFAULT_ORIGIN: string;
/* ------------------------------------------------------------------ core --- */
export interface RelayInfo {
peerId: string;
multiaddrs: string[];
}
/** A peer's verified suite identity, as carried in the sealed hello. */
export interface PeerIdent {
pub: string;
name?: string;
hue?: number;
glyph?: string;
}
/** My suite identity, as handed in by the host process. Optional — rooms work
* identity-less exactly as in the browser apps. */
export interface NetIdentity {
pub: string;
/** Sign the session binding for (roomId, my own peerId) — id-kit assert(). */
sign(roomId: string, myPeerId: string): Promise<string>;
name?: string;
hue?: number | null;
glyph?: string | null;
}
export interface NetConfig {
secret: string;
appSalt: string;
/** e.g. "/neon-grid/2/" — the per-app protocol prefix. */
protocolPrefix: string;
descriptorUrl: string;
turnUrl: string;
relayFallback: RelayInfo;
identity?: NetIdentity | null;
/** Try the WebRTC transport (default true; falls back to circuit-only). */
webrtc?: boolean;
}
export interface NetCallbacks {
onRoomRoster(peers: string[]): void;
onPeerOpen(id: string): void;
onPeerGone(id: string): void;
onMessage(from: string, payload: unknown): void;
onStatus(): void;
/** A member's suite identity verified (after onPeerOpen; optional). */
onPeerIdentity?(id: string, ident: PeerIdent): void;
}
export interface Net {
myId: string;
roomPeers(): ReadonlySet<string>;
relayConnected(): boolean;
openPeers(): string[];
openCount(): number;
send(to: string, frame: unknown): void;
broadcast(frame: unknown): void;
/** Verified suite identity of a member, if it announced one. */
identityOf(id: string): PeerIdent | null;
/** The underlying node — the social agent rides its pubsub. */
libp2p: Libp2p;
/** Salt-derived room id (leaderboard receipts hash it, never carry it). */
roomId: string;
/** Network-flap kick: revive the relay link and member streams. */
wake(): void;
/** Tear the node down. */
close(): Promise<void>;
}
export declare function createNet(cfg: NetConfig, cb: NetCallbacks): Promise<Net>;
/** A fresh 43-char base64url room secret (the invite link's fragment). */
export declare function newRoomSecret(): string;
/* --------------------------------------------------------------- connect --- */
export interface ConnectOptions {
app: GameName;
/** The room secret — the URL fragment of an invite link. */
roomSecret: string;
/** Suite identity block (from loadIdentity().netIdentity(salt)); optional. */
identity?: NetIdentity | null;
/** Allowlisted browser origin for the managed relay. */
origin?: string;
/** Attempt the WebRTC transport (default true). */
webrtc?: boolean;
}
export interface RoomPeerEvents {
roster: [peers: string[]];
peerOpen: [id: string];
peerGone: [id: string];
peerIdentity: [id: string, ident: PeerIdent];
message: [from: string, payload: unknown];
status: [];
}
export declare class RoomPeer extends EventEmitter<RoomPeerEvents> {
readonly net: Net;
readonly app: GameName;
constructor(net: Net, app: GameName);
get myId(): string;
send(to: string, frame: unknown): void;
broadcast(frame: unknown): void;
identityOf(id: string): PeerIdent | null;
close(): Promise<void>;
}
export declare function connect(opts: ConnectOptions): Promise<RoomPeer>;
/* ---------------------------------------------------------------- node/ ---- */
/**
* Install the Origin shims for the given origin (must be on the app's
* allowlist). Idempotent; call once at process start, before any libp2p node
* or credential fetch is created. Throws on a second, DIFFERENT origin.
*/
export declare function installOrigin(origin: string, hosts?: RegExp[]): void;
/**
* Minimal browser globals for the social layer (window timers, a visibility
* check that always reads "visible", and a file-backed localStorage).
*/
export declare function installBrowserGlobals(storageFile?: string): void;
export interface SuiteIdentity {
identity: Identity;
seed: string;
profile: Profile;
/** Ready-to-pass identity block for createNet (per-app salt). */
netIdentity(appSalt: string): NetIdentity;
}
export interface LoadIdentityOptions {
/** Path to the seed file; created (0600) with a fresh seed when missing. */
seedFile?: string;
/** Explicit seed (e.g. from an env var) — takes precedence over the file. */
seed?: string;
name?: string;
hue?: number | null;
glyph?: string | null;
}
export declare function loadIdentity(opts: LoadIdentityOptions): Promise<SuiteIdentity>;
/* --------------------------------------------------------------- social ---- */
export interface SocialOptions {
suite: SuiteIdentity;
/** Which app this peer presents as (e.g. "ardegazu.ro" for a hub-like bot). */
app?: string;
/** Storage namespace + backing file for friends/cursors/dedup. */
ns?: string;
storageFile?: string;
origin?: string;
/** Ride an existing node's pubsub instead of creating a bare suite node. */
pubsub?: PubsubLike | null;
/** Accept incoming friend requests automatically (default true for a bot). */
autoAcceptFriends?: boolean;
/** A link friends may use to join me (shown in my presence beacons). */
joinLink?: () => string | null;
/**
* Brain/model versions this peer is playing (game id -> version), read at
* every presence beacon (~25s) so a promotion re-advertises itself with no
* restart. Clamped before it hits the wire (at most 8 entries, keys
* /^[a-z0-9][a-z0-9-]{0,23}$/, values /^[A-Za-z0-9@._-]{1,32}$/); omitted
* entirely when unset, throwing or empty. Bots fill it.
*/
brains?: () => Record<string, string> | null;
/**
* Cross-device profile sync (social-kit 1.2.0). The vendored social copy
* peer-kit used to carry never had this; it is inherited by consuming the
* real kit.
*/
profileSync?: {
get(): Partial<Profile> | null;
apply(p: Partial<Profile>): void;
};
/**
* Cross-device app state, namespaced so only the same app reads it back
* (social-kit 1.2.0 — also absent from the vendored copy).
*/
appState?: {
ns: string;
get(): unknown;
apply(state: unknown): void;
};
}
export interface SocialEvents {
presence: [pub: string, info: PresenceInfo | null];
invite: [inv: InviteMsg];
request: [f: Friend];
accepted: [f: Friend];
}
/** A suite identity's shareable friend link — no agent, no network. */
export declare function suiteFriendLink(suite: SuiteIdentity): Promise<string>;
export declare class Social extends EventEmitter<SocialEvents> {
readonly agent: import("ardegazu-social-kit").SocialAgent;
readonly store: import("ardegazu-social-kit").FriendStore;
readonly suite: SuiteIdentity;
/** My shareable friend link (paste into the hub to add this bot). */
friendLink(): Promise<string>;
/** The bare suite node (null when riding an app node's pubsub). */
get node(): NetNode | null;
stop(): Promise<void>;
static start(opts: SocialOptions): Promise<Social>;
}
/**
* The bare libp2p node a Social agent creates when given no pubsub.
*
* An INTERFACE, not a class, on purpose: `dist/index.js` does not export the
* constructor (only `dist/internals.js` does), so declaring a class here would
* let `new NetNode(...)` type-check against a name that is undefined at
* runtime. It is reachable as a value from "ardegazu-peer-kit/games/..."-style
* deep imports, where types/internals.d.ts declares it properly.
*/
export interface NetNode {
readonly node: Libp2p;
readonly relayId: string;
/** True when the WebRTC transport actually loaded in this runtime. */
readonly webrtcEnabled: boolean;
relayConnected(): boolean;
redialRelay(): Promise<void>;
}
/* -------------------------------------------------- social-kit passthrough - */
export declare function buildFriendLink(base: string, me: FriendLink): string;
export declare function parseFriendLink(fragment: string): Promise<FriendLink | null>;
/** The invitable suite (hub excluded — you're already there). */
export declare const SUITE_APPS: readonly SuiteAppDef[];
export declare function mintRoomUrl(host: string): string;
/* ----------------------------------------------------------- game rooms ---- */
/** What a GameRoom needs from its live host driver. */
export interface HostDriverLike {
/** The empty-room claim landed — seat yourself and open the lobby. */
onClaimed(): void;
/** A frame the hosting bot sends to itself (browser: amHost() direct call). */
onSelfFrame(frame: unknown): void;
/**
* A foreign self-claim arrived while we host. Concede (adopt their roster,
* return true) or reassert (rebroadcast ours, return false) — using the same
* comparator bystanders apply.
*/
onForeignClaim(from: string, m: Record<string, unknown>): boolean;
/** The room is closing — clear every timer, abort the sim. */
close(): void;
}
export interface GameRoomOptions {
app: GameName;
roomSecret: string;
nick: string;
/** Suite identity — enables the identity hello and leaderboard co-signing. */
suite?: SuiteIdentity | null;
origin?: string;
webrtc?: boolean;
/** File for the small persisted stores (receipts); optional. */
storageFile?: string;
/** Extra fields for the "hi" announce (games differ: score vs wins). */
hiExtra?: () => Record<string, unknown>;
/**
* Revive the relay link when it drops, checked on this interval — relayed
* circuits are torn down hourly, and the peer redial ladder alone gives up
* after ~15s. 0 disables. Default 30s.
*/
keepAliveMs?: number;
}
export interface GameRoomEvents {
host: [hostId: string | null];
roster: [entries: unknown[]];
frame: [from: string, frame: Record<string, unknown>];
peerIdentity: [id: string, ident: PeerIdent];
receipt: [rec: Receipt];
/** A match concluded (séance "ov" / neon-grid "ma") — the winner, if any. */
matchEnd: [winner: string | null];
status: [];
}
export declare class GameRoom extends EventEmitter<GameRoomEvents> {
readonly peer: RoomPeer;
readonly app: GameName;
readonly nick: string;
hostId: string | null;
/** Attached by a game client when its options carry `host` (see subclasses). */
hostDriver: HostDriverLike | null;
constructor(peer: RoomPeer, opts: GameRoomOptions);
/** Polymorphic join: `SeanceClient.join(...)` yields a SeanceClient. */
static join<T extends typeof GameRoom>(this: T, opts: GameRoomOptions): Promise<InstanceType<T>>;
get myId(): string;
get hosting(): boolean;
/** The leaderboard co-signer, when a suite identity was given — a hosting
* driver calls its hostMatchEnd(), the browsers' main.ts wiring. */
get leaderboard(): GameLb | null;
/** My score as I believe it — the leaderboard co-sign guard. Null = never sign. */
score(): number | null;
/**
* Does a foreign self-claim from `from` outrank the host I follow? The
* per-game split-brain comparator — the base rule is plain lowest-id
* (séance's rule); neon-grid and valley-blocks override with live-beats-idle.
* Incumbent and bystanders MUST share this rule.
*/
claimBeats(from: string, m: Record<string, unknown>): boolean;
/** Send a frame to the current host; self-routes to the driver when hosting. */
sendToHost(frame: unknown): void;
/**
* Apply one of our own host frames through the same path every other peer
* takes — the browsers' hostEmit loopback.
*/
injectLocal(frame: unknown): void;
/** Manual relay revive (also runs on the keepAlive interval). */
wake(): void;
close(): Promise<void>;
}
/* --------------------------------------------------------------- séance ---- */
/** [peerId, nick, sigilIdx, seancesWon] */
export type SeanceRosterEntry = [string, string, number, number];
export interface SeanceView {
/** Bell number (1-based). */
bell: number;
/** My seat in the séance order (-1 = spectating). */
seat: number;
/** Candles per seat as of the last reveal/snapshot. */
candles: number[];
/** Rooms per seat as of the last reveal. */
rooms: number[];
/** The room the ghost is NOT in — medium's hint (-1 = not the medium). */
hintNot: number;
isMedium: boolean;
}
export interface SeanceOptions extends Omit<GameRoomOptions, "app" | "hiExtra"> {
app?: "seance";
/** Decide a room 0..2 for this bell (null = stay put). */
onTurn?: (view: SeanceView) => number | null | Promise<number | null>;
/**
* Delay before the pick lands, given the walk window (ms). 0 ⇒ immediate.
* Default: humanlike — min(walk·0.6, 400 + rand·max(200, walk·0.3)).
*/
actDelayMs?: number | ((walkMs: number) => number);
/** Conduct séances in rooms this bot boots into empty (self-play). */
host?: SeanceHostOptions;
}
export declare class SeanceClient extends GameRoom {
wins: number;
constructor(peer: RoomPeer, opts: GameRoomOptions);
static joinSeance(opts: SeanceOptions): Promise<SeanceClient>;
get seat(): number;
/** The attached host driver (null when this client can't conduct). */
get host(): SeanceHost | null;
view(): SeanceView;
/** Pick a room 0..2 during a walk window. */
pick(room: number): void;
/** Hosting only: start a séance now instead of waiting for auto-start. */
startMatch(): boolean;
}
/* ------------------------------------------------------------ neon-grid ---- */
export interface NeonGridView {
seat: number;
pos: [number, number];
/** Actual heading (inferred from movement), 0=up 1=right 2=down 3=left. */
dir: number;
alive: boolean;
tickN: number;
gw: number;
gh: number;
/** Occupancy map (seat+1 per cell, 0 = free) — a copy, safe to mutate. */
grid: Uint8Array;
/** Every rider's head position by seat (null once derezzed). */
heads: ([number, number] | null)[];
}
export interface NeonGridOptions extends Omit<GameRoomOptions, "app" | "hiExtra"> {
app?: "neon-grid";
/** Steer each tick while alive: absolute direction 0..3, or null to hold. */
onTick?: (view: NeonGridView) => number | null;
/** The stock wall-dodging brain. Default true; ignored when onTick given. */
autopilot?: boolean;
/** Run rounds in rooms this bot boots into empty (self-play). */
host?: HostOptions;
}
export declare class NeonGridClient extends GameRoom {
points: number;
constructor(peer: RoomPeer, opts: GameRoomOptions);
static joinGrid(opts: NeonGridOptions): Promise<NeonGridClient>;
get seat(): number;
/** The attached host driver (null when this client can't host). */
get host(): NeonGridHost | null;
view(): NeonGridView;
/** Queue a turn 0..3 (works both as guest and as host). */
steer(d: number): void;
/** Hosting only: start a match now instead of waiting for auto-start. */
startMatch(): boolean;
}
/* -------------------------------------------------- tessera / lampion / odeon */
export interface TesseraOptions extends Omit<GameRoomOptions, "app" | "hiExtra"> {
app?: "tessera";
}
export declare class TesseraClient extends GameRoom {
points: number;
constructor(peer: RoomPeer, opts: GameRoomOptions);
static joinTessera(opts: TesseraOptions): Promise<TesseraClient>;
}
export interface LampionLevel {
stairs: number[][];
rots: number[];
auto: [number, number][];
}
export interface LampionOptions extends Omit<GameRoomOptions, "app" | "hiExtra"> {
app?: "lampion";
}
export declare class LampionClient extends GameRoom {
points: number;
constructor(peer: RoomPeer, opts: GameRoomOptions);
static joinLampion(opts: LampionOptions): Promise<LampionClient>;
}
export interface OdeonOptions extends Omit<GameRoomOptions, "app" | "hiExtra"> {
app?: "odeon";
/** Instrument index (0 grand, 1 pads, 2 theremin, 3 bass, 4 audience). */
instrument?: number;
/** Play notes (default true). False = sit in the audience. */
perform?: boolean;
}
export declare class OdeonClient extends GameRoom {
constructor(peer: RoomPeer, opts: GameRoomOptions);
static joinOdeon(opts: OdeonOptions): Promise<OdeonClient>;
}
/* -------------------------------------------------------- valley-blocks ---- */
export type PieceType = "I" | "O" | "T" | "S" | "Z" | "J" | "L";
export type PartyMode = "race" | "race-survival" | "survival";
export type RoundReason = "target" | "survivor" | "score" | "void";
/** A player's own board as everyone else sees it. */
export interface BoardState {
grid: string;
score: number;
lines: number;
level: number;
snake: [number, number][] | null;
over: boolean;
}
/** [peerId, name, roundWins] */
export type VBRosterEntry = [string, string, number];
/** [peerId, name, finalScore, out] — one row of a round result. */
export type VBStandingEntry = [string, string, number, 0 | 1];
export type VBFrame =
| { t: "hi"; name: string; wins: number }
| { t: "lv" }
| { t: "ro"; host: string; ps: VBRosterEntry[]; mode: PartyMode; target: number; playing: 0 | 1 }
| { t: "st"; round: number; seed: number; order: string[]; mode: PartyMode; target: number }
| { t: "bs"; round: number; seat: number; s: BoardState }
| { t: "ov"; round: number; w: string | null; reason: RoundReason; standings: VBStandingEntry[]; ps: VBRosterEntry[] }
| { t: "lo" }
| { t: "sn"; round: number; order: string[]; mode: PartyMode; target: number };
/** What a policy sees at each placement decision (gym views match this). */
export interface ValleyBlocksView {
seat: number;
over: boolean;
score: number;
lines: number;
level: number;
piece: PieceType;
hold: PieceType | null;
canHold: boolean;
/** Every reachable placement with its afterstate — pick one by index. */
candidates: VBCandidate[];
/** The other seats' last reported boards, in seat order (self excluded). */
rivals: { score: number; over: boolean }[];
mode: PartyMode;
target: number;
}
export interface ValleyBlocksPace {
/** ms between executed inputs (default 110). */
inputMs?: number;
/** Thinking time before a placement starts, by level (default
* max(200, 700 − 30·level) plus 0–150ms jitter). */
thinkMs?: (level: number) => number;
}
export interface ValleyBlocksOptions extends Omit<GameRoomOptions, "app" | "hiExtra"> {
app?: "valley-blocks";
/** Pick a candidate index per new piece; null/out-of-range → stock pick. */
onPiece?: (view: ValleyBlocksView) => number | null;
/** The stock Dellacherie brain. Default true; ignored when onPiece given. */
autopilot?: boolean;
/** The old graceful-loser behavior: seat, announce a dead board, never win. */
forfeit?: boolean;
pace?: ValleyBlocksPace;
/** Referee rounds in rooms this bot boots into empty (self-play). */
host?: ValleyBlocksHostOptions;
}
export declare class ValleyBlocksClient extends GameRoom {
roundWins: number;
constructor(peer: RoomPeer, opts: GameRoomOptions);
static joinBlocks(opts: ValleyBlocksOptions): Promise<ValleyBlocksClient>;
get seat(): number;
/** The attached host driver (null when this client can't referee). */
get host(): ValleyBlocksHost | null;
}
/* ----------------------------------------------------------- host sims ----- */
export type Rng = () => number;
/** Seeded RNG for the host sims — the gyms' reproducibility rests on it. */
export declare function mulberry32(seed: number): Rng;
export interface SimFrame<F> {
f: F;
/** Target peer id; absent = broadcast. */
to?: string;
}
export interface SimEmit<F> {
frames: SimFrame<F>[];
/**
* The next scheduled host step. An object replaces any pending step, null
* cancels it, undefined leaves the pending schedule untouched.
*/
next?: { step: string; inMs: number } | null;
/** Set exactly when the browser would fire onHostMatchEnd: [id, nick, score]. */
matchEnd?: [id: string, nick: string, score: number][];
}
/** [peerId, nick, sigilIdx, seancesWon] */
export type NeonRosterEntry = [string, string, number, number];
export declare class SeanceSim {
constructor(opts: {
rng?: Rng;
now?: () => number;
roster: () => SeanceRosterEntry[];
addWin: (id: string) => void;
});
get running(): boolean;
get bell(): number;
get order(): readonly string[];
get candles(): readonly number[];
/** The medium's seat this bell and the room the ghost shuns (host-secret). */
get mediumSeat(): number;
get hintNot(): number;
get haunt(): number;
get inWalk(): boolean;
start(seanceNo: number, order: string[]): SimEmit<Record<string, unknown>>;
/** Execute a scheduled step ("bell" | "resolve" | "end" | "lobby"). */
step(step: string): SimEmit<Record<string, unknown>>;
pick(id: string, r: number): SimEmit<Record<string, unknown>>;
peerGone(id: string): SimEmit<Record<string, unknown>>;
snapshot(to: string): SimEmit<Record<string, unknown>>;
abort(): void;
}
export declare class NeonGridSim {
constructor(opts: {
roster: () => NeonRosterEntry[];
addScore: (id: string) => void;
resetScores: () => void;
});
get running(): boolean;
get round(): number;
get tickMs(): number;
get tickN(): number;
/** The authoritative grid (values are colorIdx+1; 0 = free). Live copy. */
get grid(): Uint8Array;
newMatch(): void;
startRound(riders: { id: string; color: number }[]): SimEmit<Record<string, unknown>>;
input(id: string, d: number): void;
peerGone(id: string): void;
/** Execute a scheduled step ("tick" | "match" | "lobby"). */
step(step: string): SimEmit<Record<string, unknown>>;
abort(): void;
snapshot(to: string): SimEmit<Record<string, unknown>>;
}
export declare class ValleyBlocksSim {
constructor(opts: {
roster: () => VBRosterEntry[];
addWin: (id: string) => void;
mode?: PartyMode;
target?: number;
});
get running(): boolean;
get round(): number;
get mode(): PartyMode;
get target(): number;
startRound(ids: string[], seed: number): SimEmit<VBFrame>;
onBoardState(from: string, round: number, seat: number, s: BoardState): SimEmit<VBFrame>;
playerLeft(id: string): SimEmit<VBFrame>;
snapshot(to: string): SimEmit<VBFrame>;
abort(): void;
}
/* -------------------------------------------------- valley-blocks engine --- */
export type SnakeDir = "up" | "down" | "left" | "right";
export interface SnakeState {
/** Head first, [x, y] in grid coordinates. */
segments: [number, number][];
dir: SnakeDir;
timeLeft: number;
duration: number;
turbo: boolean;
}
export interface ActivePiece {
type: PieceType;
rotation: number;
x: number;
y: number;
}
export interface ValleyBlocksEngineEvents {
onMove?: () => void;
onRotate?: () => void;
onLock?: () => void;
onHold?: () => void;
onHardDrop?: () => void;
onLinesCleared?: (count: number, rows: number[]) => void;
onLevelUp?: (level: number) => void;
onGameOver?: () => void;
onSnakeStart?: () => void;
onSnakeEnd?: () => void;
}
/** 0 = empty, otherwise a PieceType string, or "N" for frozen snake segments. */
export type Cell = PieceType | "N" | 0;
export declare class ValleyBlocksEngine {
readonly seed: number;
board: { grid: Cell[][] };
active: ActivePiece;
hold: PieceType | null;
holdUsed: boolean;
score: number;
lines: number;
level: number;
over: boolean;
snake: SnakeState | null;
/** Bumped whenever anything visible changes. */
rev: number;
constructor(seed: number, events?: ValleyBlocksEngineEvents);
get nextQueue(): PieceType[];
get ghostY(): number;
update(dt: number): void;
setSoftDrop(on: boolean): void;
softStep(): boolean;
move(dir: -1 | 1): boolean;
rotate(cw: boolean): boolean;
hardDrop(): void;
holdPiece(): boolean;
}
/* --------------------------------------------------- valley-blocks brain --- */
/** One legal placement and its afterstate. */
export interface VBCandidate {
/** Swap in the held (or next) piece before placing. */
useHold: boolean;
rotation: number;
x: number;
/** Rows cleared by this placement. */
cleared: number;
/** Rows-from-bottom of the piece's lowest cell before the clear (0 = floor). */
landingRow: number;
/** Dellacherie's metric: cleared × piece cells inside the cleared rows. */
erodedCells: number;
/** Afterstate occupancy, TOTAL_ROWS×COLS row-major, 1 = filled. */
grid: Uint8Array;
}
/** Board-shape metrics of an occupancy grid (the feature basis). */
export interface VBMetrics {
/** Per-column stack heights (0 = empty column). */
heights: number[];
aggregateHeight: number;
maxHeight: number;
/** Empty cells strictly below their column's top filled cell. */
holes: number;
/** Σ |h[c] − h[c+1]| over adjacent columns. */
bumpiness: number;
/** Cumulative well cells. */
wells: number;
/** Filled/empty flips scanning each row, side walls counted filled. */
rowTransitions: number;
/** Filled/empty flips scanning each column, floor counted filled. */
colTransitions: number;
}
/** A chosen placement being executed input-by-input. */
export interface VBPlan {
useHold: boolean;
rotation: number;
x: number;
}
export declare function enumeratePlacements(engine: ValleyBlocksEngine): VBCandidate[];
export declare function boardMetrics(grid: Uint8Array): VBMetrics;
/** Dellacherie's hand-tuned evaluation — the stock brain and gate baseline. */
export declare function dellacherieScore(c: VBCandidate): number;
/** Argmax over dellacherieScore, first max on ties. -1 when no candidates. */
export declare function stockPick(candidates: VBCandidate[]): number;
export declare function planOf(c: VBCandidate): VBPlan;
/** Issue ONE input toward the plan; "done" once the piece is locked. */
export declare function placementStep(
engine: ValleyBlocksEngine,
plan: VBPlan,
): "continue" | "done";
/** Run a plan to completion synchronously (the gym path). */
export declare function executePlacement(engine: ValleyBlocksEngine, c: VBCandidate): void;
/** One scripted steering step for the snake bonus piece. */
export declare function snakeStep(engine: ValleyBlocksEngine): void;
/* --------------------------------------------------------- host drivers ---- */
export interface HostMatchPolicy {
/** Never start below this many seated, connected players (default 2 —
* receipts need two distinct identities to co-sign). */
minPlayers?: number;
/** Start the moment this many are seated (default: same as minPlayers). */
expectedPlayers?: number;
/** With ≥minPlayers but <expectedPlayers, start after this long (default 15s). */
startTimeoutMs?: number;
/** Stop hosting new matches after this many (RL episode control). */
maxMatches?: number;
}
export interface HostOptions {
match?: HostMatchPolicy;
}
export interface HostSeat {
nick: string;
/** sigil (séance) / color (neon-grid) index. */
badge: number;
score: number;
}
export declare class HostDriver implements HostDriverLike {
protected readonly room: GameRoom;
protected readonly policy: Required<HostMatchPolicy>;
protected roster: Map<string, HostSeat>;
protected phase: "idle" | "lobby" | "running";
protected matches: number;
constructor(room: GameRoom, opts: HostOptions);
onMatchEnd(cb: (scores: [string, string, number][]) => void): void;
/** Manual start from the lobby (the auto-start policy normally does this). */
startNow(): boolean;
onClaimed(): void;
onSelfFrame(frame: unknown): void;
onForeignClaim(from: string, m: Record<string, unknown>): boolean;
close(): void;
}
export interface SeanceHostOptions extends HostOptions {
rng?: Rng;
}
export declare class SeanceHost extends HostDriver {
readonly sim: SeanceSim;
constructor(room: GameRoom, opts?: SeanceHostOptions);
}
export declare class NeonGridHost extends HostDriver {
readonly sim: NeonGridSim;
constructor(room: GameRoom, opts?: HostOptions);
}
export interface ValleyBlocksHostOptions extends HostOptions {
mode?: PartyMode;
target?: number;
/** Round-seed source (injectable for reproducible tests). */
rng?: Rng;
}
export declare class ValleyBlocksHost extends HostDriver {
readonly sim: ValleyBlocksSim;
constructor(room: GameRoom, opts?: ValleyBlocksHostOptions);
}
/* ------------------------------------------------------------------ gyms --- */
/** Field-identical to SeanceView — that identity is what lets a policy move. */
export interface SeanceGymView extends SeanceView {}
export interface SeanceGymStep {
views: SeanceGymView[];
rewards: number[];
done: boolean;
/** Winning seat (index into views), or null when the manor claims all. */
winner: number | null;
}
export interface SeanceGymOpts {
players: number;
seed?: number;
}
export declare class SeanceGym {
readonly players: number;
constructor(opts: SeanceGymOpts);
/** Start a séance and ring the first bell; returns the first decision views. */
reset(): SeanceGymView[];
/** One bell: actions[seat] = room 0..2 or null (stay). */
step(actions: (number | null)[]): SeanceGymStep;
}
/** Field-identical to NeonGridView. */
export interface NeonGridGymView extends NeonGridView {}
export interface NeonGridGymStep {
views: NeonGridGymView[];
rewards: number[];
done: boolean;
/** Winning seat, or null on a draw (simultaneous death). */
winner: number | null;
}
export interface NeonGridGymOpts {
players: number;
}
export declare class NeonGridGym {
readonly players: number;
constructor(opts: NeonGridGymOpts);
/** Start a fresh round; returns the first decision views (countdown skipped). */
reset(): NeonGridGymView[];
/** One tick: actions[seat] = absolute direction 0..3, or null to hold. */
step(actions: (number | null)[]): NeonGridGymStep;
}
export interface ValleyBlocksGymOpts {
players: number;
seed: number;
mode?: PartyMode;
target?: number;
/** Per-seat placement cap; hitting it forces a highest-score verdict. */
maxPlacements?: number;
}
export interface ValleyBlocksGymStep {
views: ValleyBlocksView[];
rewards: number[];
done: boolean;
/** Winning seat, or null while the round runs. */
winner: number | null;
reason: RoundReason | null;
}
export declare class ValleyBlocksGym {
readonly players: number;
readonly mode: PartyMode;
readonly target: number;
constructor(opts: ValleyBlocksGymOpts);
/** Start a fresh round; returns the first placement views. */
reset(): ValleyBlocksView[];
/** One placement per alive seat, in rotated seat order. */
step(actions: (number | null)[]): ValleyBlocksGymStep;
}
|