컴퓨터 난이도 1~60단계·방장 선택·판마다 변화·운, 공정성 확인에 표기, 업데이트 알림 팝업

- 난이도 1~60(쉬움 1~20·보통 21~40·어려움 41~60): 넣을 때 랜덤, 방장이 대기실에서 [랜덤][쉬움][보통][어려움] 선택(botLevel) → 범위 안 무작위
- 다음 판마다 -2~+2, 처음 단계 ±5·같은 범위 안(drift); 말투는 처음 단계(>30 존댓말)
- humanBest 확률을 단계별로 보간(BOT_PLAY_ANCHORS: 1·10·30·50·60)
- 운(-1~+1): 카드·주사위 게임에서 시작 전에 시드 후보 1~5개를 작업 스레드에서 끝까지 둬 보고 운에 맞는 것을 고름(luck.ts, luck-worker.ts). 해시 공개는 그대로
- 결과 화면 공정성 확인에 컴퓨터별 단계·운, 섞어 본 후보 수
- 업데이트 알림: 빌드 ID meta + /api/version + welcome.build → 상단 팝업 [지금 새로고침하기] [✕]
- 문서 03·04 §5.1·06 §12·07 §11.1·09 §9.1, 테스트(bot-level.room, luck, version, e2e bots·pwa)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-11 17:46:13 +09:00
parent 3cbc3698d3
commit 84d64b27f2
40 changed files with 1349 additions and 133 deletions

View File

@@ -29,6 +29,8 @@ export interface BrainRoom {
roomChat(bot: string, text: string): void;
setActivity(bot: string, a: BotActivity | null): void;
recentChat(): { from: string; text: string }[];
/** 똑똑한 편 (존댓말) or 허술한 편 (반말), docs/09 §9.1. */
smart(bot: string): boolean;
now(): number;
}
@@ -90,6 +92,7 @@ export class BotBrain {
return {
bot,
name: this.room.nameOf(bot),
smart: this.room.smart(bot),
game: this.room.gameName(),
situation,
task,
@@ -175,6 +178,7 @@ export class BotBrain {
this.llm,
bot,
this.room.nameOf(bot),
this.room.smart(bot),
`바퀴벌레 포커. 나는 ${target}에게 카드를 건넨다. 실제 카드는 ${KO[kind] ?? kind}다. ${target}의 앞마당: ${pile}.\n` +
`진짜 이름을 말할지(bluff=false) 다른 벌레라고 거짓말할지(bluff=true) 정하고, 건네며 할 한마디(say, 30자 이내, 실제 카드를 밝히지 말 것)를 정해.`,
{ type: 'object', properties: { bluff: { type: 'boolean' }, say: { type: 'string' } }, required: ['bluff', 'say'] },
@@ -243,6 +247,7 @@ export class BotBrain {
const line = await writeLine(this.llm, {
bot,
name: this.room.nameOf(bot),
smart: this.room.smart(bot),
game: '마피아(낮 토론, 모두가 보는 채팅)',
situation: '누가 마피아인지 추리하며 이야기하는 중이다. 너는 자신이 시민 팀이라고 말한다.',
task: hint,

View File

@@ -2,7 +2,7 @@
* What a computer says, written by the local model (docs/06 §12.1): a character (성격 + 말투) per computer, a prompt
* per moment, and a strict clean-up so only one short, kind, Korean chat line ever reaches people.
*/
import { botPersona, hash01 } from '@bg/games/bots';
import { hash01 } from '@bg/games/bots';
import { chatProblem } from '@bg/games/mafia';
import type { Llm, LlmMessage } from './llm';
@@ -27,16 +27,17 @@ export function temperOf(bot: string): Temper {
return TEMPERS[Math.floor(hash01(bot, 'temper') * TEMPERS.length)]!;
}
export function speechOf(bot: string): string {
return botPersona(bot).smart ? '존댓말(해요체), 또박또박' : '반말, 짧고 가볍게, ㅋㅋ를 가끔 붙임';
/** `smart` = 똑똑한 편 (the room's `botPersona`). */
export function speechOf(smart: boolean): string {
return smart ? '존댓말(해요체), 또박또박' : '반말, 짧고 가볍게, ㅋㅋ를 가끔 붙임';
}
export function systemPrompt(bot: string, name: string, maxLen: number): string {
export function systemPrompt(bot: string, name: string, maxLen: number, smart: boolean): string {
const t = temperOf(bot);
return [
`너는 온라인 보드게임 사이트 "같이 놀자"에서 사람들과 함께 게임하는 컴퓨터 플레이어 "${name}"이다.`,
`성격: ${t.ko} — ${t.desc}`,
`말투: ${speechOf(bot)}.`,
`말투: ${speechOf(smart)}.`,
`규칙: 한국어 채팅 한 줄만 쓴다. ${maxLen}자 이내. 대사만 쓰고 따옴표·설명·괄호·영어·한자는 쓰지 않는다.`,
'욕설, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 게임과 상관없는 이야기는 하지 않는다.',
'자신이 AI나 프로그램이라고 말하지 않는다. 숨겨진 정보(내 패, 내 카드, 내 직업)는 절대 밝히지 않는다.',
@@ -46,6 +47,8 @@ export function systemPrompt(bot: string, name: string, maxLen: number): string
export interface LineRequest {
bot: string;
name: string;
/** 똑똑한 편 (존댓말) / 허술한 편 (반말). */
smart: boolean;
game: string;
/** What is going on, in plain Korean. */
situation: string;
@@ -99,7 +102,7 @@ export async function writeLine(llm: Llm | null, req: LineRequest): Promise<stri
if (req.example) parts.push(`예시(뜻은 같게, 표현은 너답게 새로): ${req.example}`);
parts.push(`할 말: ${req.task}`);
const messages: LlmMessage[] = [
{ role: 'system', content: systemPrompt(req.bot, req.name, maxLen) },
{ role: 'system', content: systemPrompt(req.bot, req.name, maxLen, req.smart) },
{ role: 'user', content: parts.join('\n') },
];
const raw = await llm.chat(messages, { maxTokens: 70, temperature: 0.95 });
@@ -107,11 +110,11 @@ export async function writeLine(llm: Llm | null, req: LineRequest): Promise<stri
}
/** Structured choice (JSON schema) — e.g. 바퀴벌레 포커: tell the truth or bluff, and what to say. */
export async function decide<T>(llm: Llm | null, bot: string, name: string, prompt: string, schema: object): Promise<T | null> {
export async function decide<T>(llm: Llm | null, bot: string, name: string, smart: boolean, prompt: string, schema: object): Promise<T | null> {
if (!llm || !llm.available()) return null;
const raw = await llm.chat(
[
{ role: 'system', content: systemPrompt(bot, name, 40) + '\n대답은 요청한 JSON 형식으로만 한다.' },
{ role: 'system', content: systemPrompt(bot, name, 40, smart) + '\n대답은 요청한 JSON 형식으로만 한다.' },
{ role: 'user', content: prompt },
],
{ maxTokens: 120, temperature: 0.9, format: schema },

View File

@@ -16,6 +16,8 @@ import type { SettingsStore } from '../admin/settings';
export interface HttpDeps {
config: Config;
/** Web build being served (`/api/version`, docs/07 §11.1); null without a web build. */
build?: string | null;
users: Users;
sessions: Sessions;
rooms: RoomManager;
@@ -76,6 +78,12 @@ export function createHttpApp(d: HttpDeps) {
setCookie(c, SESSION_COOKIE, token, cookieOpts(SESSION_TTL[kind]));
};
// Open pages ask now and then whether the site was updated (docs/07 §11.1).
app.get('/api/version', (c) => {
c.header('Cache-Control', 'no-store');
return c.json({ build: d.build ?? null });
});
app.get('/healthz', (c) => {
const h = d.health();
return c.json(h, h.ok ? 200 : 503);

View File

@@ -0,0 +1,238 @@
/** Computer levels 1~60, the host's 쉬움/보통/어려움, drift between games and luck shuffles (docs/09 §9.1, docs/04 §5.1). */
import { afterEach, describe, expect, test } from 'bun:test';
import { seedToHex, type ChaChaSeed } from '@bg/engine';
import { GAMES } from '@bg/games';
import { BOT_BANDS, ClientMessage, bandOf, botProfile, isBotId, luckLabel, type ServerMessage } from '@bg/shared';
import type { LuckJob } from '@bg/games/bots/luck';
import { openDb } from '../db';
import { sha256Hex } from '../auth/sessions';
import { DRIFT_RANGE, DRIFT_STEP, drift, newBotProfile, profileFromId, repick, rollLevel } from './bot-profile';
import { RoomManager } from './manager';
import { Room, type Conn, type RoomSnapshot } from './room';
import { RoomStore } from './store';
const rooms: Room[] = [];
afterEach(() => {
for (const r of rooms.splice(0)) r.clearTimer();
});
function harness(luckSeed?: (job: LuckJob) => Promise<{ seed: ChaChaSeed; tried: number }>) {
const db = openDb(':memory:');
const store = new RoomStore(db);
let now = 1_000_000;
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 60_000, luckSeed });
const conn = (userId: string) => {
const msgs: ServerMessage[] = [];
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
return c;
};
const practice = (gameId: string) => {
const r = manager.createPractice('A', gameId) as Room;
rooms.push(r);
r.join(conn('A'), 'player');
return r;
};
return { db, store, clock, manager, conn, practice, users };
}
const botsOf = (room: Room) => room.seatedIds().filter(isBotId);
const seq = (...xs: number[]) => {
let i = 0;
return () => xs[i++ % xs.length]!;
};
describe('levels', () => {
test('rolls: 랜덤 1~60, 쉬움 1~20, 보통 21~40, 어려움 41~60, all values reachable', () => {
for (const pick of ['random', 'easy', 'normal', 'hard'] as const) {
const [lo, hi] = pick === 'random' ? [1, 60] : BOT_BANDS[pick];
expect(rollLevel(pick, () => 0)).toBe(lo);
expect(rollLevel(pick, () => 0.999999)).toBe(hi);
for (let i = 0; i < 500; i++) {
const l = rollLevel(pick);
expect(l >= lo && l <= hi).toBe(true);
}
}
expect(bandOf(20)).toBe('easy');
expect(bandOf(21)).toBe('normal');
expect(bandOf(41)).toBe('hard');
});
test('a new computer: any level, its own luck in [-1, 1]; picking a band keeps the luck', () => {
const p = newBotProfile(seq(0.5, 0.9));
expect(p).toEqual({ pick: 'random', base: 31, level: 31, luck: expect.closeTo(0.8, 9), played: 0 });
const q = repick(p, 'easy', () => 0.3);
expect(q).toEqual({ pick: 'easy', base: 7, level: 7, luck: p.luck, played: 0 });
expect(luckLabel(-1)).toBe('아주 나쁨');
expect(luckLabel(0)).toBe('보통');
expect(luckLabel(0.7)).toBe('아주 좋음');
});
test('drift: none before the first game, then at most 2 a game, within ±5 of the start and never out of its band', () => {
for (const base of [1, 20, 21, 33, 41, 60]) {
let p = { ...newBotProfile(), base, level: base };
p = drift(p);
expect(p.level).toBe(base);
const [lo, hi] = BOT_BANDS[bandOf(base)];
for (let g = 0; g < 300; g++) {
const prev = p.level;
p = drift(p);
expect(Math.abs(p.level - prev)).toBeLessThanOrEqual(DRIFT_STEP);
expect(Math.abs(p.level - base)).toBeLessThanOrEqual(DRIFT_RANGE);
expect(p.level >= lo && p.level <= hi).toBe(true);
}
}
// A 60 can become 58 next game, never 41.
expect(drift({ ...newBotProfile(), base: 60, level: 60, played: 1 }, () => 0).level).toBe(58);
});
test('computers saved without a level get one from their id (the same every time)', () => {
const id = 'bot:1:01J0000000ZZZZZZ0000000000';
expect(profileFromId(id)).toEqual(profileFromId(id));
expect(profileFromId(id).level).toBe(60);
});
});
describe('room', () => {
test('protocol accepts botLevel with the four choices only', () => {
expect(ClientMessage.safeParse({ t: 'botLevel', userId: 'bot:1:x', pick: 'hard' }).success).toBe(true);
expect(ClientMessage.safeParse({ t: 'botLevel', userId: 'bot:1:x', pick: 'insane' }).success).toBe(false);
});
test('the host picks a band; everyone sees the pick, nobody sees the level until the game is over', () => {
const { practice, conn } = harness();
const room = practice('omok');
const bot = botsOf(room)[0]!;
expect(room.profile(bot).pick).toBe('random');
expect(room.roomView().botPicks).toEqual({ [bot]: 'random' });
room.join(conn('S'), 'spectator');
expect(room.setBotLevel('S', bot, 'hard')).toBe('방장만 난이도를 바꿀 수 있어요.');
expect(room.setBotLevel('A', 'bot:9:nope', 'hard')).toBe('없는 컴퓨터예요.');
expect(room.setBotLevel('A', bot, 'hard')).toBeNull();
expect(room.roomView().botPicks).toEqual({ [bot]: 'hard' });
const level = room.profile(bot).level;
expect(level >= 41 && level <= 60).toBe(true);
expect(JSON.stringify(room.roomView())).not.toContain('"level"');
expect(room.start('A')).toBeNull();
expect(room.setBotLevel('A', bot, 'easy')).toBe('게임 중에는 바꿀 수 없어요.');
expect(room.roomView().lastBots).toBeUndefined();
room.act('A', 1, { type: 'resign' });
expect(room.status).toBe('finished');
expect(room.roomView().lastBots).toEqual({ [bot]: { level, luck: room.profile(bot).luck } });
expect(room.roomView().lastShuffles).toBe(1);
});
test('every next game the level moves a little around where it started', () => {
const { practice } = harness();
const room = practice('omok');
const bot = botsOf(room)[0]!;
room.setBotLevel('A', bot, 'hard');
const base = room.profile(bot).base;
const seen: number[] = [];
for (let g = 0; g < 25; g++) {
expect(g === 0 ? room.start('A') : room.rematch('A')).toBeNull();
seen.push(room.game!.bots![bot]!.level);
room.act('A', g + 1, { type: 'resign' });
}
expect(seen[0]).toBe(base);
for (let i = 1; i < seen.length; i++) expect(Math.abs(seen[i]! - seen[i - 1]!)).toBeLessThanOrEqual(DRIFT_STEP);
for (const l of seen) expect(l >= Math.max(41, base - DRIFT_RANGE) && l <= Math.min(60, base + DRIFT_RANGE)).toBe(true);
expect(new Set(seen).size).toBeGreaterThan(1);
});
test('levels and luck survive a restart; rooms saved before get them from the id', () => {
const { practice, store, clock, users } = harness();
const room = practice('omok');
const bot = botsOf(room)[0]!;
room.setBotLevel('A', bot, 'easy');
const before = room.profile(bot);
const { seq: s, stateJson } = store.openRooms()[0]!;
const deps = { store, games: GAMES, users, now: clock.now, botDelay: () => 60_000 };
const restored = Room.restore(room.id, room.code, s, JSON.parse(stateJson) as RoomSnapshot, deps);
rooms.push(restored);
expect(restored.profile(bot)).toEqual(before);
const old = JSON.parse(stateJson) as RoomSnapshot;
delete old.bots;
const legacy = Room.restore(room.id, room.code, s, old, deps);
rooms.push(legacy);
expect(legacy.profile(bot)).toEqual(profileFromId(bot));
});
});
describe('luck shuffles', () => {
const seedA = [1, 2, 3, 4, 5, 6, 7, 8] as ChaChaSeed;
test('a card game with computers waits for the shuffles, then starts with the chosen seed', async () => {
const jobs: LuckJob[] = [];
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
const { practice } = harness(async (job) => {
jobs.push(job);
await gate;
return { seed: seedA, tried: 4 };
});
const room = practice('one-card');
const bot = botsOf(room)[0]!;
room.botProfiles[bot]!.luck = 0.9;
expect(room.start('A')).toBeNull();
expect(room.status).toBe('lobby');
expect(room.roomView().starting).toBe(true);
expect(room.start('A')).toBe('게임을 준비하고 있어요.');
expect(room.setBotLevel('A', bot, 'easy')).toBe('게임을 준비하고 있어요.');
expect(jobs).toHaveLength(1);
expect(jobs[0]).toMatchObject({ gameId: 'one-card', players: room.seatedIds(), luck: { [bot]: room.profile(bot).luck }, gameNo: 1 });
release();
await gate;
await Bun.sleep(0);
expect(room.status).toBe('playing');
expect(room.roomView().starting).toBeUndefined();
expect(room.game!.seedHex).toBe(seedToHex(seedA));
expect(room.game!.seedHash).toBe(sha256Hex(seedToHex(seedA)));
expect(room.game!.shuffles).toBe(4);
});
test('if the seats change while shuffling, nothing starts', async () => {
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
const { practice } = harness(async () => {
await gate;
return { seed: seedA, tried: 2 };
});
const room = practice('one-card');
room.botProfiles[botsOf(room)[0]!]!.luck = -0.9;
expect(room.start('A')).toBeNull();
room.leave('A');
release();
await gate;
await Bun.sleep(0);
expect(room.status).toBe('lobby');
expect(room.game).toBeNull();
expect(room.starting).toBe(false);
});
test('a failed shuffle job still starts the game with a fresh seed; board games and luck near 0 never ask', async () => {
const asked: string[] = [];
const { practice } = harness(async (job) => {
asked.push(job.gameId);
throw new Error('worker down');
});
const omok = practice('omok');
expect(omok.start('A')).toBeNull();
expect(omok.status).toBe('playing');
const cards = practice('one-card');
cards.botProfiles[botsOf(cards)[0]!]!.luck = 1;
expect(cards.start('A')).toBeNull();
expect(cards.status).toBe('lobby');
await Bun.sleep(0);
await Bun.sleep(0);
expect(cards.status).toBe('playing');
expect(cards.game!.shuffles).toBe(1);
const plain = practice('one-card');
plain.botProfiles[botsOf(plain)[0]!]!.luck = 0.05;
expect(plain.start('A')).toBeNull();
expect(plain.status).toBe('playing');
expect(asked).toEqual(['one-card']);
});
});

View File

@@ -0,0 +1,62 @@
/**
* Each computer's level and luck in a room (docs/09-game-engine.md §9.1, docs/06-lobby-rooms.md §12).
* Level 1~60: drawn when the computer is added (any level) or when the host picks a band (쉬움 1~20, 보통 21~40,
* 어려움 41~60). After that it moves a little from game to game but stays near where it started.
*/
import { secureRandom } from '@bg/engine';
import { BOT_BANDS, BOT_LEVEL_MAX, bandOf, type BotPick } from '@bg/shared';
import { hash01, idLevel } from '@bg/games/bots';
export interface BotProfile {
/** What the host chose: 랜덤 (any level) or a band. */
pick: BotPick;
/** The level drawn for that choice; the drift stays around it. */
base: number;
/** The level it plays at now. */
level: number;
/** -1 (아주 나쁨) … 1 (아주 좋음), drawn once when the computer is added. */
luck: number;
/** Games it has started with this base. */
played: number;
}
/** How far a level may move from where it started, and how much in one game. */
export const DRIFT_RANGE = 5;
export const DRIFT_STEP = 2;
const int = (lo: number, hi: number, random: () => number) => lo + Math.floor(random() * (hi - lo + 1));
export function rollLevel(pick: BotPick, random: () => number = secureRandom): number {
const [lo, hi] = pick === 'random' ? [1, BOT_LEVEL_MAX] : BOT_BANDS[pick];
return int(lo, hi, random);
}
export function newBotProfile(random: () => number = secureRandom): BotProfile {
const base = rollLevel('random', random);
return { pick: 'random', base, level: base, luck: random() * 2 - 1, played: 0 };
}
/** The host picked a difficulty: a new level from that range, luck stays. */
export function repick(p: BotProfile, pick: BotPick, random: () => number = secureRandom): BotProfile {
const base = rollLevel(pick, random);
return { ...p, pick, base, level: base, played: 0 };
}
/**
* Before each game after the first: the level moves by at most `DRIFT_STEP`, never more than `DRIFT_RANGE` from where
* it started and never out of that band (a 60 can become 58, never 41).
*/
export function drift(p: BotProfile, random: () => number = secureRandom): BotProfile {
if (p.played === 0) return { ...p, played: 1 };
const [blo, bhi] = BOT_BANDS[bandOf(p.base)];
const lo = Math.max(blo, p.base - DRIFT_RANGE);
const hi = Math.min(bhi, p.base + DRIFT_RANGE);
const level = Math.min(hi, Math.max(lo, p.level + int(-DRIFT_STEP, DRIFT_STEP, random)));
return { ...p, level, played: p.played + 1 };
}
/** Computers saved before rooms kept a profile: level and luck fixed by the id. */
export function profileFromId(bot: string): BotProfile {
const base = idLevel(bot);
return { pick: 'random', base, level: base, luck: hash01(bot, 'luck') * 2 - 1, played: 0 };
}

View File

@@ -5,7 +5,7 @@
*/
import { secureRandom, type AnyGameDefinition } from '@bg/engine';
import { isBotId } from '@bg/shared';
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, type LiveBotStrategy } from '@bg/games/bots';
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots';
import type { BotBrain } from '../ai/brain';
@@ -23,6 +23,8 @@ export interface BotRoom {
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
/** Display name of a player (live bots talk about each other by name). */
nameOf?(id: string): string;
/** A computer's level now and the level it started with (docs/09 §9.1); absent = fixed by the id. */
profile?(bot: string): { level: number; base: number };
/** The computers' talk and visible activity with the local model (docs/06 §12.1). */
brain?: BotBrain;
}
@@ -157,7 +159,7 @@ export class BotDriver {
let decision: { action: unknown; next: number; hint?: string } = { action: null, next: 3000 };
const t0 = performance.now();
try {
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot), names, memory });
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, this.room.profile?.(bot).base), names, memory });
} catch (err) {
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
}
@@ -247,7 +249,7 @@ export class BotDriver {
const t0 = performance.now();
let action: unknown;
try {
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random, level: botPersona(next.bot).level });
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random, level: this.room.profile?.(next.bot).level ?? idLevel(next.bot) });
} catch (err) {
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
action = null;

View File

@@ -0,0 +1,18 @@
/** Worker thread for the computers' luck (docs/04 §5.1): plays out candidate shuffles off the rooms' thread. */
import { createSeed, secureRandom } from '@bg/engine';
import { GAMES } from '@bg/games';
import { chooseLuckySeed, type LuckJob } from '@bg/games/bots/luck';
declare const self: Worker;
self.onmessage = (e: MessageEvent<{ id: number; job: LuckJob }>) => {
const { id, job } = e.data;
try {
const def = GAMES[job.gameId];
if (!def) throw new Error(`unknown game ${job.gameId}`);
const { seed, tried } = chooseLuckySeed(def, job, createSeed, secureRandom);
self.postMessage({ id, seed, tried });
} catch (err) {
self.postMessage({ id, error: String(err) });
}
};

View File

@@ -0,0 +1,49 @@
/** The luck worker (docs/04 §5.1): real thread, real play-outs. */
import { expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import { createLuckSeeder } from './luck';
const job = (gameId: string, luck: number) => ({
gameId,
players: ['human', 'bot:1:a'],
options: GAMES[gameId]?.defaultOptions ?? {},
now: Date.now(),
gameNo: 1,
luck: { 'bot:1:a': luck },
levels: { 'bot:1:a': 30 },
budgetMs: 1500,
});
test('plays out the shuffles on a worker thread and returns one of them', async () => {
const seeder = createLuckSeeder();
try {
const [lucky, plain] = await Promise.all([seeder.seed(job('one-card', 1)), seeder.seed(job('one-card', 0))]);
expect(lucky.seed).toHaveLength(8);
expect(lucky.tried).toBe(5);
expect(plain.tried).toBe(1);
expect(lucky.seed.every((w) => Number.isInteger(w) && w >= 0 && w < 2 ** 32)).toBe(true);
} finally {
seeder.stop();
}
}, 20_000);
test('an unknown game or a slow worker falls back to one fresh seed', async () => {
const logs: string[] = [];
const seeder = createLuckSeeder({ log: (_l, msg) => logs.push(msg) });
try {
const r = await seeder.seed(job('nope', 1));
expect(r.tried).toBe(1);
expect(r.seed).toHaveLength(8);
expect(logs).toContain('luck shuffle failed');
} finally {
seeder.stop();
}
const slow = createLuckSeeder({ timeoutMs: 1, log: (_l, msg) => logs.push(msg) });
try {
const r = await slow.seed(job('mahjong', 1));
expect(r.tried).toBe(1);
expect(logs).toContain('luck shuffle timed out');
} finally {
slow.stop();
}
}, 20_000);

View File

@@ -0,0 +1,76 @@
/**
* The rooms' side of the luck worker (docs/04-stability-security.md §5.1). Playing out a few shuffles takes up to a
* couple of seconds for the heaviest games (마작), so it runs on its own thread; the rooms keep running meanwhile.
* One worker, jobs in order. If the worker fails or takes too long, the game starts with one fresh seed (no luck).
*/
import { createSeed, type ChaChaSeed } from '@bg/engine';
import type { LuckJob } from '@bg/games/bots/luck';
type Picked = { seed: ChaChaSeed; tried: number };
export interface LuckSeeder {
seed(job: LuckJob): Promise<Picked>;
stop(): void;
}
export function createLuckSeeder(opts: { timeoutMs?: number; log?: (level: 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void } = {}): LuckSeeder {
const timeoutMs = opts.timeoutMs ?? 8000;
let worker: Worker | null = null;
let nextId = 1;
const pending = new Map<number, { resolve: (p: Picked) => void; timer: ReturnType<typeof setTimeout> }>();
const fallback = (): Picked => ({ seed: createSeed(), tried: 1 });
const settle = (id: number, p: Picked) => {
const job = pending.get(id);
if (!job) return;
pending.delete(id);
clearTimeout(job.timer);
job.resolve(p);
};
const reset = (why: string) => {
opts.log?.('error', 'luck worker failed', { why });
worker?.terminate();
worker = null;
for (const id of [...pending.keys()]) settle(id, fallback());
};
const get = (): Worker => {
if (worker) return worker;
const w = new Worker(new URL('./luck-worker.ts', import.meta.url).href);
w.onmessage = (e: MessageEvent<{ id: number; seed?: ChaChaSeed; tried?: number; error?: string }>) => {
const { id, seed, tried, error } = e.data;
if (error || !seed) {
opts.log?.('warn', 'luck shuffle failed', { error });
settle(id, fallback());
} else settle(id, { seed, tried: tried ?? 1 });
};
w.onerror = (e) => reset(String((e as ErrorEvent).message ?? e));
w.unref();
worker = w;
return w;
};
return {
seed(job) {
return new Promise<Picked>((resolve) => {
const id = nextId++;
const timer = setTimeout(() => {
opts.log?.('warn', 'luck shuffle timed out', { game: job.gameId });
settle(id, fallback());
}, timeoutMs);
pending.set(id, { resolve, timer });
try {
get().postMessage({ id, job });
} catch (err) {
reset(String(err));
}
});
},
stop() {
worker?.terminate();
worker = null;
for (const id of [...pending.keys()]) settle(id, fallback());
},
};
}

View File

@@ -29,6 +29,8 @@ export interface ManagerDeps {
ai?: RoomDeps['ai'];
aiSleep?: RoomDeps['aiSleep'];
aiRandom?: RoomDeps['aiRandom'];
/** Shuffles for the computers' luck (docs/04 §5.1); absent = one fresh seed per game. */
luckSeed?: RoomDeps['luckSeed'];
/** When the user's last socket to the site closed; null while the site is open somewhere (the gateway knows). */
offlineSince?: (userId: string) => number | null;
}
@@ -56,6 +58,7 @@ export class RoomManager {
ai: this.deps.ai,
aiSleep: this.deps.aiSleep,
aiRandom: this.deps.aiRandom,
luckSeed: this.deps.luckSeed,
onEmpty: (room, why) => {
// The last person left on purpose and nobody holds a seat (only computers, or nobody joined): close it now.
if (why === 'leave' && this.byCode.get(room.code) === room && !room.hasPeopleSeated()) this.close(room);

View File

@@ -3,10 +3,13 @@
* All mutations run on the single JS thread, so a room never sees concurrent updates.
*/
import { ulid } from 'ulid';
import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type GameResult, type RngState } from '@bg/engine';
import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine';
import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
import { botPersona } from '@bg/games/bots';
import { luckApplies, shufflesFor, type LuckJob } from '@bg/games/bots/luck';
import { sha256Hex } from '../auth/sessions';
import { BotDriver, type BotDelayInput } from './bots';
import { drift, newBotProfile, profileFromId, repick, type BotProfile } from './bot-profile';
import { BotBrain, type BotActivity } from '../ai/brain';
import type { Llm } from '../ai/llm';
import type { LogEntry, RoomStore } from './store';
@@ -54,6 +57,10 @@ interface GameSlot {
finished: boolean;
/** After a restore, deadlines are not enforced before this time (docs/04 §3.3). */
deadlineFloor: number | null;
/** Each computer's level and luck in this game (shown in the fairness check afterwards). */
bots?: Record<string, { level: number; luck: number }>;
/** Shuffles tried for the computers' luck (docs/04 §5.1); 1 or absent = the first one. */
shuffles?: number;
}
/** Shape persisted to room_state.state_json. */
@@ -70,6 +77,8 @@ export interface RoomSnapshot {
lastResult: GameResult | null;
game: GameSlot | null;
joinedAt: Record<string, number>;
/** Computers' level and luck (absent in rooms saved before 2026-10-11: then fixed by the bot id). */
bots?: Record<string, BotProfile>;
}
export interface RoomDeps {
@@ -91,9 +100,16 @@ export interface RoomDeps {
aiSleep?: (ms: number) => Promise<void>;
/** Dice for the computers' talk (whether to speak now); tests may pin it. */
aiRandom?: () => number;
/**
* Tries shuffles for the computers' luck off the main thread (docs/04 §5.1). Absent (tests): every game starts at
* once with one fresh seed.
*/
luckSeed?: (job: LuckJob) => Promise<{ seed: ChaChaSeed; tried: number }>;
}
const CHAT_HISTORY = 30;
/** Time the luck worker may spend on more shuffles (the first is always played out), docs/04 §5.1. */
export const LUCK_BUDGET_MS = 1500;
const ERROR_LIMIT = 3;
/** Streaming actions (drawing) are logged in batches: at most this long between snapshot writes. */
const STREAM_FLUSH_MS = 1000;
@@ -117,6 +133,12 @@ export class Room {
lastSeed: string | null = null;
lastResult: GameResult | null = null;
game: GameSlot | null = null;
/** Computers' level and luck (docs/09 §9.1), by bot id. */
botProfiles: Record<string, BotProfile> = {};
/** The computers' shuffles are being tried; the game starts when they're done. */
starting = false;
/** Shut down or closed: late callbacks (the luck worker) must not touch it. */
private closed = false;
chatLog: Extract<ServerMessage, { t: 'chat' }>[] = [];
lastActiveAt: number;
/** When the last connection went away (null while someone is connected). */
@@ -166,6 +188,7 @@ export class Room {
this.broadcastRoom();
},
recentChat: () => this.chatLog.slice(-8).map((m) => ({ from: m.from?.nickname ?? '누군가', text: m.text })),
smart: (bot) => botPersona(bot, this.profile(bot).base).smart,
now: this.now,
},
deps.ai ?? null,
@@ -191,6 +214,7 @@ export class Room {
},
log: deps.log,
nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가',
profile: (bot) => this.profile(bot),
brain: this.brain,
},
secureRandom,
@@ -289,6 +313,7 @@ export class Room {
lastResult: this.lastResult,
game: this.game,
joinedAt,
bots: this.botProfiles,
};
}
@@ -303,6 +328,7 @@ export class Room {
room.lastSeed = snap.lastSeed;
room.lastResult = snap.lastResult;
room.game = snap.game;
room.botProfiles = snap.bots ?? {};
const now = room.now();
for (const s of room.seats) {
// Computer players have no connection (and so no reconnect grace period).
@@ -396,6 +422,10 @@ export class Room {
lastSeed: this.lastSeed,
lastGamePk: this.game?.finished ? this.game.gamePk : null,
...(this.botActivity.size ? { botActivity: Object.fromEntries(this.botActivity) } : {}),
...(this.hasBots() ? { botPicks: Object.fromEntries(this.seatedIds().filter(isBotId).map((b) => [b, this.profile(b).pick])) } : {}),
...(this.starting ? { starting: true } : {}),
// Levels are revealed only once the game is over (fairness check).
...(this.game?.finished && this.game.bots ? { lastBots: this.game.bots, lastShuffles: this.game.shuffles ?? 1 } : {}),
};
}
@@ -574,9 +604,15 @@ export class Room {
// ---------------------------------------------------------------- lobby commands
private requireLobby(): string | null {
if (this.starting) return '게임을 준비하고 있어요.';
return this.status === 'lobby' || this.status === 'finished' ? null : '게임 중에는 바꿀 수 없어요.';
}
/** A computer's level and luck; computers saved without one get it from their id. */
profile(bot: string): BotProfile {
return (this.botProfiles[bot] ??= profileFromId(bot));
}
seat(userId: string, seat?: number): string | null {
const err = this.requireLobby();
if (err) return err;
@@ -712,9 +748,10 @@ export class Room {
const used = new Set(this.seatedIds().map(botNumber));
let n = 1;
while (used.has(n)) n++;
// The id's random part is the computer's level roll (`botDraw`): uniform OS randomness.
const id = makeBotId(n, ulid(this.now(), secureRandom));
this.seats[target] = { userId: id, ready: true };
// Any level 1~60 and its own luck, from OS randomness; the host may pick 쉬움/보통/어려움 afterwards.
this.botProfiles[id] = newBotProfile();
if (this.config.visibility === 'public') this.config = { ...this.config, visibility: 'private' };
this.persist({ actorId: userId, kind: 'addBot', data: { seat: target, bot: id } });
this.broadcastRoom();
@@ -729,11 +766,24 @@ export class Room {
if (seat < 0 || !isBotId(botId)) return '없는 컴퓨터예요.';
this.seats[seat] = null;
this.rematchVotes.delete(botId);
delete this.botProfiles[botId];
this.persist({ actorId: userId, kind: 'removeBot', data: { bot: botId } });
this.broadcastRoom();
return null;
}
/** Host picks a computer's difficulty: a new level from that range (랜덤 = any), hidden until the game is over. */
setBotLevel(userId: string, botId: string, pick: BotPick): string | null {
if (userId !== this.hostId) return '방장만 난이도를 바꿀 수 있어요.';
const err = this.requireLobby();
if (err) return err;
if (this.seatOf(botId) < 0 || !isBotId(botId)) return '없는 컴퓨터예요.';
this.botProfiles[botId] = repick(this.profile(botId), pick);
this.persist({ actorId: userId, kind: 'botLevel', data: { bot: botId, pick } });
this.broadcastRoom();
return null;
}
chat(userId: string, text: string): string | null {
if (!this.config.chatEnabled) return '이 방은 채팅을 쓰지 않아요.';
if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.';
@@ -781,17 +831,18 @@ export class Room {
if (players.length > range.max) return `최대 ${range.max}명까지 할 수 있어요.`;
if (this.hasBots() && !botsAllowed(this.config.gameId)) return '컴퓨터는 이 게임을 할 수 없어요.';
if (players.every(isBotId)) return '사람이 한 명은 앉아야 해요.';
return this.startGame(players);
return this.beginGame(players);
}
rematch(userId: string): string | null {
if (this.status !== 'finished') return '게임이 끝난 뒤에 누를 수 있어요.';
if (this.starting) return '게임을 준비하고 있어요.';
if (this.seatOf(userId) < 0) return '자리에 앉아야 해요.';
this.rematchVotes.add(userId);
const seated = this.seatedIds();
const range = this.playerRange();
if (seated.length >= range.min && seated.every((u) => isBotId(u) || this.rematchVotes.has(u))) {
return this.startGame(this.orderedPlayers());
return this.beginGame(this.orderedPlayers());
}
this.persist(null);
this.broadcastRoom();
@@ -805,7 +856,8 @@ export class Room {
return h > 0 ? [...ids.slice(h), ...ids.slice(0, h)] : ids;
}
private startGame(players: string[]): string | null {
/** The options the game would start with, or why it can't start. */
private startOptions(players: string[]): { options: unknown } | string {
const def = this.def;
const lk = this.locked(def.id);
const parsed = def.optionsSchema.safeParse(lk.paths.length ? applyLocks(this.config.options, lk.defaults, lk.paths) : this.config.options);
@@ -814,22 +866,75 @@ export class Room {
if (countErr) return countErr;
const eff = this.deps.settings?.game(def.id);
if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.';
this.config = { ...this.config, options: parsed.data };
const seed = createSeed();
return { options: parsed.data };
}
/**
* Starts a game. With computers in a game of chance, a few shuffles are tried first for their luck (docs/04 §5.1)
* on the luck worker; the room shows "섞는 중" and starts when they are done (well under a few seconds). If the
* seats changed meanwhile, nothing starts and the host can press start again.
*/
private beginGame(players: string[]): string | null {
const ok = this.startOptions(players);
if (typeof ok === 'string') return ok;
const bots = players.filter(isBotId);
const luckSeed = this.deps.luckSeed;
if (!luckSeed || !luckApplies(this.def.id) || shufflesFor(bots.map((b) => this.profile(b).luck)) <= 1) return this.startGame(players, null);
const job: LuckJob = {
gameId: this.def.id,
players,
options: ok.options,
now: this.now(),
gameNo: this.gameNo + 1,
luck: Object.fromEntries(bots.map((b) => [b, this.profile(b).luck])),
levels: Object.fromEntries(bots.map((b) => [b, this.profile(b).level])),
budgetMs: LUCK_BUDGET_MS,
};
this.starting = true;
this.broadcastRoom();
const gameNo = this.gameNo;
void luckSeed(job)
.catch((err) => {
this.deps.log?.('warn', 'luck shuffle failed', { room: this.code, err: String(err) });
return null;
})
.then((picked) => {
this.starting = false;
if (this.closed) return;
const same = this.gameNo === gameNo && this.requireLobby() === null && this.orderedPlayers().join() === players.join();
const err = same ? this.startGame(players, picked) : null;
if (err) this.notice('start-failed', err);
if (!same || err) this.broadcastRoom();
});
return null;
}
private startGame(players: string[], picked: { seed: ChaChaSeed; tried: number } | null): string | null {
const def = this.def;
const ok = this.startOptions(players);
if (typeof ok === 'string') return ok;
this.config = { ...this.config, options: ok.options };
const seed = picked?.seed ?? createSeed();
const seedHex = seedToHex(seed);
const rng = SeededRng.fromSeed(seed);
const now = this.now();
const gameNo = this.gameNo + 1;
let state: unknown;
try {
state = def.setup({ players, options: parsed.data, rng, now, gameNo });
state = def.setup({ players, options: ok.options, rng, now, gameNo });
} catch (err) {
this.deps.log?.('error', 'setup failed', { room: this.code, err: String(err) });
return '게임을 시작하지 못했어요.';
}
const gamePk = ulid(now);
const seedHash = sha256Hex(seedHex);
this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: parsed.data, seedHash, startedAt: now });
// From the second game on, each computer's level moves a little around where it started (docs/09 §9.1).
const bots: Record<string, { level: number; luck: number }> = {};
for (const b of players.filter(isBotId)) {
const p = (this.botProfiles[b] = drift(this.profile(b)));
bots[b] = { level: p.level, luck: p.luck };
}
this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: ok.options, seedHash, startedAt: now });
this.gameNo = gameNo;
this.game = {
gameId: def.id,
@@ -843,6 +948,7 @@ export class Room {
players,
finished: false,
deadlineFloor: null,
...(Object.keys(bots).length ? { bots, shuffles: picked?.tried ?? 1 } : {}),
};
this.status = 'playing';
this.rematchVotes.clear();
@@ -1074,6 +1180,7 @@ export class Room {
/** Ends a running game uncounted and sends everyone still in the room away (the manager then closes it). */
closeWith(summary: string, notice: string): void {
this.closed = true;
if (this.game && !this.game.finished) {
this.finishGame({ ranking: [this.game.players], summary, reason: 'abandoned' }, true);
}
@@ -1087,6 +1194,7 @@ export class Room {
}
shutdown(): void {
this.closed = true;
this.flushStream();
this.clearTimer();
for (const c of this.conns.values()) {

View File

@@ -1,5 +1,5 @@
/** Wires DB, auth, rooms, HTTP and WebSocket into one Bun server (docs/02 §2). */
import { existsSync } from 'node:fs';
import { existsSync, readFileSync } from 'node:fs';
import { join, normalize } from 'node:path';
import type { Server } from 'bun';
import { GAMES } from '@bg/games';
@@ -11,6 +11,7 @@ import { SESSION_COOKIE, Sessions } from './auth/sessions';
import { Users, toPublicUser } from './auth/users';
import { createHttpApp, type HttpDeps } from './http/app';
import { RoomManager } from './rooms/manager';
import { createLuckSeeder } from './rooms/luck';
import type { BotDelayInput } from './rooms/bots';
import { RoomStore } from './rooms/store';
import { Replays } from './rooms/replay';
@@ -38,6 +39,8 @@ export interface StartOptions {
botDelay?: (input: BotDelayInput) => number;
/** Upper bound for waiting on Bun's server.stop() (tests shorten it). */
stopWaitMs?: number;
/** Computers' luck on a worker thread (docs/04 §5.1); default on. */
luck?: boolean;
}
export function startServer(opts: StartOptions) {
@@ -60,10 +63,21 @@ export function startServer(opts: StartOptions) {
// Computers talk and play like people with a local model on the GPU when AI_URL is set (docs/06 §12.1, docs/11 §8).
const ai = config.ai ? new Llm({ url: config.ai.url, model: config.ai.model, log }) : null;
if (ai) void ai.warm().then((ok) => log('info', 'ai model', { model: config.ai!.model, ready: ok }));
const rooms = new RoomManager({ store, games: GAMES, users: { publicUser }, log, settings, botDelay: opts.botDelay, ai, offlineSince: (id): number | null => gateway.offlineSince(id) });
const luck = opts.luck === false ? null : createLuckSeeder({ log });
const rooms = new RoomManager({
store,
games: GAMES,
users: { publicUser },
log,
settings,
botDelay: opts.botDelay,
ai,
luckSeed: luck ? (job) => luck.seed(job) : undefined,
offlineSince: (id): number | null => gateway.offlineSince(id),
});
const restored = rooms.restoreAll();
log('info', 'rooms restored', restored);
const gateway = new Gateway({ rooms, me: publicUser, log, onClose: (id) => users.touch(id) });
const gateway = new Gateway({ rooms, me: publicUser, log, onClose: (id) => users.touch(id), build: () => build });
const removeGuest = (id: string) => {
rooms.leaveAll(id);
gateway.closeUser(id);
@@ -85,8 +99,13 @@ export function startServer(opts: StartOptions) {
server?.requestIP(req)?.address ||
'unknown';
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
const serveStatic = staticDir && existsSync(staticDir);
// The web build being served (docs/07 §11.1): pages that were opened with an older one offer to refresh.
const build = serveStatic ? webBuildId(staticDir!) : null;
const app = createHttpApp({
config,
build,
users,
sessions,
rooms,
@@ -121,8 +140,6 @@ export function startServer(opts: StartOptions) {
},
});
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
const serveStatic = staticDir && existsSync(staticDir);
const server: Server<WsData> = Bun.serve<WsData>({
port: config.port,
@@ -171,6 +188,7 @@ export function startServer(opts: StartOptions) {
clearInterval(sweeper);
gateway.shutdown();
rooms.shutdown();
luck?.stop();
// Bun's stop() promise can stay pending after server-initiated WS closes even though the
// listener is already closed, so bound the wait.
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);
@@ -180,6 +198,15 @@ export function startServer(opts: StartOptions) {
return { server, stop, rooms, users, sessions, db, gateway, settings, roles, purgeIdleGuests };
}
/** The build id the web build wrote into its index.html (`<meta name="bg-build">`, vite.config.ts), or null. */
export function webBuildId(root: string): string | null {
try {
return /<meta name="bg-build" content="([0-9a-f]+)"/.exec(readFileSync(join(root, 'index.html'), 'utf8'))?.[1] ?? null;
} catch {
return null;
}
}
async function serveFile(root: string, pathname: string): Promise<Response> {
const safe = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, '');
const candidate = join(root, safe);

View File

@@ -0,0 +1,44 @@
/** "업데이트 내용이 있습니다" (docs/07 §11.1): the server tells which web build it serves. */
import { afterEach, expect, test } from 'bun:test';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { webBuildId } from './server';
import { Client, api, boot, guest } from './test-utils';
const running: ReturnType<typeof boot>[] = [];
const clients: Client[] = [];
afterEach(async () => {
for (const c of clients.splice(0)) c.close();
for (const s of running.splice(0)) await s.stop();
});
function webDir(html: string): string {
const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), 'bg-web-'));
writeFileSync(join(dir, 'index.html'), html);
return dir;
}
test('the build id comes from the meta tag of the served index.html', () => {
expect(webBuildId(webDir('<html><head><meta name="bg-build" content="abc123def456"></head></html>'))).toBe('abc123def456');
expect(webBuildId(webDir('<html><head></head></html>'))).toBeNull();
expect(webBuildId('/nonexistent/dir')).toBeNull();
});
test('/api/version and the socket welcome carry the build', async () => {
const s = boot(undefined, { staticDir: webDir('<html><head><meta name="bg-build" content="0123456789ab"></head></html>') });
running.push(s);
const r = await api(s.base, '/api/version');
expect(r.res.headers.get('cache-control')).toBe('no-store');
expect(r.body).toEqual({ build: '0123456789ab' });
const g = await guest(s.base, '버전확인');
const c = await new Client(s.base, g.cookie, g.id).connect();
clients.push(c);
expect(c.lastOf('welcome')!.build).toBe('0123456789ab');
});
test('without a web build (dev, tests) there is nothing to compare', async () => {
const s = boot();
running.push(s);
expect((await api(s.base, '/api/version')).body).toEqual({ build: null });
});

View File

@@ -21,6 +21,8 @@ export interface GatewayDeps {
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
/** A socket closed (the user may have left the site). */
onClose?: (userId: string) => void;
/** Web build being served (pages opened with an older one offer to refresh, docs/07 §11.1). */
build?: () => string | null;
}
export const MAX_CONNS_PER_USER = 5;
@@ -84,6 +86,7 @@ export class Gateway {
serverTime: (this.deps.now ?? Date.now)(),
protocol: PROTOCOL,
activeRoom: this.deps.rooms.activeRoomFor(ws.data.userId),
build: this.deps.build?.() ?? null,
});
},
@@ -193,6 +196,9 @@ export class Gateway {
case 'removeBot':
e = room.removeBot(u, m.userId);
break;
case 'botLevel':
e = room.setBotLevel(u, m.userId, m.pick);
break;
case 'act':
room.act(u, m.cs, m.a);
return;