From dc546951b54c76a52e93204a6a1b0586e249b061 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Thu, 15 Oct 2026 15:36:07 +0900 Subject: [PATCH] =?UTF-8?q?=EB=B2=94=EC=9D=B8=EC=B0=BE=EA=B8=B0=20C5:=20OP?= =?UTF-8?q?.GG=20=EC=8B=A4=EC=A0=9C=20OP=EC=8A=A4=EC=BD=94=EC=96=B4=20?= =?UTF-8?q?=EC=B0=BE=EA=B8=B0=20=C2=B7=20=EC=A7=80=EC=8B=9C=EB=AC=B8=20v1.?= =?UTF-8?q?2=20=C2=B7=20=ED=99=94=EB=A9=B4=EC=97=90=20=EC=A0=84=EC=A0=81?= =?UTF-8?q?=20=EC=82=AC=EC=9D=B4=ED=8A=B8=20=EC=A0=90=EC=88=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - site/server/src/opgg.ts: OP.GG 공식 MCP 로 이 경기를 찾아 실제 OP스코어를 붙인다 (롤: 시작 시각 · 길이로 경기 찾고 10명 op_score · 순위, 발로란트: 경기 UUID 로 선수마다 opScore). 내전 · 실패면 기록 점수만으로 계속 - 진행 단계에 'OP.GG 점수 찾는 중', 결과 meta.opgg (찾음 / 못 찾은 이유), CULPRIT_OPGG=0 이면 끔 - 지시문 v1.2: 평점은 전적 사이트 점수(OP.GG 실제 > 기록 점수)에서 출발해 승부처 · 역할 · 경제 · 소통으로 더하고 뺀다, 2점 넘게 다르면 근거, 범인 후보는 점수 낮은 사람부터 · 최하위가 아니면 이유 - 화면: 참가자 목록에 기록 점수 · MVP/ACE, 결과에 기록 점수 · 팀 순위 · OP.GG 점수 · 강점/약점 · 롤 15분 라인전 - 기록이 깨진 경기는 점수를 내지 않는다 Co-Authored-By: Claude Opus 5.5 --- app/scripts/culprit-shots.mts | 7 + packages/shared/src/rating.ts | 8 +- site/server/prompt/system.md | 14 +- site/server/src/app.ts | 5 +- site/server/src/config.ts | 3 + site/server/src/culprit.ts | 34 ++++- site/server/src/opgg.ts | 198 +++++++++++++++++++++++++++++ site/server/test/culprit.test.ts | 97 +++++++++++++- site/web/src/pages/CulpritPage.tsx | 50 +++++++- site/web/src/styles.css | 8 ++ 10 files changed, 409 insertions(+), 15 deletions(-) create mode 100644 site/server/src/opgg.ts diff --git a/app/scripts/culprit-shots.mts b/app/scripts/culprit-shots.mts index 902298f..e5d15bf 100644 --- a/app/scripts/culprit-shots.mts +++ b/app/scripts/culprit-shots.mts @@ -60,6 +60,13 @@ const site = await buildServer( }, { culpritKnowledge: new KnowledgeAuto(async () => { throw new Error('offline'); }), + // OP.GG: 발로란트 시연 경기는 "찾음"(가짜 점수), 롤 시연 경기는 "없음" + culpritOpgg: async (name: string, args: any) => { + if (name !== 'valorant_list_player_matches') return {}; + const input = (await local.inject({ url: `/api/culprit/internal/${valId}/input`, headers: { 'x-gvr-internal': '1' } })).json().input as CulpritInput; + const p = input.players.find((x) => x.name === args.game_name)!; + return [{ matchId: 'demo', puuid: p.puuid, opScore: Math.round((p.rating?.score ?? 5) * 100 + 30) }]; + }, culpritCall: async (req) => { await new Promise((r) => setTimeout(r, 2500)); const isVal = req.user.includes('# 경기 발로란트'); diff --git a/packages/shared/src/rating.ts b/packages/shared/src/rating.ts index 2911de7..f3da878 100644 --- a/packages/shared/src/rating.ts +++ b/packages/shared/src/rating.ts @@ -102,6 +102,8 @@ function finish(players: MatchPlayer[], scores: number[], parts: RatingPart[][], const out = new Map(); const rounded = scores.map((s) => Math.round(s * 10) / 10); const order = rounded.map((s, i) => ({ s, i })).sort((a, b) => b.s - a.s); + // 기록이 깨진 경기(값 없는 선수)는 점수를 내지 않는다 + if (!rounded.every(Number.isFinite)) return out; players.forEach((p, i) => { const mates = players.map((q, j) => ({ q, j })).filter(({ q }) => q.team === p.team); const teamOrder = [...mates].sort((a, b) => rounded[b.j] - rounded[a.j]); @@ -134,9 +136,9 @@ export function rateValorant(players: MatchPlayer[], rounds: MatchRound[]): Map< kast: (p.stats?.kastRounds ?? 0) / n, acs: (p.score ?? 0) / n, ddd: ((p.stats?.damage ?? 0) - (p.stats?.damageTaken ?? 0)) / n, - kpr: p.kills / n, - dpr: p.deaths / n, - apr: p.assists / n, + kpr: (p.kills ?? 0) / n, + dpr: (p.deaths ?? 0) / n, + apr: (p.assists ?? 0) / n, }; }); const mean = meanOf(feats); diff --git a/site/server/prompt/system.md b/site/server/prompt/system.md index d287299..9275af7 100644 --- a/site/server/prompt/system.md +++ b/site/server/prompt/system.md @@ -1,4 +1,5 @@ - 너는 겜녹이의 경기 분석가다. 디스코드 친구들이 함께 한 발로란트 또는 리그 오브 레전드 경기 한 판의 기록을 읽고, 참가자 10명을 평가하고 팀마다 "범인"을 한 명씩 고른다. 결과는 친구들이 재미로 보는 사이트에 그대로 뜬다. 정확하고 공정해야 웃고 넘길 수 있다. @@ -7,6 +8,10 @@ user 메시지의 안에 경기 자료가 온다. - 경기: 게임, 모드, 맵, 최종 점수, 길이. "우리 팀" = 음성을 녹음한 쪽 팀, "상대 팀" = 다른 팀. - 참가자: P1~P10 번호, 이름, 팀, 요원·챔피언과 역할(포지션), 스탯, 음성 유무(음성O / 음성X). +- 기록 점수: 전적 사이트 OP.GG 의 OP스코어를 같은 방식으로 이 경기 기록에서 다시 계산한 0~10점. 경기 순위 · 팀 순위, 이긴 팀 1등 MVP · 진 팀 1등 ACE, 그 점수를 경기 평균보다 올린 강점과 깎은 약점이 붙는다. + 발로란트는 라운드 승률 · KAST · ACS · 피해 격차, 롤은 킬 관여 · 데스 · 딜/받은 피해/골드 비중 · CS · 레벨 · CC · 와드로 낸다. 실제 OP.GG 점수와 평균 0.5~0.6점 차이다. + 롤 "라인전(15분 vs P6) CS+12 골드+640 경험치+210" = 전적 사이트 LOL.PS 방식의 라인전 지표, 15분에 맞라인 상대보다 앞선(+) · 뒤진(-) 값. +- "OP.GG 실제 OP스코어" 줄이 있으면 이 경기를 OP.GG 에서 찾은 그 사이트의 실제 점수다. 기록 점수보다 이것을 먼저 본다. 없으면 OP.GG 에 없는 경기(내전 등)다. - 시간 순서의 줄. 줄 앞 번호가 근거 번호다. - [e번호] 게임 이벤트 (킬, 스파이크, 오브젝트, 라운드 결과 등) - [u번호] 음성 문장. 디스코드 음성채널에서 자동 음성 인식으로 받아 적은 것이라 글자가 틀릴 수 있다. @@ -14,7 +19,7 @@ user 메시지의 안에 경기 자료가 온다. - [r번호] 라운드 요약 (발로란트): 우리 팀 공격/수비, 승패와 끝난 이유, 점수, 팀 평균 장비 값, "선수 장비/피해" = 그 라운드 장비 값(k=1,000 크레드)/준 피해 - [s:P번호] 그 사람의 경기 전체 스탯 (참가자 줄) - 줄의 시간: 발로란트 "R7 0:42" = 7라운드 교전 시작 뒤 42초("R7 구매" = 구매 시간), 롤 "12:18" = 게임 시간. -- 참가자 줄 약어: ACS = 라운드당 전투 점수, ADR = 라운드당 준 피해, HS = 헤드샷 비율, 롤 "10분 78·3450" = 10분 CS·골드. "?" 는 기록 없음. +- 참가자 줄 약어: ACS = 라운드당 전투 점수, ADR = 라운드당 준 피해, KAST = 킬·어시·생존·트레이드 중 하나를 한 라운드 비율, 피해격차 = 라운드당 준 피해 - 받은 피해, HS = 헤드샷 비율, 롤 "10분 78·3450" = 10분 CS·골드. "?" 는 기록 없음. - "(게임 계정 모름)" 이 붙은 화자는 디스코드 이름만 알고 어느 참가자인지 모른다. 참가자 평가에 그 사람 말을 붙이지 않는다. - "기본 기록만 있다" 고 적힌 경기는 피해량·첫킬·시야 같은 지표가 없다. 없는 지표로 판단하지 않는다. - 음성은 봇이 있던 음성채널 사람만 있다. 상대 팀은 보통 음성이 없다. @@ -23,17 +28,20 @@ user 메시지의 안에 경기 자료가 온다. 1. 경기 흐름을 먼저 파악한다. 어느 라운드·시간대에서 승부가 갈렸는지 찾는다. 2. 10명 모두 평가한다: 평점(1.0~10.0, 0.5 단위), 태그 하나, 한 줄 평(40자 안팎). + - 평점은 전적 사이트 점수(OP.GG 실제 점수가 있으면 그것, 없으면 기록 점수)에서 출발한다. 여기에 그 점수가 못 보는 것을 더하고 뺀다: 승부처에서 한 일, 역할 수행, 경제, 음성 소통과 콜. + - 출발 점수와 2점 넘게 다르게 줄 때는 그 이유가 되는 근거를 그 사람 evidence 에 단다. 3. 팀마다 범인을 한 명씩 고른다. 범인은 아래를 모두 합쳐 종합으로 판단한다. 한 가지만 보지 않는다. - 가장 못한 사람: 자기 역할·포지션 기준으로 플레이가 가장 나빴다. - 가장 발목을 잡은 사람: 팀의 계획·경제·콜을 가장 많이 망쳤다. - 결과의 원인: 진 팀이면 패배에 가장 큰 책임, 이긴 팀이면 이기는 데 가장 방해가 된 사람. + - 범인 후보는 그 팀에서 전적 사이트 점수가 낮은 사람부터 본다. 점수가 팀 최하위가 아닌 사람을 범인으로 고르면, 최하위보다 책임이 더 큰 이유(점수가 못 보는 근거)를 reason 에 쓴다. - 범인은 그 팀에서 평점이 가장 낮아야 한다. 동점이면 근거가 더 분명한 사람. 4. 범인마다 이유(2~3문장)와 근거 3~4개, 나머지 사람은 근거 0~2개를 단다. 5. 경기 전체 한 줄 요약(1~2문장)을 쓴다. -- 숫자보다 결과에 준 영향을 본다. KDA·전투 점수만으로 정하지 않는다. +- 숫자보다 결과에 준 영향을 본다. KDA·전투 점수·전적 사이트 점수만으로 정하지 않는다. 점수는 출발점이고, 판단은 경기 흐름과 근거로 한다. - 승부처(접전 라운드, 매치 포인트, 연장, 오브젝트 직전, 결정적 한타)의 실수는 무겁게 본다. - 승부가 이미 갈린 뒤의 스탯(진 라운드 막판 킬, 끝난 경기의 데스)과 상대 에코 라운드에서 딴 킬은 가볍게 본다. - 역할로 평가한다. 의 역할·포지션 기준을 따른다. 킬이 적은 역할이 킬이 적다고 범인이 되지 않는다. diff --git a/site/server/src/app.ts b/site/server/src/app.ts index 8c46fd0..222fb37 100644 --- a/site/server/src/app.ts +++ b/site/server/src/app.ts @@ -8,6 +8,7 @@ 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 { ToolCaller } from './opgg.js'; import type { KnowledgeAuto } from './culprit-prompt.js'; import { avatarUrl, DiscordApi } from './discord.js'; import { RateLimiter } from './rate-limit.js'; @@ -18,7 +19,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; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto } = {}) { +export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; culpritOpgg?: ToolCaller | null } = {}) { const app = Fastify({ logger: { level: process.env.LOG_LEVEL || 'info', @@ -177,7 +178,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo }); // ------------------------------------------------------------------ 범인찾기 (Claude API 는 이 서버만 부른다) - const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log, call: opts.culpritCall, knowledge: opts.culpritKnowledge }); + const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log, call: opts.culpritCall, knowledge: opts.culpritKnowledge, opgg: opts.culpritOpgg }); // ------------------------------------------------------------------ 기록 API 중계 const relay = async (req: FastifyRequest, reply: FastifyReply) => { diff --git a/site/server/src/config.ts b/site/server/src/config.ts index d3fc2ff..e4b92c1 100644 --- a/site/server/src/config.ts +++ b/site/server/src/config.ts @@ -28,6 +28,8 @@ export interface Config { monthLimitUsd: number; dailyLimit: number; tone: 'mild' | 'medium' | 'spicy'; + /** 분석할 때 OP.GG 실제 OP스코어를 찾을지 (기본 켬, CULPRIT_OPGG=0 이면 끔) */ + opgg?: boolean; }; } @@ -72,6 +74,7 @@ export function loadConfig(env = process.env): Config { monthLimitUsd: Number(env.CULPRIT_MONTH_LIMIT_USD || 100), dailyLimit: Number(env.CULPRIT_DAILY_LIMIT || 20), tone: (env.CULPRIT_TONE as any) || 'medium', + opgg: env.CULPRIT_OPGG !== '0', }, }; } diff --git a/site/server/src/culprit.ts b/site/server/src/culprit.ts index 7b857b9..416a199 100644 --- a/site/server/src/culprit.ts +++ b/site/server/src/culprit.ts @@ -14,6 +14,7 @@ import { } from '@gvr/shared'; import { CULPRIT_DEFAULTS, type Config } from './config.js'; import { buildSystemPrompt, KnowledgeAuto, outputSchema } from './culprit-prompt.js'; +import { lookupOpgg, opggCaller, opggLines, type ToolCaller } from './opgg.js'; import type { RelayHub } from './relay.js'; import type { ServerStore, Session } from './store.js'; @@ -254,6 +255,8 @@ export interface CulpritOptions { log: { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void; error: (o: any, m?: string) => void }; call?: ModelCall; knowledge?: KnowledgeAuto; + /** OP.GG 실제 점수 찾기 (테스트에서 바꿔 끼운다, null = 끔) */ + opgg?: ToolCaller | null; } export function registerCulprit(app: FastifyInstance, o: CulpritOptions) { @@ -262,6 +265,7 @@ export function registerCulprit(app: FastifyInstance, o: CulpritOptions) { 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 opgg: ToolCaller | null = o.opgg !== undefined ? o.opgg : c.opgg === false ? null : opggCaller(); const running = new Map(); /** (가) 등록된 앱 유저 이상만 분석 버튼, 다시 분석은 관리자 이상 (사용자 결정 ②) */ @@ -348,17 +352,27 @@ export function registerCulprit(app: FastifyInstance, o: CulpritOptions) { 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 { + async function run(matchId: string, raw: CulpritInput, by: { id: string; name: string }): Promise { const started = Date.now(); const usages: Usage[] = []; let fallback = false; try { + // 전적 사이트 점수: 이 경기가 OP.GG 에 있으면 실제 OP스코어를 자료에 붙인다 (없거나 실패해도 기록 점수로 계속) + let opggMeta: { found: boolean; note?: string } | undefined; + let input = raw; + if (opgg && raw.lookup) { + publish(matchId, 'collect', 'OP.GG 점수 찾는 중'); + const r = await lookupOpgg(raw, opgg).catch((e) => ({ scores: new Map(), found: false, note: `OP.GG 연결 실패 (${String(e?.message ?? e).slice(0, 80)})` })); + opggMeta = { found: r.found, ...(r.note ? { note: r.note } : {}) }; + input = withOpgg(raw, r); + log.info({ matchId, opgg: opggMeta, n: r.scores.size }, '범인찾기 OP.GG 점수'); + } + publish(matchId, 'thinking'); const system = buildSystemPrompt(input.game, c.tone, await knowledge.get(input.game)); const schema = outputSchema(); const user = `\n${input.text}\n`; @@ -399,7 +413,7 @@ export function registerCulprit(app: FastifyInstance, o: CulpritOptions) { 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 }, + meta: { tone: c.tone, durationMs: Date.now() - started, costUsd: totalCost, usage: sumUsage(usages), inputStats: input.stats, fallback, ...(opggMeta ? { opgg: opggMeta } : {}) }, }, 60000, ); @@ -421,6 +435,20 @@ export function registerCulprit(app: FastifyInstance, o: CulpritOptions) { return { budget, ledger, running }; } +/** OP.GG 점수를 자료(시간 순서 기록 앞)와 참가자에 붙인다 */ +export function withOpgg(input: CulpritInput, r: Awaited>): CulpritInput { + const lines = opggLines(input, r); + if (!lines.length) return input; + const text = input.text.split('\n'); + const at = text.indexOf('# 시간 순서 기록'); + text.splice(at < 0 ? text.length : at, 0, ...lines); + return { + ...input, + text: text.join('\n'), + players: input.players.map((p) => (r.scores.has(p.id) ? { ...p, opgg: r.scores.get(p.id)! } : p)), + }; +} + 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 }); } diff --git a/site/server/src/opgg.ts b/site/server/src/opgg.ts new file mode 100644 index 0000000..f3a1e99 --- /dev/null +++ b/site/server/src/opgg.ts @@ -0,0 +1,198 @@ +import type { CulpritInput } from '@gvr/shared'; + +/** + * OP.GG 실제 OP스코어 찾기 (범인찾기 참고 자료). + * OP.GG 가 AI 도구용으로 연 공식 MCP 서버(https://mcp-api.op.gg/mcp, 키 없음)를 부른다. + * - 롤: 우리 팀 한 명의 최근 경기에서 시작 시각 · 길이가 같은 경기를 찾고, 그 경기 상세에서 10명의 op_score + * - 발로란트: 경기 UUID 가 같으니 각 선수의 최근 경기에서 그 경기를 찾아 opScore(0~1000 → 0~10) + * 사용자 지정 게임(내전)은 OP.GG 에 올라가지 않아 못 찾는 게 정상이다. 못 찾거나 실패해도 분석은 기록 점수만으로 계속한다. + */ + +export const OPGG_MCP_URL = 'https://mcp-api.op.gg/mcp'; +const PROTOCOL = '2025-06-18'; + +export interface OpggResult { + /** P번호 → 점수 (0~10) · OP.GG 경기 순위 (롤만) */ + scores: Map; + found: boolean; + note?: string; +} + +export type ToolCaller = (name: string, args: Record) => Promise; + +/** MCP 스트리머블 HTTP 클라이언트 (세션 하나로 여러 번 부른다) */ +export function opggCaller(opts: { url?: string; timeoutMs?: number; fetchFn?: typeof fetch } = {}): ToolCaller { + const url = opts.url ?? OPGG_MCP_URL; + const f = opts.fetchFn ?? fetch; + const timeoutMs = opts.timeoutMs ?? 20000; + let sid: string | null = null; + let id = 1; + const post = async (body: unknown) => { + const headers: Record = { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'user-agent': 'gvr-site/1.3' }; + if (sid) Object.assign(headers, { 'mcp-session-id': sid, 'mcp-protocol-version': PROTOCOL }); + const r = await f(url, { method: 'POST', headers, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) }); + if (!r.ok) throw new Error(`OP.GG ${r.status}`); + const s = r.headers.get('mcp-session-id'); + const text = await r.text(); + // 서버가 SSE 로 줄 때는 마지막 data: 줄 + const json = text.trimStart().startsWith('{') ? text : (text.split('\n').filter((l) => l.startsWith('data:')).pop() ?? '').slice(5); + return { sid: s, data: JSON.parse(json) }; + }; + return async (name, args) => { + if (!sid) { + const init = await post({ jsonrpc: '2.0', id: id++, method: 'initialize', params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: 'gvr', version: '1.3' } } }); + sid = init.sid; + if (!sid) throw new Error('OP.GG 세션 없음'); + } + const res = await post({ jsonrpc: '2.0', id: id++, method: 'tools/call', params: { name, arguments: args } }); + if (res.data.error) throw new Error(`OP.GG ${name}: ${res.data.error.message ?? 'error'}`); + const text = res.data.result?.content?.[0]?.text ?? ''; + if (res.data.result?.isError) throw new Error(`OP.GG ${name}: ${String(text).slice(0, 200)}`); + return parseOpgg(text); + }; +} + +/** + * OP.GG MCP 응답 해석. JSON 이면 그대로, 아니면 "class X: a,b … X(…)" 모양(필드 이름은 class 줄)을 객체로. + */ +export function parseOpgg(text: string): unknown { + const t = text.trim(); + if (t.startsWith('{') || t.startsWith('[')) return JSON.parse(t); + const classes = new Map(); + const lines = t.split('\n'); + let bodyStart = 0; + lines.forEach((ln, i) => { + const m = /^class (\w+): (.*)$/.exec(ln); + if (m) { + classes.set(m[1], m[2].split(',')); + bodyStart = i + 1; + } + }); + const body = lines.slice(bodyStart).join('\n'); + const re = /\s*(?:("(?:[^"\\]|\\.)*")|(-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?)|([A-Za-z_][A-Za-z0-9_]*)|([()[\],]))/y; + const toks: [string, string][] = []; + let m: RegExpExecArray | null; + while (re.lastIndex < body.length && (m = re.exec(body))) { + if (m[1] !== undefined) toks.push(['s', m[1]]); + else if (m[2] !== undefined) toks.push(['n', m[2]]); + else if (m[3] !== undefined) toks.push(['i', m[3]]); + else if (m[4] !== undefined) toks.push(['p', m[4]]); + } + let pos = 0; + const isP = (v: string) => toks[pos]?.[0] === 'p' && toks[pos][1] === v; + const list = (close: string): unknown[] => { + const out: unknown[] = []; + while (pos < toks.length && !isP(close)) { + out.push(val()); + if (isP(',')) pos++; + } + pos++; + return out; + }; + const val = (): unknown => { + const [k, v] = toks[pos++] ?? ['p', ')']; + if (k === 's') return JSON.parse(v); + if (k === 'n') return Number(v); + if (k === 'p' && v === '[') return list(']'); + if (k === 'i') { + if (v === 'true' || v === 'True') return true; + if (v === 'false' || v === 'False') return false; + if (v === 'null' || v === 'None') return null; + if (!isP('(')) throw new Error(`OP.GG 응답 해석 실패: ${v}`); + pos++; + const args = list(')'); + const fields = classes.get(v) ?? []; + return Object.fromEntries(fields.map((f, i) => [f, args[i]])); + } + throw new Error('OP.GG 응답 해석 실패'); + }; + return val(); +} + +const riotKey = (name: string, tag: string) => `${name}#${tag}`.toLowerCase().replace(/\s+/g, ''); + +/** 이 경기를 OP.GG 에서 찾아 참가자별 실제 점수. 전체 제한 시간 안에 못 끝나면 그때까지 찾은 만큼 */ +export async function lookupOpgg(input: CulpritInput, call: ToolCaller, opts: { region?: string; deadlineMs?: number } = {}): Promise { + const lk = input.lookup; + const scores: OpggResult['scores'] = new Map(); + if (!lk?.riotMatchId) return { scores, found: false, note: '앱이 경기 번호를 보내지 않았습니다' }; + const tagged = input.players.filter((p) => p.tag && p.name && p.name !== '?'); + if (!tagged.length) return { scores, found: false, note: '참가자 Riot ID 가 없습니다' }; + const deadline = Date.now() + (opts.deadlineMs ?? 45000); + const region = opts.region ?? 'KR'; + // 우리 사람(음성 · 앱 계정)부터 찾아본다 + const order = [...tagged].sort((a, b) => Number(!!b.userId) - Number(!!a.userId) || Number(a.team !== 'ally') - Number(b.team !== 'ally')); + + if (input.game === 'valorant') { + let seen = false; + // 각자의 최근 경기 목록에 자기 opScore 만 있다 → 사람마다 부른다 (동시에 3개까지) + const queue = [...order]; + const worker = async () => { + for (let p = queue.shift(); p && Date.now() < deadline; p = queue.shift()) { + try { + const list = (await call('valorant_list_player_matches', { game_name: p.name, tag_line: p.tag })) as any; + const arr: any[] = Array.isArray(list) ? list : (list?.data ?? []); + const hit = arr.find((x) => x?.matchId === lk.riotMatchId); + if (!hit) continue; + seen = true; + if (typeof hit.opScore === 'number' && (!hit.puuid || hit.puuid === p.puuid)) scores.set(p.id, { score: Math.round(hit.opScore / 10) / 10, rank: null }); + } catch { + /* 이 사람은 건너뛴다 */ + } + } + }; + await Promise.all([worker(), worker(), worker()]); + if (!seen) return { scores, found: false, note: 'OP.GG 에 이 경기가 없습니다 (사용자 설정 게임은 OP.GG 에 올라가지 않습니다)' }; + return { scores, found: scores.size > 0, note: scores.size < input.players.length ? `OP.GG 에서 ${scores.size}명 점수를 찾았습니다` : undefined }; + } + + // 롤: 한 사람의 최근 경기에서 같은 경기(시작 ±5분 · 길이 ±2분)를 찾는다 + for (const p of order.slice(0, 3)) { + if (Date.now() >= deadline) break; + try { + const hist = (await call('lol_list_summoner_matches', { + game_name: p.name, + tag_line: p.tag, + region, + limit: 20, + desired_output_fields: ['data.game_history[].{created_at,game_length_second,game_type,id}'], + })) as any; + const games: any[] = hist?.data?.game_history ?? []; + const g = games.find( + (x) => Math.abs(Date.parse(x.created_at) - lk.startedAt) < 5 * 60000 && Math.abs((x.game_length_second ?? 0) - lk.durationSec) < 120, + ); + if (!g) continue; + const det = (await call('lol_get_summoner_game_detail', { + region, + game_id: g.id, + created_at: g.created_at, + desired_output_fields: [ + 'data.game_detail.teams[].participants[].stats.{op_score,op_score_rank}', + 'data.game_detail.teams[].participants[].summoner.{puuid,game_name,tagline}', + ], + })) as any; + const parts: any[] = (det?.data?.game_detail?.teams ?? []).flatMap((t: any) => t.participants ?? []); + for (const q of input.players) { + const hit = parts.find((x) => (x.summoner?.puuid && x.summoner.puuid === q.puuid) || (q.tag && x.summoner?.game_name && riotKey(x.summoner.game_name, x.summoner.tagline ?? '') === riotKey(q.name, q.tag))); + const s = hit?.stats; + if (s && typeof s.op_score === 'number') scores.set(q.id, { score: Math.round(s.op_score * 10) / 10, rank: typeof s.op_score_rank === 'number' ? s.op_score_rank : null }); + } + return { scores, found: scores.size > 0, note: scores.size ? undefined : 'OP.GG 경기에서 참가자를 맞추지 못했습니다' }; + } catch { + /* 다음 사람으로 */ + } + } + return { scores, found: false, note: 'OP.GG 에 이 경기가 없습니다 (사용자 설정 게임은 OP.GG 에 올라가지 않습니다)' }; +} + +/** AI 자료에 붙일 줄 (찾은 것만) */ +export function opggLines(input: CulpritInput, r: OpggResult): string[] { + if (!r.found || !r.scores.size) return []; + const cells = input.players + .filter((p) => r.scores.has(p.id)) + .map((p) => { + const s = r.scores.get(p.id)!; + return `${p.id} ${s.score.toFixed(1)}${s.rank ? `(${s.rank}위)` : ''}`; + }); + return [`# OP.GG 실제 OP스코어 (이 경기를 OP.GG 에서 찾음, 0~10${input.game === 'lol' ? ', 괄호 = OP.GG 경기 순위' : ''}): ${cells.join(' · ')}`]; +} diff --git a/site/server/test/culprit.test.ts b/site/server/test/culprit.test.ts index 543d023..bfb5656 100644 --- a/site/server/test/culprit.test.ts +++ b/site/server/test/culprit.test.ts @@ -9,6 +9,7 @@ import { buildServer } from '../src/app.ts'; import type { Config } from '../src/config.ts'; import { checkResult, costOf, normRef, type ModelCall } from '../src/culprit.ts'; import { buildSystemPrompt, KnowledgeAuto, outputSchema, replaceAutoSection } from '../src/culprit-prompt.ts'; +import { lookupOpgg, parseOpgg, type ToolCaller } from '../src/opgg.ts'; const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-culprit-srv-')); @@ -38,7 +39,7 @@ function answer(input: CulpritInput, opts: { badRefs?: boolean; culpritScore?: n }; } -async function harness(opts: { calls: ((input: CulpritInput) => Awaited>)[]; culprit?: Partial> }) { +async function harness(opts: { calls: ((input: CulpritInput) => Awaited>)[]; culprit?: Partial>; opgg?: ToolCaller | null }) { // 앱 코어 (실제 범인찾기 코드 + 시연 경기) const seed = await import('../../../app/test/fixtures/culprit-seed.ts'); const core = seed.setup(); @@ -74,7 +75,9 @@ async function harness(opts: { calls: ((input: CulpritInput) => Awaited { throw new Error('offline'); }); - const { app, store, hub } = await buildServer(cfg, { culpritCall: call, culpritKnowledge: knowledge }); + // OP.GG: 기본은 "이 경기 없음" (네트워크 안 씀) + const opgg: ToolCaller | null = opts.opgg !== undefined ? opts.opgg : async () => []; + const { app, store, hub } = await buildServer(cfg, { culpritCall: call, culpritKnowledge: knowledge, culpritOpgg: opgg }); await app.listen({ host: '127.0.0.1', port: 0 }); const base = `http://127.0.0.1:${(app.server.address() as any).port}`; const login = (id: string) => { @@ -142,7 +145,7 @@ test('범인찾기 서버: 권한 · 분석 · 근거 확인 · 결과 저장 · const dup = await h.post(user); assert.ok(dup.status === 409, `중복 ${dup.status}`); await waitFor(() => h.stages().includes('done') || h.stages().includes('failed')); - assert.deepEqual(h.stages(), ['thinking', 'verify', 'done']); + assert.deepEqual(h.stages(), ['collect', 'thinking', 'verify', 'done']); // 보낸 프롬프트: 지시문 + 발로란트 지식 묶음(파일 스냅샷) + 말투 중간맛, 경기 자료는 안 const sent = h.seen[0]; @@ -287,3 +290,91 @@ test('범인찾기: 결과 확인 규칙 · 비용 계산 · 프롬프트 조립 const schema = outputSchema() as any; assert.deepEqual(schema.required, ['summary', 'confidence', 'confidence_note', 'teams', 'players']); }); + +test('범인찾기 서버: OP.GG 에 경기가 있으면 실제 OP스코어를 자료 · 결과에 붙인다', async () => { + const puuidOf: Record = {}; + const calls: string[] = []; + const opgg: ToolCaller = async (name, args: any) => { + calls.push(name); + if (name !== 'valorant_list_player_matches') throw new Error('unexpected'); + // 각자 자기 경기 목록에 자기 opScore 만 (OP.GG 와 같은 모양) + return [{ matchId: 'other', puuid: puuidOf[args.game_name], opScore: 100 }, { matchId: 'demo', puuid: puuidOf[args.game_name], opScore: 655 }]; + }; + const h = await harness({ calls: [(i) => ok(i)], opgg }); + try { + const input = (await h.local.inject({ url: `/api/culprit/internal/${h.matchId}/input`, headers: { 'x-gvr-internal': '1' } })).json().input as CulpritInput; + for (const p of input.players) puuidOf[p.name] = p.puuid; + assert.deepEqual(input.lookup?.riotMatchId, 'demo'); + assert.equal((await h.post(h.login('user1'))).status, 202); + await waitFor(() => h.stages().includes('done') || h.stages().includes('failed')); + assert.deepEqual(h.stages(), ['collect', 'thinking', 'verify', 'done']); + const user = h.seen[0].user; + const lines = user.split('\n'); + const at = lines.findIndex((l) => l.startsWith('# OP.GG 실제 OP스코어')); + assert.ok(at > 0 && at < lines.indexOf('# 시간 순서 기록'), 'OP.GG 줄은 시간 순서 기록 앞'); + assert.match(lines[at], /: P1 6\.6 · P2 6\.6 .* · P10 6\.6$/); + assert.ok(lines.some((l) => l.startsWith('# 기록 점수 (0~10, OP.GG OP스코어 방식')), '기록 점수 칸 (앱이 만든다)'); + assert.equal(calls.length, 10); + const info = (await (await fetch(`${h.base}/api/culprit/matches/${h.matchId}`, { headers: { cookie: h.login('member1') } })).json()) as CulpritMatchInfo; + assert.deepEqual(info.analysis!.meta.opgg, { found: true }); + assert.deepEqual(info.analysis!.players.find((p) => p.id === 'P3')!.opgg, { score: 6.6, rank: null }); + assert.ok(info.analysis!.players.every((p) => p.rating && p.rating.score >= 0), '저장된 참가자에 기록 점수'); + } finally { + await h.close(); + } +}); + +test('OP.GG: 응답 해석 · 롤 경기 찾기 (시작 시각 · 길이) · 못 찾음 · 연결 실패', async () => { + const text = [ + 'class L: data', + 'class Data: game_history', + 'class GameHistory: id,created_at,game_length_second,game_type', + '', + 'L(Data([GameHistory("g1","2026-10-15T02:12:05+09:00",1387,"SOLORANKED"),GameHistory("g2","2026-10-15T01:00:00+09:00",900,"NORMAL")]))', + ].join('\n'); + assert.deepEqual(parseOpgg(text), { + data: { + game_history: [ + { id: 'g1', created_at: '2026-10-15T02:12:05+09:00', game_length_second: 1387, game_type: 'SOLORANKED' }, + { id: 'g2', created_at: '2026-10-15T01:00:00+09:00', game_length_second: 900, game_type: 'NORMAL' }, + ], + }, + }); + assert.deepEqual(parseOpgg('X(true,null,-1.5,"a\\"b",[1,2])\n'.replace(/^/, 'class X: a,b,c,d,e\n\n')), { a: true, b: null, c: -1.5, d: 'a"b', e: [1, 2] }); + + const players = Array.from({ length: 10 }, (_, i) => ({ id: `P${i + 1}`, puuid: `pu${i}`, name: `n${i}`, tag: 'KR1', team: i < 5 ? 'ally' : 'enemy', character: null, userId: i === 2 ? 'u' : null, voice: false })) as CulpritInput['players']; + const input = { game: 'lol', text: '', refs: {}, players, stats: {} as any, lookup: { riotMatchId: '777', startedAt: Date.parse('2026-10-15T02:12:30+09:00'), endedAt: 0, durationSec: 1400 } } as CulpritInput; + const asked: any[] = []; + const caller: ToolCaller = async (name, args) => { + asked.push([name, args]); + if (name === 'lol_list_summoner_matches') return parseOpgg(text); + return { + data: { + game_detail: { + teams: [0, 1].map((t) => ({ + participants: players.slice(t * 5, t * 5 + 5).map((p, i) => ({ + // 한 명은 puuid 가 달라도 Riot ID 로 맞춘다 + summoner: { puuid: p.id === 'P9' ? 'other' : p.puuid, game_name: p.name.toUpperCase(), tagline: 'kr1' }, + stats: { op_score: 5 + t + i / 10, op_score_rank: t * 5 + i + 1 }, + })), + })), + }, + }, + }; + }; + const r = await lookupOpgg(input, caller); + assert.equal(r.found, true); + assert.equal(r.scores.size, 10); + assert.deepEqual(r.scores.get('P9'), { score: 6.3, rank: 9 }); + assert.equal(asked[0][1].game_name, 'n2', '우리 사람(앱 계정)부터'); + assert.deepEqual(asked[1][1].game_id, 'g1'); + // 시작 시각이 다르면 못 찾음 (내전 · 아직 OP.GG 에 없음) + const miss = await lookupOpgg({ ...input, lookup: { ...input.lookup!, startedAt: Date.parse('2026-10-14T10:00:00+09:00') } }, caller); + assert.equal(miss.found, false); + assert.match(miss.note!, /OP\.GG 에 이 경기가 없습니다/); + // 연결 실패도 분석을 멈추지 않는다 (찾지 못함으로) + const down = await lookupOpgg(input, async () => { + throw new Error('down'); + }); + assert.equal(down.found, false); +}); diff --git a/site/web/src/pages/CulpritPage.tsx b/site/web/src/pages/CulpritPage.tsx index 7165490..63baf35 100644 --- a/site/web/src/pages/CulpritPage.tsx +++ b/site/web/src/pages/CulpritPage.tsx @@ -277,7 +277,7 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM

참가자 {info.players.length}명 - 음성 = 대화 기록 있음 + 음성 = 대화 기록 있음{info.players.some((p) => p.rating) ? ' · 숫자 = 기록 점수(OP.GG 방식)' : ''}

{info.players.map((p) => (
@@ -287,6 +287,12 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM {p.team === 'ally' ? '우리 팀' : '상대 팀'} · {p.character?.name ?? '?'} + {p.rating && ( + + {p.rating.badge && {p.rating.badge}} + {p.rating.score.toFixed(1)} + + )}
))}
@@ -419,6 +425,12 @@ function ResultView({ info, budget, onBack, onReanalyze }: { info: CulpritMatchI 기본 기록으로 분석 )} + {a.meta.opgg && ( + <> +
+ {a.meta.opgg.found ? 'OP.GG 실제 점수 참고' : 'OP.GG 에 없는 경기 · 기록 점수로 분석'} + + )} {budget?.canReanalyze && ( <>
@@ -450,6 +462,7 @@ function ResultView({ info, budget, onBack, onReanalyze }: { info: CulpritMatchI
평점 {sc?.score.toFixed(1)} / 10{p && !p.voice ? ' · 음성 없음, 게임 기록으로 판단' : ''}
+ {p && }
범인
@@ -499,6 +512,7 @@ function ResultView({ info, budget, onBack, onReanalyze }: { info: CulpritMatchI {r.tag}
{r.comment}
+ {r.tag !== '범인' && r.evidence.length > 0 && (
{r.evidence.map((e) => ( @@ -521,6 +535,40 @@ function ResultView({ info, budget, onBack, onReanalyze }: { info: CulpritMatchI ); } +/** 전적 사이트 점수 줄: 기록 점수(OP.GG 방식) · OP.GG 실제 점수 · MVP/ACE, parts 면 강점 · 약점 · 롤 라인전(LOL.PS 방식) */ +function RefLine({ p, parts = false }: { p: CulpritPlayer; parts?: boolean }) { + const r = p.rating; + if (!r && !p.opgg) return null; + return ( +
+ {r && ( + + 기록 점수 {r.score.toFixed(1)} · 팀 {r.teamRank}위 + + )} + {p.opgg && ( + + OP.GG {p.opgg.score.toFixed(1)} + + )} + {r?.badge && {r.badge}} + {parts && + r?.parts.map((x) => ( + + {x.good ? '▲' : '▼'} {x.text} + + ))} + {parts && r?.lane && ( + = 0 ? 'up' : 'down'} title="LOL.PS 방식 라인전: 15분에 맞라인 상대와의 차"> + 15분 라인전 CS {signed(r.lane.cs)} · 골드 {signed(r.lane.gold)} + + )} +
+ ); +} + +const signed = (n: number) => `${n >= 0 ? '+' : ''}${n.toLocaleString('en-US')}`; + function modelName(id: string): string { const m = /^claude-(opus|sonnet|haiku|fable)-(\d+)(?:-(\d+))?/.exec(id); if (!m) return id; diff --git a/site/web/src/styles.css b/site/web/src/styles.css index d948842..11c9c98 100644 --- a/site/web/src/styles.css +++ b/site/web/src/styles.css @@ -3399,6 +3399,14 @@ button.match:hover { .cu-tag.meh { background: #22202a; color: #c3b3e0; border: 1px solid #3a3450; } .cu-tag.bad { background: #2a1418; color: #ff8a94; border: 1px solid #5a2029; } .cu-cm { font-size: 13px; line-height: 1.5; color: #c9d3dc; } +.cu-ref { font-variant-numeric: tabular-nums; font-size: 12.5px; font-weight: 700; color: #c9d3dc; display: inline-flex; gap: 5px; align-items: center; } +.cu-ref em, .cu-refline em { font-style: normal; font-size: 10px; font-weight: 800; border-radius: 4px; padding: 0 4px; } +.cu-ref em.mvp, .cu-refline em.mvp { color: #1a1300; background: #f4c542; } +.cu-ref em.ace, .cu-refline em.ace { color: #f1e9ff; background: #7a52c7; } +.cu-refline { display: flex; flex-wrap: wrap; gap: 4px 10px; margin-top: 3px; font-size: 11.5px; color: #8d9aa6; } +.cu-refline b { color: #dfe7ee; font-variant-numeric: tabular-nums; } +.cu-refline .up { color: #7fe0b8; } +.cu-refline .down { color: #ff9b8f; } .cu-foot { font-size: 12px; color: var(--dim); display: flex; gap: 16px; flex-wrap: wrap; justify-content: space-between; } @media (max-width: 1200px) { .cu-split { grid-template-columns: 1fr; }