범인찾기 v1.3.1: OP.GG 세션 재시작 · 조회 실패 구분 · LOL.PS 라인전 10/15분

- opgg.ts: 세션 404 → 새 initialize 후 한 번 다시 (MCP 규격), 실패를 '경기 없음'과 나눠 meta.opgg.error · 화면 · 지시문에 반영
- rating.ts: 라인전을 LOL.PS 원문 정의대로 10 · 15분 맞라이너 CS · 골드 · 경험치 차로
- tools/opscore-fit/README.md: OP.GG(롤 · 발로란트) · LOL.PS 원문 인용과 구현 대응
- 테스트: 세션 재시작 · 503 · 일부 실패 · 서버 메타, 라인전 10/15분

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 15:57:00 +09:00
parent 34b1822426
commit 0e0a2723e3
14 changed files with 189 additions and 45 deletions

View File

@@ -10,8 +10,8 @@ user 메시지의 <match> 안에 경기 자료가 온다.
- 참가자: 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 에 없는 경기(내전 등)다.
롤 "라인전(vs P6) 10분 CS+5 골드+300 경험치+120 15분 CS+12 골드+640 경험치+210" = 전적 사이트 LOL.PS 가 라인전 점수를 낼 때 쓰는 값. 10분 · 15분에 맞라이너보다 앞선(+) · 뒤진(-) CS · 골드 · 경험치.
- "OP.GG 실제 OP스코어" 줄이 있으면 이 경기를 OP.GG 에서 찾은 그 사이트의 실제 점수다. 기록 점수보다 이것을 먼저 본다. 이 줄이 없으면 OP.GG 에 없는 경기(내전 등)이거나 조회하지 못한 경기다.
- 시간 순서의 줄. 줄 앞 번호가 근거 번호다.
- [e번호] 게임 이벤트 (킬, 스파이크, 오브젝트, 라운드 결과 등)
- [u번호] 음성 문장. 디스코드 음성채널에서 자동 음성 인식으로 받아 적은 것이라 글자가 틀릴 수 있다.

View File

@@ -363,12 +363,12 @@ export function registerCulprit(app: FastifyInstance, o: CulpritOptions) {
let fallback = false;
try {
// 전적 사이트 점수: 이 경기가 OP.GG 에 있으면 실제 OP스코어를 자료에 붙인다 (없거나 실패해도 기록 점수로 계속)
let opggMeta: { found: boolean; note?: string } | undefined;
let opggMeta: { found: boolean; error?: 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 } : {}) };
const r = await lookupOpgg(raw, opgg).catch((e) => ({ scores: new Map(), found: false, error: true, note: `OP.GG 연결 실패 (${String(e?.message ?? e).slice(0, 80)})` }));
opggMeta = { found: r.found, ...(r.error ? { error: true } : {}), ...(r.note ? { note: r.note } : {}) };
input = withOpgg(raw, r);
log.info({ matchId, opgg: opggMeta, n: r.scores.size }, '범인찾기 OP.GG 점수');
}

View File

@@ -15,9 +15,14 @@ export interface OpggResult {
/** P번호 → 점수 (0~10) · OP.GG 경기 순위 (롤만) */
scores: Map<string, { score: number; rank: number | null }>;
found: boolean;
/** 조회가 실패해서 경기가 있는지 확인하지 못했다 (OP.GG 장애 · 연결 실패). "경기 없음"과 다르다 */
error?: boolean;
note?: string;
}
/** 세션이 끝났다는 서버 응답 (MCP 규격: 404 → 새로 initialize) */
class SessionExpired extends Error {}
export type ToolCaller = (name: string, args: Record<string, unknown>) => Promise<unknown>;
/** MCP 스트리머블 HTTP 클라이언트 (세션 하나로 여러 번 부른다) */
@@ -31,6 +36,7 @@ export function opggCaller(opts: { url?: string; timeoutMs?: number; fetchFn?: t
const headers: Record<string, string> = { '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 (sid && r.status === 404) throw new SessionExpired('OP.GG 세션 만료');
if (!r.ok) throw new Error(`OP.GG ${r.status}`);
const s = r.headers.get('mcp-session-id');
const text = await r.text();
@@ -38,13 +44,26 @@ export function opggCaller(opts: { url?: string; timeoutMs?: number; fetchFn?: t
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) {
let starting: Promise<void> | null = null;
const start = () =>
(starting ??= (async () => {
sid = null;
const init = await post({ jsonrpc: '2.0', id: id++, method: 'initialize', params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: 'gvr', version: '1.3' } } });
if (!init.sid) throw new Error('OP.GG 세션 없음');
sid = init.sid;
if (!sid) throw new Error('OP.GG 세션 없음');
})().finally(() => (starting = null)));
const toolCall = (name: string, args: Record<string, unknown>) => post({ jsonrpc: '2.0', id: id++, method: 'tools/call', params: { name, arguments: args } });
return async (name, args) => {
if (!sid) await start();
let res;
try {
res = await toolCall(name, args);
} catch (e) {
// 세션이 끝났으면(서버 재시작 · 만료) 새 세션으로 한 번 다시
if (!(e instanceof SessionExpired)) throw e;
await start();
res = await toolCall(name, args);
}
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)}`);
@@ -109,6 +128,7 @@ export function parseOpgg(text: string): unknown {
return val();
}
const NOT_FOUND = 'OP.GG 에 이 경기가 없습니다 (사용자 설정 게임은 OP.GG 에 올라가지 않습니다)';
const riotKey = (name: string, tag: string) => `${name}#${tag}`.toLowerCase().replace(/\s+/g, '');
/** 이 경기를 OP.GG 에서 찾아 참가자별 실제 점수. 전체 제한 시간 안에 못 끝나면 그때까지 찾은 만큼 */
@@ -123,12 +143,26 @@ export async function lookupOpgg(input: CulpritInput, call: ToolCaller, opts: {
// 우리 사람(음성 · 앱 계정)부터 찾아본다
const order = [...tagged].sort((a, b) => Number(!!b.userId) - Number(!!a.userId) || Number(a.team !== 'ally') - Number(b.team !== 'ally'));
let calls = 0;
let failed = 0;
let lastError = '';
const fail = (e: unknown) => {
failed++;
lastError = String((e as Error)?.message ?? e).slice(0, 80);
};
/** 못 찾았을 때: 조회가 모두(또는 일부) 실패했으면 "확인 못 함", 다 성공했는데 없으면 "경기 없음" */
const missing = (): OpggResult =>
failed
? { scores, found: false, error: true, note: `OP.GG 조회 실패로 이 경기를 확인하지 못했습니다 (${calls}번 중 ${failed}번 실패: ${lastError})` }
: { scores, found: false, note: NOT_FOUND };
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()) {
calls++;
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 ?? []);
@@ -136,19 +170,20 @@ export async function lookupOpgg(input: CulpritInput, call: ToolCaller, opts: {
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 {
/* 이 사람은 건너뛴다 */
} catch (e) {
fail(e); // 이 사람은 건너뛴다
}
}
};
await Promise.all([worker(), worker(), worker()]);
if (!seen) return { scores, found: false, note: 'OP.GG 에 이 경기가 없습니다 (사용자 설정 게임은 OP.GG 에 올라가지 않습니다)' };
if (!seen) return missing();
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;
calls++;
try {
const hist = (await call('lol_list_summoner_matches', {
game_name: p.name,
@@ -162,6 +197,7 @@ export async function lookupOpgg(input: CulpritInput, call: ToolCaller, opts: {
(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;
calls++;
const det = (await call('lol_get_summoner_game_detail', {
region,
game_id: g.id,
@@ -178,11 +214,11 @@ export async function lookupOpgg(input: CulpritInput, call: ToolCaller, opts: {
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 {
/* 다음 사람으로 */
} catch (e) {
fail(e); // 다음 사람으로
}
}
return { scores, found: false, note: 'OP.GG 에 이 경기가 없습니다 (사용자 설정 게임은 OP.GG 에 올라가지 않습니다)' };
return missing();
}
/** AI 자료에 붙일 줄 (찾은 것만) */

View File

@@ -9,7 +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';
import { lookupOpgg, opggCaller, parseOpgg, type ToolCaller } from '../src/opgg.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-culprit-srv-'));
@@ -291,6 +291,27 @@ test('범인찾기: 결과 확인 규칙 · 비용 계산 · 프롬프트 조립
assert.deepEqual(schema.required, ['summary', 'confidence', 'confidence_note', 'teams', 'players']);
});
test('범인찾기 서버: OP.GG 조회 실패는 "경기 없음"과 따로 저장하고 기록 점수로 분석을 마친다', async () => {
const h = await harness({
calls: [(i) => ok(i)],
opgg: async () => {
throw new Error('OP.GG 503');
},
});
try {
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']);
assert.ok(!h.seen[0].user.includes('# OP.GG 실제 OP스코어'));
const info = (await (await fetch(`${h.base}/api/culprit/matches/${h.matchId}`, { headers: { cookie: h.login('member1') } })).json()) as CulpritMatchInfo;
assert.equal(info.analysis!.meta.opgg!.found, false);
assert.equal(info.analysis!.meta.opgg!.error, true);
assert.match(info.analysis!.meta.opgg!.note!, /조회 실패/);
} finally {
await h.close();
}
});
test('범인찾기 서버: OP.GG 에 경기가 있으면 실제 OP스코어를 자료 · 결과에 붙인다', async () => {
const puuidOf: Record<string, string> = {};
const calls: string[] = [];
@@ -372,9 +393,56 @@ test('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');
throw new Error('OP.GG 503');
});
assert.equal(down.found, false);
assert.equal(down.error, true);
assert.match(down.note!, /OP\.GG 조회 실패로 이 경기를 확인하지 못했습니다 \(3번 중 3번 실패: OP\.GG 503\)/);
assert.equal(miss.error, undefined, '조회는 됐는데 없으면 error 아님');
const vMiss = await lookupOpgg({ ...input, game: 'valorant' }, async () => []);
assert.deepEqual([vMiss.found, vMiss.error, /이 경기가 없습니다/.test(vMiss.note!)], [false, undefined, true]);
// 일부만 실패하고 못 찾았으면 확인 못 함
let k = 0;
const vHalf = await lookupOpgg({ ...input, game: 'valorant' }, async () => {
if (k++ % 2) throw new Error('OP.GG 503');
return [];
});
assert.equal(vHalf.error, true);
});
test('OP.GG 클라이언트: 세션이 끝나면(404) 새로 initialize 하고 다시 부른다', async () => {
let serverSid = 's1';
let inits = 0;
const seen: { method: string; sid: string | null }[] = [];
const fetchFn = (async (_url: string, init: any) => {
const body = JSON.parse(init.body);
const sid = init.headers['mcp-session-id'] ?? null;
seen.push({ method: body.method, sid });
if (body.method === 'initialize') {
inits++;
if (sid) return new Response('bad', { status: 400 });
return new Response(JSON.stringify({ jsonrpc: '2.0', id: body.id, result: {} }), { status: 200, headers: { 'mcp-session-id': serverSid } });
}
if (sid !== serverSid) return new Response('session not found', { status: 404 });
if (body.params.name === 'boom') return new Response('unavailable', { status: 503 });
// SSE 로 줄 때도 읽는다
const msg = JSON.stringify({ jsonrpc: '2.0', id: body.id, result: { content: [{ type: 'text', text: JSON.stringify({ ok: body.params.name, sid }) }] } });
return new Response(`event: message\ndata: ${msg}\n\n`, { status: 200, headers: { 'content-type': 'text/event-stream' } });
}) as typeof fetch;
const call = opggCaller({ url: 'http://opgg.test/mcp', fetchFn });
assert.deepEqual(await call('a', {}), { ok: 'a', sid: 's1' });
// 서버가 재시작해 세션이 사라졌다
serverSid = 's2';
assert.deepEqual(await call('b', {}), { ok: 'b', sid: 's2' });
assert.deepEqual(await call('c', {}), { ok: 'c', sid: 's2' }, '새 세션을 계속 쓴다');
assert.equal(inits, 2);
assert.deepEqual(
seen.map((x) => `${x.method}:${x.sid ?? '-'}`),
['initialize:-', 'tools/call:s1', 'tools/call:s1', 'initialize:-', 'tools/call:s2', 'tools/call:s2'],
);
// 세션 문제가 아닌 실패(503)는 다시 initialize 하지 않고 그대로 실패
await assert.rejects(call('boom', {}), /OP\.GG 503/);
assert.equal(inits, 2);
});