컴퓨터 채팅 고침: 부르면 매번 빨리 대답(느리거나 모델 없으면 내장 대답), 혼잣말은 판에서 눈에 띈 일에만 드물게, 수와 어긋난 말("풀 베팅인데 쫄았네") 거르고 수 종류별 한마디

- 대답: 이름·이어 말하기·대화 중인 컴퓨터에 매번 대답, 입력 중에 온 말은 끝나고 대답, 모델 2.5초만 기다리고 내장 대답, 한 사람에게 1분 8번까지
- 모델 대기열 1칸(GPU 하나), 대답이 혼잣말보다 먼저, 혼잣말은 바쁘면 버림, 타자 0.7~3.5초
- 혼잣말: 센 베팅·다이·고/스톱 등 눈에 띈 수에만, 방 40초·컴퓨터 90초 간격, 시작 인사·끼어들기 없앰, 수의 뜻과 판 공개 정보(판돈·칩·점수)를 모델에 줌
- 수 종류(센 베팅·콜·체크/삥·다이/폴드·과감·안전·기권)별 내장 한마디, 어긋나거나 게임과 상관없는 말은 그걸로 바꿈
- 막말·지시문 되풀이 거름, 마피아·라이어 게임은 계획된 대사만

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 13:11:41 +09:00
parent f620faf70b
commit 2136916a28
7 changed files with 1027 additions and 97 deletions

298
apps/server/src/ai/acts.ts Normal file
View File

@@ -0,0 +1,298 @@
/**
* What a move means, for the computers' talk (docs/06 §12.1): the model is told what someone did *and what it says
* about them* (풀 베팅 = 세게 나옴, 다이 = 물러섬), and a line that contradicts it ("풀 베팅이라니 쫄았네") is thrown
* away. Also the public facts of the table (칩·점수·카드 수) so the computers talk about this game, not in general.
*/
/** strong = 세게·자신 있게 나옴, weak = 물러섬·포기, careful = 조심·지켜봄, neutral = 그냥 둔 수. */
export type Tone = 'strong' | 'weak' | 'careful' | 'neutral';
/**
* What kind of event a move is, for the built-in lines: the betting moves each have their own (센 베팅 = raise,
* 콜 = call, 체크·삥 = check, 다이·폴드 = fold); other moves go by tone (bold = 고·론·우노 외침…, safe = 스톱·넘김,
* giveUp = 기권). neutral = an ordinary move (a stone, a card): no line of its own.
*/
export type ActKind = 'raise' | 'call' | 'check' | 'fold' | 'bold' | 'safe' | 'giveUp' | 'neutral';
export interface ActMeaning {
/** A few words for the move, e.g. "풀 베팅". */
ko: string;
/** What it means, for the model. */
mean?: string;
tone: Tone;
/** Worth a word on its own (big bets, giving up, 고/스톱, …). Ordinary moves never get one. */
notable: boolean;
kind: ActKind;
}
const TONE_KIND: Record<Tone, ActKind> = { strong: 'bold', weak: 'giveUp', careful: 'safe', neutral: 'neutral' };
const m = (ko: string, tone: Tone = 'neutral', notable = false, mean?: string, kind: ActKind = TONE_KIND[tone]): ActMeaning => ({
ko,
tone,
notable,
kind,
...(mean ? { mean } : {}),
});
const BET_TONE: Record<'raise' | 'call' | 'check' | 'fold', [Tone, boolean]> = {
raise: ['strong', true],
call: ['neutral', false],
check: ['careful', false],
fold: ['weak', true],
};
/** A betting move (섯다·포커): 센 베팅, 콜, 체크·삥, 다이·폴드. */
const bet = (ko: string, kind: keyof typeof BET_TONE, mean: string): ActMeaning => m(ko, BET_TONE[kind][0], BET_TONE[kind][1], mean, kind);
const FULL = '판돈만큼 더 거는 가장 센 베팅. 패에 자신 있거나 세게 블러핑하는 공격적인 수다(겁먹은 게 아니다)';
const HALF = '판돈의 절반을 더 걸며 크게 올림. 자신 있다는 뜻의 센 수다';
const DIE = '이번 판을 포기하고 패를 접음. 물러선 것이다';
const QUARTER = '판돈의 4분의 1을 더 걸며 올림. 세게 나온 수다';
const DDADANG = '앞사람 베팅의 두 배로 올림. 세게 나온 것';
const RAISE = '베팅을 올림. 자신 있다는 뜻의 센 수';
const ALL_IN = '가진 것을 전부 검. 가장 센 승부수(겁먹은 게 아니다)';
const CALL = '앞사람이 건 만큼 따라감. 승부를 받아들인 것';
const CHECK = '더 걸지 않고 지켜봄. 조심스러운 수';
const PING = '가장 작은 베팅으로 간을 봄. 조심스러운 수';
const GIVE_UP = '이 판을 포기함';
/** Any game, by action type. */
const COMMON: Record<string, ActMeaning> = {
place: m('돌을 놓음'), drop: m('돌을 떨어뜨림'), move: m('말을 움직임'), MOVE: m('말을 움직임'), placeWall: m('벽을 세움'), castle: m('캐슬링'),
play: m('카드를 냄'), discard: m('패를 버림'), DISCARD: m('패를 버림'), draw: m('패를 가져옴'), pass: m('넘김', 'careful'), PASS: m('넘김', 'careful'),
// 섯다 (한게임식 이름: 삥·콜·따당·쿼터·하프·풀·다이)
call: bet('콜', 'call', CALL),
check: bet('체크', 'check', CHECK),
ping: bet('삥', 'check', PING),
die: bet('다이', 'fold', DIE),
quarter: bet('쿼터 베팅', 'raise', QUARTER),
half: bet('하프 베팅', 'raise', HALF),
ddadang: bet('따당', 'raise', DDADANG),
full: bet('풀 베팅', 'raise', FULL),
raise: bet('레이즈', 'raise', RAISE),
allIn: bet('올인', 'raise', ALL_IN),
fold: bet('폴드', 'fold', DIE),
roll: m('주사위를 굴림'), ROLL: m('주사위를 굴림'), hold: m('주사위를 고정함'), score: m('점수를 적음'),
guess: m('추리함'), stop: m('추리를 멈춤', 'careful', true, '맞힌 뒤 더 노리지 않고 멈춤. 안전하게 간 것'),
continue: m('계속 추리', 'strong', true, '맞힌 뒤 멈추지 않고 한 번 더 노림. 과감한 수'),
offer: m('카드를 건넴'), peek: m('카드를 몰래 봄'), claim: m('선언함', 'strong', true), declare: m('선언함'),
tsumo: m('쯔모', 'strong', true, '직접 뽑은 패로 났음'), ring: m('종을 침', 'strong', true), flip: m('카드를 뒤집음'),
BUY: m('땅을 삼'), BUILD: m('건물을 지음'), sell: m('패를 팖'), SELL: m('땅을 팖', 'weak', false, undefined, 'neutral'),
TAKEOVER: m('땅을 인수함', 'strong', true, '남의 땅을 빼앗아 옴'),
THROW: m('윷을 던짐'), commit: m('타일을 내려놓음'), respond: m('대답함'), choose: m('골랐음'), vote: m('투표'),
declareOneCard: m('원카드를 외침', 'strong', true, '카드가 한 장 남았다'), callUno: m('우노를 외침', 'strong', true, '카드가 한 장 남았다'),
catchUno: m('우노 안 외친 사람을 잡음', 'strong', true), challenge: m('도전함', 'strong', true),
accuse: m('최종 추리를 함', 'strong', true, '범인을 확신하고 승부를 건 것'),
resign: m('기권', 'weak', true, GIVE_UP), concede: m('기권', 'weak', true, GIVE_UP), CONCEDE: m('기권', 'weak', true, GIVE_UP),
giveUp: m('포기', 'weak', true, GIVE_UP),
offerDraw: m('무승부를 제안함', 'careful', true), requestUndo: m('무르기를 부탁함', 'weak', true, undefined, 'neutral'),
// 포커 (한국식 / 노리밋)
'k.check': bet('체크', 'check', CHECK),
'k.ping': bet('삥', 'check', PING),
'k.call': bet('콜', 'call', CALL),
'k.ddadang': bet('따당', 'raise', DDADANG),
'k.quarter': bet('쿼터 베팅', 'raise', QUARTER),
'k.half': bet('하프 베팅', 'raise', HALF),
'k.full': bet('풀 베팅', 'raise', FULL),
'k.die': bet('다이', 'fold', DIE),
'nl.fold': bet('폴드', 'fold', DIE),
'nl.check': bet('체크', 'check', CHECK),
'nl.call': bet('콜', 'call', CALL),
'nl.raise': bet('레이즈', 'raise', RAISE),
'nl.allIn': bet('올인', 'raise', ALL_IN),
};
/** Every move type the computers know the meaning of (for tests). */
export const KNOWN_ACTIONS: readonly string[] = Object.keys(COMMON);
/** The meaning of `action` in `gameId` (payload-aware where one type covers opposite moves). */
export function meaningOf(gameId: string, action: unknown): ActMeaning {
const a = (action ?? {}) as { type?: string; decision?: string; call?: string; bet?: unknown; kind?: unknown; choice?: unknown };
const type = String(a.type ?? '');
if (gameId === 'gostop' && type === 'goStop') {
return a.decision === 'go'
? m('고', 'strong', true, '점수가 났는데 멈추지 않고 더 노림. 배짱 있는 수')
: m('스톱', 'careful', true, '점수를 확정하고 판을 끝냄. 안전하게 간 것');
}
if (gameId === 'mahjong' && type === 'claim') {
return a.call === 'ron' ? m('론', 'strong', true, '남이 버린 패로 났음') : m(`${a.call === 'pon' ? '퐁' : a.call === 'kan' ? '깡' : '치'}`, 'neutral');
}
if (gameId === 'dobble' && type === 'claim') return m('같은 그림을 찾음', 'strong');
if (gameId === 'davinci-code' && type === 'guess') return m('상대 숫자를 추리함');
if (COMMON[type]) return COMMON[type];
// One action type for every bet with the bet in the payload ({ type: 'bet', bet: 'half' }).
for (const k of [a.bet, a.kind, a.choice]) if (typeof k === 'string' && COMMON[k]) return COMMON[k];
return m('수를 둠');
}
// ---------------------------------------------------------------- contradictions
/** "겁먹었다", said about someone. */
const FEAR = /쫄(?!깃)|겁\s?(먹|쟁이|나서|났|나냐|나지)|무서(웠|워서|워\s*[?ㅋ]|우냐|운가|운\s?거|운\s?가)|떨(려|리|고\s?있)|소심|도망|꽁무니|엄살/;
/** "세게 나왔다", said about someone. */
const BOLD = /세게|세다|과감|질렀|지르|지른|배짱|대담|공격적|화끈|자신감|용감|올인|풀\s?베팅|풀베|크게\s?(걸|건|질|나)/;
/** "I'm scared / giving up", said about oneself while making a strong move. */
const SELF_WEAK = /포기|접을|접어야|무섭|무서워|겁나|떨려|자신\s?없/;
/** Bet names: a line naming another bet than the one made is talking about something that did not happen. */
const BET_WORDS: [string, RegExp][] = [
['다이', /다이/], ['콜', /콜(?!라)/], ['체크', /체크/], ['하프', /하프/], ['풀', /풀\s?(베팅|뱃|로)|풀베/], ['따당', /따당/],
['삥', /삥/], ['쿼터', /쿼터/], ['올인', /올인/], ['폴드', /폴드/], ['레이즈', /레이즈/],
];
const betNames = (s: string) => BET_WORDS.filter(([, re]) => re.test(s)).map(([w]) => w);
/**
* True when `line` says something the move contradicts. `mine` = the speaker made the move (taunting the others as
* scared is fine then); otherwise the line is about the person who moved. `known` = other move names that came up
* just before (a line may mention those).
*/
export function contradicts(line: string, meaning: ActMeaning, mine: boolean, known: string[] = []): boolean {
if (meaning.tone === 'strong' && (mine ? SELF_WEAK : FEAR).test(line)) return true;
if ((meaning.tone === 'weak' || meaning.tone === 'careful') && BOLD.test(line)) return true;
const own = betNames(meaning.ko);
if (!own.length) return false; // not a betting move: bet names don't apply
const ok = new Set([...own, ...known.flatMap(betNames)]);
return BET_WORDS.some(([w, re]) => re.test(line) && !ok.has(w));
}
// ---------------------------------------------------------------- built-in lines
type Pool = { smart: string[]; casual: string[] };
/**
* Built-in lines per kind of event, about someone else's move (`other`, `{who}` = that person) or one's own
* (`mine`); `{act}` = the move's name (콜, 하프 베팅, 다이…). Said when the model is slow, down, or wrote a line
* that contradicts the move — each one fits only its kind (no "쫄았네" on a raise, no "세게 나오네" on a fold;
* tests check every line against `contradicts`). Ordinary moves (`neutral`) have none.
*/
const LINES: Partial<Record<ActKind, { other: Pool; mine: Pool }>> = {
raise: {
other: {
casual: ['오 {who}, {act}? 세게 나오네 ㅋㅋ', '{act}? 패가 좋은가 보네 ㅋㅋ', '{who} 자신 있나 본데? 판이 커졌다 ㅋㅋ'],
smart: ['{who}님, {act}? 세게 나오시네요.', '{act}? 패가 좋으신가 봐요.', '{who}님 자신 있으신가 봐요. 판이 커졌네요.'],
},
mine: {
casual: ['{act} 간다! 따라올 수 있어? ㅋㅋ', '나는 {act}! 받을 거야? ㅋㅋ', '이번 판은 세게 간다 ㅋㅋ'],
smart: ['{act} 갈게요. 따라오실 건가요?', '저는 {act}! 받으실 건가요?', '이번 판은 세게 가 볼게요.'],
},
},
call: {
other: {
casual: ['{who}, {act} 받았네? 승부 보자는 거지 ㅋㅋ', '{act}? 좋아, 끝까지 가 보자 ㅋㅋ'],
smart: ['{who}님, {act} 받으셨네요. 승부 보시죠.', '{act}? 좋아요, 끝까지 가 봐요.'],
},
mine: {
casual: ['{act}! 어디 패 한번 보자 ㅋㅋ', '받아 줄게, {act}!'],
smart: ['{act}할게요. 패 한번 봐요.', '받아 드릴게요, {act}!'],
},
},
check: {
other: {
casual: ['{who}, {act}? 간 보는 거야? ㅋㅋ', '{act}? 조심하는데? ㅋㅋ'],
smart: ['{who}님, {act}? 간 보시는 건가요?', '{act}? 조심스럽게 가시네요.'],
},
mine: {
casual: ['일단 {act}. 천천히 가자 ㅋㅋ', '{act}! 아직은 지켜볼게'],
smart: ['일단 {act}할게요.', '{act}! 아직은 지켜볼게요.'],
},
},
fold: {
other: {
casual: ['{who} 이번엔 {act}? 다음 판에 보자 ㅋㅋ', '{act}? 현명한 선택일지도 ㅋㅋ'],
smart: ['{who}님은 이번엔 물러나시는군요.', '{act}? 다음 판을 노리시는군요.'],
},
mine: {
casual: ['이번 판은 {act}. 다음에 보자 ㅋㅋ', '아 이건 아니다, {act}!'],
smart: ['이번 판은 {act}할게요.', '이번엔 물러날게요. 다음 판에 봬요.'],
},
},
bold: {
other: {
casual: ['오 {who}, 과감한데? ㅋㅋ', '{who} 제법인데? 나도 질 수 없지 ㅋㅋ'],
smart: ['{who}님, 과감하시네요.', '{who}님 제법이신데요? 저도 질 수 없죠.'],
},
mine: {
casual: ['간다! 이번 판은 내가 가져간다 ㅋㅋ', '이 정도는 해 줘야지 ㅋㅋ'],
smart: ['가 볼게요! 이번엔 제가 가져갈게요.', '이 정도는 해 봐야죠.'],
},
},
safe: {
other: {
casual: ['{who}, 안전하게 가네? ㅋㅋ', '{who} 신중한데?'],
smart: ['{who}님, 안전하게 가시네요.', '{who}님 신중하시네요.'],
},
mine: {
casual: ['여기선 안전하게 갈게 ㅋㅋ', '욕심은 여기까지 ㅋㅋ'],
smart: ['여기선 안전하게 갈게요.', '욕심은 여기까지만 낼게요.'],
},
},
giveUp: {
other: {
casual: ['{who}, 이번 판은 여기까지야? 아쉽다', '{who} 다음 판에 또 하자 ㅋㅋ'],
smart: ['{who}님, 이번 판은 여기까지인가요?', '아쉽네요, 다음 판에 또 해요!'],
},
mine: {
casual: ['이번 판은 내가 졌다 ㅋㅋ 다음 판!', '여기까지! 다음 판에 보자'],
smart: ['이번 판은 제가 졌네요. 다음 판에 봬요.', '여기까지 할게요. 다음 판에 봬요.'],
},
},
};
/** Every built-in line for `meaning` (about `who`'s move, or one's own when `mine`); empty for ordinary moves. */
export function cannedLines(meaning: ActMeaning, who: string, smart: boolean, mine: boolean): string[] {
const pool = LINES[meaning.kind]?.[mine ? 'mine' : 'other'][smart ? 'smart' : 'casual'] ?? [];
return pool.map((l) => l.replaceAll('{who}', who).replaceAll('{act}', meaning.ko));
}
/** One built-in line for the move (null for ordinary moves). */
export function cannedLine(meaning: ActMeaning, who: string, smart: boolean, mine: boolean, random: () => number): string | null {
const all = cannedLines(meaning, who, smart, mine);
return all.length ? all[Math.floor(random() * all.length) % all.length]! : null;
}
// ---------------------------------------------------------------- facts
const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);
/**
* Public facts of the table as `bot` sees them, in short Korean: 판돈, each player's 칩/돈/점수/카드 수, who has
* folded. Read from the common shapes of the games' views (`seats`/`players` with ids, `money`, `sheets`, `pot`);
* hidden things (anyone's hand) are never read. Empty when the view has none of these.
*/
export function tableFacts(view: unknown, bot: string, nameOf: (id: string) => string): string[] {
if (!view || typeof view !== 'object') return [];
const v = view as Record<string, unknown>;
const out: string[] = [];
const pot = num(v.pot);
if (pot !== null && pot > 0) out.push(`판돈 ${pot}`);
const who = (id: string) => (id === bot ? `${nameOf(id)}(나)` : nameOf(id));
const rows = (Array.isArray(v.seats) ? v.seats : Array.isArray(v.players) ? v.players : []) as Record<string, unknown>[];
const per: string[] = [];
for (const r of rows) {
if (!r || typeof r !== 'object' || typeof r.id !== 'string') continue;
const bits: string[] = [];
const stack = num(r.stack);
if (stack !== null) bits.push(`칩 ${stack}`);
const cash = num(r.cash);
if (cash !== null) bits.push(`돈 ${cash}`);
const score = num(r.score) ?? num(r.total);
if (score !== null) bits.push(`${score}점`);
const cards = num(r.cards) ?? num(r.handCount);
if (cards !== null) bits.push(`카드 ${cards}장`);
const tiles = num(r.tiles);
if (tiles !== null) bits.push(`타일 ${tiles}장`);
if (r.folded === true) bits.push('다이함');
if (r.allIn === true) bits.push('올인함');
if (bits.length) per.push(`${who(r.id)} ${bits.join(' ')}`);
}
for (const [key, label] of [['money', '돈'], ['sheets', '점']] as const) {
const rec = v[key];
if (!per.length && rec && typeof rec === 'object' && !Array.isArray(rec)) {
for (const [id, x] of Object.entries(rec as Record<string, unknown>)) {
const n = num(x) ?? num((x as { total?: unknown } | null)?.total);
if (n !== null) per.push(label === '점' ? `${who(id)} ${n}점` : `${who(id)} 돈 ${n}`);
}
}
}
if (per.length) out.push(per.slice(0, 6).join(', '));
return out;
}

View File

@@ -6,7 +6,8 @@ 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 { cannedLines, contradicts, KNOWN_ACTIONS, meaningOf, tableFacts, type ActKind } from './acts';
import { ANSWERS_PER_MINUTE, BotBrain, TALK_BOT_GAP, TALK_ROOM_GAP, type BrainRoom } from './brain';
import { cleanLine, temperOf, TEMPERS } from './lines';
import { Llm } from './llm';
@@ -109,7 +110,7 @@ function harness(reply: (user: string, body: { format?: unknown }) => string | E
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 () => {
test('omok: the computer thinks (visible) and moves; an ordinary move gets no word on its own (신고: 혼잣말)', async () => {
const h = harness((u) => (u.includes('할 말') ? '흐음, 여기 두면 아프겠는데?' : '좋아'));
const room = h.manager.createPractice('A', 'omok') as Room;
rooms.push(room);
@@ -118,19 +119,18 @@ describe('rooms with the model', () => {
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' }, botChat: true });
expect(room.start('A')).toBeNull();
await settle();
h.clock.advance(TALK_BOT_GAP);
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);
// No greeting, no word with a stone: the model was only warmed up.
expect(a.msgs.some((m) => m.t === 'chat')).toBe(false);
expect(h.prompts.every((p) => !p.includes('할 말'))).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 () => {
@@ -266,11 +266,402 @@ describe('rooms with the model', () => {
});
});
test('BotBrain typing time grows with the line and stays human (0.9~6.5 s)', () => {
test('BotBrain typing time grows with the line and stays quick (0.7~3.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(short).toBeGreaterThanOrEqual(700);
expect(long).toBeGreaterThan(short);
expect(long).toBeLessThanOrEqual(6500);
for (let i = 0; i < 50; i++) expect(brain.typingMs(`bot:${i}:x`, '가'.repeat(40))).toBeLessThanOrEqual(3500);
});
// ---------------------------------------------------------------- talking (fake room, fake model)
/**
* A BotBrain on a fake room: 철수 (A) with `bots` computers at 섯다. The model answers with `reply(prompt)`. Typing
* advances the room clock; `hold` keeps a computer typing until `release()`.
*/
function talkHarness(
reply: (user: string) => string | Error,
opts: { bots?: number; humans?: string[]; random?: () => number; game?: string; llm?: (fetchFn: typeof fetch) => Llm | null } = {},
) {
let now = 1_000_000;
const bots = Array.from({ length: opts.bots ?? 2 }, (_, i) => `bot:${i + 1}:x`);
const humans = opts.humans ?? ['A'];
const chats: { from: string; text: string; at: number }[] = [];
const activity: { bot: string; a: string | null; at: number }[] = [];
let hold: Promise<void> | null = null;
let release = () => {};
const { fetchFn, prompts } = fakeOllama((u) => reply(u));
const llm = opts.llm ? opts.llm(fetchFn) : new Llm({ url: 'http://gpu', model: 'gemma3:4b', fetch: fetchFn });
const view = { pot: 120, seats: [{ id: 'A', stack: 800, folded: false }, ...bots.map((b) => ({ id: b, stack: 500, folded: false }))] };
const room: BrainRoom = {
gameId: () => opts.game ?? 'seotda',
gameName: () => '섯다',
nameOf: (id) => (id === 'A' ? '철수' : id === 'B' ? '영희' : `컴퓨터 ${id.split(':')[1]}`),
humans: () => humans,
bots: () => bots,
playing: () => true,
roomChat: (bot, text) => void chats.push({ from: bot, text, at: now }),
setActivity: (bot, a) => void activity.push({ bot, a, at: now }),
recentChat: () => chats.slice(-8).map((c) => ({ from: c.from, text: c.text })),
smart: () => false,
chatty: () => true,
now: () => now,
view: () => view,
};
const brain = new BotBrain(room, llm, opts.random ?? (() => 0), async (ms) => {
now += ms;
if (hold) await hold;
});
return {
brain,
bots,
chats,
activity,
prompts,
advance: (ms: number) => (now += ms),
now: () => now,
holdTyping: () => {
hold = new Promise<void>((r) => (release = () => ((hold = null), r())));
},
release: () => release(),
/** Lets the fake model and typing finish. */
flush: async () => {
for (let i = 0; i < 12; i++) await new Promise((r) => setImmediate(r));
},
};
}
describe('answering people (신고: 한 번 답하고 그 뒤로 답장이 없음)', () => {
test('every message to a computer gets an answer — named once, then just talking to it', async () => {
let n = 0;
// random 0.99: nothing is left to chance (the old code answered an unnamed line only 40% of the time).
const h = talkHarness(() => `대답 ${++n}번째 ㅋㅋ`, { random: () => 0.99 });
const msgs = ['컴퓨터1 뒤질래?', '왜 대답 안해', 'ㅋㅋ 너 지금 쫄았지?', '야', '이번 판 누가 이길 것 같아?'];
for (const text of msgs) {
h.brain.onHumanChat('A', text);
await h.flush();
h.advance(4000);
}
expect(h.chats.map((c) => c.from)).toEqual(msgs.map(() => 'bot:1:x'));
expect(h.chats).toHaveLength(msgs.length);
// Each prompt carries the person's message.
for (const text of msgs) expect(h.prompts.some((p) => p.includes(text))).toBe(true);
});
test('a message while the computer is typing is answered right after it, not dropped; a burst gets one answer', async () => {
const h = talkHarness((u) => (u.includes('뒤질래') ? '어휴 무섭네 ㅋㅋ' : u.includes('세 번째') ? '세 번째에 대답 ㅋㅋ' : '첫 마디 ㅋㅋ'));
h.holdTyping();
h.brain.onHumanChat('A', '컴퓨터 1 안녕');
await h.flush();
expect(h.chats).toHaveLength(0); // still typing
h.brain.onHumanChat('A', '컴퓨터1 뒤질래?');
h.brain.onHumanChat('A', '컴퓨터1 두 번째');
h.brain.onHumanChat('A', '컴퓨터1 세 번째');
h.release();
await h.flush();
expect(h.chats.map((c) => c.text)).toEqual(['첫 마디 ㅋㅋ', '세 번째에 대답 ㅋㅋ']);
});
test('the model writes something unusable (rude, echo): the computer still answers, with a safe line', async () => {
const h = talkHarness(() => '철수 이 망할 놈! 닥쳐 ㅋㅋ');
h.brain.onHumanChat('A', '컴퓨터1 뒤질래?');
await h.flush();
expect(h.chats).toHaveLength(1);
expect(h.chats[0]!.text).not.toMatch(/놈|닥쳐/);
});
test('with two people, an unnamed line is not taken as talking to a computer (unless it answers one)', async () => {
const h = talkHarness(() => '응 ㅋㅋ', { humans: ['A', 'B'], random: () => 0.99 });
h.brain.onHumanChat('A', '영희야 이번 판 어때');
await h.flush();
expect(h.chats).toHaveLength(0);
h.brain.onHumanChat('A', '컴퓨터 2 너는?');
await h.flush();
expect(h.chats.map((c) => c.from)).toEqual(['bot:2:x']);
h.advance(5000);
h.brain.onHumanChat('B', 'ㅋㅋ 진짜?'); // right after 컴퓨터 2 spoke: an answer to it
await h.flush();
expect(h.chats.map((c) => c.from)).toEqual(['bot:2:x', 'bot:2:x']);
});
test('quick: "입력 중…" shows at once, a short answer is up within 3 s and a long one within 3.5 s', async () => {
for (const [line, limit] of [['ㅋㅋ 내가 이기지', 3000], ['이번 판은 칩 많은 내가 무조건 가져간다 각오해 ㅋㅋ', 3500]] as const) {
const h = talkHarness(() => line);
const t0 = h.now();
h.brain.onHumanChat('A', '컴퓨터1 누가 이겨?');
// Before the model has answered: typing already shows.
expect(h.activity[0]).toEqual({ bot: 'bot:1:x', a: 'typing', at: t0 });
await h.flush();
expect(h.chats).toHaveLength(1);
expect(h.chats[0]!.at - t0).toBeLessThanOrEqual(limit);
}
});
});
describe('answering without a quick model (신고: 답장이 느림)', () => {
test('no model at all: every message to a computer still gets a fitting built-in answer, fast', async () => {
const h = talkHarness(() => 'x', { llm: () => null });
const msgs = ['컴퓨터1 뒤질래?', '왜 대답 안해', '컴퓨터1 안녕', '이번 판 누가 이길 것 같아?'];
for (const text of msgs) {
const t0 = h.now();
h.brain.onHumanChat('A', text);
await h.flush();
expect(h.chats.at(-1)!.at - t0).toBeLessThanOrEqual(3500);
h.advance(4000);
}
expect(h.chats.map((c) => c.from)).toEqual(msgs.map(() => 'bot:1:x'));
const [jab, , hello, question] = h.chats.map((c) => c.text);
expect(['ㅋㅋ 말로 하지 말고 게임으로 해!', '워워~ 판에서 보자 ㅋㅋ']).toContain(jab!);
expect(['ㅎㅇ! 잘 해 보자 ㅋㅋ', '안녕~ 한 판 붙자!']).toContain(hello!);
expect(['ㅋㅋ 글쎄~ 두고 봐', '비밀이지롱~', '끝나 보면 알겠지 ㅋㅋ']).toContain(question!);
for (const c of h.chats) expect(cleanLine(c.text)).toBe(c.text);
});
test('a hung model: the built-in answer is up within the wait (2.5 s), not after the model gives up', 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 h = talkHarness(() => 'x', { llm: () => new Llm({ url: 'http://gpu', model: 'm', fetch: hang, timeoutMs: 3000 }) });
const t0 = Date.now();
h.brain.onHumanChat('A', '컴퓨터1 뭐해?');
for (let i = 0; i < 400 && !h.chats.length; i++) await new Promise((r) => setTimeout(r, 10));
expect(h.chats).toHaveLength(1);
expect(Date.now() - t0).toBeLessThan(2900);
expect(h.activity[0]!.a).toBe('typing'); // "입력 중…" from the start
});
test('a flood is cut off: at most a few answers a minute to one person', async () => {
const h = talkHarness(() => '응 ㅋㅋ');
for (let i = 0; i < 40; i++) {
h.brain.onHumanChat('A', `컴퓨터1 ${i}`);
await h.flush();
h.advance(1500);
}
expect(h.chats.length).toBeGreaterThanOrEqual(ANSWERS_PER_MINUTE);
expect(h.chats.length).toBeLessThanOrEqual(ANSWERS_PER_MINUTE * 2);
});
test('two people: after a computer answered, the next line is an answer to it — later lines between people are not', async () => {
const h = talkHarness(() => '응 ㅋㅋ', { humans: ['A', 'B'], random: () => 0.99 });
h.brain.onHumanChat('A', '컴퓨터 2 너는?');
await h.flush();
h.advance(3000);
h.brain.onHumanChat('B', 'ㅋㅋ 진짜?');
await h.flush();
expect(h.chats).toHaveLength(2);
h.advance(1000);
h.brain.onHumanChat('A', '영희야 우리 둘이 하자');
h.brain.onHumanChat('B', '그래 좋아');
await h.flush();
expect(h.chats).toHaveLength(2);
});
});
describe('talking on its own (신고: 게임과 상관없는 혼잣말만 엄청함)', () => {
test('rare: over 10 minutes of busy play at most one line per 40 s in the room and per 90 s per computer', async () => {
const h = talkHarness(() => '판돈 커졌네 ㅋㅋ 받아줄게');
for (let t = 0; t < 600_000; t += 2000) {
h.brain.onAction('A', { type: t % 4000 ? 'half' : 'call' });
for (const b of h.bots) await h.brain.beforeMove(b, { type: 'full' }, {});
await h.flush();
h.advance(2000);
}
const lines = h.chats.length;
expect(lines).toBeGreaterThan(0);
expect(lines).toBeLessThanOrEqual(Math.ceil(700_000 / TALK_ROOM_GAP));
for (const b of h.bots) expect(h.chats.filter((c) => c.from === b).length).toBeLessThanOrEqual(Math.ceil(700_000 / TALK_BOT_GAP));
for (let i = 1; i < h.chats.length; i++) expect(h.chats[i]!.at - h.chats[i - 1]!.at).toBeGreaterThanOrEqual(TALK_ROOM_GAP - 4000);
});
test("a person's ordinary move never gets a word on its own", async () => {
const h = talkHarness(() => '판돈 커졌네 ㅋㅋ');
for (let i = 0; i < 30; i++) {
h.brain.onAction('A', { type: 'call' });
h.brain.onAction('A', { type: 'check' });
await h.flush();
h.advance(30_000);
}
expect(h.chats).toHaveLength(0);
});
test('the prompt has the facts: who did what, what it means, the pot and stacks', async () => {
const h = talkHarness(() => '오 철수 세게 나오네 ㅋㅋ');
h.brain.onAction('A', { type: 'full' });
await h.flush();
const p = h.prompts.at(-1)!;
expect(p).toContain('철수: 풀 베팅 — 판돈만큼 더 거는 가장 센 베팅');
expect(p).toContain('판돈 120');
expect(p).toContain('컴퓨터 1(나) 칩 500');
expect(h.chats.map((c) => c.text)).toEqual(['오 철수 세게 나오네 ㅋㅋ']);
});
test('a line about nothing in this game ("다들 준비됐냐?") is not said: a line for the move is said instead', async () => {
const h = talkHarness(() => '흥, 또 시작이네 ㅋㅋ 다들 준비됐냐?');
await h.brain.beforeMove('bot:1:x', { type: 'full' }, {});
h.advance(TALK_ROOM_GAP);
h.brain.onAction('A', { type: 'die' });
await h.flush();
expect(h.chats.map((c) => c.text)).toEqual([
cannedLines(meaningOf('seotda', { type: 'full' }), '컴퓨터 1', false, true)[0]!,
cannedLines(meaningOf('seotda', { type: 'die' }), '철수', false, false)[0]!,
]);
expect(h.chats.some((c) => c.text.includes('준비'))).toBe(false);
});
test('without the model the computers play silently; a notable move gets a word only while the model is up', async () => {
const h = talkHarness(() => new Error('down'));
for (let i = 0; i < 4; i++) {
h.brain.onAction('A', { type: 'full' });
await h.flush();
h.advance(TALK_BOT_GAP);
}
// The model failed three times and is backing off: no more words on its own (the first ones were built-in lines).
const said = h.chats.length;
expect(said).toBeLessThanOrEqual(3);
for (const c of h.chats) expect(cannedLines(meaningOf('seotda', { type: 'full' }), '철수', false, false)).toContain(c.text);
h.brain.onAction('A', { type: 'full' });
await h.flush();
expect(h.chats).toHaveLength(said);
});
});
describe('lines that contradict the move (신고: 풀 베팅인데 "쫄았네")', () => {
test('풀 베팅 → "쫄았네" is thrown away and a safe line said instead; 다이 → "세게 나오네" likewise', async () => {
const h = talkHarness(() => 'ㅋㅋ 풀 베팅이라니, 완전 쫄앗네 풉!');
h.brain.onAction('A', { type: 'full' });
await h.flush();
expect(h.chats.map((c) => c.text)).toEqual(['오 철수, 풀 베팅? 세게 나오네 ㅋㅋ']);
const d = talkHarness(() => '철수 오늘 세게 나오네 ㅋㅋ');
d.brain.onAction('A', { type: 'die' });
await d.flush();
expect(d.chats.map((c) => c.text)).toEqual(['철수 이번엔 다이? 다음 판에 보자 ㅋㅋ']);
});
test('my own 풀 베팅 with "무섭다, 포기할까" or a wrong bet name is not said (a line for a raise is)', async () => {
for (const bad of ['아 무섭다 그냥 포기할까 ㅋㅋ', '다이할게 판돈 가져가라 ㅋㅋ']) {
const h = talkHarness(() => bad);
await h.brain.beforeMove('bot:1:x', { type: 'full' }, {});
await h.flush();
expect(h.chats.map((c) => c.text)).toEqual(['풀 베팅 간다! 따라올 수 있어? ㅋㅋ']);
}
});
test('each kind of move has its own lines, and every line fits only its kind (no "쫄" on a raise)', () => {
const kinds: Record<string, ActKind> = {
half: 'raise', full: 'raise', ddadang: 'raise', quarter: 'raise', 'k.half': 'raise', 'k.full': 'raise', 'k.ddadang': 'raise',
'nl.raise': 'raise', 'nl.allIn': 'raise', call: 'call', 'k.call': 'call', 'nl.call': 'call',
check: 'check', ping: 'check', 'k.check': 'check', 'k.ping': 'check', 'nl.check': 'check', die: 'fold', 'k.die': 'fold', 'nl.fold': 'fold',
};
for (const [type, kind] of Object.entries(kinds)) expect([type, meaningOf('seotda', { type }).kind]).toEqual([type, kind]);
// A rebuilt game may put the bet in the payload.
expect(meaningOf('seotda', { type: 'bet', bet: 'half' }).kind).toBe('raise');
expect(meaningOf('seotda', { type: 'bet', kind: 'die' }).kind).toBe('fold');
const SCARED = /쫄|겁|무서|소심|도망|엄살|떨/;
const BRAVE = /세게|과감|질렀|배짱|화끈|자신|올인|풀\s?베팅/;
const metas = [
...KNOWN_ACTIONS.map((type) => meaningOf('seotda', { type })),
meaningOf('gostop', { type: 'goStop', decision: 'go' }),
meaningOf('gostop', { type: 'goStop', decision: 'stop' }),
meaningOf('mahjong', { type: 'claim', call: 'ron' }),
];
let checked = 0;
for (const meaning of metas) {
for (const smart of [true, false]) {
for (const mine of [true, false]) {
const lines = cannedLines(meaning, '철수', smart, mine);
// Notable moves always have a fitting line (unless deliberately neutral); ordinary moves never get one.
if (meaning.kind === 'neutral') expect(lines).toEqual([]);
else expect(lines.length).toBeGreaterThan(1);
for (const line of lines) {
checked++;
expect([meaning.ko, line, contradicts(line, meaning, mine)]).toEqual([meaning.ko, line, false]);
expect(cleanLine(line, 40)).toBe(line);
if (meaning.kind === 'raise' || meaning.kind === 'bold') expect([meaning.ko, line, SCARED.test(line)]).toEqual([meaning.ko, line, false]);
if (['fold', 'check', 'safe', 'giveUp', 'call'].includes(meaning.kind)) expect([meaning.ko, line, BRAVE.test(line)]).toEqual([meaning.ko, line, false]);
// A 존댓말 computer never talks down.
if (smart) expect(line).toMatch(/요|죠/);
}
}
}
}
expect(checked).toBeGreaterThan(150);
});
test('every kind of bet, with the model writing the opposite: the line said fits the bet', async () => {
const wrong: Record<string, string> = {
full: 'ㅋㅋ 풀 베팅이라니, 완전 쫄았네 풉!',
half: '겁먹었구나 철수 ㅋㅋ 하프 베팅',
ddadang: '따당? 떨고 있네 ㅋㅋ',
die: '다이? 와 과감하게 질렀네 ㅋㅋ',
check: '체크? 화끈하게 지르네 ㅋㅋ',
ping: '삥이라니 배짱 좋네 ㅋㅋ',
};
for (const [type, bad] of Object.entries(wrong)) {
const h = talkHarness(() => bad);
h.brain.onAction('A', { type });
await h.flush();
const meaning = meaningOf('seotda', { type });
if (!meaning.notable) {
expect(h.chats).toHaveLength(0); // 체크·삥: ordinary, no word at all
continue;
}
expect(h.chats).toHaveLength(1);
expect(cannedLines(meaning, '철수', false, false)).toContain(h.chats[0]!.text);
}
});
test('rules: who made the move matters; other games are not judged by bet names', () => {
const full = meaningOf('seotda', { type: 'full' });
const die = meaningOf('seotda', { type: 'die' });
expect(contradicts('ㅋㅋ 풀 베팅이라니, 완전 쫄앗네 풉!', full, false)).toBe(true);
expect(contradicts('겁먹었냐? ㅋㅋ', full, false)).toBe(true);
expect(contradicts('내 풀 베팅에 쫄았지? ㅋㅋ', full, true)).toBe(false); // my big bet, the others scared: fine
expect(contradicts('오 세게 나오네 판돈 커졌다', full, false)).toBe(false);
expect(contradicts('벌써 다이야? 쫄았구나 ㅋㅋ', die, false)).toBe(false);
expect(contradicts('와 과감하게 질렀네', die, false)).toBe(true);
expect(contradicts('하프 베팅이라니 대단해', full, false)).toBe(true); // a bet that wasn't made
expect(contradicts('하프 받고 풀 베팅 간다', full, true, ['하프 베팅'])).toBe(false); // it was, just before
expect(contradicts('여기 두면 아프겠는데? 체크야', meaningOf('omok', { type: 'place' }), true)).toBe(false);
expect(meaningOf('poker', { type: 'k.full' }).tone).toBe('strong');
expect(meaningOf('gostop', { type: 'goStop', decision: 'go' }).ko).toBe('고');
expect(meaningOf('gostop', { type: 'goStop', decision: 'stop' }).tone).toBe('careful');
});
test('table facts read only public numbers (stacks, scores, card counts), never a hand', () => {
const names = (id: string) => (id === 'A' ? '철수' : '컴퓨터 1');
expect(tableFacts({ pot: 30, seats: [{ id: 'A', stack: 990, folded: true, cards: [{ hidden: true }] }, { id: 'bot:1:x', stack: 980 }], myHand: { name: '38광땡' } }, 'bot:1:x', names)).toEqual([
'판돈 30',
'철수 칩 990 다이함, 컴퓨터 1(나) 칩 980',
]);
expect(tableFacts({ seats: [{ id: 'A', cards: 3, score: 10 }] }, 'bot:1:x', names)).toEqual(['철수 10점 카드 3장']);
expect(tableFacts({ sheets: { A: { total: 120 } } }, 'bot:1:x', names)).toEqual(['철수 120점']);
expect(tableFacts(null, 'bot:1:x', names)).toEqual([]);
});
});
describe('Llm queue (one GPU slot)', () => {
test('one request at a time; an answer to a person goes ahead of waiting talk; talk is dropped when busy', async () => {
const order: string[] = [];
let open = 0;
let maxOpen = 0;
const fetchFn = (async (_u: string, init: RequestInit) => {
const body = JSON.parse(String(init.body)) as { messages: { content: string }[]; options: { stop?: string[] } };
open++;
maxOpen = Math.max(maxOpen, open);
await new Promise((r) => setTimeout(r, 5));
order.push(body.messages[0]!.content);
open--;
return new Response(JSON.stringify({ message: { content: 'ok' } }));
}) as unknown as typeof fetch;
const llm = new Llm({ url: 'http://x', model: 'm', fetch: fetchFn });
const first = llm.chat([{ role: 'user', content: 'first' }]);
const normal = llm.chat([{ role: 'user', content: 'normal' }]);
const answer = llm.chat([{ role: 'user', content: 'answer' }], { priority: 'high' });
expect(await llm.chat([{ role: 'user', content: 'talk' }], { priority: 'low' })).toBeNull();
await Promise.all([first, normal, answer]);
expect(order).toEqual(['first', 'answer', 'normal']);
expect(maxOpen).toBe(1);
});
});

View File

@@ -3,8 +3,13 @@
*
* - 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.
* - They talk in character (도발형·허세형·차분형·수다형·소심형, 존댓말/반말). A person who talks to a computer (by
* name, by answering what it just said, or as the only computer at the table) always gets an answer within a few
* seconds — the model's if it is quick, a built-in one if it is slow, busy or down (a flood is cut off).
* - On their own they speak rarely and only about what just happened at this table (a big bet, someone folding,
* 고/스톱…; never an ordinary move, never a greeting or small talk), with the move's meaning and the table's public
* facts in the prompt. A line that contradicts the move ("풀 베팅이라니 쫄았네") or is about nothing in this game
* is replaced with a built-in line made for that kind of move (acts.ts).
* - 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
@@ -13,6 +18,8 @@
*/
import { secureRandom } from '@bg/engine';
import { botPace, hash01 } from '@bg/games/bots';
import { botChatRequired } from '@bg/shared';
import { cannedLine, contradicts, meaningOf, tableFacts, type ActMeaning } from './acts';
import type { Llm } from './llm';
import { cleanLine, decide, temperOf, writeLine, type LineRequest } from './lines';
@@ -38,26 +45,78 @@ export interface BrainRoom {
*/
chatty(): boolean;
now(): number;
/** What `viewer` sees of the running game (public facts for the prompt); null outside a game. */
view?(viewer: string): unknown;
}
/** 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: '투표',
};
/** Talking on its own: at most one line per room every 40 s, and per computer every 90 s. */
export const TALK_ROOM_GAP = 40_000;
export const TALK_BOT_GAP = 90_000;
/** A person keeps talking with the computer that answered them this long without naming it again (1 person rooms). */
export const CONVERSATION_MS = 60_000;
/** A line right after a computer's line is an answer to it. */
const REPLY_MS = 20_000;
/** Chance a computer reacts to a person's notable move (big bet, folding, 고, …) when it may talk. */
const REACT_P = 0.3;
/** How long an answer waits for the model before a built-in one is said instead. */
export const ANSWER_WAIT_MS = 2500;
/** A word about a move is dropped after this long (the game has moved on). */
const TALK_WAIT_MS = 4000;
/** Answers to one person: at most this many a minute (someone flooding a computer is not answered line by line). */
export const ANSWERS_PER_MINUTE = 8;
/** Built-in answers (the model slow, busy, down, or its line unusable): by what the person said. */
const QUICK_ANSWER: { test: RegExp; smart: string[]; casual: string[] }[] = [
{ test: /안녕|ㅎㅇ|하이|반가/, smart: ['안녕하세요! 잘 부탁드려요.', '반가워요! 재밌게 해 봐요.'], casual: ['ㅎㅇ! 잘 해 보자 ㅋㅋ', '안녕~ 한 판 붙자!'] },
{
test: /뒤질|뒤져|죽을|죽여|쫄|겁|덤벼|이길\s?수|못\s?하|약하|ㅗ|ㅄ|\*{2,}/,
smart: ['하하, 실력으로 답해 드릴게요.', '말보다 게임으로 보여 드릴게요.'],
casual: ['ㅋㅋ 말로 하지 말고 게임으로 해!', '워워~ 판에서 보자 ㅋㅋ'],
},
{
test: /\?|뭐|왜|누가|누구|어때|어떻게|몇|언제|할래|하냐|했냐|맞지|맞아/,
smart: ['글쎄요, 두고 보시죠!', '음… 그건 비밀이에요.', '판이 끝나 보면 알겠죠?'],
casual: ['ㅋㅋ 글쎄~ 두고 봐', '비밀이지롱~', '끝나 보면 알겠지 ㅋㅋ'],
},
{ test: /[\s\S]/, smart: ['하하, 그러게요.', '네, 계속 해 봐요!'], casual: ['ㅋㅋ 그치', 'ㅇㅋ 계속 가자!'] },
];
/** Waits for `p` at most `ms` (real time): null after that. */
function withDeadline<T>(p: Promise<T | null>, ms: number): Promise<T | null> {
let timer: ReturnType<typeof setTimeout> | undefined;
const late = new Promise<null>((r) => (timer = setTimeout(() => r(null), ms)));
return Promise.race([p.catch(() => null), late]).finally(() => clearTimeout(timer));
}
/** Words that tie a line to the game (a line on its own must mention the move, a player or one of these). */
const GAME_WORDS = /판돈|베팅|칩|점수|\d+점|패|카드|돌|주사위|윷|족보|땅|타일|보석|차례|이번 판|한 판|수(?![가-힣])|여기|두면|둬|둔다|놓/;
const sleepReal = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
interface Happening {
actor: string;
meaning: ActMeaning;
}
export class BotBrain {
private lastRoomLine = -Infinity;
private lastBotLine = new Map<string, number>();
private happened: string[] = [];
private happened: Happening[] = [];
/** Showing "입력 중…". */
private typing = new Set<string>();
/** Writing or typing an answer, or typing a line: a new message to it waits in `pending`. */
private busy = new Set<string>();
/** The latest message to a busy computer, answered as soon as it is free. */
private pending = new Map<string, { from: string; text: string; reply: boolean }>();
/** Who each person is talking with. */
private partner = new Map<string, { bot: string; at: number }>();
private lastSpeaker: { bot: string; at: number } | null = null;
/** When a person last chatted (a line after it is not an answer to a computer's earlier line). */
private lastHumanChat = -Infinity;
/** When each person was last answered (for the flood limit). */
private answered = new Map<string, number[]>();
/** The last built-in answer of each computer (not said twice in a row). */
private lastQuick = new Map<string, string>();
constructor(
private room: BrainRoom,
@@ -71,27 +130,53 @@ export class BotBrain {
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). */
/** Games whose computers talk by their own plan (마피아, 라이어 게임): no small talk or answers from here. */
private planned(): boolean {
return botChatRequired(this.room.gameId());
}
/**
* Answers to people work in and out of a game (lobby, result screen) while the computers sit in the room, and
* without the model too (built-in answers): someone who talks to a computer is never left without a word.
*/
private canAnswer(): boolean {
return this.room.chatty() && !this.planned() && this.room.humans().length > 0 && this.room.bots().length > 0;
}
/**
* How long `bot` takes to type `text` (each computer types at its own speed): 8~16 characters a second, at least
* 0.7 s and at most 3.5 s, so a short answer is up within 1~3 s of the question (the model's time counts toward it).
*/
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)));
const perChar = (60 + 40 * hash01(bot, 'typing')) * botPace(bot);
return Math.round(Math.min(3500, Math.max(700, [...text].length * perChar)));
}
thinking(bot: string, on: boolean): void {
if (!this.typing.has(bot)) this.room.setActivity(bot, on ? 'thinking' : null);
}
private showTyping(bot: string, on: boolean): void {
if (on) this.typing.add(bot);
else this.typing.delete(bot);
this.room.setActivity(bot, on ? 'typing' : 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');
async type(bot: string, text: string, send: () => void, needPlaying = true, alreadyMs = 0): Promise<void> {
this.busy.add(bot);
this.showTyping(bot, true);
try {
await this.sleep(this.typingMs(bot, text));
await this.sleep(Math.max(0, this.typingMs(bot, text) - alreadyMs));
} finally {
this.typing.delete(bot);
this.room.setActivity(bot, null);
this.showTyping(bot, false);
this.busy.delete(bot);
}
if (!needPlaying || this.room.playing()) send();
if (!needPlaying || this.room.playing()) {
send();
this.lastSpeaker = { bot, at: this.room.now() };
}
this.answerPending(bot);
}
private request(bot: string, situation: string, task: string, extra: Partial<LineRequest> = {}): LineRequest {
@@ -107,9 +192,10 @@ export class BotBrain {
};
}
private canTalk(bot: string, roomGap = 8000, botGap = 20_000): boolean {
/** May talk on its own: rare (room and computer gaps) and never while busy. */
private canTalk(bot: string): boolean {
const now = this.room.now();
return now - this.lastRoomLine >= roomGap && now - (this.lastBotLine.get(bot) ?? -Infinity) >= botGap && !this.typing.has(bot);
return now - this.lastRoomLine >= TALK_ROOM_GAP && now - (this.lastBotLine.get(bot) ?? -Infinity) >= TALK_BOT_GAP && !this.busy.has(bot);
}
private spoke(bot: string): void {
@@ -118,30 +204,63 @@ export class BotBrain {
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 {
/** What is going on, as facts: the last moves with what they mean, and the table (칩·점수·카드 수). */
private situation(bot: string): string {
const parts: string[] = [];
const last = this.happened.slice(-4);
return last.length ? `최근: ${last.join(', ')}` : '게임이 막 시작됐다';
if (last.length) {
const said = last.map((h, i) => `${this.room.nameOf(h.actor)}${h.actor === bot ? '(나)' : ''}: ${h.meaning.ko}${i === last.length - 1 && h.meaning.mean ? ` — ${h.meaning.mean}` : ''}`);
parts.push(`방금 일어난 일(오래된 것부터): ${said.join(' / ')}`);
} else parts.push('게임이 막 시작됐다');
let view: unknown = null;
try {
view = this.room.view?.(bot) ?? null;
} catch {
view = null;
}
const facts = tableFacts(view, bot, (id) => this.room.nameOf(id));
if (facts.length) parts.push(`지금 판: ${facts.join(' / ')}`);
return parts.join('\n');
}
/** Someone played: remembered for the computers' sense of the game; now and then a computer reacts to a person. */
/** Move names that came up just before (a line may mention those). */
private known(): string[] {
return this.happened.slice(-3).map((h) => h.meaning.ko);
}
/** A line said on its own must be about this game: the move, a player, or a game word. */
private relevant(line: string, meaning: ActMeaning | null, people: string[]): boolean {
if (GAME_WORDS.test(line)) return true;
if (people.some((p) => p && (line.includes(p) || line.includes(p.replace(/\s/g, ''))))) return true;
// "카드를 뒤집음" → 카드, 뒤집; a stem shorter than two letters is not used ("다이" → "다" would match "다들").
const stems = (meaning?.ko ?? '').split(' ').map((w) => {
const stem = w.replace(/(을|를|이|가|은|는|음|함)$/, '');
return stem.length >= 2 ? stem : w;
});
return stems.some((w) => line.includes(w));
}
/** Someone played: remembered for the computers' sense of the game; a notable move by a person may get a word. */
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] ?? '행동함'}`);
const meaning = meaningOf(this.room.gameId(), action);
this.happened.push({ actor, meaning });
if (this.happened.length > 12) this.happened.shift();
if (!this.enabled() || !this.room.chatty() || 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;
if (!meaning.notable || !this.enabled() || !this.room.chatty() || this.room.bots().includes(actor) || this.planned()) return;
const bots = this.room.bots().filter((b) => this.canTalk(b));
if (!bots.length || this.random() > REACT_P) 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));
const known = this.known();
const task = `${who}이(가) 방금 "${meaning.ko}"를 했다${meaning.mean ? `(${meaning.mean})` : ''}. 그 뜻에 맞게 ${who}에게 반응하는 한마디(떠보거나 장난스럽게 받아치기).`;
void writeLine(this.llm, this.request(bot, this.situation(bot), task, { maxLen: 36, priority: 'low', timeoutMs: TALK_WAIT_MS })).then((raw) => {
let line = raw;
// Contradicting the move, or about nothing in this game: a built-in line made for this kind of move instead.
if (line && (contradicts(line, meaning, false, known) || !this.relevant(line, meaning, [who]))) line = null;
line ??= cannedLine(meaning, who, this.room.smart(bot), false, this.random);
if (line && !this.busy.has(bot) && this.room.playing()) return this.type(bot, line, () => this.room.roomChat(bot, line!));
});
}
@@ -154,6 +273,7 @@ export class BotBrain {
let act = action;
let line: string | null = null;
const a = action as { type?: string; claim?: string; cardId?: string; to?: string };
const meaning = meaningOf(this.room.gameId(), action);
if (this.room.gameId() === 'cockroach-poker' && (a.type === 'offer' || a.type === 'pass') && a.claim) {
const r = await this.cockroachBluff(bot, a, view);
if (r) {
@@ -161,12 +281,20 @@ export class BotBrain {
// Chat off: the model still decides truth or bluff, the computer just hands the card over without a word.
line = this.room.chatty() ? r.say : null;
}
} else if (this.room.chatty() && 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] ?? '내 수'}"를 하려 한다. 이 수를 두며 상대에게 던지는 도발이나 심리전 한마디.`));
} else if (meaning.notable && this.room.chatty() && !this.planned() && this.canTalk(bot) && this.random() < temperOf(bot).talk) {
// Only a notable move of its own (a big bet, 다이, 고…) gets a word; ordinary moves are played in silence.
this.spoke(bot);
const known = this.known();
const others = this.room.humans().map((h) => this.room.nameOf(h));
const task = `나는 지금 "${meaning.ko}"를 하려 한다${meaning.mean ? `(${meaning.mean})` : ''}. 이 수에 맞게 상대에게 던지는 도발이나 심리전 한마디.`;
line = await writeLine(this.llm, this.request(bot, this.situation(bot), task, { maxLen: 36, priority: 'low', timeoutMs: TALK_WAIT_MS }));
if (line && (contradicts(line, meaning, true, known) || !this.relevant(line, meaning, others))) line = null;
line ??= cannedLine(meaning, this.room.nameOf(bot), this.room.smart(bot), true, this.random);
}
if (line && this.room.playing()) {
await this.say(bot, line);
if (line && this.room.playing() && !this.busy.has(bot)) {
this.spoke(bot);
const said = line;
await this.type(bot, said, () => this.room.roomChat(bot, said));
await this.sleep(Math.round((300 + 500 * this.random()) * botPace(bot)));
}
return act;
@@ -200,48 +328,123 @@ export class BotBrain {
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.chatty() || this.room.gameId() === 'mafia') return;
/**
* The computer a person is talking to: named ("컴퓨터 1", "컴1", "1번", or its full name), or answering what a
* computer just said (no one else spoke since), or — with one person in the room — the computer they were talking
* with a moment ago or the only computer there.
*/
private addressee(from: string, text: string, prevHumanChat: number): { bot: string; reply: boolean } | undefined {
const bots = this.room.bots();
const flat = text.replace(/\s/g, '');
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));
const name = this.room.nameOf(b);
const n = /^컴퓨터 (\d+)$/.exec(name)?.[1];
if (n) return new RegExp(`(컴퓨터\\s?${n}|컴${n}|(?<![0-9])${n}번)(?![0-9])`).test(text);
return name.length >= 2 && flat.includes(name.replace(/\s/g, ''));
});
if (named) return { bot: named, reply: false };
const now = this.room.now();
const alone = this.room.humans().length === 1;
const partner = this.partner.get(from);
if (alone && partner && now - partner.at <= CONVERSATION_MS && bots.includes(partner.bot)) return { bot: partner.bot, reply: false };
const last = this.lastSpeaker;
if (last && last.at >= prevHumanChat && now - last.at <= REPLY_MS && bots.includes(last.bot)) return { bot: last.bot, reply: true };
if (alone && bots.length === 1) return { bot: bots[0]!, reply: false };
return undefined;
}
/** At most `ANSWERS_PER_MINUTE` answers a minute to one person. */
private mayAnswer(from: string): boolean {
const now = this.room.now();
const recent = (this.answered.get(from) ?? []).filter((t) => now - t < 60_000);
this.answered.set(from, recent);
return recent.length < ANSWERS_PER_MINUTE;
}
/**
* People chatting: a computer spoken to always answers (right after the line it is typing, if any). People
* talking among themselves are left alone.
*/
onHumanChat(from: string, text: string): void {
const prev = this.lastHumanChat;
this.lastHumanChat = this.room.now();
if (!this.canAnswer()) return;
const to = this.addressee(from, text, prev);
if (!to || !this.mayAnswer(from)) return;
const { bot, reply } = to;
this.partner.set(from, { bot, at: this.room.now() });
// Busy: the newest message waits and is answered right after (a burst of lines gets one answer, not none).
if (this.busy.has(bot)) this.pending.set(bot, { from, text, reply });
else void this.answer(bot, from, text, reply);
}
private answerPending(bot: string): void {
const next = this.pending.get(bot);
if (!next) return;
this.pending.delete(bot);
if (this.canAnswer()) void this.answer(bot, next.from, next.text, next.reply);
}
/** A built-in answer that fits what the person said (a greeting, a jab, a question), not the same twice in a row. */
quickAnswer(bot: string, text: string): string {
const kind = QUICK_ANSWER.find((q) => q.test.test(text))!;
const pool = kind[this.room.smart(bot) ? 'smart' : 'casual'].filter((l) => l !== this.lastQuick.get(bot));
const line = pool[Math.floor(this.random() * pool.length) % pool.length]!;
this.lastQuick.set(bot, line);
return line;
}
/**
* Answers a person at once: "입력 중…" shows while the model writes (that time counts as typing), then the line.
* The model gets `ANSWER_WAIT_MS`; slow, busy, down or unusable, a built-in answer is said instead.
*/
private async answer(bot: string, from: string, text: string, reply = false): Promise<void> {
this.busy.add(bot);
this.showTyping(bot, true);
this.answered.set(from, [...(this.answered.get(from) ?? []), this.room.now()]);
const t0 = this.room.now();
let line: string | null = null;
if (this.llm?.available()) {
const who = this.room.nameOf(from);
const task =
`${who}이(가) 나(${this.room.nameOf(bot)})에게 채팅으로 "${text.slice(0, 100)}"라고 했다. ${who}에게 바로 대답한다. ` +
'질문이면 그 질문에 직접 답하고(성격대로, 허세·도발·엄살 가능, 판 상황에 근거해서), 질문이 아니면 맞장구치거나 받아친다. 짧게.';
try {
line = await withDeadline(writeLine(this.llm, this.request(bot, this.situation(bot), task, { maxLen: 34, priority: 'high' })), ANSWER_WAIT_MS);
} catch {
line = null;
}
}
line ??= this.quickAnswer(bot, text);
this.busy.delete(bot);
const said = line;
// Sent in or out of a game (the person asked); the model's time already counted as typing.
await this.type(bot, said, () => this.room.roomChat(bot, said), false, this.room.now() - t0);
this.partner.set(from, { bot, at: this.room.now() });
// An answer to an unnamed reply does not invite the next line in turn: people talking among themselves after
// it are left alone (otherwise the computer would answer every line between two people forever).
if (reply && this.lastSpeaker?.bot === bot) this.lastSpeaker = null;
}
onGameStart(): void {
this.happened = [];
// A game with computers and people where the model will be used: make sure it is loaded before anyone talks.
// No greeting: the computers speak on their own only about what happens in the game.
const usesModel = this.room.chatty() || this.room.gameId() === 'cockroach-poker';
if (usesModel && this.llm?.available() && this.room.humans().length && this.room.bots().length) void this.llm.warm();
if (!this.enabled() || !this.room.chatty() || 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.chatty() || !this.room.humans().length || this.room.gameId() === 'mafia' || this.random() > 0.85) return;
if (!this.llm?.available() || !this.room.chatty() || !this.room.humans().length || this.planned() || this.random() > 0.6) 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);
const first = (ranking[0] ?? []).map((p) => this.room.nameOf(p)).join(', ');
const task = winner ? '내가 이겼다. 상대를 살짝 놀리며 이긴 소감 한마디(한 판 더 하자고 해도 좋다).' : `내가 졌다(1등: ${first}). 아쉬워하며 다음엔 이기겠다는 한마디.`;
void writeLine(this.llm, this.request(bot, `게임이 끝났다. 1등: ${first}`, task, { priority: 'low' })).then((line) => {
if (line && !this.busy.has(bot)) return this.type(bot, line, () => this.room.roomChat(bot, line), false);
});
}

View File

@@ -39,7 +39,10 @@ export function systemPrompt(bot: string, name: string, maxLen: number, smart: b
`성격: ${t.ko} — ${t.desc}`,
`말투: ${speechOf(smart)}.`,
`규칙: 한국어 채팅 한 줄만 쓴다. ${maxLen}자 이내. 대사만 쓰고 따옴표·설명·괄호·영어·한자는 쓰지 않는다.`,
'욕설, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 게임과 상관없는 이야기는 하지 않는다.',
'욕설·막말·깔보는 호칭, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 상대가 거친 말을 해도 장난스럽게 받아넘긴다.',
'"상황"에 적힌 사실에만 근거해서 말한다. 적히지 않은 점수·패·행동은 지어내지 않고, 게임과 상관없는 혼잣말이나 "다들 준비됐냐" 같은 뻔한 말은 하지 않는다.',
'최근 채팅에서 "(나)"가 붙은 줄은 내가 한 말이다. 내가 했던 말의 시작이나 표현을 되풀이하지 않는다.',
'누가 한 수의 뜻이 적혀 있으면 그 뜻에 맞게 말한다(센 베팅을 한 사람에게 겁먹었다고 하지 않고, 포기한 사람에게 세게 나왔다고 하지 않는다).',
'자신이 AI나 프로그램이라고 말하지 않는다. 숨겨진 정보(내 패, 내 카드, 내 직업)는 절대 밝히지 않는다.',
].join('\n');
}
@@ -61,10 +64,21 @@ export interface LineRequest {
maxLen?: number;
/** Extra patterns the line must not contain (e.g. a mafia computer saying it is mafia). */
forbid?: RegExp[];
/** answer = a person spoke to it (goes ahead of everything); talk = on its own (dropped when the model is busy). */
priority?: 'high' | 'normal' | 'low';
/** Give up on the model after this long (a word about a move is no use once the game has moved on). */
timeoutMs?: number;
}
const AI_WORDS = /인공\s*지능|\bAI\b|챗봇|언어\s*모델|어시스턴트|프로그램입니다|GPT|모델로서/i;
const FOREIGN = /[一-鿿぀-ヿ]|[A-Za-z]{4,}/;
/**
* Rude words the shared kid-safe filter lets through but the model likes to use when it plays "도발형" or is sworn at
* ("망할 놈", "닥쳐", "뒤져라", "꼬맹이" — all seen from gemma3:4b in testing).
*/
const RUDE = /뒤지겠|뒤지게|놈|(이|저|그|미친)\s?년|새끼|지랄|닥치|닥쳐|꺼져|뒤질|뒤져|죽을래|죽여|죽인다|팰\s?거|때려|병신|멍청|바보|어리석|꼬맹|찐따|빌어먹|망할|씹|좆|미친|븅|등신|한심/;
/** The model repeating its instructions instead of talking ("철수이(가) 채팅으로 … 라고 했다"). */
const ECHO = /이\(가\)|채팅으로|라고 했다|할 말:|상황:|최근 채팅/;
/** 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 {
@@ -79,7 +93,7 @@ export function cleanLine(raw: string, maxLen = 40, forbid: RegExp[] = []): stri
.replace(/[*_#>]/g, '')
.replace(/\s+/g, ' ')
.trim();
if (!line || FOREIGN.test(line) || AI_WORDS.test(line)) return null;
if (!line || FOREIGN.test(line) || AI_WORDS.test(line) || RUDE.test(line) || ECHO.test(line)) return null;
if ([...line].length > maxLen) {
const chars = [...line];
const cut = chars.slice(0, maxLen).join('');
@@ -98,14 +112,15 @@ export async function writeLine(llm: Llm | null, req: LineRequest): Promise<stri
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.recent?.length) parts.push(`최근 채팅:\n${req.recent.slice(-8).map((m) => `${m.from}${m.from === req.name ? '(나)' : ''}: ${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, req.smart) },
{ role: 'user', content: parts.join('\n') },
];
const raw = await llm.chat(messages, { maxTokens: 70, temperature: 0.95 });
// One line of at most ~40 Korean characters is 15~30 tokens; stop at the first newline.
const raw = await llm.chat(messages, { maxTokens: 56, temperature: 0.9, stop: ['\n'], priority: req.priority ?? 'normal', ...(req.timeoutMs ? { timeoutMs: req.timeoutMs } : {}) });
return raw === null ? null : cleanLine(raw, maxLen, req.forbid);
}

View File

@@ -13,7 +13,10 @@ export interface LlmConfig {
/** Ollama base URL, e.g. http://192.168.10.9:11434. */
url: string;
model: string;
/** Requests running at once (one GPU). */
/**
* Requests sent at once. Default 1: Ollama on the one GPU runs one request at a time (`n_slots = 1`), so a second
* one would only wait inside Ollama — where an answer to a person could not get ahead of small talk.
*/
maxConcurrent?: number;
/** Requests allowed to wait; more are refused at once (the caller uses a built-in line). */
maxQueue?: number;
@@ -39,7 +42,7 @@ export interface LlmStats {
export class Llm {
private running = 0;
private waiting: (() => void)[] = [];
private waiting: { go: () => void; high: boolean }[] = [];
private totalMs = 0;
private backoffUntil = 0;
private failures = 0;
@@ -60,17 +63,31 @@ export class Llm {
/**
* 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).
* not be had in time (busy, down, timeout). `priority`: `high` (answering a person) goes ahead of everything that
* waits; `low` (small talk nobody asked for) is dropped at once when the model is busy, so it never delays the rest.
* `stop` ends the answer early (one chat line: a newline).
*/
async chat(messages: LlmMessage[], opts: { maxTokens?: number; temperature?: number; format?: object; timeoutMs?: number } = {}): Promise<string | null> {
async chat(
messages: LlmMessage[],
opts: { maxTokens?: number; temperature?: number; format?: object; timeoutMs?: number; priority?: 'high' | 'normal' | 'low'; stop?: string[] } = {},
): 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) {
const max = this.cfg.maxConcurrent ?? 1;
const busy = this.running >= max;
const full = busy && this.waiting.length >= (this.cfg.maxQueue ?? 6) && opts.priority !== 'high';
if (!this.available() || full || (busy && opts.priority === 'low')) {
this.stats.skipped++;
return null;
}
if (this.running >= (this.cfg.maxConcurrent ?? 2)) await new Promise<void>((r) => this.waiting.push(r));
this.running++;
if (busy) {
await new Promise<void>((go) => {
const high = opts.priority === 'high';
// Answers wait only behind earlier answers.
const at = high ? this.waiting.findIndex((w) => !w.high) : -1;
if (at >= 0) this.waiting.splice(at, 0, { go, high });
else this.waiting.push({ go, high });
});
} else this.running++; // a waiter is handed the finished request's place (`running` stays)
const t0 = this.now();
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), opts.timeoutMs ?? this.cfg.timeoutMs ?? 6000);
@@ -85,7 +102,7 @@ export class Llm {
stream: false,
keep_alive: this.cfg.keepAlive ?? '2h',
...(opts.format ? { format: opts.format } : {}),
options: { temperature: opts.temperature ?? 0.9, num_predict: opts.maxTokens ?? 80 },
options: { temperature: opts.temperature ?? 0.9, num_predict: opts.maxTokens ?? 80, ...(opts.stop ? { stop: opts.stop } : {}) },
}),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
@@ -110,8 +127,9 @@ export class Llm {
return null;
} finally {
clearTimeout(timer);
this.running--;
this.waiting.shift()?.();
const next = this.waiting.shift();
if (next) next.go();
else this.running--;
}
}

View File

@@ -197,6 +197,7 @@ export class Room {
smart: (bot) => botPersona(bot, this.profile(bot).base).smart,
chatty: () => this.botChatOn(),
now: this.now,
view: (viewer) => (this.game && !this.game.finished ? this.def.view(this.game.state, viewer) : null),
},
deps.ai ?? null,
deps.aiRandom ?? secureRandom,