Compare commits
3 Commits
0fe7e27eb2
...
c7dab689ca
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7dab689ca | ||
|
|
13974181e7 | ||
|
|
65a0f34d93 |
221
apps/server/src/ai/ai.test.ts
Normal file
221
apps/server/src/ai/ai.test.ts
Normal file
@@ -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<string, string> } }).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);
|
||||
});
|
||||
254
apps/server/src/ai/brain.ts
Normal file
254
apps/server/src/ai/brain.ts
Normal file
@@ -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<string, string> = {
|
||||
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<void>((r) => setTimeout(r, ms));
|
||||
|
||||
export class BotBrain {
|
||||
private lastRoomLine = -Infinity;
|
||||
private lastBotLine = new Map<string, number>();
|
||||
private happened: string[] = [];
|
||||
private typing = new Set<string>();
|
||||
|
||||
constructor(
|
||||
private room: BrainRoom,
|
||||
readonly llm: Llm | null,
|
||||
private random: () => number = Math.random,
|
||||
private sleep: (ms: number) => Promise<void> = 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<void> {
|
||||
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> = {}): 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<void> {
|
||||
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<unknown> {
|
||||
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<string, { counts: Record<string, number> }> };
|
||||
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<string, string> = { 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}|(?<![0-9])${n}번)(?![0-9])`).test(text) : false;
|
||||
});
|
||||
const bot = named ?? (this.random() < 0.4 ? bots[Math.floor(this.random() * bots.length)] : undefined);
|
||||
if (!bot || this.typing.has(bot)) return;
|
||||
this.spoke(bot);
|
||||
const who = this.room.nameOf(from);
|
||||
void writeLine(this.llm, this.request(bot, this.situation(), `${who}이(가) 채팅으로 "${text.slice(0, 100)}"라고 했다. 같이 게임하는 사람으로서 대답한다. 질문이면 그 질문에 직접 답하고(성격대로, 허세·도발·엄살 가능), 질문이 아니면 맞장구치거나 받아친다.`)).then((line) => {
|
||||
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<string> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
125
apps/server/src/ai/lines.ts
Normal file
125
apps/server/src/ai/lines.ts
Normal file
@@ -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<string | null> {
|
||||
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<T>(llm: Llm | null, bot: string, name: string, 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: '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;
|
||||
}
|
||||
}
|
||||
123
apps/server/src/ai/llm.ts
Normal file
123
apps/server/src/ai/llm.ts
Normal file
@@ -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<string, unknown>) => 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<string | null> {
|
||||
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<void>((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<boolean> {
|
||||
const r = await this.chat([{ role: 'user', content: '안녕' }], { maxTokens: 1, timeoutMs: 60_000 });
|
||||
return r !== null;
|
||||
}
|
||||
}
|
||||
@@ -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<string, string | undefined> = process.env): Config {
|
||||
@@ -35,5 +37,7 @@ export function loadConfig(env: Record<string, string | undefined> = 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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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<string, unknown>) => 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<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,
|
||||
@@ -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<string, string> = {};
|
||||
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<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()));
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -10,7 +10,7 @@ import { GAMES } from '@bg/games';
|
||||
import { openDb } from '../db';
|
||||
import { Room, type Conn, type RoomConfig } from './room';
|
||||
import { RoomStore } from './store';
|
||||
import { Replays, rebuildGame, type ReplayInput } from './replay';
|
||||
import { Replays, rebuildGame, sameOutcome, type ReplayInput } from './replay';
|
||||
|
||||
const json = (v: unknown) => JSON.parse(JSON.stringify(v));
|
||||
|
||||
@@ -262,6 +262,24 @@ describe('replay: access and edge cases', () => {
|
||||
expect(await new Replays(db, GAMES, users).get(pk, 'A')).toMatchObject({ ok: false, status: 410 });
|
||||
});
|
||||
|
||||
test('practice games (marked "practice") and games recorded before final scores existed are replayable', async () => {
|
||||
const { db, room, users } = omokRoom();
|
||||
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
||||
room.leave('B');
|
||||
const pk = room.game!.gamePk;
|
||||
const stored = JSON.parse(db.query<{ result_json: string }, [string]>('SELECT result_json FROM games WHERE id = ?').get(pk)!.result_json);
|
||||
// As the store writes a game played with computers.
|
||||
db.query('UPDATE games SET result_json = ? WHERE id = ?').run(JSON.stringify({ ...stored, practice: true }), pk);
|
||||
const practice = await new Replays(db, GAMES, users).get(pk, 'A');
|
||||
expect(practice.ok).toBe(true);
|
||||
// A scored game recorded without scoreText gets it from the rebuilt game; a changed outcome still fails.
|
||||
const scored = { ...GAMES, omok: { ...GAMES.omok!, result: (st: unknown) => { const r = GAMES.omok!.result(st); return r && { ...r, scoreText: { A: '1점', B: '0점' } }; } } };
|
||||
const old = await new Replays(db, scored, users).get(pk, 'A');
|
||||
if (!old.ok) throw new Error(old.error);
|
||||
expect((JSON.parse(old.body) as ReplayData).result.scoreText).toEqual({ A: '1점', B: '0점' });
|
||||
expect(sameOutcome({ ranking: [['A'], ['B']], summary: 'x', reason: 'normal' }, { ranking: [['B'], ['A']], summary: 'x', reason: 'normal' })).toBe(false);
|
||||
});
|
||||
|
||||
test('my games list: newest first, paged, with ranks and nicknames', async () => {
|
||||
const { db, room, clock, users } = omokRoom();
|
||||
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
||||
|
||||
@@ -41,6 +41,20 @@ function* replaySteps(def: AnyGameDefinition, input: ReplayInput): Generator<Ste
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Did the rebuilt game end the way it was recorded? Compares the outcome (ranking, scores, reason, summary), not
|
||||
* labels added around it: the store marks practice games (`practice`), and `scoreText` is display wording that games
|
||||
* recorded before 2026-10-11 don't have. (Comparing the raw JSON made every practice game and every older scored
|
||||
* game "not replayable".)
|
||||
*/
|
||||
export function sameOutcome(rebuilt: GameResult, stored: GameResult): boolean {
|
||||
const core = (r: GameResult) => {
|
||||
const { practice: _p, scoreText: _t, ...rest } = r as GameResult & { practice?: boolean };
|
||||
return JSON.stringify(rest);
|
||||
};
|
||||
return core(rebuilt) === core(stored);
|
||||
}
|
||||
|
||||
/** Final state of a rebuilt game. */
|
||||
export function rebuildGame(def: AnyGameDefinition, input: ReplayInput): unknown {
|
||||
let state: unknown;
|
||||
@@ -233,10 +247,12 @@ export class Replays {
|
||||
return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
|
||||
}
|
||||
// The rebuilt game must end exactly as recorded; otherwise the replay would show a different game.
|
||||
const result = JSON.parse(g.result_json) as GameResult;
|
||||
const stored = JSON.parse(g.result_json) as GameResult;
|
||||
const rebuilt = def.result(built.final);
|
||||
const matches = g.end_reason === 'void' ? rebuilt === null : JSON.stringify(rebuilt) === g.result_json;
|
||||
const matches = g.end_reason === 'void' ? rebuilt === null : !!rebuilt && sameOutcome(rebuilt, stored);
|
||||
if (!matches) return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
|
||||
// Games recorded before the result screen showed final scores get them from the rebuilt game.
|
||||
const result: GameResult = rebuilt?.scoreText && !stored.scoreText ? { ...stored, scoreText: rebuilt.scoreText } : stored;
|
||||
|
||||
const ids = this.idMap(start.players, seats.map((s) => s.user_id));
|
||||
const players: Record<string, PublicUser> = {};
|
||||
|
||||
@@ -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<void>;
|
||||
/** 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<string, BotActivity>();
|
||||
|
||||
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
|
||||
|
||||
@@ -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,
|
||||
|
||||
21
apps/web/src/components/BotActivity.tsx
Normal file
21
apps/web/src/components/BotActivity.tsx
Normal file
@@ -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 (
|
||||
<div className="bot-activity small" aria-hidden>
|
||||
{entries.map(([id, a]) => (
|
||||
<span key={id} data-activity={a}>
|
||||
{a === 'typing' ? '💬' : '🤖'} {name(id)} {a === 'typing' ? '입력 중' : '생각 중'}
|
||||
<span className="bot-dots" />
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<BotActivity room={room} only="typing" />
|
||||
<div className="emote-row">
|
||||
{EMOTES.map((id) => (
|
||||
<button key={id} type="button" onClick={() => socket.send({ t: 'emote', id })}>
|
||||
|
||||
@@ -14,6 +14,7 @@ import { loadGameUI } from '../games/registry';
|
||||
import type { GameUI } from '../games/types';
|
||||
import { sounds } from '../lib/feedback';
|
||||
import { ChatPanel, EmoteBubbles, useChatSeen } from '../components/ChatPanel';
|
||||
import { BotActivity } from '../components/BotActivity';
|
||||
import { useWide } from '../lib/media';
|
||||
import { GameHelp } from '../components/GameHelp';
|
||||
import { PlayerName } from '../components/PlayerCard';
|
||||
@@ -653,6 +654,7 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui
|
||||
{status}
|
||||
<GameHelp room={room} ui={ui} title={gameName(room.gameId)} me={me.id} players={players} />
|
||||
</div>
|
||||
<BotActivity room={room} />
|
||||
{room.status === 'paused' && room.hostId === me.id && (
|
||||
<button className="btn btn-danger btn-block" onClick={() => socket.send({ t: 'void' })}>
|
||||
⏹ 게임 끝내기(무효)
|
||||
|
||||
@@ -1523,3 +1523,10 @@ button.header-user {
|
||||
min-height: 40px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Computers' visible activity (docs/06 §12.1) */
|
||||
.bot-activity { display: flex; flex-wrap: wrap; gap: 4px 12px; color: var(--text-sub); padding: 2px 4px; }
|
||||
.bot-activity > span { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.bot-dots::after { content: '…'; display: inline-block; width: 1.2em; animation: bot-dots 1.2s steps(4, end) infinite; overflow: hidden; vertical-align: bottom; }
|
||||
@keyframes bot-dots { 0% { width: 0; } 100% { width: 1.2em; } }
|
||||
@media (prefers-reduced-motion: reduce) { .bot-dots::after { animation: none; } }
|
||||
|
||||
14
deploy/docker-compose.ai.yml
Normal file
14
deploy/docker-compose.ai.yml
Normal file
@@ -0,0 +1,14 @@
|
||||
# GPU host (.9, RTX 5050): the computers talk and play like people with the local model (docs/06 §12.1, docs/11 §8).
|
||||
# Ollama runs on this host as a system service on the GPU (OLLAMA_HOST=0.0.0.0:11434, model gemma3:4b);
|
||||
# the app container reaches it through the host gateway. Use together with the proxy file:
|
||||
# cd deploy && docker --context default compose -f docker-compose.proxy.yml -f docker-compose.ai.yml up -d --build
|
||||
services:
|
||||
app:
|
||||
environment:
|
||||
AI_URL: http://host.docker.internal:11434
|
||||
AI_MODEL: gemma3:4b
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
# .9 also runs the chat bots and desktop services: keep the site small.
|
||||
mem_limit: 1g
|
||||
cpus: 2
|
||||
@@ -112,3 +112,12 @@ interface Room {
|
||||
- 움직임: 서버의 `BotDriver`(`apps/server/src/rooms/bots.ts`)가 게임이 컴퓨터를 기다릴 때(차례, 반응 창, 동시 선택, 다음 판 준비) 사람처럼 생각할 시간을 두고 한 수를 둔다(2026-10-11). 할 게 하나뿐이면 0.7~1.3초, 고를 게 있으면 1.6~3.9초(고를 수가 많을수록 길게), 가끔(12%) 1~3초 더 멈칫한다. 컴퓨터마다 빠르기가 달라서(`botPace`: 0.7배 빠른 편~1.5배 신중한 편, 컴퓨터 id로 고정) 같은 판에서도 반응 속도가 다르다. 같은 컴퓨터가 이어서 두는 동작(요트 굴리기 → 고르기 등)은 절반 시간, 사람도 함께 반응할 수 있는 창(원카드 외치기 등)은 1.5초 더. 차례 시간이 있으면 남은 시간의 절반을 넘기지 않는다. 사람과 같은 행동 경로(검사·기록)를 거치고, 서버가 다시 켜져도 이어서 둔다.
|
||||
- 수 고르기: `packages/games/src/<게임>/bot.ts`. 자기 화면(`view(state, 나)`)과 둘 수 있는 수만 보고 고르므로 남의 패를 볼 수 없다. 강하지 않지만 엉뚱하지 않게(오목은 4를 막고, 오셀로는 귀를 잡고, 카드 게임은 패 세기에 맞게).
|
||||
- 사람이 모두 나가면 게임은 무효로 끝난다.
|
||||
|
||||
### 12.1 사람처럼 노는 컴퓨터 (GPU 로컬 모델, 2026-10-11)
|
||||
- 수 고르기는 게임별 전략(자기 화면만 봄) 그대로다. 그 위에 GPU의 로컬 언어 모델(gemma3:4b, docs/11 §8)이 말과 심리전을 맡는다(`apps/server/src/ai/`).
|
||||
- 성격: 컴퓨터 id로 정해지는 5가지 — 도발형·허세형·차분형·수다형·소심형 — 와 말투(똑똑한 편 존댓말, 허술한 편 반말).
|
||||
- 보이는 행동: 수를 고르는 동안 "🤖 컴퓨터 1 생각 중…", 말할 때는 그 줄을 치는 만큼(글자 수 × 컴퓨터마다 다른 타자 속도, 0.9~6.5초) "💬 입력 중…"이 보인 뒤 채팅이 올라가고, 잠깐 뒤 수를 둔다(상태 줄과 채팅 칸, `RoomView.botActivity`).
|
||||
- 말하는 때: 자기 수와 함께 도발·심리전 한마디(성격별 14~38%, 방 전체 8초·컴퓨터마다 20초 간격), 사람의 수에 가끔 반응(12%), 사람이 이름을 부르거나 말을 걸면 대답(이름 부르면 꼭, 아니면 40%), 시작 인사, 끝나면 이긴 컴퓨터가 놀리거나 진 컴퓨터가 아쉬워함.
|
||||
- 심리전 판단: 바퀴벌레 포커에서 카드를 건넬 때 진짜를 말할지 블러핑할지를 모델이 정하고, 그걸 파는 한마디를 한다(실제 카드 이름이 들어간 말은 버림). 마피아는 컴퓨터가 계획한 대사(의심 지목·반박·반론 등)를 모델이 자기 말로 바꾼다. 모델에게 그 컴퓨터의 직업은 알려 주지 않고, "저 경찰이에요"·"나 마피아" 같은 직업 주장이 나오면 버리고 원래 대사를 쓴다.
|
||||
- 안전: 한 줄만, 40자 안팎, 한국어만(외국 문자·영어 단어·"AI"류 말 거름), 고운 말 필터·링크·전화번호 차단, 숨은 정보는 말하지 않게 지시.
|
||||
- 모델이 없거나 바쁘면 전처럼 조용히 둔다(게임은 모델을 기다리지 않는다).
|
||||
|
||||
@@ -126,6 +126,7 @@ export interface GameUI<V> {
|
||||
- **다시 만들기**: 끝난 게임을 공개된 시드 + `room_log`의 `act`/`auto` 기록으로 처음부터 다시 돌린다. `setup`(시작 시각)과 각 `apply`(그 행동을 적용한 정확한 `now`, 로그의 `at`)를 방과 똑같이 부르고 RNG도 이어서 쓰므로 결과가 방에서 끝난 상태와 한 글자도 다르지 않다. `start` 로그에 `stateVersion`을 남긴다.
|
||||
- **보이는 것**: 그 판에 앉았던 플레이어만 볼 수 있고(관전자·남은 403), 각자 게임 중에 받던 자기 `view`(있으면 `syncView`)만 받는다. 시드와 원본 로그는 서버 밖으로 나가지 않는다. 응답은 `private, no-store`.
|
||||
- **장면**: 스트리밍 행동(그림 맞히기 선)이 아닌 행동 하나가 한 장면. 첫 장면만 view 전체, 나머지는 앞 장면과의 차이(`packages/shared/src/view-patch.ts`)만 보낸다. 다시 만든 결과가 저장된 결과와 다르면 보여 주지 않는다.
|
||||
- **같은 결과인지 비교**(2026-10-11): 순위·점수·끝난 이유·요약만 비교한다(`sameOutcome`). 저장할 때 붙는 `practice` 표시와 화면용 `scoreText`는 뺀다. 전에는 JSON 전체를 비교해서 컴퓨터와 한 판, 그리고 점수 문구가 생기기 전에 끝난 점수 게임(라스베가스·요트·할리갈리·도블 등)이 모두 "다시 볼 수 없어요"였다(운영 DB 44판 중 21판 → 0판). 예전 게임은 다시 만든 `scoreText`를 붙여 보여 준다.
|
||||
- **못 보는 경우**(410, 한국어 안내): 90일이 지나 로그가 지워짐, 그 뒤로 게임 규칙 버전(`stateVersion`)이 바뀜, 다시 만든 결과가 다름.
|
||||
- **API**: `GET /api/me/games?before=&limit=`(내가 끝까지 한 게임, 최신순), `GET /api/replays/:gamePk`. 다시 만든 결과는 잠깐(10분, 32개) 캐시하고, 한 번에 하나씩 조금씩 끊어 만들어 방 처리를 막지 않는다.
|
||||
- **화면**: 게임의 `Board`/`Side`를 그대로 쓰되 읽기 전용(`act`는 아무것도 안 함, 판 안의 누르기·키 입력은 막음). 처음 / 이전 / 재생·멈춤 / 다음 / 끝 버튼, 슬라이더, "n번째 / 전체 n번", 장면 설명(누가 움직였는지, 자동 진행). 키보드 ←/→/Home/End. 들어가는 곳: 결과 화면 [▶ 다시 보기](`RoomView.lastGamePk`), 내 정보 › 내 게임 기록 [다시 보기].
|
||||
|
||||
@@ -73,3 +73,20 @@ deploy/
|
||||
- 업데이트: `git pull && docker compose -f docker-compose.proxy.yml up -d --build`
|
||||
- 확인: `curl http://192.168.10.5:2970/healthz`, `curl -I https://game.tkrmagid.kr/`
|
||||
|
||||
|
||||
## 8. .9 GPU 호스트로 이전 + 로컬 AI 모델 (2026-10-11)
|
||||
사이트를 .9(192.168.10.9, RTX 5050 8GB가 붙은 VM)의 도커로 옮겼다. 컴퓨터 플레이어가 GPU의 로컬 언어 모델로 말하고 사람처럼 움직인다(06 §12.1).
|
||||
|
||||
```
|
||||
인터넷 → game.tkrmagid.kr → NPMplus 192.168.10.3:443 → 192.168.10.9:2970 → app:3000 ─→ Ollama(.9 호스트, GPU) :11434
|
||||
```
|
||||
|
||||
- 코드: `/home/claude/projects/joke-app` (Gitea clone, `main`). 설정 `deploy/.env`(권한 600, .5에서 옮김). 데이터는 도커 볼륨 `joke-app_app-data`(.5의 DB를 멈춘 상태에서 그대로 복사).
|
||||
- 실행(.9는 기본 도커 컨텍스트가 `docker5`라 꼭 `--context default`):
|
||||
`cd /home/claude/projects/joke-app/deploy && docker --context default compose -f docker-compose.proxy.yml -f docker-compose.ai.yml up -d --build`
|
||||
- `docker-compose.ai.yml`: `AI_URL=http://host.docker.internal:11434`, `AI_MODEL=gemma3:4b`, `host-gateway`, 메모리 1GB·CPU 2개 제한(.9에는 채팅 봇·데스크톱 서비스가 같이 돈다).
|
||||
- 모델: 호스트의 시스템 서비스 `ollama`(이미 GPU 사용, `OLLAMA_HOST=0.0.0.0:11434`)에 `gemma3:4b`(3.3GB, Q4) — 후보 비교: exaone3.5:2.4b(0.25초, 말이 길고 영어 섞임), qwen2.5:7b(1.0초, 중국어 섞임), gemma3:4b(0.6초, 한국어가 가장 자연스러움). GPU 메모리: 음성 봇(whisper·melo) 약 3GB + gemma3 약 3.5GB.
|
||||
- 모델이 꺼지거나 바쁘면(동시 2개, 대기 6개, 6초 제한, 3번 연속 실패 시 30초~5분 쉼) 컴퓨터는 예전처럼 조용히 두고 마피아는 정해 둔 대사를 쓴다. 게임이 모델을 기다리지 않는다.
|
||||
- 확인: `curl http://192.168.10.9:2970/healthz` → `ai: { model, available, ok, failed, avgMs }`.
|
||||
- NPMplus 프록시 호스트 id 10의 대상이 `192.168.10.9:2970`. 되돌리기: .5의 `joke-app-app-1`은 멈춰만 두었다(`docker compose -f docker-compose.proxy.yml start` 후 NPMplus 대상을 .5로).
|
||||
- 업데이트: `git pull` 후 위 실행 명령. 이전 이미지를 `boardgame-site:rollback-<sha>`로 태그해 둔다.
|
||||
|
||||
@@ -260,3 +260,4 @@ interface MafiaResult {
|
||||
- 반응 속도: 컴퓨터마다 빠르기(`botPace` 0.7~1.5배)가 달라 대답·투표·밤 행동 시점이 다르다. 시간은 늘 그 페이즈 안(투표는 남은 시간의 75% 안).
|
||||
- 채팅: 인사, 아침 소식 반응(두 명이 이미 말했으면 조용히), 의심 지목, 남의 지목에 동의·반박, 이름이 불리면 대답(질문·의심에는 꼭), 최후의 반론, 투표·찬반 한마디, 마피아 채팅으로 상의(사람 마피아가 고르면 따른다), 연인 채팅, 탈락 뒤 한마디. 자기나 남이 방금 한 말은 되풀이하지 않는다. 이름은 "컴퓨터 3", "컴퓨터3", "컴3", "3번"을 모두 알아듣는다.
|
||||
- 비공개 정보: 컴퓨터는 자기 화면만 본다(남의 직업은 모름). 마피아 컴퓨터는 낮 채팅에서 자기 팀을 지목하지 않는다(테스트).
|
||||
- GPU 로컬 모델(2026-10-11, 06 §12.1): 위 대사 중 뜻만 정해진 줄(인사·소식 반응·지목·동의·반박·반론·잡담·탈락 뒤 한마디)은 모델이 그 컴퓨터의 성격과 말투로 새로 쓴다(`hint`). 경찰 결과·직업 주장·마피아 채팅 상의는 정해 둔 문장 그대로. 모든 말은 "입력 중…"을 치는 시간만큼 보인 뒤 올라간다.
|
||||
|
||||
97
e2e/ai.e2e.ts
Normal file
97
e2e/ai.e2e.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* E2E (docs/06 §12.1): computers with the real local model on the GPU. Skipped unless AI_URL is set.
|
||||
* 1) 오목 연습: "생각 중…" shows while the computer chooses; a person asks it something by name → "입력 중…", then an
|
||||
* answer written by the model appears in the room chat.
|
||||
* 2) 마피아 연습: the computers' greetings/lines come out of the model (not only the built-in lines).
|
||||
* Run: AI_URL=http://localhost:11434 E2E_PORT=4545 bun e2e/ai.e2e.ts (needs apps/web/dist built)
|
||||
*/
|
||||
import { chromium, type Page } from 'playwright-core';
|
||||
import { mkdirSync, mkdtempSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { loadConfig } from '../apps/server/src/config';
|
||||
import { startServer } from '../apps/server/src/server';
|
||||
|
||||
if (!process.env.AI_URL) {
|
||||
console.log('AI_URL not set: skipped');
|
||||
process.exit(0);
|
||||
}
|
||||
const PORT = Number(process.env.E2E_PORT ?? 4545);
|
||||
const ORIGIN = `http://localhost:${PORT}`;
|
||||
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
|
||||
mkdirSync(SHOTS, { recursive: true });
|
||||
const dbDir = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'bg-e2e-'));
|
||||
const app = startServer({
|
||||
config: loadConfig({ PORT: String(PORT), DB_PATH: join(dbDir, 'app.db'), PUBLIC_ORIGIN: ORIGIN, AI_URL: process.env.AI_URL, AI_MODEL: process.env.AI_MODEL }),
|
||||
log: (level, msg, extra) => {
|
||||
if (level !== 'info' || msg.startsWith('ai')) console.log(` [${level}] ${msg} ${JSON.stringify(extra ?? {})}`);
|
||||
},
|
||||
staticDir: join(import.meta.dir, '../apps/web/dist'),
|
||||
});
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
|
||||
let failed = false;
|
||||
const step = async (name: string, fn: () => Promise<void>) => {
|
||||
const t0 = performance.now();
|
||||
try {
|
||||
await fn();
|
||||
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
|
||||
} catch (e) {
|
||||
failed = true;
|
||||
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
const BUILT_IN = /^(ㅎㅇㅎㅇ|안녕ㅋㅋ|하이~ 나 시민임ㅋㅋ|ㅎㅇ 마피아 누구냐|오 재밌겠다ㅋㅋ|안녕하세요! 잘 부탁드려요|반가워요~ 이번 판 재밌게 해요|안녕하세요\. 차분하게 찾아봐요|다들 반가워요! 마피아 꼭 찾아요)$/;
|
||||
|
||||
try {
|
||||
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
|
||||
await ctx.addInitScript(() => { for (const g of ['omok', 'mafia']) localStorage.setItem(`bg:qs:${g}`, '1'); });
|
||||
const a = await ctx.newPage();
|
||||
const errors: string[] = [];
|
||||
a.on('pageerror', (e) => errors.push(e.message));
|
||||
// Warm the model first (the first load takes ~20 s).
|
||||
for (let i = 0; i < 60 && !(await (await fetch(`${ORIGIN}/healthz`)).json()).ai?.ok; i++) await Bun.sleep(1000);
|
||||
|
||||
await step('오목 연습: 생각 중… → 이름을 불러 물으면 입력 중… → 모델이 쓴 대답', async () => {
|
||||
await a.goto(`${ORIGIN}/g/omok`);
|
||||
await a.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click();
|
||||
await a.getByLabel('내 이름(닉네임)').fill('사람');
|
||||
await a.getByRole('button', { name: '이 이름으로 시작하기' }).click();
|
||||
await a.waitForURL(/\/r\/\d{6}$/);
|
||||
await a.getByLabel('자리').getByText('컴퓨터 1').waitFor();
|
||||
await a.getByRole('button', { name: '▶ 게임 시작' }).click();
|
||||
await a.locator('svg[role="grid"]').waitFor();
|
||||
const before = await a.locator('.chat-line').count();
|
||||
await a.getByPlaceholder(/메시지/).fill('컴퓨터 1 너 오목 잘해?');
|
||||
await a.getByPlaceholder(/메시지/).press('Enter');
|
||||
await a.locator('.bot-activity [data-activity="typing"]').first().waitFor({ timeout: 20_000 });
|
||||
await a.screenshot({ path: join(SHOTS, 'ai-1-typing.png') });
|
||||
await a.waitForFunction((n) => [...document.querySelectorAll('.chat-line')].slice(n).some((l) => l.querySelector('strong')?.textContent === '컴퓨터 1'), before + 1, { timeout: 30_000 });
|
||||
const lines = await a.locator('.chat-line').allInnerTexts();
|
||||
console.log(' omok chat:', lines.map((l) => l.replace(/\n/g, ' ').replace(/가리기$/, '')).join(' | '));
|
||||
await a.screenshot({ path: join(SHOTS, 'ai-2-answer.png') });
|
||||
});
|
||||
|
||||
await step('마피아 연습: 컴퓨터 말이 모델에서 나온다', async () => {
|
||||
await a.goto(`${ORIGIN}/g/mafia`);
|
||||
await a.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click();
|
||||
await a.waitForURL(/\/r\/\d{6}$/);
|
||||
await a.getByLabel('자리').getByText('컴퓨터 5').waitFor();
|
||||
await a.getByRole('button', { name: '▶ 게임 시작' }).click();
|
||||
await a.waitForFunction(() => document.querySelectorAll('.mf-msgs .mf-msg:not(.sys)').length >= 3, null, { timeout: 60_000 });
|
||||
const lines = (await a.locator('.mf-msgs .mf-msg:not(.sys)').allInnerTexts()).map((l) => l.replace(/\n/g, ' '));
|
||||
console.log(' mafia chat:', lines.join(' | '));
|
||||
const texts = lines.map((l) => l.replace(/^컴퓨터 \d\s*/, ''));
|
||||
if (texts.every((t) => BUILT_IN.test(t))) throw new Error('only built-in lines');
|
||||
await a.screenshot({ path: join(SHOTS, 'ai-3-mafia.png') });
|
||||
});
|
||||
console.log(' ai stats:', JSON.stringify((await (await fetch(`${ORIGIN}/healthz`)).json()).ai));
|
||||
if (errors.length) throw new Error(`page errors: ${errors.join(' | ')}`);
|
||||
} catch (e) {
|
||||
failed = true;
|
||||
console.error(e);
|
||||
} finally {
|
||||
await browser.close();
|
||||
app.stop?.();
|
||||
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
|
||||
process.exit(failed ? 1 : 0);
|
||||
}
|
||||
@@ -44,6 +44,11 @@ export interface LiveBotDecision<A = any> {
|
||||
action: A | null;
|
||||
/** Ask again after this many ms. */
|
||||
next: number;
|
||||
/**
|
||||
* For a chat line: what it means, so a language model may say it in the computer's own words (the action's text is
|
||||
* the built-in wording, used when no model is available).
|
||||
*/
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export type LiveBotStrategy<V = any, A = any> = (input: LiveBotInput<V>) => LiveBotDecision<A>;
|
||||
|
||||
@@ -98,6 +98,31 @@ const L = {
|
||||
};
|
||||
type LineKey = keyof typeof L;
|
||||
|
||||
/**
|
||||
* What a line means, for a language model to say it in its own words (docs/games/mafia.md §13). Lines that carry
|
||||
* exact information (police results, role claims, mafia-chat plans) are not listed: they are always said as written.
|
||||
*/
|
||||
const HINT: Partial<Record<LineKey, string>> = {
|
||||
greet: '게임을 시작하며 인사',
|
||||
died: '밤사이 {V}이(가) 마피아에게 당한 것에 대한 반응',
|
||||
healed: '의사가 살려서 밤에 아무도 안 죽은 것에 대한 반응',
|
||||
soldier: '{V}이(가) 군인이라 공격을 버틴 것에 대한 반응',
|
||||
quiet: '조용한 밤이었다는 반응',
|
||||
accuse: '{X}이(가) 마피아 같다고 의심하며 지목',
|
||||
unsure: '아직 누가 마피아인지 모르겠다며 다른 사람 의견을 묻기',
|
||||
agree: '{X}이(가) 수상하다는 의견에 동의',
|
||||
disagree: '{X}은(는) 마피아가 아닌 것 같다고 반박하고 차라리 {Y}을(를) 의심',
|
||||
defend: '자신은 시민이라며 억울함을 호소하고 {Y}을(를) 의심해 보라고 하기',
|
||||
role: '직업을 묻는 질문에 시민이라고 대답',
|
||||
called: '이름이 불려서 짧게 반응',
|
||||
copHeard: '경찰이라고 밝힌 사람의 말에 반응',
|
||||
voted: '{X}에게 투표했다고 말하기',
|
||||
yes: '처형에 찬성한다고 말하기',
|
||||
no: '아직 확실하지 않아 처형에 반대한다고 말하기',
|
||||
filler: '분위기를 띄우는 짧은 잡담',
|
||||
dead: '탈락한 뒤 남은 사람들에게 한마디',
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- reading the chat
|
||||
|
||||
const ACCUSE = /마피아|마피|수상|의심|범인|찍|투표|죽이|처형|거짓|가짜|너지|이상|맞는|맞음|맞아/;
|
||||
@@ -243,10 +268,15 @@ class MafiaBot {
|
||||
return m ? `${m[1]}번` : n;
|
||||
}
|
||||
|
||||
/** The meaning of the last line made (for the language model), or null for exact-information lines. */
|
||||
lastHint: string | null = null;
|
||||
|
||||
/** A line of this character; skips ones it already said and ones just said by others (people don't echo). */
|
||||
private line(key: LineKey, salt: string | number, vars?: Record<string, string>): string;
|
||||
private line(key: LineKey, salt: string | number, vars: Record<string, string>, optional: true): string | null;
|
||||
private line(key: LineKey, salt: string | number, vars: Record<string, string> = {}, optional = false): string | null {
|
||||
const h = HINT[key];
|
||||
this.lastHint = h ? fill(h, { ...vars, R: '' }) + (key === 'accuse' && vars.R ? ` (이유:${vars.R})` : '') : null;
|
||||
const set = L[key];
|
||||
const pool = this.smart ? set.smart : set.dumb;
|
||||
const used = new Set([
|
||||
@@ -725,8 +755,12 @@ export function mafiaBot(input: In): LiveBotDecision<MafiaAction> {
|
||||
continue;
|
||||
}
|
||||
done[it.key] = true;
|
||||
bot.lastHint = null;
|
||||
const action = it.make();
|
||||
if (action) return { action, next: Math.round(400 + 600 * input.persona.pace) };
|
||||
if (action) {
|
||||
const hint = action.type === 'chat' && (action.channel === 'day' || action.channel === 'dead') ? bot.lastHint : null;
|
||||
return { action, next: Math.round(400 + 600 * input.persona.pace), ...(hint ? { hint } : {}) };
|
||||
}
|
||||
}
|
||||
const idle = v.my.alive ? 1500 : 4000;
|
||||
const wait = soonest === Infinity ? idle : soonest - input.now;
|
||||
|
||||
@@ -56,6 +56,8 @@ export interface RoomView {
|
||||
lastSeed: string | null;
|
||||
/** The game that just ended (for 다시 보기), null while playing or before the first game. */
|
||||
lastGamePk: string | null;
|
||||
/** Computers doing something people can see (docs/06 §12.1): "생각 중…" / "입력 중…". */
|
||||
botActivity?: Record<string, 'thinking' | 'typing'>;
|
||||
}
|
||||
|
||||
export interface GameResultView {
|
||||
|
||||
Reference in New Issue
Block a user