/** * Computer players' driver (docs/06-lobby-rooms.md §12, docs/09-game-engine.md §9). * After every state change the room calls `schedule()`: if the game waits on a bot, one action is planned after a * short human-like pause and played through the room's normal action path (validated, logged as `act`). */ import { secureRandom, type AnyGameDefinition } from '@bg/engine'; import { isBotId } from '@bg/shared'; import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots'; import type { BotBrain } from '../ai/brain'; export { botPace }; export interface BotRoom { readonly status: string; readonly game: { state: unknown; players: string[]; finished: boolean } | null; readonly def: AnyGameDefinition; now(): number; /** When the turn timer runs out (room clock), or null without one. */ deadline?(): number | null; /** Runs the action as `actor` through the room's normal path; returns an error message on rejection. */ run(actor: string, action: unknown): string | null; log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record) => 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; } /** What a planned computer move looks like, for its thinking time. */ export interface BotDelayInput { /** How many moves the bot can choose from. */ choices: number; /** People may act in the same window (e.g. 원카드 외치기, 마작 울기, simultaneous choices). */ withPeople: boolean; /** The bot's user id: each computer has its own pace. */ bot: string; /** The same bot just acted and is still on (e.g. yacht keep → roll): it already knows what it wants. */ followUp: boolean; } /** * Human-like thinking time (ms). A forced move still takes a moment to notice (0.7~1.3 s); a real choice takes longer * the more moves there are (1.6~3.9 s), and now and then the computer hesitates (+1~3 s). Each bot scales it by its * own pace, and a follow-up move of the same turn is quicker. When people may act in the same window the computer * waits 1.5 s more so it never beats a person to a reaction just by being fast. */ export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom): number { const { choices, withPeople, bot, followUp } = input; let ms = choices <= 1 ? 700 + random() * 600 : 1300 + 300 * Math.min(Math.log2(choices), 4) + random() * 1400; if (choices > 1 && !followUp && random() < 0.12) ms += 1000 + random() * 2000; ms *= botPace(bot); if (followUp) ms *= 0.5; return Math.round(withPeople ? ms + 1500 : ms); } /** Never use more than this share of the time left on the turn timer for thinking. */ export const BOT_DEADLINE_SHARE = 0.5; /** Bot move budget (ms); slower decisions are logged. */ export const BOT_SLOW_MS = 50; export class BotDriver { private timer: ReturnType | null = null; /** When the planned action is due (room clock); null when nothing is planned. */ dueAt: number | null = null; /** Bot the planned action is for. */ private planned: string | null = null; /** Bot whose action is being played right now: if it is still on afterwards, its next move is a follow-up. */ private acting: string | null = null; /** Live games (마피아): when each computer looks at the game again, and its notes for the current game. */ private liveDue = new Map(); private liveMemory = new Map>(); private liveGame: unknown = null; /** A computer is typing / about to move with the model (turn games: one at a time; live games: per computer). */ private busy: string | null = null; private liveBusy = new Set(); constructor( private room: BotRoom, private random: () => number = secureRandom, private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random), ) {} /** Plans the next bot action if the game is waiting on a bot. Keeps an already planned one (the bot is "thinking"). */ schedule(): void { if (this.liveStrategy()) return this.scheduleLive(); if (this.dueAt !== null || this.busy) return; const next = this.next(); if (!next) return; // People can see it think: "생각 중…" until it moves. if (this.room.brain?.enabled()) this.room.brain.thinking(next.bot, true); const now = this.room.now(); let ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting }); const deadline = this.room.deadline?.() ?? null; if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE)); this.dueAt = now + ms; this.planned = next.bot; this.arm(); } cancel(): void { if (this.timer) clearTimeout(this.timer); this.timer = null; if (this.planned) this.room.brain?.thinking(this.planned, false); this.dueAt = null; this.planned = null; this.liveDue.clear(); } private liveStrategy(): LiveBotStrategy | null { return LIVE_BOT_STRATEGIES[this.room.def.id] ?? null; } /** * Live games: every computer has its own timer and is asked again and again (it may also do nothing), so several * computers talk and vote at the same time, each at its own speed. A planned look stays planned. */ private scheduleLive(): void { const g = this.room.game; if (!g || g.finished || this.room.status !== 'playing') { if (this.timer) clearTimeout(this.timer); this.timer = null; this.dueAt = null; return; } if (this.liveGame !== g) { this.liveGame = g; this.liveMemory.clear(); this.liveDue.clear(); } const now = this.room.now(); for (const p of g.players) { if (isBotId(p) && !this.liveDue.has(p)) this.liveDue.set(p, now + Math.round((300 + this.random() * 1200) * botPace(p))); } const next = Math.min(...this.liveDue.values()); this.dueAt = Number.isFinite(next) ? next : null; if (this.dueAt !== null) this.arm(); } /** Lets every computer whose time has come look at the game once. */ private fireLive(strategy: LiveBotStrategy): void { const now = this.room.now(); const due = [...this.liveDue.entries()].filter(([, t]) => t <= now).sort((a, b) => a[1] - b[1]); for (const [bot] of due) { const g = this.room.game; if (!g || g.finished || this.room.status !== 'playing') return; if (this.liveBusy.has(bot)) { this.liveDue.set(bot, now + 500); continue; } const def = this.room.def; const memory = this.liveMemory.get(bot) ?? {}; this.liveMemory.set(bot, memory); const names: Record = {}; for (const p of g.players) names[p] = this.room.nameOf?.(p) ?? p; let decision: { action: unknown; next: number; hint?: string } = { action: null, next: 3000 }; const t0 = performance.now(); try { const profile = this.room.profile?.(bot); decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, profile?.base), level: profile?.level ?? idLevel(bot), names, memory }); } catch (err) { this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) }); } const ms = performance.now() - t0; if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) }); this.liveDue.set(bot, now + Math.max(100, decision.next)); if (decision.action == null) continue; if (!def.validate(g.state, bot, decision.action, { now }).ok) continue; // the moment passed (phase changed); look again later const brain = this.room.brain; const say = decision.action as { type?: string; channel?: string; text?: string }; if (brain && say.type === 'chat' && brain.enabled()) { this.typeLive(brain, bot, say as { type: 'chat'; channel: string; text: string }, decision.hint ?? null, names, g); continue; } const err = this.room.run(bot, decision.action); if (err) this.room.log?.('warn', 'bot action rejected', { game: def.id, action: decision.action, err }); } this.scheduleLive(); } /** * Live chat like a person: the model may say the planned line in the computer's own words, then "입력 중…" for the * typing time, then it is sent (if it still may be: the phase can end meanwhile). */ private typeLive(brain: BotBrain, bot: string, chat: { type: 'chat'; channel: string; text: string }, hint: string | null, names: Record, g: unknown): void { this.liveBusy.add(bot); const view = this.room.def.view(this.room.game!.state, bot) as { chat?: { channel: string; from: string; text: string }[] }; const recent = (view.chat ?? []).filter((m) => m.channel === chat.channel).slice(-8).map((m) => ({ from: names[m.from] ?? '누군가', text: m.text })); void (hint ? brain.mafiaLine(bot, hint, chat.text, recent) : Promise.resolve(chat.text)) .catch(() => chat.text) .then((text) => brain.type(bot, text, () => { const game = this.room.game; if (!game || game !== g || game.finished) return; const action = { ...chat, text }; const ok = this.room.def.validate(game.state, bot, action, { now: this.room.now() }).ok; const err = ok ? this.room.run(bot, action) : this.room.def.validate(game.state, bot, chat, { now: this.room.now() }).ok ? this.room.run(bot, chat) : null; if (err) this.room.log?.('warn', 'bot chat rejected', { game: this.room.def.id, err }); }), ) .finally(() => { this.liveBusy.delete(bot); }); } private arm(): void { if (this.timer) clearTimeout(this.timer); this.timer = setTimeout(() => this.fire(), Math.max(0, (this.dueAt ?? 0) - this.room.now())); } /** Bot waited on by the game that has something to do, in seat order. */ private next(): { bot: string; choices: number; withPeople: boolean } | null { const g = this.room.game; if (!g || g.finished || this.room.status !== 'playing' || !g.players.some(isBotId)) return null; const def = this.room.def; const active = def.activePlayers(g.state); const waiting = new Set([...active, ...(def.timeoutPlayers?.(g.state) ?? [])]); const withPeople = active.some((p) => !isBotId(p)); for (const p of g.players) { if (!isBotId(p) || !waiting.has(p)) continue; const choices = botCandidates(def, g.state, p).length; if (choices > 0) return { bot: p, choices, withPeople }; } return null; } /** Plays the planned action when due. Public for tests (with a fake clock). */ fire(): void { if (this.timer) clearTimeout(this.timer); this.timer = null; if (this.dueAt === null) return; if (this.room.now() < this.dueAt) return this.arm(); const live = this.liveStrategy(); if (live) { this.dueAt = null; return this.fireLive(live); } const planned = this.planned; this.dueAt = null; this.planned = null; const next = this.next(); const g = this.room.game; if (!next || !g) return; // Another bot's turn came up meanwhile: give it its own thinking time. if (next.bot !== planned) return this.schedule(); const def = this.room.def; const t0 = performance.now(); let action: unknown; try { 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; } const ms = performance.now() - t0; if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) }); const brain = this.room.brain; if (brain && action != null && brain.enabled()) { // Like a person: maybe type something first (the model writes it; "입력 중…" while typing), then move. const bot = next.bot; this.busy = bot; void brain .beforeMove(bot, action, def.view(g.state, bot)) .catch(() => action) .then((chosen) => { this.busy = null; brain.thinking(bot, false); if (this.room.game !== g || g.finished || this.room.status !== 'playing') return; const ok = (a: unknown) => def.validate(g.state, bot, a, { now: this.room.now() }).ok; // The game moved on while it was typing (a timer, someone left): think again. if (!ok(chosen) && !ok(action)) return this.schedule(); this.acting = bot; try { this.playPlanned(bot, ok(chosen) ? chosen : action); } finally { this.acting = null; } }); return; } brain?.thinking(next.bot, false); this.acting = next.bot; try { this.playPlanned(next.bot, action); } finally { this.acting = null; } } private playPlanned(bot: string, action: unknown): void { const def = this.room.def; let err = action == null ? 'no action' : this.room.run(bot, action); if (err) { this.room.log?.('warn', 'bot action rejected', { game: def.id, action, err }); // Last resort before the turn timer: the game's own timeout action. try { if (!this.room.game?.finished) err = this.room.run(bot, def.onTimeout(this.room.game!.state, bot)); } catch { // keep err } if (err) return; // give up until the next state change; the room's deadline still applies } this.schedule(); } }