Files
joke-app/apps/server/src/rooms/bots.ts
EJClaw fcc79f05bc 라이어 게임: 토론 채팅을 게임 내내 열기, 설명은 별도 describe 액션으로
- chat은 확인 시간·설명 중(말하는 사람 포함)·토론·투표·정답 맞히기 내내 모두 쓸 수 있다
- 설명은 새 describe 액션(차례인 사람만, 80자). 채팅에 쓴 말은 설명으로 치지 않는다
- 자기 제시어 금지·고운 말 검사는 설명과 채팅 모두 그대로
- 컴퓨터 설명도 describe로 보내고, 모델이 켜져 있으면 "입력 중…" 뒤에 보낸다
- 화면: 채팅 입력칸을 항상 보이게, 설명 차례인 사람에게는 채팅 칸 안내 문구
- 문서(docs/games/liar.md)와 테스트 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:20:38 +09:00

372 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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, botReactionAt, 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<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;
/** Multiplies the computers' thinking time and live games' look intervals (game speed, docs/14 §5); absent = 1. */
timeScale?(): number;
}
/** 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;
/** An out-of-turn reaction the game timed itself (원카드 외치기·잡기, `botReactionAt`): wait exactly this long. */
reactMs?: number;
}
/**
* 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. `scale` (game speed, `BOT_SLOWDOWN /
* speed`) multiplies the whole thinking time; a reaction the game timed itself (`reactMs`) is never scaled, so who
* calls first stays fair.
*/
export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom, scale = 1): number {
const { choices, withPeople, bot, followUp } = input;
if (input.reactMs !== undefined) return Math.max(0, Math.round(input.reactMs));
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) * scale);
}
/** At game speed ×1 the computers take this much longer than `defaultBotDelay`'s base times (2026-10-14: a bit slower). */
export const BOT_SLOWDOWN = 1.5;
/** 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<typeof setTimeout> | 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;
/** The planned action is that bot's out-of-turn reaction due at this time (not its normal move). */
private plannedReact: number | 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<string, number>();
private liveMemory = new Map<string, Record<string, unknown>>();
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<string>();
constructor(
private room: BotRoom,
private random: () => number = secureRandom,
private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random, room.timeScale?.() ?? 1),
) {}
/** 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.busy) return;
if (this.dueAt !== null) {
// A planned reaction the moment has passed for (someone called first): plan again; anything else stays planned.
if (this.plannedReact === null || this.reactionDue()?.bot === this.planned) return;
if (this.timer) clearTimeout(this.timer);
this.timer = null;
this.dueAt = null;
this.planned = null;
this.plannedReact = null;
}
const next = this.next();
const react = this.reactionDue();
if (!next && !react) return;
const now = this.room.now();
let ms = Infinity;
if (next) {
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));
}
// An out-of-turn reaction (원카드!) comes first when it is due earlier; it is not squeezed by the turn clock, so a
// slow computer can really be late.
if (react) {
const rms = this.delay({ choices: 1, withPeople: true, bot: react.bot, followUp: false, reactMs: react.at - now });
if (rms <= ms) {
this.dueAt = now + rms;
this.planned = react.bot;
this.plannedReact = react.at;
return this.arm();
}
}
// People can see it think: "생각 중…" until it moves.
if (this.room.brain?.enabled()) this.room.brain.thinking(next!.bot, true);
this.dueAt = now + ms;
this.planned = next!.bot;
this.plannedReact = null;
this.arm();
}
/** The earliest out-of-turn reaction of a computer that may act now (games with `BOT_REACTIONS`). */
private reactionDue(): { bot: string; at: number } | null {
const g = this.room.game;
if (!g || g.finished || this.room.status !== 'playing') return null;
let best: { bot: string; at: number } | null = null;
for (const p of g.players) {
if (!isBotId(p)) continue;
const at = botReactionAt(this.room.def, g.state, p, this.room.profile?.(p).level ?? idLevel(p));
if (typeof at === 'number' && (!best || at < best.at)) best = { bot: p, at };
}
return best;
}
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.plannedReact = null;
this.liveDue.clear();
}
private timeScale(): number {
return this.room.timeScale?.() ?? 1;
}
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) * this.timeScale()));
}
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<string, string> = {};
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, Math.round(decision.next * this.timeScale())));
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 };
// 라이어 게임's description is typed like a chat line too ("입력 중…" before it appears).
if (brain && (say.type === 'chat' || say.type === 'describe') && brain.enabled()) {
this.typeLive(brain, bot, say as { type: 'chat' | 'describe'; 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' | 'describe'; channel: string; text: string }, hint: string | null, names: Record<string, string>, 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));
const timed = new Set(def.timeoutPlayers?.(g.state) ?? active);
for (const p of g.players) {
if (!isBotId(p) || !waiting.has(p)) continue;
// Only there to react out of turn (원카드!): `reactionDue` times that, not the thinking time.
if (!timed.has(p) && botReactionAt(def, g.state, p, this.room.profile?.(p).level ?? idLevel(p)) !== null) 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;
const wasReact = this.plannedReact !== null;
this.dueAt = null;
this.planned = null;
this.plannedReact = null;
const react = wasReact ? this.reactionDue() : null;
const next = wasReact ? (react && react.bot === planned ? { bot: react.bot } : null) : this.next();
const g = this.room.game;
if (!g) return;
// Another bot's turn came up meanwhile (or the reaction is moot): give it its own thinking time.
if (!next || 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;
// A reaction (원카드!) is a reflex: no chat before it.
if (brain && action != null && brain.enabled() && !wasReact) {
// 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();
}
}