컴퓨터 플레이어 + GPU 로컬 모델(gemma3:4b): 생각 중/입력 중 표시, 성격대로 채팅·도발·심리전, 바퀴벌레 포커 블러핑, 마피아 대사
- ai/llm.ts: Ollama 클라이언트(동시 2개·대기열·시간 제한·연속 실패 시 쉬기), 꺼져 있으면 예전처럼 조용히 둔다 - ai/lines.ts: 성격 5가지(도발·허세·차분·수다·소심)×말투(존댓말/반말), 한 줄 정리(외국어·AI 말·욕·링크 거르기) - ai/brain.ts: 수 두기 전 생각 중… → 가끔 입력 중…(타자 시간) → 채팅 → 수, 사람 수에 반응, 이름 부르면 대답, 시작·끝 한마디 바퀴벌레 포커: 진실/블러핑과 건네는 말을 모델이 정함. 마피아: 계획한 대사를 모델이 자기 말로(직업 주장은 버림) - RoomView.botActivity + 화면 표시(상태 줄, 채팅 칸), AI_URL/AI_MODEL 설정, /healthz에 ai 통계 - 테스트: 클라이언트·정리·방 동작(가짜 모델), 실제 GPU 모델 브라우저 E2E(e2e/ai.e2e.ts) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user