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 = { '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; 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; 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(); /** (가) 등록된 앱 유저 이상만 분석 버튼, 다시 분석은 관리자 이상 (사용자 결정 ②) */ 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 { 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 = `\n${input.text}\n`; let checked: ReturnType | 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 }); }