컴퓨터 플레이어 + 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);
|
||||
|
||||
Reference in New Issue
Block a user