/** * A room's computers, played like people with the local model (docs/06 §12.1). * * - They show what they are doing: "생각 중…" while choosing a move and "입력 중…" while typing, for as long as a * person would take to type that line — then they send it and make the move ("채팅 치고 클릭"). * - They talk in character (도발형·허세형·차분형·수다형·소심형, 존댓말/반말): a word with their own move, a reaction * to a person's move, answers when people chat, a greeting at the start and a word at the end. * - Psychological choices go to the model: in 바퀴벌레 포커 it decides whether to tell the truth or bluff, and says * something to sell it. In 마피아 it says each line of the computer's plan in its own words. * Moves themselves still come from each game's computer strategy (it sees only its own screen). Without a model * (not configured, busy, down) the computers simply play as before, silently, and 마피아 uses its built-in lines. * Talking on their own is a room setting (`chatty`, off by default); 마피아 talks always because the game needs it. */ import { secureRandom } from '@bg/engine'; import { botPace, hash01 } from '@bg/games/bots'; import type { Llm } from './llm'; import { cleanLine, decide, temperOf, writeLine, type LineRequest } from './lines'; export type BotActivity = 'thinking' | 'typing'; export interface BrainRoom { gameId(): string; gameName(): string; nameOf(id: string): string; /** People and computers seated in the running game. */ humans(): string[]; bots(): string[]; playing(): boolean; /** Posts in the room chat as `bot` (games without their own chat channels). */ 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; /** * The computers may chat on their own (room setting "컴퓨터 채팅"; always on in 마피아). Off: no small talk, * reactions, answers, greetings or end-of-game words — they just play (still showing "생각 중…"). */ chatty(): boolean; now(): number; } /** A few words for what someone just did (any game). */ const ACTION_KO: Record = { place: '돌을 놓음', move: '말을 움직임', MOVE: '말을 움직임', placeWall: '벽을 세움', castle: '캐슬링', play: '카드를 냄', discard: '패를 버림', DISCARD: '패를 버림', draw: '패를 가져옴', pass: '넘김', PASS: '넘김', call: '콜', check: '체크', die: '다이(포기)', half: '하프 베팅', quarter: '쿼터 베팅', ddadang: '따당', full: '풀 베팅', roll: '주사위를 굴림', hold: '주사위를 고정함', score: '점수를 적음', guess: '추리함', stop: '멈춤', continue: '계속 추리', offer: '카드를 건넴', peek: '카드를 몰래 봄', claim: '선언함', declare: '선언함', tsumo: '쯔모', ring: '종을 침', flip: '카드를 뒤집음', BUY: '땅을 삼', sell: '땅을 팖', THROW: '윷을 던짐', commit: '타일을 내려놓음', goStop: '고/스톱', respond: '대답함', resign: '기권', concede: '기권', CONCEDE: '기권', giveUp: '포기', choose: '골랐음', vote: '투표', }; const sleepReal = (ms: number) => new Promise((r) => setTimeout(r, ms)); export class BotBrain { private lastRoomLine = -Infinity; private lastBotLine = new Map(); private happened: string[] = []; private typing = new Set(); constructor( private room: BrainRoom, readonly llm: Llm | null, private random: () => number = secureRandom, private sleep: (ms: number) => Promise = sleepReal, ) {} /** The model is set up and answering, and there is someone to play for. */ enabled(): boolean { return !!this.llm && this.llm.available() && this.room.playing() && this.room.humans().length > 0; } /** How long `bot` takes to type `text` (each computer types at its own speed). */ typingMs(bot: string, text: string): number { const perChar = (120 + 90 * hash01(bot, 'typing')) * botPace(bot); return Math.round(Math.min(6500, Math.max(900, [...text].length * perChar))); } thinking(bot: string, on: boolean): void { if (!this.typing.has(bot)) this.room.setActivity(bot, on ? 'thinking' : null); } /** "입력 중…" for as long as typing takes, then `send` (skipped if the game ended meanwhile). */ async type(bot: string, text: string, send: () => void, needPlaying = true): Promise { this.typing.add(bot); this.room.setActivity(bot, 'typing'); try { await this.sleep(this.typingMs(bot, text)); } finally { this.typing.delete(bot); this.room.setActivity(bot, null); } if (!needPlaying || this.room.playing()) send(); } private request(bot: string, situation: string, task: string, extra: Partial = {}): LineRequest { return { bot, name: this.room.nameOf(bot), smart: this.room.smart(bot), game: this.room.gameName(), situation, task, recent: this.room.recentChat(), ...extra, }; } private canTalk(bot: string, roomGap = 8000, botGap = 20_000): boolean { const now = this.room.now(); return now - this.lastRoomLine >= roomGap && now - (this.lastBotLine.get(bot) ?? -Infinity) >= botGap && !this.typing.has(bot); } private spoke(bot: string): void { const now = this.room.now(); this.lastRoomLine = now; this.lastBotLine.set(bot, now); } private say(bot: string, line: string): Promise { this.spoke(bot); return this.type(bot, line, () => this.room.roomChat(bot, line)); } private situation(): string { const last = this.happened.slice(-4); return last.length ? `최근: ${last.join(', ')}` : '게임이 막 시작됐다'; } /** Someone played: remembered for the computers' sense of the game; now and then a computer reacts to a person. */ onAction(actor: string, action: unknown): void { const type = String((action as { type?: string } | null)?.type ?? ''); if (!type || type === 'chat' || type === 'say' || type === 'reaction' || type === 'ping' || type === 'timeout') return; this.happened.push(`${this.room.nameOf(actor)} ${ACTION_KO[type] ?? '행동함'}`); if (this.happened.length > 12) this.happened.shift(); if (!this.enabled() || !this.room.chatty() || this.room.bots().includes(actor) || this.room.gameId() === 'mafia') return; const bots = this.room.bots().filter((b) => this.canTalk(b, 10_000, 30_000)); if (!bots.length || this.random() > 0.12) return; const bot = bots[Math.floor(this.random() * bots.length)]!; this.spoke(bot); const who = this.room.nameOf(actor); void writeLine(this.llm, this.request(bot, this.situation(), `${who}이(가) 방금 ${ACTION_KO[type] ?? '수를 뒀다'}. ${who}에게 반응하는 한마디(놀리거나 떠보기).`)).then((line) => { if (line) return this.type(bot, line, () => this.room.roomChat(bot, line)); }); } /** * Before a computer's own move: maybe a word with it (typed first, then the move), and in 바퀴벌레 포커 the * truth-or-bluff choice. Returns the action to play (possibly with a different claim). */ async beforeMove(bot: string, action: unknown, view: unknown): Promise { if (!this.enabled()) return action; let act = action; let line: string | null = null; const a = action as { type?: string; claim?: string; cardId?: string; to?: string }; if (this.room.gameId() === 'cockroach-poker' && (a.type === 'offer' || a.type === 'pass') && a.claim) { const r = await this.cockroachBluff(bot, a, view); if (r) { act = r.action; // Chat off: the model still decides truth or bluff, the computer just hands the card over without a word. line = this.room.chatty() ? r.say : null; } } else if (this.room.chatty() && this.canTalk(bot) && this.random() < temperOf(bot).talk) { const type = String(a.type ?? ''); line = await writeLine(this.llm, this.request(bot, this.situation(), `나는 지금 "${ACTION_KO[type] ?? '내 수'}"를 하려 한다. 이 수를 두며 상대에게 던지는 도발이나 심리전 한마디.`)); } if (line && this.room.playing()) { await this.say(bot, line); await this.sleep(Math.round((300 + 500 * this.random()) * botPace(bot))); } return act; } /** 바퀴벌레 포커: the model decides to tell the truth or bluff (and what to say); the strategy picked card and person. */ private async cockroachBluff(bot: string, a: { type?: string; claim?: string; cardId?: string; to?: string }, view: unknown): Promise<{ action: unknown; say: string | null } | null> { const v = view as { myHand?: { kind: string; ids: string[] }[]; card?: { known: boolean; kind?: string } | null; fronts?: Record }> }; const kind = a.type === 'offer' ? v.myHand?.find((g) => g.ids.includes(a.cardId!))?.kind : v.card?.known ? v.card.kind : undefined; if (!kind || !a.to) return null; const KO: Record = { cockroach: '바퀴벌레', bat: '박쥐', fly: '파리', toad: '두꺼비', rat: '쥐', scorpion: '전갈', spider: '거미', stinkbug: '노린재' }; const target = this.room.nameOf(a.to); const front = v.fronts?.[a.to]?.counts ?? {}; const pile = Object.entries(front).filter(([, n]) => n > 0).map(([k, n]) => `${KO[k] ?? k} ${n}장`).join(', ') || '없음'; const r = await decide<{ bluff: boolean; say: string }>( 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'] }, ); if (!r) return null; let claim = a.claim!; if (r.bluff && claim === kind) claim = Object.keys(KO).filter((k) => k !== kind)[Math.floor(this.random() * 7)]!; if (!r.bluff) claim = kind; // The line must not give the real card away. const say = cleanLine(String(r.say ?? ''), 36, [new RegExp(KO[kind] ?? kind)]); // Selling the claim is part of the move, so it is said even right after another line. return { action: { ...a, claim }, say }; } /** People chatting: a named computer answers; otherwise sometimes one of them joins in. */ onHumanChat(from: string, text: string): void { if (!this.enabled() || !this.room.chatty() || this.room.gameId() === 'mafia') return; const bots = this.room.bots(); const named = bots.find((b) => { const n = /^컴퓨터 (\d+)$/.exec(this.room.nameOf(b))?.[1]; return n ? new RegExp(`(컴퓨터\\s?${n}|컴${n}|(? { if (line) return this.type(bot, line, () => this.room.roomChat(bot, line)); }); } onGameStart(): void { this.happened = []; // A game with computers and people where the model will be used: make sure it is loaded before anyone talks. const usesModel = this.room.chatty() || this.room.gameId() === 'cockroach-poker'; if (usesModel && this.llm?.available() && this.room.humans().length && this.room.bots().length) void this.llm.warm(); if (!this.enabled() || !this.room.chatty() || this.room.gameId() === 'mafia' || this.random() > 0.7) return; const bots = this.room.bots(); const bot = bots[Math.floor(this.random() * bots.length)]; if (!bot) return; this.spoke(bot); void writeLine(this.llm, this.request(bot, '게임이 막 시작됐다', '시작 인사 겸 가벼운 선전포고 한마디.')).then((line) => { if (line) return this.type(bot, line, () => this.room.roomChat(bot, line)); }); } /** The game ended: a computer that won gloats a little, or one that lost takes it with a word. */ onGameEnd(ranking: string[][]): void { if (!this.llm?.available() || !this.room.chatty() || !this.room.humans().length || this.room.gameId() === 'mafia' || this.random() > 0.85) return; const bots = this.room.bots(); const winner = (ranking[0] ?? []).find((p) => bots.includes(p)); const bot = winner ?? bots[Math.floor(this.random() * bots.length)]; if (!bot) return; const task = winner ? '내가 이겼다. 상대를 살짝 놀리며 이긴 소감 한마디(한 판 더 하자고 해도 좋다).' : '내가 졌다. 아쉬워하며 다음엔 이기겠다는 한마디.'; void writeLine(this.llm, this.request(bot, '게임이 끝났다', task)).then((line) => { if (line) return this.type(bot, line, () => this.room.roomChat(bot, line), false); }); } /** * 마피아: a computer's planned line (`hint` = what it means, `text` = built-in wording) in its own words. The model is * told only what the line means and the public chat — never the computer's role — and a line that claims a role * or "I'm mafia" is thrown away. Returns the built-in text when there is no usable answer. */ async mafiaLine(bot: string, hint: string, text: string, recent: { from: string; text: string }[]): Promise { if (!this.llm?.available()) return text; const line = await writeLine(this.llm, { bot, name: this.room.nameOf(bot), smart: this.room.smart(bot), game: '마피아(낮 토론, 모두가 보는 채팅)', situation: '누가 마피아인지 추리하며 이야기하는 중이다. 너는 자신이 시민 팀이라고 말한다.', task: hint, recent, example: text, maxLen: 45, // Never a role claim of its own ("저 경찰이에요", "나 마피아임"): the plan decides those, word for word. forbid: [/(저|제가|나|내가|난|전)\s*(는|가|도)?\s*(진짜\s*)?(마피아|경찰|의사|군인|정치인|영매|연인)/], }); return line ?? text; } }