범인찾기 C2: 사이트 서버 Claude 호출 · 근거 확인 · 예산 장부

- POST /api/culprit/matches/:id/analyze: 등록된 앱 유저 이상(다시 분석은 관리자), 월 $100 · 하루 20회 · 중복 잠금
- Claude Opus 5.5 (생각 high, 구조화 출력, 출력 32k 상한, 거절 시 서버 측 fallback), 지시문 + 게임별 지식 묶음(자동 갱신 칸은 공식 데이터로 하루 한 번)
- 결과 확인: 10명 · 0.5 단위 점수 · 태그 · 팀마다 범인 1명(팀 최저점) · 없는 근거 번호 제거, 범인 근거가 안 맞으면 한 번 다시
- 비용 장부(culprit-ledger.json)는 토큰 · 비용만, 진행 단계는 실시간 알림(culprit.progress)
- 지시문 v1.1: 범인 = 가장 못함 + 가장 발목 + 결과의 원인 종합 판단, 자료 약어 설명 추가
- 배포: Dockerfile 에 prompt/ 복사, ANTHROPIC_API_KEY 넣는 스크립트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 14:27:59 +09:00
parent de64f9818d
commit dc67f2105b
17 changed files with 1241 additions and 85 deletions

View File

@@ -7,6 +7,8 @@ import path from 'node:path';
import type { Config } from './config.js';
import { registerAppAuth } from './app-auth.js';
import { BotBroker, type BotSource } from './bot-broker.js';
import { registerCulprit, type ModelCall } from './culprit.js';
import type { KnowledgeAuto } from './culprit-prompt.js';
import { avatarUrl, DiscordApi } from './discord.js';
import { RateLimiter } from './rate-limit.js';
import { RelayHub } from './relay.js';
@@ -16,7 +18,7 @@ const SID = 'gvr_sid';
const RECHECK_MS = 10 * 60000;
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number } = {}) {
export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto } = {}) {
const app = Fastify({
logger: {
level: process.env.LOG_LEVEL || 'info',
@@ -174,6 +176,9 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
return r;
});
// ------------------------------------------------------------------ 범인찾기 (Claude API 는 이 서버만 부른다)
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log, call: opts.culpritCall, knowledge: opts.culpritKnowledge });
// ------------------------------------------------------------------ 기록 API 중계
const relay = async (req: FastifyRequest, reply: FastifyReply) => {
const s = await requireSession(req, reply);
@@ -281,7 +286,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
store.flush();
});
return { app, store, hub, broker };
return { app, store, hub, broker, culprit };
}
/** 로그에 남길 주소: /auth/* 는 쿼리를 지우고 앱 로그인 요청 아이디를 가린다, 다른 주소도 쿼리 값은 지운다 */

View File

@@ -20,8 +20,19 @@ export interface Config {
/** 테스트용: 디스코드 API 주소 바꾸기 */
discordApi: string;
assetUpstream: Record<string, string>;
/** 범인찾기 (Claude API). apiKey 가 없으면 꺼진다 (없으면 CULPRIT_DEFAULTS) */
culprit?: {
apiKey: string | null;
model: string;
effort: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
monthLimitUsd: number;
dailyLimit: number;
tone: 'mild' | 'medium' | 'spicy';
};
}
export const CULPRIT_DEFAULTS: NonNullable<Config['culprit']> = { apiKey: null, model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium' };
/** 앱 최고 관리자 (사용자 지정, 고정). SUPER_ADMIN_IDS 환경변수로 더할 수 있다 */
export const SUPER_ADMINS = ['293719842274541579', '1352267557213573160'];
@@ -53,5 +64,14 @@ export function loadConfig(env = process.env): Config {
ddragon: 'https://ddragon.leagueoflegends.com/',
cdragon: 'https://raw.communitydragon.org/',
},
culprit: {
apiKey: env.ANTHROPIC_API_KEY || null,
// 사용자 결정 ③ Opus 5.5 · ⑤ 중간맛. 예산: 월 $100 · 하루 20회 (계획서 7장)
model: env.CULPRIT_MODEL || 'claude-opus-5-5',
effort: (env.CULPRIT_EFFORT as any) || 'high',
monthLimitUsd: Number(env.CULPRIT_MONTH_LIMIT_USD || 100),
dailyLimit: Number(env.CULPRIT_DAILY_LIMIT || 20),
tone: (env.CULPRIT_TONE as any) || 'medium',
},
};
}

View File

@@ -0,0 +1,113 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* 범인찾기 지시문 · 지식 묶음 (계획서 v1.1 6장, prompt/*.md).
* 지식 묶음의 "## 자동 갱신" 칸은 공식 게임 데이터(valorant-api.com · Riot Data Dragon, 한국어)로 하루에 한 번 다시 만든다.
* 못 받으면 파일에 있는 스냅샷을 그대로 쓴다.
*/
export type Tone = 'mild' | 'medium' | 'spicy';
const TONE_KO: Record<Tone, string> = { mild: 'mild(순한맛)', medium: 'medium(중간맛)', spicy: 'spicy(매운맛)' };
export function promptDir(): string {
if (process.env.PROMPT_DIR) return process.env.PROMPT_DIR;
// 개발: site/server/src → site/server/prompt, 배포: /app/dist → /app/prompt
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'prompt');
}
const stripComments = (s: string) => s.replace(/<!--[\s\S]*?-->\n?/g, '').trim();
export function readPromptFile(name: string, dir = promptDir()): string {
return stripComments(fs.readFileSync(path.join(dir, name), 'utf8'));
}
/** 지식 묶음의 "## 자동 갱신 …" 칸을 바꾼다 (없으면 그대로) */
export function replaceAutoSection(knowledge: string, auto: string | null): string {
if (!auto) return knowledge;
const i = knowledge.indexOf('## 자동 갱신');
const j = knowledge.lastIndexOf('</knowledge>');
if (i < 0 || j < i) return knowledge;
return `${knowledge.slice(0, i)}${auto.trim()}\n${knowledge.slice(j)}`;
}
export function buildSystemPrompt(game: 'valorant' | 'lol', tone: Tone, auto: string | null, dir = promptDir()): string {
const system = readPromptFile('system.md', dir).replace('{{tone}}', TONE_KO[tone] ?? TONE_KO.medium);
const knowledge = replaceAutoSection(readPromptFile(game === 'valorant' ? 'knowledge-valorant.md' : 'knowledge-lol.md', dir), auto);
return `${system}\n\n${knowledge}`;
}
export function outputSchema(dir = promptDir()): Record<string, unknown> {
return JSON.parse(fs.readFileSync(path.join(dir, 'output-schema.json'), 'utf8'));
}
// ------------------------------------------------------------------ 자동 갱신
const ROLE_KO: Record<string, string> = { Fighter: '전사', Tank: '탱커', Mage: '마법사', Assassin: '암살자', Marksman: '원거리', Support: '서포터' };
const DAY = 24 * 3600 * 1000;
export class KnowledgeAuto {
private cache: Record<'valorant' | 'lol', { at: number; text: string } | null> = { valorant: null, lol: null };
private inflight: Partial<Record<'valorant' | 'lol', Promise<void>>> = {};
constructor(
private fetchJson: (url: string) => Promise<any> = defaultFetchJson,
private log: { warn: (o: any, m?: string) => void } = { warn: () => undefined },
) {}
/** 하루 지난 칸은 다시 만든다. 실패하면 이전 값(또는 null = 파일 스냅샷) */
async get(game: 'valorant' | 'lol'): Promise<string | null> {
const c = this.cache[game];
if (!c || Date.now() - c.at > DAY) {
this.inflight[game] ??= (game === 'valorant' ? this.buildValorant() : this.buildLol())
.then((text) => {
this.cache[game] = { at: Date.now(), text };
})
.catch((e) => this.log.warn(e, `범인찾기 지식 묶음 자동 갱신 실패 (${game}), 이전 값 사용`))
.finally(() => delete this.inflight[game]);
await this.inflight[game];
}
return this.cache[game]?.text ?? null;
}
async buildValorant(): Promise<string> {
const [agents, maps, weapons] = await Promise.all([
this.fetchJson('https://valorant-api.com/v1/agents?language=ko-KR&isPlayableCharacter=true'),
this.fetchJson('https://valorant-api.com/v1/maps?language=ko-KR'),
this.fetchJson('https://valorant-api.com/v1/weapons?language=ko-KR'),
]);
const byRole = new Map<string, string[]>();
for (const a of agents.data || []) {
const r = a.role?.displayName || '기타';
if (!byRole.has(r)) byRole.set(r, []);
byRole.get(r)!.push(a.displayName);
}
if (!byRole.size) throw new Error('요원 목록이 비었습니다');
// 경쟁 맵만 (미니맵 좌표 변환값이 있는 맵)
const mapNames = [...new Set((maps.data || []).filter((m: any) => m.xMultiplier && m.tacticalDescription).map((m: any) => m.displayName as string))];
const weaponList = (weapons.data || []).map((w: any) => `${w.displayName} ${w.shopData?.cost ?? 0}`);
const today = new Date().toISOString().slice(0, 10);
return [
`## 자동 갱신 (${today}, valorant-api.com)`,
`- 요원 (역할): ${[...byRole.entries()].map(([r, list]) => `${r}: ${list.sort((x, y) => x.localeCompare(y, 'ko')).join(', ')}`).join(' / ')}`,
`- 맵: ${mapNames.join(', ')}`,
`- 무기 (가격): ${weaponList.join(', ')}`,
].join('\n');
}
async buildLol(): Promise<string> {
const versions = await this.fetchJson('https://ddragon.leagueoflegends.com/api/versions.json');
const v = versions[0];
const champs = (await this.fetchJson(`https://ddragon.leagueoflegends.com/cdn/${v}/data/ko_KR/champion.json`)).data;
const list = Object.values<any>(champs)
.map((c) => `${c.name}(${(c.tags || []).map((t: string) => ROLE_KO[t] ?? t).join('/')})`)
.sort((x, y) => x.localeCompare(y, 'ko'));
if (!list.length) throw new Error('챔피언 목록이 비었습니다');
return [`## 자동 갱신 (패치 ${v}, Riot Data Dragon)`, `- 챔피언 (분류): ${list.join(' · ')}`].join('\n');
}
}
async function defaultFetchJson(url: string): Promise<any> {
const r = await fetch(url, { signal: AbortSignal.timeout(20000) });
if (!r.ok) throw new Error(`${url} ${r.status}`);
return r.json();
}

426
site/server/src/culprit.ts Normal file
View File

@@ -0,0 +1,426 @@
import fs from 'node:fs';
import path from 'node:path';
import Anthropic from '@anthropic-ai/sdk';
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import {
CULPRIT_TAGS,
type CulpritBudget,
type CulpritEligibility,
type CulpritEvidence,
type CulpritInput,
type CulpritResult,
type CulpritStage,
type LiveEvent,
} from '@gvr/shared';
import { CULPRIT_DEFAULTS, type Config } from './config.js';
import { buildSystemPrompt, KnowledgeAuto, outputSchema } from './culprit-prompt.js';
import type { RelayHub } from './relay.js';
import type { ServerStore, Session } from './store.js';
/**
* 범인찾기 서버 쪽 (계획서 v1.1 5장).
* - Claude API 키는 이 서버에만 있다 (환경변수 ANTHROPIC_API_KEY). 앱 · 브라우저로 가지 않는다
* - 순서: 권한 · 예산 · 하루 횟수 · 중복 확인 → 게임 PC 에서 AI 자료 받기 → Claude 호출(구조화 출력) → 근거 번호 확인 → 게임 PC 에 결과 저장
* - 서버에는 비용 장부만 남긴다 (경기 번호 · 누른 사람 · 토큰 수 · 비용 · 시각). 대화 내용은 저장하지 않고 로그에도 남기지 않는다
*/
/** 100만 토큰당 달러 (입력, 출력). 모르는 모델은 비싼 쪽으로 잡는다 */
const PRICES: Record<string, [number, number]> = {
'claude-opus-5-5': [4, 20],
'claude-sonnet-5-5': [2, 10],
'claude-haiku-4-5': [1, 5],
'claude-opus-5': [5, 25],
'claude-opus-4-8': [5, 25],
};
const UNKNOWN_PRICE: [number, number] = [5, 25];
/** 출력 상한 (생각 포함). 경기 하나가 약 $1 을 넘지 않게 (계획서 7장) */
const MAX_TOKENS = 32000;
const DEFAULT_ESTIMATE = 0.45;
export interface Usage {
model: string;
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
}
export function costOf(usages: Usage[]): number {
let usd = 0;
for (const u of usages) {
const [inp, out] = PRICES[u.model] ?? PRICES[u.model.replace(/-\d{8}$/, '')] ?? UNKNOWN_PRICE;
usd += (u.input * inp + u.cacheWrite * inp * 1.25 + u.cacheRead * inp * 0.1 + u.output * out) / 1e6;
}
return Math.round(usd * 10000) / 10000;
}
/** Claude 를 부르는 부분 (테스트에서 바꿔 끼운다) */
export interface ModelCall {
(req: { model: string; system: string; user: string; schema: Record<string, unknown>; effort: string; maxTokens: number }): Promise<{
text: string | null;
stopReason: string | null;
usages: Usage[];
fallback: boolean;
}>;
}
export function anthropicCall(apiKey: string): ModelCall {
const client = new Anthropic({ apiKey, timeout: 6 * 60000, maxRetries: 2 });
return async (req) => {
const stream = client.beta.messages.stream({
model: req.model,
max_tokens: req.maxTokens,
thinking: { type: 'adaptive' },
output_config: { effort: req.effort as any, format: { type: 'json_schema', schema: req.schema } },
// 안전 분류기가 거절하면 서버가 권장 모델로 한 번 다시 돌린다
betas: ['server-side-fallback-2026-07-01'],
fallbacks: 'default',
system: [{ type: 'text', text: req.system, cache_control: { type: 'ephemeral' } }],
messages: [{ role: 'user', content: req.user }],
});
const msg = await stream.finalMessage();
const iters = (msg.usage.iterations ?? []) as any[];
const usages: Usage[] = iters.length
? iters.map((it) => ({
model: it.model || msg.model,
input: it.input_tokens ?? 0,
output: it.output_tokens ?? 0,
cacheRead: it.cache_read_input_tokens ?? 0,
cacheWrite: it.cache_creation_input_tokens ?? 0,
}))
: [
{
model: msg.model,
input: msg.usage.input_tokens,
output: msg.usage.output_tokens,
cacheRead: msg.usage.cache_read_input_tokens ?? 0,
cacheWrite: msg.usage.cache_creation_input_tokens ?? 0,
},
];
const text = msg.content
.filter((b: any) => b.type === 'text')
.map((b: any) => b.text)
.join('');
return { text: text || null, stopReason: msg.stop_reason, usages, fallback: iters.some((it) => it.type === 'fallback_message') };
};
}
// ------------------------------------------------------------------ 결과 확인
/** 근거 번호 모양 맞추기: "[u12]" · "U12" · "s:p4" → "u12" · "s:P4" */
export function normRef(ref: string): string {
const r = String(ref ?? '').trim().replace(/^\[|\]$/g, '');
const s = /^s\s*:\s*p(\d+)$/i.exec(r);
if (s) return `s:P${s[1]}`;
const m = /^([uecr])\s*(\d+)$/i.exec(r);
return m ? `${m[1].toLowerCase()}${m[2]}` : r;
}
const PLAY_REF = /^(e|r|s:)/;
/**
* AI 답을 확인한다: 10명이 빠짐없이 한 번씩, 점수 1~10 (0.5 단위), 태그 목록 안, 팀마다 범인 1명(그 팀 사람, 그 팀 최저점),
* 근거 번호는 이 경기 자료에 있는 것만 (없는 번호는 뺀다). 범인 근거가 하나도 안 남으면 needRetry.
*/
export function checkResult(raw: unknown, input: CulpritInput): { result: CulpritResult | null; problems: string[]; needRetry: boolean } {
const problems: string[] = [];
const r = raw as any;
if (!r || typeof r !== 'object' || !Array.isArray(r.players) || !Array.isArray(r.teams)) return { result: null, problems: ['형식이 맞지 않음'], needRetry: true };
const ids = input.players.map((p) => p.id);
const teamOf = new Map(input.players.map((p) => [p.id, p.team]));
const fixEvidence = (list: any[]): CulpritEvidence[] => {
const out: CulpritEvidence[] = [];
for (const e of Array.isArray(list) ? list : []) {
const ref = normRef(e?.ref);
const target = input.refs[ref];
if (!target) {
problems.push(`없는 근거 ${String(e?.ref)}`);
continue;
}
if (out.some((x) => x.ref === ref)) continue;
out.push({ ref, note: String(e?.note ?? '').slice(0, 300), target });
}
return out;
};
const players: CulpritResult['players'] = [];
for (const id of ids) {
const p = r.players.find((x: any) => String(x?.id).toUpperCase() === id);
if (!p) return { result: null, problems: [...problems, `${id} 평가 없음`], needRetry: true };
let score = Number(p.score);
if (!Number.isFinite(score)) return { result: null, problems: [...problems, `${id} 점수 없음`], needRetry: true };
score = Math.min(10, Math.max(1, Math.round(score * 2) / 2));
const tag = (CULPRIT_TAGS as readonly string[]).includes(p.tag) ? p.tag : '무난';
players.push({ id, score, tag, comment: String(p.comment ?? '').slice(0, 120), evidence: fixEvidence(p.evidence) });
}
const sides = [...new Set(input.players.map((p) => p.team))];
const teams: CulpritResult['teams'] = [];
let needRetry = false;
for (const side of (['ally', 'enemy'] as const).filter((s) => sides.includes(s))) {
const t = r.teams.find((x: any) => x?.team === side);
const culprit = String(t?.culprit ?? '').toUpperCase();
if (!t || teamOf.get(culprit) !== side) return { result: null, problems: [...problems, `${side} 팀 범인이 없거나 다른 팀 사람`], needRetry: true };
const evidence = fixEvidence(t.evidence);
if (!evidence.length) {
problems.push(`${side} 팀 범인 근거가 모두 없는 번호`);
needRetry = true;
}
// 음성O 인 범인은 플레이 근거([e] [r] [s:])가 하나는 있어야 한다 (말이 기록된 사람이 불리하지 않게)
const cp = input.players.find((p) => p.id === culprit)!;
if (cp.voice && evidence.length && !evidence.some((e) => PLAY_REF.test(e.ref))) {
problems.push(`${culprit} 은 음성O 인데 플레이 근거가 없음`);
needRetry = true;
}
teams.push({ team: side, culprit, reason: String(t.reason ?? '').slice(0, 600), evidence });
// 범인 태그는 팀마다 범인 한 명에게만, 범인은 그 팀 최저점
for (const p of players) {
if (teamOf.get(p.id) !== side) continue;
if (p.id === culprit) p.tag = '범인';
else if (p.tag === '범인') p.tag = '아쉬움';
}
const others = players.filter((p) => teamOf.get(p.id) === side && p.id !== culprit);
const me = players.find((p) => p.id === culprit)!;
const min = Math.min(...others.map((p) => p.score));
if (others.length && me.score > min) {
problems.push(`${culprit} 점수 ${me.score} → ${min} (팀 최저점으로)`);
me.score = min;
}
}
const confidence = ['high', 'medium', 'low'].includes(r.confidence) ? r.confidence : 'medium';
return {
result: { summary: String(r.summary ?? '').slice(0, 400), confidence, confidence_note: String(r.confidence_note ?? '').slice(0, 300), teams, players },
problems,
needRetry,
};
}
// ------------------------------------------------------------------ 비용 장부
export interface LedgerEntry {
at: number;
matchId: string;
by: string;
model: string;
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
costUsd: number;
ok: boolean;
/** 하루 횟수에 세는 요청인지 (자동 재시도는 세지 않는다) */
counted: boolean;
}
const kstDate = (t: number) => new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Seoul', year: 'numeric', month: '2-digit', day: '2-digit' }).format(t);
export class Ledger {
private file: string;
private entries: LedgerEntry[];
constructor(dir: string) {
fs.mkdirSync(dir, { recursive: true });
this.file = path.join(dir, 'culprit-ledger.json');
try {
this.entries = JSON.parse(fs.readFileSync(this.file, 'utf8'));
} catch {
this.entries = [];
}
}
add(e: LedgerEntry): void {
this.entries.push(e);
const tmp = this.file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(this.entries), { mode: 0o600 });
fs.renameSync(tmp, this.file);
}
/** 이번 달(한국 시간) 쓴 돈 */
monthSpent(now = Date.now()): number {
const m = kstDate(now).slice(0, 7);
return Math.round(this.entries.filter((e) => kstDate(e.at).slice(0, 7) === m).reduce((n, e) => n + e.costUsd, 0) * 10000) / 10000;
}
/** 오늘(한국 시간) 누른 횟수 */
todayCount(now = Date.now()): number {
const d = kstDate(now);
return this.entries.filter((e) => e.counted && kstDate(e.at) === d).length;
}
/** 최근 성공한 분석 비용 평균 (예상 비용 표시) */
estimate(): number {
const ok = this.entries.filter((e) => e.ok).slice(-10);
if (!ok.length) return DEFAULT_ESTIMATE;
return Math.round((ok.reduce((n, e) => n + e.costUsd, 0) / ok.length) * 100) / 100;
}
}
// ------------------------------------------------------------------ 서비스
export interface CulpritOptions {
cfg: Config;
store: ServerStore;
hub: RelayHub;
requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<Session | null>;
log: { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void; error: (o: any, m?: string) => void };
call?: ModelCall;
knowledge?: KnowledgeAuto;
}
export function registerCulprit(app: FastifyInstance, o: CulpritOptions) {
const { cfg, store, hub, log } = o;
const c = cfg.culprit ?? CULPRIT_DEFAULTS;
const ledger = new Ledger(cfg.dataDir);
const call: ModelCall | null = o.call ?? (c.apiKey ? anthropicCall(c.apiKey) : null);
const knowledge = o.knowledge ?? new KnowledgeAuto(undefined, log);
const running = new Map<string, { by: string; at: number; stage: CulpritStage }>();
/** (가) 등록된 앱 유저 이상만 분석 버튼, 다시 분석은 관리자 이상 (사용자 결정 ②) */
const roleOf = (uid: string): 'superadmin' | 'admin' | 'user' | null =>
cfg.superAdmins.includes(uid) ? 'superadmin' : (store.appUser(uid)?.role ?? null);
const budget = (uid: string): CulpritBudget => {
const role = roleOf(uid);
return {
enabled: !!call,
canAnalyze: !!role,
canReanalyze: role === 'admin' || role === 'superadmin',
monthSpentUsd: ledger.monthSpent(),
monthLimitUsd: c.monthLimitUsd,
todayCount: ledger.todayCount(),
dailyLimit: c.dailyLimit,
estimateUsd: ledger.estimate(),
model: c.model,
running: [...running.keys()],
};
};
const publish = (matchId: string, stage: CulpritStage, message?: string) => {
const r = running.get(matchId);
if (r) r.stage = stage;
hub.publish({ type: 'culprit.progress', data: { matchId, stage, ...(message ? { message } : {}) } } satisfies LiveEvent);
};
const internal = async (method: string, p: string, body: unknown, timeoutMs = 30000) => {
const r = await hub.request(method, p, { 'x-gvr-internal': '1', 'content-type': 'application/json', accept: 'application/json' }, { id: 'server', name: '사이트 서버', avatar: null }, body === null ? null : JSON.stringify(body), timeoutMs);
let data: any = null;
try {
data = JSON.parse(r.body.toString('utf8'));
} catch {
/* JSON 아님 */
}
return { status: r.status, data };
};
app.get('/api/culprit/budget', async (req, reply) => {
const s = await o.requireSession(req, reply);
if (!s) return;
return budget(s.user.id);
});
// 브라우저는 앱의 내부 경로를 부를 수 없다 (중계도 x-gvr-internal 헤더를 넘기지 않지만 한 번 더 막는다)
app.route({ method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], url: '/api/culprit/internal/*', handler: async (_req, reply) => reply.code(404).send({ error: 'not_found' }) });
app.post<{ Params: { id: string }; Body: { reanalyze?: boolean } }>('/api/culprit/matches/:id/analyze', async (req, reply) => {
const s = await o.requireSession(req, reply);
if (!s) return;
const origin = String(req.headers.origin || '');
if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' });
const matchId = req.params.id;
if (!/^[\w.:-]{1,80}$/.test(matchId)) return reply.code(400).send({ error: 'bad_id' });
const b = budget(s.user.id);
const reanalyze = !!req.body?.reanalyze;
if (!b.enabled) return reply.code(503).send({ error: 'disabled', message: '범인찾기가 아직 설정되지 않았습니다 (API 키 없음)' });
if (!b.canAnalyze) return reply.code(403).send({ error: 'forbidden', message: '등록된 앱 유저만 분석할 수 있습니다' });
if (reanalyze && !b.canReanalyze) return reply.code(403).send({ error: 'forbidden', message: '다시 분석은 관리자만 할 수 있습니다' });
if (running.has(matchId)) return reply.code(409).send({ error: 'running', message: '이 경기는 이미 분석 중입니다' });
if (b.todayCount >= b.dailyLimit) return reply.code(429).send({ error: 'daily_limit', message: `오늘 분석 횟수(${b.dailyLimit}회)를 다 썼습니다` });
if (b.monthLimitUsd - b.monthSpentUsd < b.estimateUsd) return reply.code(429).send({ error: 'budget', message: '이번 달 분석 예산을 다 썼습니다' });
// 잠금을 먼저 걸고 (동시에 눌러도 한 번만), 게임 PC 에서 분석 자료를 받는다
running.set(matchId, { by: s.user.id, at: Date.now(), stage: 'collect' });
let input: CulpritInput;
try {
const r = await internal('GET', `/api/culprit/internal/${encodeURIComponent(matchId)}/input`, null);
// 예전 앱은 이 경로가 없다 (Fastify 기본 404 { error: 'Not Found' })
if (r.status === 404 && r.data?.error === 'not_found') throw Object.assign(new Error('not_found'), { code: 'not_found' });
if (r.status === 404) throw Object.assign(new Error('old_app'), { code: 'old_app' });
if (r.status === 409) throw Object.assign(new Error('not_ready'), { code: 'not_ready', eligibility: r.data?.eligibility });
if (r.status !== 200 || !r.data?.input) throw new Error(`input ${r.status}`);
const elig = r.data.eligibility as CulpritEligibility;
if (elig.state === 'done' && !reanalyze) throw Object.assign(new Error('done'), { code: 'done' });
input = r.data.input;
} catch (e: any) {
running.delete(matchId);
if (e.message === 'device_offline') return reply.code(503).send({ error: 'device_offline', message: '게임 PC 가 꺼져 있습니다' });
if (e.code === 'old_app') return reply.code(426).send({ error: 'old_app', message: '게임 PC 앱을 업데이트해 주세요' });
if (e.code === 'not_found') return reply.code(404).send({ error: 'not_found' });
if (e.code === 'not_ready') return reply.code(409).send({ error: 'not_ready', eligibility: e.eligibility, message: e.eligibility?.reasons?.join(', ') || '분석할 수 없는 경기입니다' });
if (e.code === 'done') return reply.code(409).send({ error: 'done', message: '이미 분석한 경기입니다. 다시 분석은 관리자만 할 수 있습니다' });
log.error(e, '범인찾기 자료 받기 실패');
return reply.code(502).send({ error: 'input_failed' });
}
publish(matchId, 'thinking');
void run(matchId, input, { id: s.user.id, name: s.user.name }).finally(() => running.delete(matchId));
return reply.code(202).send({ ok: true });
});
/** AI 분석 (버튼 응답 뒤에 돈다. 창을 닫아도 계속, 끝나면 실시간 알림) */
async function run(matchId: string, input: CulpritInput, by: { id: string; name: string }): Promise<void> {
const started = Date.now();
const usages: Usage[] = [];
let fallback = false;
try {
const system = buildSystemPrompt(input.game, c.tone, await knowledge.get(input.game));
const schema = outputSchema();
const user = `<match>\n${input.text}\n</match>`;
let checked: ReturnType<typeof checkResult> | null = null;
for (let attempt = 1; attempt <= 2; attempt++) {
if (attempt > 1 && c.monthLimitUsd - ledger.monthSpent() < ledger.estimate()) break;
const res = await call!({ model: c.model, system, user, schema, effort: c.effort, maxTokens: MAX_TOKENS });
usages.push(...res.usages);
fallback ||= res.fallback;
const cost = costOf(res.usages);
ledger.add({ at: Date.now(), matchId, by: by.id, model: res.usages.at(-1)?.model ?? c.model, ...sumUsage(res.usages), costUsd: cost, ok: res.stopReason === 'end_turn', counted: attempt === 1 });
if (res.stopReason === 'refusal') throw new Error('AI 가 이 경기 분석을 거절했습니다');
if (res.stopReason === 'max_tokens') throw new Error('AI 답이 너무 길어 잘렸습니다');
publish(matchId, 'verify');
let parsed: unknown = null;
try {
parsed = JSON.parse(res.text ?? '');
} catch {
/* 아래에서 다시 시도 */
}
checked = checkResult(parsed, input);
if (checked.problems.length) log.warn({ matchId, attempt, problems: checked.problems.slice(0, 10) }, '범인찾기 결과 확인');
if (checked.result && !checked.needRetry) break;
if (attempt === 1) publish(matchId, 'thinking', '근거를 다시 확인하는 중');
}
if (!checked?.result) throw new Error('AI 답을 확인하지 못했습니다');
if (checked.needRetry) {
// 다시 해도 근거가 약하면 결과는 보여 주되 확신도를 낮춘다
checked.result.confidence = 'low';
checked.result.confidence_note = [checked.result.confidence_note, '일부 근거를 기록에서 찾지 못했습니다'].filter(Boolean).join(' ');
}
const totalCost = costOf(usages);
const r = await internal(
'PUT',
`/api/culprit/internal/${encodeURIComponent(matchId)}/result`,
{
result: checked.result,
players: input.players,
model: usages.at(-1)?.model ?? c.model,
createdBy: by,
meta: { tone: c.tone, durationMs: Date.now() - started, costUsd: totalCost, usage: sumUsage(usages), inputStats: input.stats, fallback },
},
60000,
);
if (r.status !== 200) throw new Error(`결과 저장 실패 (${r.status})`);
log.info({ matchId, costUsd: totalCost, ms: Date.now() - started, usage: sumUsage(usages) }, '범인찾기 완료');
publish(matchId, 'done');
} catch (e: any) {
log.error({ matchId, err: e?.message, status: e?.status }, '범인찾기 실패');
const msg =
e?.message === 'device_offline'
? '게임 PC 연결이 끊겼습니다'
: e instanceof Anthropic.APIError
? `AI 호출 실패 (${e.status ?? '연결'})`
: String(e?.message || '분석 실패');
publish(matchId, 'failed', msg);
}
}
return { budget, ledger, running };
}
function sumUsage(us: Usage[]) {
return us.reduce((a, u) => ({ input: a.input + u.input, output: a.output + u.output, cacheRead: a.cacheRead + u.cacheRead, cacheWrite: a.cacheWrite + u.cacheWrite }), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
}

View File

@@ -62,6 +62,11 @@ export class RelayHub {
this.broadcast({ type: 'status', data: { device: st } });
}
/** 서버가 만든 실시간 이벤트 (범인찾기 진행 단계 등) */
publish(ev: LiveEvent): void {
this.broadcast(ev);
}
private broadcast(m: BrowserMessage): void {
const txt = JSON.stringify(m);
for (const b of this.browsers) if (b.readyState === WebSocket.OPEN) b.send(txt);