diff --git a/apps/server/src/ai/ai.test.ts b/apps/server/src/ai/ai.test.ts new file mode 100644 index 0000000..5d69833 --- /dev/null +++ b/apps/server/src/ai/ai.test.ts @@ -0,0 +1,221 @@ +/** Computers with the local model (docs/06 §12.1): client limits, clean lines, and how rooms use it. */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import { botProfile, isBotId } from '@bg/shared'; +import { openDb } from '../db'; +import { RoomManager } from '../rooms/manager'; +import type { Room } from '../rooms/room'; +import { RoomStore } from '../rooms/store'; +import { BotBrain } from './brain'; +import { cleanLine, temperOf, TEMPERS } from './lines'; +import { Llm } from './llm'; + +/** A fake Ollama: answers with `reply(prompt)`; records the prompts. */ +function fakeOllama(reply: (user: string, body: { format?: unknown }) => string | Error) { + const prompts: string[] = []; + const fetchFn = (async (_url: string, init: RequestInit) => { + const body = JSON.parse(String(init.body)) as { messages: { role: string; content: string }[]; format?: unknown }; + const user = body.messages.find((m) => m.role === 'user')!.content; + prompts.push(user); + const r = reply(user, body); + if (r instanceof Error) throw r; + return new Response(JSON.stringify({ message: { content: r } }), { headers: { 'content-type': 'application/json' } }); + }) as unknown as typeof fetch; + return { fetchFn, prompts }; +} + +describe('Llm client', () => { + test('returns the text; a few failures in a row back off; a full queue is refused at once', async () => { + let fail = false; + const { fetchFn } = fakeOllama(() => (fail ? new Error('down') : '안녕')); + let now = 0; + const llm = new Llm({ url: 'http://x', model: 'm', fetch: fetchFn, now: () => now, maxQueue: 0, maxConcurrent: 1 }); + expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBe('안녕'); + fail = true; + for (let i = 0; i < 3; i++) expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBeNull(); + expect(llm.available()).toBe(false); + expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBeNull(); // skipped, not even sent + expect(llm.stats.skipped).toBe(1); + now += 31_000; + fail = false; + expect(llm.available()).toBe(true); + // One running, no waiting room: the second is refused immediately. + const a = llm.chat([{ role: 'user', content: 'a' }]); + const b = await llm.chat([{ role: 'user', content: 'b' }]); + expect(b).toBeNull(); + expect(await a).toBe('안녕'); + }); + + test('a hung model times out', async () => { + const hang = (async (_u: string, init: RequestInit) => + new Promise((_, rej) => init.signal!.addEventListener('abort', () => rej(new Error('aborted'))))) as unknown as typeof fetch; + const llm = new Llm({ url: 'http://x', model: 'm', fetch: hang, timeoutMs: 30 }); + expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBeNull(); + expect(llm.stats.failed).toBe(1); + }); +}); + +describe('clean lines', () => { + test('one short Korean line; quotes, names and markdown stripped; foreign, AI talk and bad words refused', () => { + expect(cleanLine('"흐음, 또 막았네? 😎 잘 봤다!"')).toBe('흐음, 또 막았네? 😎 잘 봤다!'); + expect(cleanLine('컴퓨터 2: 이번엔 내가 이긴다!\n두 번째 줄')).toBe('이번엔 내가 이긴다!'); + expect(cleanLine('**좋아요**')).toBe('좋아요'); + expect(cleanLine('철수님真爱吗')).toBeNull(); + expect(cleanLine('Nice move, buddy!')).toBeNull(); + expect(cleanLine('저는 AI라서 잘 몰라요')).toBeNull(); + expect(cleanLine('시발 뭐야')).toBeNull(); + expect(cleanLine('www.example.com 와봐')).toBeNull(); + expect(cleanLine('나 마피아임 ㅋㅋ', 40, [/(나|저)\s*마피아/])).toBeNull(); + // Too long: cut at a sentence end, or refused when there is none early enough. + expect(cleanLine('이번 판은 정말 재밌겠네요. 다들 준비됐나요', 20)).toBe('이번 판은 정말 재밌겠네요.'); + expect(cleanLine('가'.repeat(80), 20)).toBeNull(); + }); + + test('every computer has one of five characters, fixed by its id', () => { + const seen = new Set(Array.from({ length: 200 }, (_, i) => temperOf(`bot:${i}:x`).key)); + expect(seen.size).toBe(TEMPERS.length); + expect(temperOf('bot:1:abc')).toBe(temperOf('bot:1:abc')); + }); +}); + +// ---------------------------------------------------------------- rooms + +const rooms: Room[] = []; +afterEach(() => { + for (const r of rooms.splice(0)) r.clearTimer(); +}); + +function harness(reply: (user: string, body: { format?: unknown }) => string | Error, random = () => 0) { + 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 === 'A' ? '철수' : id, avatar: null, kind: 'guest' as const } }; + const { fetchFn, prompts } = fakeOllama(reply); + const ai = new Llm({ url: 'http://gpu', model: 'gemma3:4b', fetch: fetchFn }); + const slept: number[] = []; + const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0, ai, aiRandom: random, aiSleep: async (ms) => { + // Typing takes time on the room clock too. + slept.push(ms); + clock.advance(ms); + } }); + const conn = (userId: string) => { + const msgs: import('@bg/shared').ServerMessage[] = []; + return { userId, msgs, send: (m: (typeof msgs)[number]) => msgs.push(m), close: () => {} }; + }; + return { manager, clock, conn, prompts, slept, store }; +} + +const settle = () => new Promise((r) => setTimeout(r, 5)); + +describe('rooms with the model', () => { + test('omok: the computer thinks (visible), types a taunt in the chat, then moves', async () => { + const h = harness((u) => (u.includes('할 말') ? '흐음, 여기 두면 아프겠는데?' : '좋아')); + const room = h.manager.createPractice('A', 'omok') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } }); + expect(room.start('A')).toBeNull(); + await settle(); + room.act('A', 1, { type: 'place', x: 7, y: 7 }); + const activity = a.msgs.filter((m) => m.t === 'room').map((m) => (m as { room: { botActivity?: Record } }).room.botActivity ?? {}); + expect(activity.some((x) => Object.values(x).includes('thinking'))).toBe(true); + room.bots.fire(); + for (let i = 0; i < 20 && (room.game!.state as { moves: unknown[] }).moves.length < 2; i++) await settle(); + expect((room.game!.state as { moves: unknown[] }).moves).toHaveLength(2); + const chats = a.msgs.filter((m) => m.t === 'chat') as { from: { id: string } | null; text: string }[]; + expect(chats.some((c) => c.from && isBotId(c.from.id) && c.text === '흐음, 여기 두면 아프겠는데?')).toBe(true); + // It typed for a while before sending, and "입력 중" was shown then cleared. + expect(h.slept.some((ms) => ms >= 900)).toBe(true); + const last = a.msgs.filter((m) => m.t === 'room').at(-1) as { room: { botActivity?: object } }; + expect(last.room.botActivity).toBeUndefined(); + expect(h.prompts.some((p) => p.includes('오목'))).toBe(true); + }); + + test('a person asks a computer by name: it answers in the room chat', async () => { + const h = harness(() => '저요? 저 오목 잘 둬요 ㅎㅎ', () => 0.99); + const room = h.manager.createPractice('A', 'omok') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + room.chat('A', '컴퓨터 1 오목 잘해?'); + for (let i = 0; i < 20 && !a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text.startsWith('저요?')); i++) await settle(); + expect(a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text === '저요? 저 오목 잘 둬요 ㅎㅎ')).toBe(true); + expect(h.prompts.at(-1)).toContain('컴퓨터 1 오목 잘해?'); + }); + + test('without a model, or with a model that is down, computers play silently as before', async () => { + const h = harness(() => new Error('down')); + const room = h.manager.createPractice('A', 'omok') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } }); + expect(room.start('A')).toBeNull(); + for (let i = 0; i < 3; i++) { + room.act('A', i + 1, { type: 'place', x: [0, 14, 0][i]!, y: [0, 14, 14][i]! }); // corners: the computer never needs them + room.bots.fire(); + for (let k = 0; k < 20 && (room.game!.state as { moves: unknown[] }).moves.length < 2 * (i + 1); k++) await settle(); + } + expect((room.game!.state as { moves: unknown[] }).moves.length).toBe(6); + expect(a.msgs.some((m) => m.t === 'chat')).toBe(false); + }); + + test('바퀴벌레 포커: the model decides truth or bluff; telling the truth sets the real kind', async () => { + let checked = false; + // The starter is random: try new rooms until the computer offers first. + for (let attempt = 0; attempt < 12 && !checked; attempt++) { + const h = harness((_u, body) => (body.format ? JSON.stringify({ bluff: false, say: '이건 진짜야, 믿어봐~' }) : '흠')); + const room = h.manager.createPractice(`A${attempt}`, 'cockroach-poker') as Room; + rooms.push(room); + const a = h.conn(`A${attempt}`); + room.join(a, 'player'); + expect(room.start(`A${attempt}`)).toBeNull(); + const st = () => room.game!.state as { round: { claim: string | null; card: string | null; starter: string } }; + if (!isBotId(st().round.starter)) continue; + + await settle(); // the start greeting goes out first + h.clock.advance(20_000); + for (let i = 0; i < 30 && !st().round.claim; i++) { + room.bots.fire(); + await settle(); + } + const kind = st().round.card!.replace(/-\d+$/, ''); + expect(st().round.claim).toBe(kind); + expect(a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text === '이건 진짜야, 믿어봐~')).toBe(true); + checked = true; + } + expect(checked).toBe(true); + }); + + test('마피아: a computer says its planned line in its own words; a line claiming a role is thrown away', async () => { + let n = 0; + const h = harness(() => (n++ % 2 === 0 ? '안녕하세요~ 오늘 마피아 꼭 잡아봐요!' : '저 경찰이에요 믿어주세요')); + const room = h.manager.createPractice('A', 'mafia') as Room; + rooms.push(room); + room.join(h.conn('A'), 'player'); + expect(room.start('A')).toBeNull(); + for (let i = 0; i < 4 * 40; i++) { + h.clock.advance(250); + if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); + const d = room.effectiveDeadline(); + if (d !== null && d <= h.clock.now()) room.onTimer(); + await settle(); + } + const chat = (room.game!.state as { chat: { from: string; channel: string; text: string }[] }).chat.filter((m) => isBotId(m.from) && m.channel === 'day'); + expect(chat.length).toBeGreaterThan(0); + expect(chat.some((m) => m.text === '안녕하세요~ 오늘 마피아 꼭 잡아봐요!')).toBe(true); + expect(chat.some((m) => m.text === '저 경찰이에요 믿어주세요')).toBe(false); + }); +}); + +test('BotBrain typing time grows with the line and stays human (0.9~6.5 s)', () => { + const brain = new BotBrain({} as never, null); + const short = brain.typingMs('bot:1:x', 'ㅋㅋ'); + const long = brain.typingMs('bot:1:x', '이번 판은 내가 무조건 이긴다 각오해라 진짜로'); + expect(short).toBeGreaterThanOrEqual(900); + expect(long).toBeGreaterThan(short); + expect(long).toBeLessThanOrEqual(6500); +}); diff --git a/apps/server/src/ai/brain.ts b/apps/server/src/ai/brain.ts new file mode 100644 index 0000000..c20622e --- /dev/null +++ b/apps/server/src/ai/brain.ts @@ -0,0 +1,254 @@ +/** + * 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. + */ +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 }[]; + 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 = Math.random, + 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), + 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.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; + line = r.say; + } + } else if (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), + `바퀴벌레 포커. 나는 ${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.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 = []; + if (!this.enabled() || 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.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), + 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; + } +} diff --git a/apps/server/src/ai/lines.ts b/apps/server/src/ai/lines.ts new file mode 100644 index 0000000..e8d53fd --- /dev/null +++ b/apps/server/src/ai/lines.ts @@ -0,0 +1,125 @@ +/** + * 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 { chatProblem } from '@bg/games/mafia'; +import type { Llm, LlmMessage } from './llm'; + +export interface Temper { + key: 'taunt' | 'bluff' | 'calm' | 'chatty' | 'timid'; + ko: string; + desc: string; + /** How often it speaks up on its own move (before rate limits). */ + talk: number; +} + +export const TEMPERS: readonly Temper[] = [ + { key: 'taunt', ko: '도발형', desc: '장난스럽게 상대를 도발하고 약을 올린다. 그래도 욕이나 비하는 절대 하지 않는다.', talk: 0.32 }, + { key: 'bluff', ko: '허세형', desc: '자신감이 넘치고 허세를 부린다. 질 것 같아도 이길 거라고 큰소리친다.', talk: 0.28 }, + { key: 'calm', ko: '차분형', desc: '차분하고 담담하다. 짧게 말하고, 가끔 날카로운 한마디로 심리전을 건다.', talk: 0.14 }, + { key: 'chatty', ko: '수다형', desc: '말이 많고 리액션이 크다. 감탄사를 자주 쓴다.', talk: 0.38 }, + { key: 'timid', ko: '소심형', desc: '소심하고 엄살이 많다. 걱정하는 척하면서 은근히 상대를 떠본다.', talk: 0.18 }, +]; + +/** Each computer's character: 성격 from its id, 말투 from 똑똑한 편(존댓말)/허술한 편(반말). */ +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 ? '존댓말(해요체), 또박또박' : '반말, 짧고 가볍게, ㅋㅋ를 가끔 붙임'; +} + +export function systemPrompt(bot: string, name: string, maxLen: number): string { + const t = temperOf(bot); + return [ + `너는 온라인 보드게임 사이트 "같이 놀자"에서 사람들과 함께 게임하는 컴퓨터 플레이어 "${name}"이다.`, + `성격: ${t.ko} — ${t.desc}`, + `말투: ${speechOf(bot)}.`, + `규칙: 한국어 채팅 한 줄만 쓴다. ${maxLen}자 이내. 대사만 쓰고 따옴표·설명·괄호·영어·한자는 쓰지 않는다.`, + '욕설, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 게임과 상관없는 이야기는 하지 않는다.', + '자신이 AI나 프로그램이라고 말하지 않는다. 숨겨진 정보(내 패, 내 카드, 내 직업)는 절대 밝히지 않는다.', + ].join('\n'); +} + +export interface LineRequest { + bot: string; + name: string; + game: string; + /** What is going on, in plain Korean. */ + situation: string; + /** What to say now. */ + task: string; + /** Recent chat, oldest first. */ + recent?: { from: string; text: string }[]; + /** Example line (the built-in one), so the model keeps the meaning. */ + example?: string; + maxLen?: number; + /** Extra patterns the line must not contain (e.g. a mafia computer saying it is mafia). */ + forbid?: RegExp[]; +} + +const AI_WORDS = /인공\s*지능|\bAI\b|챗봇|언어\s*모델|어시스턴트|프로그램입니다|GPT|모델로서/i; +const FOREIGN = /[一-鿿぀-ヿ]|[A-Za-z]{4,}/; + +/** One clean chat line out of whatever the model wrote, or null when nothing usable is left. */ +export function cleanLine(raw: string, maxLen = 40, forbid: RegExp[] = []): string | null { + let line = raw + .split('\n') + .map((l) => l.trim()) + .find((l) => l.length > 0); + if (!line) return null; + line = line + .replace(/^[^::]{1,12}[::]\s*/, (m) => (/[ㄱ-ㅎ가-힣]/.test(m) && m.length <= 12 ? '' : m)) // "컴퓨터 2: …" + .replace(/^["'“”‘’`「」『』]+|["'“”‘’`「」『』]+$/g, '') + .replace(/[*_#>]/g, '') + .replace(/\s+/g, ' ') + .trim(); + if (!line || FOREIGN.test(line) || AI_WORDS.test(line)) return null; + if ([...line].length > maxLen) { + const chars = [...line]; + const cut = chars.slice(0, maxLen).join(''); + const end = Math.max(cut.lastIndexOf('.'), cut.lastIndexOf('!'), cut.lastIndexOf('?'), cut.lastIndexOf('~')); + if ([...line].length > maxLen * 1.6 || end < maxLen * 0.4) return null; + line = cut.slice(0, end + 1); + } + if (!/[가-힣ㅋㅎㅠ]/.test(line)) return null; + if (chatProblem(line, true)) return null; + if (forbid.some((re) => re.test(line!))) return null; + return line; +} + +/** Asks the model for one line; null when the model is unavailable or wrote nothing usable. */ +export async function writeLine(llm: Llm | null, req: LineRequest): Promise { + if (!llm || !llm.available()) return null; + const maxLen = req.maxLen ?? 40; + const parts = [`게임: ${req.game}`, `상황: ${req.situation}`]; + if (req.recent?.length) parts.push(`최근 채팅:\n${req.recent.slice(-8).map((m) => `${m.from}: ${m.text}`).join('\n')}`); + if (req.example) parts.push(`예시(뜻은 같게, 표현은 너답게 새로): ${req.example}`); + parts.push(`할 말: ${req.task}`); + const messages: LlmMessage[] = [ + { role: 'system', content: systemPrompt(req.bot, req.name, maxLen) }, + { role: 'user', content: parts.join('\n') }, + ]; + const raw = await llm.chat(messages, { maxTokens: 70, temperature: 0.95 }); + return raw === null ? null : cleanLine(raw, maxLen, req.forbid); +} + +/** Structured choice (JSON schema) — e.g. 바퀴벌레 포커: tell the truth or bluff, and what to say. */ +export async function decide(llm: Llm | null, bot: string, name: string, prompt: string, schema: object): Promise { + if (!llm || !llm.available()) return null; + const raw = await llm.chat( + [ + { role: 'system', content: systemPrompt(bot, name, 40) + '\n대답은 요청한 JSON 형식으로만 한다.' }, + { role: 'user', content: prompt }, + ], + { maxTokens: 120, temperature: 0.9, format: schema }, + ); + if (raw === null) return null; + try { + return JSON.parse(raw) as T; + } catch { + return null; + } +} diff --git a/apps/server/src/ai/llm.ts b/apps/server/src/ai/llm.ts new file mode 100644 index 0000000..e3b0cff --- /dev/null +++ b/apps/server/src/ai/llm.ts @@ -0,0 +1,123 @@ +/** + * Local language model on the GPU (Ollama, docs/11 §8). Used by computer players to talk and think out loud + * (docs/06 §12.1). Everything here is best effort: when the model is slow, busy or down the caller gets `null` + * and the computers fall back to their built-in lines — a game never waits on the model. + */ + +export interface LlmMessage { + role: 'system' | 'user' | 'assistant'; + content: string; +} + +export interface LlmConfig { + /** Ollama base URL, e.g. http://192.168.10.9:11434. */ + url: string; + model: string; + /** Requests running at once (one GPU). */ + maxConcurrent?: number; + /** Requests allowed to wait; more are refused at once (the caller uses a built-in line). */ + maxQueue?: number; + timeoutMs?: number; + /** How long Ollama keeps the model in GPU memory after the last request. */ + keepAlive?: string; + fetch?: typeof fetch; + log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record) => void; + now?: () => number; +} + +export interface LlmStats { + model: string; + requests: number; + ok: number; + failed: number; + /** Refused because the queue was full or the model was backing off. */ + skipped: number; + avgMs: number; + lastError: string | null; + backingOffUntil: number | null; +} + +export class Llm { + private running = 0; + private waiting: (() => void)[] = []; + private totalMs = 0; + private backoffUntil = 0; + private failures = 0; + readonly stats: LlmStats; + + constructor(private cfg: LlmConfig) { + this.stats = { model: cfg.model, requests: 0, ok: 0, failed: 0, skipped: 0, avgMs: 0, lastError: null, backingOffUntil: null }; + } + + private now(): number { + return this.cfg.now ? this.cfg.now() : Date.now(); + } + + /** False while backing off after errors (then callers don't even try). */ + available(): boolean { + return this.now() >= this.backoffUntil; + } + + /** + * One chat completion. `format` is a JSON schema for structured answers. Returns the text, or null when it could + * not be had in time (busy, down, timeout). + */ + async chat(messages: LlmMessage[], opts: { maxTokens?: number; temperature?: number; format?: object; timeoutMs?: number } = {}): Promise { + this.stats.requests++; + const full = this.running >= (this.cfg.maxConcurrent ?? 2) && this.waiting.length >= (this.cfg.maxQueue ?? 6); + if (!this.available() || full) { + this.stats.skipped++; + return null; + } + if (this.running >= (this.cfg.maxConcurrent ?? 2)) await new Promise((r) => this.waiting.push(r)); + this.running++; + const t0 = this.now(); + const ctl = new AbortController(); + const timer = setTimeout(() => ctl.abort(), opts.timeoutMs ?? this.cfg.timeoutMs ?? 6000); + try { + const res = await (this.cfg.fetch ?? fetch)(`${this.cfg.url.replace(/\/$/, '')}/api/chat`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + signal: ctl.signal, + body: JSON.stringify({ + model: this.cfg.model, + messages, + stream: false, + keep_alive: this.cfg.keepAlive ?? '30m', + ...(opts.format ? { format: opts.format } : {}), + options: { temperature: opts.temperature ?? 0.9, num_predict: opts.maxTokens ?? 80 }, + }), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const body = (await res.json()) as { message?: { content?: string } }; + const text = body.message?.content ?? ''; + const ms = this.now() - t0; + this.stats.ok++; + this.totalMs += ms; + this.stats.avgMs = Math.round(this.totalMs / this.stats.ok); + this.failures = 0; + return text; + } catch (err) { + this.stats.failed++; + this.stats.lastError = String(err).slice(0, 200); + this.failures++; + // A few failures in a row: stop asking for a while (30 s, up to 5 min) instead of slowing every move. + if (this.failures >= 3) { + this.backoffUntil = this.now() + Math.min(300_000, 30_000 * 2 ** (this.failures - 3)); + this.stats.backingOffUntil = this.backoffUntil; + this.cfg.log?.('warn', 'ai backing off', { failures: this.failures, err: this.stats.lastError }); + } + return null; + } finally { + clearTimeout(timer); + this.running--; + this.waiting.shift()?.(); + } + } + + /** Loads the model into GPU memory ahead of the first real request (the first load takes ~20 s). */ + async warm(): Promise { + const r = await this.chat([{ role: 'user', content: '안녕' }], { maxTokens: 1, timeoutMs: 60_000 }); + return r !== null; + } +} diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 438706f..1968817 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -12,6 +12,8 @@ export interface Config { superadminDiscordIds: string[]; /** Load-test only: lift per-IP HTTP limits. Ignored for https origins. */ loadTestNoHttpLimits: boolean; + /** Local language model for the computers (docs/06 §12.1, docs/11 §8); null = computers play without it. */ + ai: { url: string; model: string } | null; } export function loadConfig(env: Record = process.env): Config { @@ -35,5 +37,7 @@ export function loadConfig(env: Record = process.env loadTestNoHttpLimits: env.LOADTEST_NO_HTTP_LIMITS === '1' && !publicOrigin.startsWith('https://'), /** Superadmin Discord IDs, comma-separated (docs/14-admin.md §2). Only in deploy/.env, never in the repo. */ superadminDiscordIds: (env.SUPERADMIN_DISCORD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean), + /** AI_URL = Ollama on the GPU host (e.g. http://host.docker.internal:11434); AI_MODEL defaults to gemma3:4b. */ + ai: env.AI_URL ? { url: env.AI_URL, model: env.AI_MODEL || 'gemma3:4b' } : null, }; } diff --git a/apps/server/src/rooms/bots.ts b/apps/server/src/rooms/bots.ts index d8d1f4d..bc65630 100644 --- a/apps/server/src/rooms/bots.ts +++ b/apps/server/src/rooms/bots.ts @@ -7,6 +7,8 @@ import 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 type { BotBrain } from '../ai/brain'; + export { botPace }; export interface BotRoom { @@ -21,6 +23,8 @@ export interface BotRoom { 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; + /** 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. */ @@ -68,6 +72,9 @@ export class BotDriver { 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, @@ -78,9 +85,11 @@ export class BotDriver { /** 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) return; + 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; @@ -93,6 +102,7 @@ export class BotDriver { 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(); @@ -135,12 +145,16 @@ export class BotDriver { 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 } = { action: null, next: 3000 }; + 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 }); @@ -152,12 +166,43 @@ export class BotDriver { 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())); @@ -209,6 +254,31 @@ export class BotDriver { } 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); diff --git a/apps/server/src/rooms/manager.ts b/apps/server/src/rooms/manager.ts index 81487f9..16416ee 100644 --- a/apps/server/src/rooms/manager.ts +++ b/apps/server/src/rooms/manager.ts @@ -25,6 +25,10 @@ export interface ManagerDeps { random?: () => number; settings?: SettingsStore; botDelay?: RoomDeps['botDelay']; + /** Local language model shared by every room's computers. */ + ai?: RoomDeps['ai']; + aiSleep?: RoomDeps['aiSleep']; + aiRandom?: RoomDeps['aiRandom']; /** 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; } @@ -49,6 +53,9 @@ export class RoomManager { log: this.deps.log, settings: this.deps.settings, botDelay: this.deps.botDelay, + ai: this.deps.ai, + aiSleep: this.deps.aiSleep, + aiRandom: this.deps.aiRandom, 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); diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index 43795dd..a565d49 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -7,6 +7,8 @@ import { SeededRng, createSeed, seedToHex, type AnyGameDefinition, type GameResu import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared'; import { sha256Hex } from '../auth/sessions'; import { BotDriver, type BotDelayInput } from './bots'; +import { BotBrain, type BotActivity } from '../ai/brain'; +import type { Llm } from '../ai/llm'; import type { LogEntry, RoomStore } from './store'; import { applyLocks, type EffectiveGame, type SiteSettings } from '../admin/settings'; @@ -83,6 +85,12 @@ export interface RoomDeps { settings?: { game(id: string): EffectiveGame | null; getSite(): SiteSettings }; /** Computer players' thinking time (ms) for a decision with `choices` options; tests may pin it. */ botDelay?: (input: BotDelayInput) => number; + /** Local language model for the computers' talk and play-like-people behaviour (docs/06 §12.1); null = off. */ + ai?: Llm | null; + /** Waiting inside the computers' talk (typing time); tests may make it instant. */ + aiSleep?: (ms: number) => Promise; + /** Dice for the computers' talk (whether to speak now); tests may pin it. */ + aiRandom?: () => number; } const CHAT_HISTORY = 30; @@ -123,6 +131,9 @@ export class Room { private readonly now: () => number; /** Plays the computer players' moves (docs/06 §12). */ readonly bots: BotDriver; + /** The computers' talk and visible activity with the local model (docs/06 §12.1). */ + readonly brain: BotBrain; + private botActivity = new Map(); constructor( readonly id: string, @@ -137,6 +148,30 @@ export class Room { this.lastActiveAt = this.now(); this.emptySince = this.now(); const room = this; + this.brain = new BotBrain( + { + gameId: () => this.config.gameId, + gameName: () => this.def.nameKo, + nameOf: (id) => this.nick(id), + humans: () => (this.game && !this.game.finished ? this.game.players : this.seatedIds()).filter((u) => !isBotId(u)), + bots: () => (this.game && !this.game.finished ? this.game.players : this.seatedIds()).filter(isBotId), + playing: () => this.status === 'playing', + roomChat: (bot, text) => { + this.chat(bot, text); + }, + setActivity: (bot, a) => { + if ((this.botActivity.get(bot) ?? null) === a) return; + if (a) this.botActivity.set(bot, a); + else this.botActivity.delete(bot); + this.broadcastRoom(); + }, + recentChat: () => this.chatLog.slice(-8).map((m) => ({ from: m.from?.nickname ?? '누군가', text: m.text })), + now: this.now, + }, + deps.ai ?? null, + deps.aiRandom ?? Math.random, + deps.aiSleep, + ); this.bots = new BotDriver( { get status() { @@ -156,6 +191,7 @@ export class Room { }, log: deps.log, nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가', + brain: this.brain, }, Math.random, deps.botDelay, @@ -359,6 +395,7 @@ export class Room { lockedOptions: this.deps.settings?.game(this.config.gameId)?.lockedOptions ?? [], lastSeed: this.lastSeed, lastGamePk: this.game?.finished ? this.game.gamePk : null, + ...(this.botActivity.size ? { botActivity: Object.fromEntries(this.botActivity) } : {}), }; } @@ -714,6 +751,7 @@ export class Room { this.chatLog.push(msg); if (this.chatLog.length > CHAT_HISTORY) this.chatLog.shift(); for (const c of this.conns.values()) c.send(msg); + if (!isBotId(userId)) this.brain.onHumanChat(userId, msg.text); return null; } @@ -814,6 +852,7 @@ export class Room { this.broadcastRoom(); this.broadcastState([{ type: 'gameStarted' }]); this.scheduleTimer(); + this.brain.onGameStart(); return null; } @@ -870,6 +909,7 @@ export class Room { } else { this.persist({ actorId: userId, kind: system ? 'auto' : 'act', data: action, at: now }); this.broadcastState(next.events, userId, cs); + this.brain.onAction(userId, action); } const result = def.result(g.state); if (result) this.finishGame(result); @@ -935,7 +975,9 @@ export class Room { this.persist({ actorId: null, kind: 'finish', data: { result, voided } }); this.broadcastState([{ type: 'gameOver' }]); for (const c of this.conns.values()) c.send({ t: 'result', seq: this.seq, result }); + if (this.botActivity.size) this.botActivity.clear(); this.broadcastRoom(); + if (!voided) this.brain.onGameEnd(result.ranking); } // ---------------------------------------------------------------- timers diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index a1a55d8..ddc7fff 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -4,6 +4,7 @@ import { join, normalize } from 'node:path'; import type { Server } from 'bun'; import { GAMES } from '@bg/games'; import { botProfile } from '@bg/shared'; +import { Llm } from './ai/llm'; import type { Config } from './config'; import { openDb } from './db'; import { SESSION_COOKIE, Sessions } from './auth/sessions'; @@ -56,7 +57,10 @@ export function startServer(opts: StartOptions) { const roles = new Roles(db, config.superadminDiscordIds); const audit = new Audit(db); const startedAt = Date.now(); - const rooms = new RoomManager({ store, games: GAMES, users: { publicUser }, log, settings, botDelay: opts.botDelay, offlineSince: (id): number | null => gateway.offlineSince(id) }); + // 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 restored = rooms.restoreAll(); log('info', 'rooms restored', restored); const gateway = new Gateway({ rooms, me: publicUser, log, onClose: (id) => users.touch(id) }); @@ -89,7 +93,12 @@ export function startServer(opts: StartOptions) { replays: new Replays(db, GAMES, { publicUser }), ipOf, discordExchange: opts.discordExchange, - health: () => ({ ok: ready, rooms: rooms.all().length, connections: gateway.connectionCount }), + health: () => ({ + ok: ready, + rooms: rooms.all().length, + connections: gateway.connectionCount, + ...(ai ? { ai: { model: ai.stats.model, available: ai.available(), ok: ai.stats.ok, failed: ai.stats.failed, avgMs: ai.stats.avgMs } } : {}), + }), roles, settings, removeGuest, diff --git a/apps/web/src/components/BotActivity.tsx b/apps/web/src/components/BotActivity.tsx new file mode 100644 index 0000000..1fc7526 --- /dev/null +++ b/apps/web/src/components/BotActivity.tsx @@ -0,0 +1,21 @@ +import type { RoomView } from '@bg/shared/lite'; + +/** + * What the computers are doing right now (docs/06 §12.1): "🤖 컴퓨터 1 생각 중…", "💬 컴퓨터 2 입력 중…". + * Not announced to screen readers: the chat line or the move that follows is. + */ +export function BotActivity({ room, only }: { room: RoomView; only?: 'typing' }) { + const entries = Object.entries(room.botActivity ?? {}).filter(([, a]) => !only || a === only); + if (!entries.length) return null; + const name = (id: string) => room.seats.find((s) => s?.user.id === id)?.user.nickname ?? '컴퓨터'; + return ( +
+ {entries.map(([id, a]) => ( + + {a === 'typing' ? '💬' : '🤖'} {name(id)} {a === 'typing' ? '입력 중' : '생각 중'} + + + ))} +
+ ); +} diff --git a/apps/web/src/components/ChatPanel.tsx b/apps/web/src/components/ChatPanel.tsx index 616d932..fe1239a 100644 --- a/apps/web/src/components/ChatPanel.tsx +++ b/apps/web/src/components/ChatPanel.tsx @@ -3,6 +3,7 @@ import { useEffect, useRef, useState } from 'react'; import { CHAT_MAX, EMOTE_LABEL, EMOTES, type PublicUser, type RoomView } from '@bg/shared/lite'; import { create } from 'zustand'; import { socket, useRoom } from '../net/socket'; +import { BotActivity } from './BotActivity'; export const useChatSeen = create<{ seen: number }>(() => ({ seen: 0 })); @@ -52,6 +53,7 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ ))} +
{EMOTES.map((id) => (
+ {room.status === 'paused' && room.hostId === me.id && (