컴퓨터 플레이어 + 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:
EJClaw
2026-10-11 03:37:04 +09:00
parent 65a0f34d93
commit 13974181e7
17 changed files with 1030 additions and 5 deletions

View File

@@ -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