diff --git a/app/subs/otel/[tenant]/e/[id]/page.tsx b/app/subs/otel/[tenant]/e/[id]/page.tsx new file mode 100644 index 0000000..c794f07 --- /dev/null +++ b/app/subs/otel/[tenant]/e/[id]/page.tsx @@ -0,0 +1,100 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { findTenant, getSession, tenantPath } from "@/app/subs/otel/lib/tenant"; +import { eventById } from "@/app/subs/otel/lib/queries"; +import { Card, Header, kst } from "../../ui"; + +export const dynamic = "force-dynamic"; + +const PRE = + "max-h-[70vh] overflow-auto whitespace-pre-wrap break-all rounded-proofer-xs bg-proofer-bg-alt p-3 text-xs"; + +// 이벤트 한 건의 원본(속성, 리소스, 스코프, 본문)을 그대로 보여준다. +export default async function EventDetail({ + params, +}: { + params: Promise<{ tenant: string; id: string }>; +}) { + const { tenant: slug, id } = await params; + const tenant = await findTenant(slug); + if (!tenant) notFound(); + const session = await getSession(tenant); + if (!session) redirect(tenantPath(slug)); + + const eventId = Number(id); + if (!Number.isSafeInteger(eventId)) notFound(); + const e = await eventById(tenant.id, eventId); + if (!e) notFound(); + + // 긴 문자열 속성(prompt, response, tool_input)은 따로 펼쳐 읽기 쉽게 한다. + const longText = Object.entries(e.attributes).filter( + ([, v]) => typeof v === "string" && (v.length > 200 || v.includes("\n")), + ) as [string, string][]; + + return ( + <> +
+
+ + 이벤트 목록으로 + +

+ {e.event_name} +

+

+ {kst(e.at)} / {e.service_name} / {e.user_email} + {e.session_id && ( + <> + {" / "} + + 세션 리플레이 + + + )} + {e.prompt_id && ( + <> + {" / "} + + 같은 프롬프트의 이벤트 + + + )} +

+ {longText.map(([k, v]) => ( + +
{v}
+
+ ))} + +
{JSON.stringify(e.attributes, null, 2)}
+
+
+ +
{JSON.stringify(e.resource, null, 2)}
+
+ +
+              {JSON.stringify(
+                { scope: e.scope, body: e.body, severity: e.severity },
+                null,
+                2,
+              )}
+            
+
+
+
+ + ); +} diff --git a/app/subs/otel/[tenant]/events/page.tsx b/app/subs/otel/[tenant]/events/page.tsx new file mode 100644 index 0000000..41aec9b --- /dev/null +++ b/app/subs/otel/[tenant]/events/page.tsx @@ -0,0 +1,177 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { findTenant, getSession, tenantPath } from "@/app/subs/otel/lib/tenant"; +import { + EVENT_PAGE, + RANGES, + eventFacets, + listEvents, + parseRange, +} from "@/app/subs/otel/lib/queries"; +import { Card, Header, Table, kst, n } from "../ui"; + +export const dynamic = "force-dynamic"; + +type Search = { + days?: string; + event?: string; + user?: string; + session?: string; + prompt?: string; + before?: string; +}; + +const SELECT = + "h-9 rounded-proofer-xs border border-proofer-line bg-white px-2 text-sm"; + +// 모든 이벤트를 종류, 사용자, 세션, 프롬프트로 걸러 본다. 행을 누르면 원본 전체가 보인다. +export default async function Events({ + params, + searchParams, +}: { + params: Promise<{ tenant: string }>; + searchParams: Promise; +}) { + const { tenant: slug } = await params; + const q = await searchParams; + const tenant = await findTenant(slug); + if (!tenant) notFound(); + const session = await getSession(tenant); + if (!session) redirect(tenantPath(slug)); + + const days = parseRange(q.days); + const before = Number(q.before) || undefined; + const [facets, list] = await Promise.all([ + eventFacets(tenant.id, days), + listEvents(tenant.id, { + days, + event: q.event || undefined, + user: q.user || undefined, + session: q.session || undefined, + prompt: q.prompt || undefined, + before, + }), + ]); + + const base = tenantPath(slug, "/events"); + const keep = new URLSearchParams( + Object.entries({ ...q, before: undefined }).filter( + (e): e is [string, string] => typeof e[1] === "string" && e[1] !== "", + ), + ); + const nextHref = + list.length === EVENT_PAGE + ? `${base}?${new URLSearchParams({ ...Object.fromEntries(keep), before: String(list[list.length - 1].id) })}` + : null; + + return ( + <> +
+
+

이벤트

+
+ + + + + + + + 초기화 + +
+ + + [ + + {kst(e.at)} + , + + {e.event_name} + , + + {e.summary} + , + e.user_email ?? "", + e.session_id ? ( + + {e.session_id.slice(0, 8)} + + ) : ( + "" + ), + + 원본 + , + ])} + /> + {nextHref && ( +
+ + 다음 {EVENT_PAGE}건 + +
+ )} + + + + ); +} diff --git a/app/subs/otel/[tenant]/page.tsx b/app/subs/otel/[tenant]/page.tsx index edafff8..0cca087 100644 --- a/app/subs/otel/[tenant]/page.tsx +++ b/app/subs/otel/[tenant]/page.tsx @@ -11,6 +11,7 @@ import { kpis, parseRange, recentPrompts, + textOrNull, } from "@/app/subs/otel/lib/queries"; import DailyChart from "./DailyChart"; import { Card, Header, Stat, Table, compact, kst, n, usd } from "./ui"; @@ -135,7 +136,13 @@ export default async function TenantDashboard({ params, searchParams }: Props) { head={["사용자", "프롬프트", "세션", "비용", "마지막 활동"]} align={["left", "right", "right", "right", "right"]} rows={users.map((u) => [ - u.user_email ?? "(없음)", + + {u.user_email ?? "(없음)"} + , n(u.prompts), n(u.sessions), usd(u.cost_usd), @@ -175,25 +182,44 @@ export default async function TenantDashboard({ params, searchParams }: Props) {
[ - - {kst(p.at)} - , - p.user_email ?? "", - p.service_name ?? "", - p.prompt_id ? ( - - {p.prompt ?? `(본문 미수집, ${p.prompt_length ?? "?"}자)`} - - ) : ( - (p.prompt ?? `(본문 미수집, ${p.prompt_length ?? "?"}자)`) - ), - ])} + head={["시각", "사용자", "출처", "프롬프트", ""]} + rows={prompts.map((p) => { + const text = + textOrNull(p.prompt) ?? + `(본문 미수집, ${p.prompt_length ?? "?"}자)`; + return [ + + {kst(p.at)} + , + p.user_email ?? "", + p.service_name ?? "", + p.prompt_id ? ( + + {text} + + ) : ( + text + ), + p.session_id ? ( + + 리플레이 + + ) : ( + "" + ), + ]; + })} /> diff --git a/app/subs/otel/[tenant]/s/[sessionId]/Replay.tsx b/app/subs/otel/[tenant]/s/[sessionId]/Replay.tsx new file mode 100644 index 0000000..92cff39 --- /dev/null +++ b/app/subs/otel/[tenant]/s/[sessionId]/Replay.tsx @@ -0,0 +1,210 @@ +"use client"; + +import React, { useCallback, useEffect, useRef, useState } from "react"; +import type { ReplayItem } from "@/app/subs/otel/lib/replay"; + +const SPEEDS = [1, 4, 16] as const; +const MIN_STEP_MS = 250; +const MAX_STEP_MS = 1500; + +const time = (iso: string) => + new Date(iso).toLocaleTimeString("ko-KR", { + timeZone: "Asia/Seoul", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); + +const usd = (v: number) => `$${v.toFixed(4)}`; + +function Missing({ what, length }: { what: string; length: number | null }) { + return ( + + {what} 본문 미수집 + {length !== null ? ` (${length.toLocaleString("ko-KR")}자)` : ""} + + ); +} + +function Item({ item }: { item: ReplayItem }) { + switch (item.kind) { + case "user": + return ( +
+
+ {item.text ?? } +
+ + {time(item.at)} + +
+ ); + case "assistant": + return ( +
+
+ {item.text ?? } +
+ + {time(item.at)} + {item.model ? ` / ${item.model}` : ""} + +
+ ); + case "tool": { + const failed = item.success === false; + return ( +
+ + + {item.name} + + + {item.decision === "reject" + ? "거부됨" + : item.success === true + ? "성공" + : item.success === false + ? "실패" + : ""} + + {item.durationMs !== null && ( + {Math.round(item.durationMs)}ms + )} + {item.decisionSource && ({item.decisionSource})} + {time(item.at)} + +
+ {item.input ? ( +
+                {item.input}
+              
+ ) : ( +

툴 입력 미수집

+ )} + {item.error && ( +
+                {item.error}
+              
+ )} +
+
+ ); + } + case "api": + return ( +

+ API {item.model ?? ""} / 입력{" "} + {item.inputTokens.toLocaleString("ko-KR")} / 출력{" "} + {item.outputTokens.toLocaleString("ko-KR")} / 캐시{" "} + {item.cacheReadTokens.toLocaleString("ko-KR")} / {usd(item.costUsd)} + {item.durationMs !== null + ? ` / ${(item.durationMs / 1000).toFixed(1)}s` + : ""}{" "} + / {time(item.at)} +

+ ); + case "error": + return ( +

+ API 에러 {item.status ?? ""} {item.model ?? ""}:{" "} + {item.message ?? "(메시지 미수집)"} / {time(item.at)} +

+ ); + case "system": + return ( +
+ + 시스템 이벤트 {item.events.length}건 / {time(item.at)} + +
    + {item.events.map((e) => ( +
  • + {e.name} + {e.detail ? ` ${e.detail}` : ""} +
  • + ))} +
+
+ ); + } +} + +// 실제 대화가 오간 간격을 배속에 맞춰 줄여 하나씩 보여준다. 한 단계는 0.25초에서 1.5초 사이. +export default function Replay({ items }: { items: ReplayItem[] }) { + const [shown, setShown] = useState(items.length); + const [playingRaw, setPlaying] = useState(false); + const playing = playingRaw && shown < items.length; + const [speed, setSpeed] = useState<(typeof SPEEDS)[number]>(4); + const bottom = useRef(null); + + const play = useCallback(() => { + setShown((s) => (s >= items.length ? 0 : s)); + setPlaying(true); + }, [items.length]); + + useEffect(() => { + if (!playing) return; + const prev = shown > 0 ? Date.parse(items[shown - 1].at) : NaN; + const next = Date.parse(items[shown].at); + const gap = Number.isFinite(prev) ? Math.max(0, next - prev) / speed : 0; + const delay = Math.min(MAX_STEP_MS, Math.max(MIN_STEP_MS, gap)); + const t = setTimeout(() => { + setShown((s) => s + 1); + if (shown + 1 >= items.length) setPlaying(false); + }, delay); + return () => clearTimeout(t); + }, [playing, shown, items, speed]); + + useEffect(() => { + if (playing) + bottom.current?.scrollIntoView({ behavior: "smooth", block: "end" }); + }, [shown, playing]); + + return ( +
+
+ + + 배속 + {SPEEDS.map((s) => ( + + ))} + + {shown} / {items.length} + +
+
+ {items.slice(0, shown).map((item) => ( + + ))} +
+
+
+ ); +} diff --git a/app/subs/otel/[tenant]/s/[sessionId]/page.tsx b/app/subs/otel/[tenant]/s/[sessionId]/page.tsx new file mode 100644 index 0000000..9e26f9e --- /dev/null +++ b/app/subs/otel/[tenant]/s/[sessionId]/page.tsx @@ -0,0 +1,71 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { findTenant, getSession, tenantPath } from "@/app/subs/otel/lib/tenant"; +import { sessionEvents } from "@/app/subs/otel/lib/queries"; +import { buildReplay } from "@/app/subs/otel/lib/replay"; +import { Header, kst, n, usd } from "../../ui"; +import Replay from "./Replay"; + +export const dynamic = "force-dynamic"; + +// 세션 하나를 채팅 화면처럼 다시 본다. +export default async function SessionReplay({ + params, +}: { + params: Promise<{ tenant: string; sessionId: string }>; +}) { + const { tenant: slug, sessionId } = await params; + const tenant = await findTenant(slug); + if (!tenant) notFound(); + const session = await getSession(tenant); + if (!session) redirect(tenantPath(slug)); + + const events = await sessionEvents(tenant.id, decodeURIComponent(sessionId)); + if (events.length === 0) notFound(); + const items = buildReplay(events); + + const user = events.find((e) => e.user_email)?.user_email; + const cost = items.reduce( + (s, i) => s + (i.kind === "api" ? i.costUsd : 0), + 0, + ); + const prompts = items.filter((i) => i.kind === "user").length; + const tools = items.filter((i) => i.kind === "tool").length; + const contentMissing = items.some( + (i) => (i.kind === "user" || i.kind === "assistant") && i.text === null, + ); + + return ( + <> +
+
+ + 세션 목록으로 + +

세션 리플레이

+

+ {user} / {kst(items[0]?.at ?? events[0].at)} 시작 / 프롬프트{" "} + {n(prompts)} / 툴 {n(tools)} / {usd(cost)} /{" "} + + 원본 이벤트 {n(events.length)}건 + +

+ {contentMissing && ( +

+ 이 세션은 본문 수집(otlpContentCapture)이 꺼진 기기에서 왔습니다. + 프롬프트와 응답은 글자 수만 보입니다. +

+ )} +
+ +
+
+ + ); +} diff --git a/app/subs/otel/[tenant]/sessions/page.tsx b/app/subs/otel/[tenant]/sessions/page.tsx new file mode 100644 index 0000000..e1edce5 --- /dev/null +++ b/app/subs/otel/[tenant]/sessions/page.tsx @@ -0,0 +1,96 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { findTenant, getSession, tenantPath } from "@/app/subs/otel/lib/tenant"; +import { RANGES, parseRange, sessions } from "@/app/subs/otel/lib/queries"; +import { Card, Header, Table, kst, n, usd } from "../ui"; + +export const dynamic = "force-dynamic"; + +export default async function Sessions({ + params, + searchParams, +}: { + params: Promise<{ tenant: string }>; + searchParams: Promise<{ days?: string; user?: string }>; +}) { + const { tenant: slug } = await params; + const { days: d, user } = await searchParams; + const tenant = await findTenant(slug); + if (!tenant) notFound(); + const session = await getSession(tenant); + if (!session) redirect(tenantPath(slug)); + + const days = parseRange(d); + const list = await sessions(tenant.id, days, user); + const base = tenantPath(slug, "/sessions"); + + return ( + <> +
+
+
+

+ 세션{" "} + {user ? / {user} : null} +

+ +
+ +
[ + + {kst(s.started_at)} + , + + {s.user_email ?? "(없음)"} + , + + {s.first_prompt ?? "(본문 미수집)"} + , + n(s.prompts), + n(s.tool_calls), + usd(s.cost_usd), + + 리플레이 + , + ])} + /> + + + + ); +} diff --git a/app/subs/otel/[tenant]/ui.tsx b/app/subs/otel/[tenant]/ui.tsx index a959714..bd9b1c7 100644 --- a/app/subs/otel/[tenant]/ui.tsx +++ b/app/subs/otel/[tenant]/ui.tsx @@ -104,9 +104,31 @@ export function Header({ session }: { session: Session }) { return (
- - {session.tenantName} OTel - +
+ + {session.tenantName} OTel + + +
{session.email ?? session.name}
{ const r = await rows(sql` - select prompt_id, ${TS} as at, user_email, service_name, + select prompt_id, session_id, ${TS} as at, user_email, service_name, left(attributes->>'prompt', 300) as prompt, (attributes->>'prompt_length')::int as prompt_length from otel_log_record @@ -254,3 +255,171 @@ export async function promptEvents( limit 500 `); } + +// ---- 세션, 이벤트 탐색, 리플레이 ---- + +// Cowork 는 본문 수집이 꺼져 있으면 이 문자열을 보낸다. +export const REDACTED = ""; +export const textOrNull = (v: unknown): string | null => + typeof v === "string" && v !== "" && v !== REDACTED ? v : null; + +export type SessionRow = { + session_id: string; + user_email: string | null; + service_name: string | null; + started_at: string; + ended_at: string; + events: number; + prompts: number; + tool_calls: number; + cost_usd: number; + first_prompt: string | null; +}; + +export async function sessions( + tenantId: number, + days: number, + user?: string, +): Promise { + const r = await rows>(sql` + select session_id, + max(user_email) as user_email, + max(service_name) as service_name, + min(${TS}) as started_at, + max(${TS}) as ended_at, + count(*) as events, + count(*) filter (where event_name = 'user_prompt') as prompts, + count(*) filter (where event_name = 'tool_result') as tool_calls, + coalesce(sum(${num("cost_usd")}) filter (where event_name = 'api_request'), 0) as cost_usd, + (array_agg(attributes->>'prompt' order by ${TS}) filter (where event_name = 'user_prompt'))[1] as first_prompt + from otel_log_record + where tenant_id = ${tenantId} and ${since(days)} and session_id is not null + ${user ? sql`and user_email = ${user}` : sql``} + group by session_id + order by max(${TS}) desc + limit 200 + `); + return r.map((x) => ({ + session_id: x.session_id, + user_email: x.user_email, + service_name: x.service_name, + started_at: x.started_at, + ended_at: x.ended_at, + events: Number(x.events), + prompts: Number(x.prompts), + tool_calls: Number(x.tool_calls), + cost_usd: Number(x.cost_usd), + first_prompt: textOrNull(x.first_prompt), + })); +} + +export type FullEvent = { + id: number; + at: string; + event_name: string | null; + service_name: string | null; + user_email: string | null; + session_id: string | null; + prompt_id: string | null; + severity: string | null; + body: string | null; + attributes: Record; + resource: Record; + scope: Record | null; +}; + +// 같은 배치가 재전송되면 같은 이벤트가 두 번 들어올 수 있어 내용이 같은 행은 하나만 남긴다. +export async function sessionEvents( + tenantId: number, + sessionId: string, +): Promise { + return rows(sql` + select distinct on (event_name, attributes->>'event.timestamp', attributes->>'event.sequence', prompt_id, attributes->>'tool_use_id', attributes->>'request_id') + id, ${TS} as at, event_name, service_name, user_email, session_id, prompt_id, + severity, body, attributes, resource, scope + from otel_log_record + where tenant_id = ${tenantId} and session_id = ${sessionId} + order by event_name, attributes->>'event.timestamp', attributes->>'event.sequence', prompt_id, + attributes->>'tool_use_id', attributes->>'request_id', id + limit 3000 + `); +} + +export type EventFilter = { + event?: string; + user?: string; + session?: string; + prompt?: string; + days: number; + before?: number; +}; + +export type EventListRow = { + id: number; + at: string; + event_name: string | null; + service_name: string | null; + user_email: string | null; + session_id: string | null; + prompt_id: string | null; + summary: string | null; +}; + +export const EVENT_PAGE = 100; + +export async function listEvents( + tenantId: number, + f: EventFilter, +): Promise { + return rows(sql` + select id, ${TS} as at, event_name, service_name, user_email, session_id, prompt_id, + left(coalesce( + attributes->>'tool_name', + attributes->>'model', + attributes->>'plugin.name', + attributes->>'hook_event', + attributes->>'status', + attributes->>'error', + body + ), 120) as summary + from otel_log_record + where tenant_id = ${tenantId} and ${since(f.days)} + ${f.event ? sql`and event_name = ${f.event}` : sql``} + ${f.user ? sql`and user_email = ${f.user}` : sql``} + ${f.session ? sql`and session_id = ${f.session}` : sql``} + ${f.prompt ? sql`and prompt_id = ${f.prompt}` : sql``} + ${f.before ? sql`and id < ${f.before}` : sql``} + order by id desc + limit ${EVENT_PAGE} + `); +} + +export async function eventFacets(tenantId: number, days: number) { + const [events, users] = await Promise.all([ + rows<{ v: string; n: string }>(sql` + select event_name as v, count(*) as n from otel_log_record + where tenant_id = ${tenantId} and ${since(days)} and event_name is not null + group by 1 order by 2 desc`), + rows<{ v: string; n: string }>(sql` + select user_email as v, count(*) as n from otel_log_record + where tenant_id = ${tenantId} and ${since(days)} and user_email is not null + group by 1 order by 2 desc`), + ]); + return { + events: events.map((x) => ({ v: x.v, n: Number(x.n) })), + users: users.map((x) => ({ v: x.v, n: Number(x.n) })), + }; +} + +export async function eventById( + tenantId: number, + id: number, +): Promise { + const [r] = await rows(sql` + select id, ${TS} as at, event_name, service_name, user_email, session_id, prompt_id, + severity, body, attributes, resource, scope + from otel_log_record + where tenant_id = ${tenantId} and id = ${id} + `); + return r ?? null; +} diff --git a/app/subs/otel/lib/replay.test.ts b/app/subs/otel/lib/replay.test.ts new file mode 100644 index 0000000..4edd464 --- /dev/null +++ b/app/subs/otel/lib/replay.test.ts @@ -0,0 +1,96 @@ +/** + * @jest-environment node + */ +import { buildReplay } from "./replay"; + +const ev = ( + id: number, + event_name: string, + seq: number, + attrs: Record = {}, +) => ({ + id, + at: "2026-11-14T15:00:00.000Z", + event_name, + attributes: { + "event.timestamp": `2026-11-14T15:00:${String(seq).padStart(2, "0")}.000Z`, + "event.sequence": seq, + ...attrs, + }, +}); + +describe("buildReplay", () => { + it("프롬프트, 툴, 응답을 시간 순서대로 채팅 항목으로 만든다", () => { + const items = buildReplay([ + ev(4, "assistant_response", 4, { response: "끝났습니다", model: "m" }), + ev(1, "user_prompt", 1, { prompt: "파일 정리해줘", prompt_length: 7 }), + ev(2, "tool_decision", 2, { + tool_use_id: "t1", + decision: "accept", + source: "config", + }), + ev(3, "tool_result", 3, { + tool_use_id: "t1", + tool_name: "Bash", + success: "true", + duration_ms: 120, + tool_input: '{"command":"ls"}', + }), + ]); + expect(items.map((i) => i.kind)).toEqual(["user", "tool", "assistant"]); + expect(items[0]).toMatchObject({ text: "파일 정리해줘", length: 7 }); + expect(items[1]).toMatchObject({ + name: "Bash", + success: true, + decision: "accept", + decisionSource: "config", + input: '{"command":"ls"}', + }); + expect(items[2]).toMatchObject({ text: "끝났습니다" }); + }); + + it(" 는 본문 없음(null)으로 바꾸고 길이는 남긴다", () => { + const [u, a] = buildReplay([ + ev(1, "user_prompt", 1, { prompt: "", prompt_length: 42 }), + ev(2, "assistant_response", 2, { + response: "", + response_length: 900, + }), + ]); + expect(u).toMatchObject({ kind: "user", text: null, length: 42 }); + expect(a).toMatchObject({ kind: "assistant", text: null, length: 900 }); + }); + + it("연속된 시스템 이벤트는 한 묶음으로 접는다", () => { + const items = buildReplay([ + ev(1, "plugin_loaded", 1, { "plugin.name": "a" }), + ev(2, "mcp_server_connection", 2, { status: "connected" }), + ev(3, "user_prompt", 3, { prompt: "hi" }), + ev(4, "hook_execution_start", 4, { hook_event: "Stop" }), + ]); + expect(items.map((i) => i.kind)).toEqual(["system", "user", "system"]); + expect(items[0]).toMatchObject({ + events: [ + { name: "plugin_loaded", detail: "a" }, + { name: "mcp_server_connection", detail: "connected" }, + ], + }); + }); + + it("결과 없이 거부된 툴은 거부 항목으로 남긴다", () => { + const [t] = buildReplay([ + ev(1, "tool_decision", 1, { + tool_use_id: "t9", + tool_name: "Write", + decision: "reject", + source: "user_reject", + }), + ]); + expect(t).toMatchObject({ + kind: "tool", + name: "Write", + decision: "reject", + success: false, + }); + }); +}); diff --git a/app/subs/otel/lib/replay.ts b/app/subs/otel/lib/replay.ts new file mode 100644 index 0000000..a1809c3 --- /dev/null +++ b/app/subs/otel/lib/replay.ts @@ -0,0 +1,227 @@ +// 세션의 이벤트를 채팅 화면처럼 보여줄 항목으로 바꾼다. DB 를 모르는 순수 함수라 테스트한다. + +const REDACTED = ""; +const text = (v: unknown): string | null => + typeof v === "string" && v !== "" && v !== REDACTED ? v : null; +const num = (v: unknown): number | null => { + const n = typeof v === "number" ? v : Number(v); + return Number.isFinite(n) ? n : null; +}; + +export type ReplayEventInput = { + id: number; + at: string | Date; + event_name: string | null; + attributes: Record; +}; + +export type ReplayItem = + | { + kind: "user"; + key: string; + at: string; + text: string | null; + length: number | null; + promptId: string | null; + } + | { + kind: "assistant"; + key: string; + at: string; + text: string | null; + length: number | null; + model: string | null; + } + | { + kind: "tool"; + key: string; + at: string; + name: string; + success: boolean | null; + durationMs: number | null; + input: string | null; + error: string | null; + decision: string | null; + decisionSource: string | null; + } + | { + kind: "api"; + key: string; + at: string; + model: string | null; + inputTokens: number; + outputTokens: number; + cacheReadTokens: number; + costUsd: number; + durationMs: number | null; + } + | { + kind: "error"; + key: string; + at: string; + message: string | null; + status: string | null; + model: string | null; + } + | { + kind: "system"; + key: string; + at: string; + events: { id: number; name: string; detail: string | null }[]; + }; + +const iso = (v: string | Date) => new Date(v).toISOString(); + +function eventTime(e: ReplayEventInput): number { + const ts = e.attributes["event.timestamp"]; + const t = typeof ts === "string" ? Date.parse(ts) : NaN; + return Number.isFinite(t) ? t : new Date(e.at).getTime(); +} + +export function sortEvents(events: T[]): T[] { + return [...events].sort((a, b) => { + const dt = eventTime(a) - eventTime(b); + if (dt !== 0) return dt; + const sa = num(a.attributes["event.sequence"]) ?? 0; + const sb = num(b.attributes["event.sequence"]) ?? 0; + return sa - sb || a.id - b.id; + }); +} + +function systemDetail(e: ReplayEventInput): string | null { + const a = e.attributes; + return ( + text(a["plugin.name"]) ?? + text(a["hook_event"]) ?? + text(a["status"]) ?? + text(a["managed_settings.trigger"]) ?? + null + ); +} + +export function buildReplay(input: ReplayEventInput[]): ReplayItem[] { + const events = sortEvents(input); + const items: ReplayItem[] = []; + // tool_use_id 별 권한 결정. tool_result 에 붙이고, 결과 없이 거부된 것만 따로 보인다. + const decisions = new Map(); + const resulted = new Set(); + for (const e of events) { + const id = text(e.attributes["tool_use_id"]); + if (e.event_name === "tool_decision" && id) decisions.set(id, e); + if (e.event_name === "tool_result" && id) resulted.add(id); + } + + let system: Extract | null = null; + const flushSystem = () => { + if (system) items.push(system); + system = null; + }; + + for (const e of events) { + const a = e.attributes; + const at = iso(new Date(eventTime(e))); + const key = String(e.id); + switch (e.event_name) { + case "user_prompt": + flushSystem(); + items.push({ + kind: "user", + key, + at, + text: text(a["prompt"]) ?? text(a["prompt_text"]), + length: num(a["prompt_length"]), + promptId: text(a["prompt.id"]), + }); + break; + case "assistant_response": + flushSystem(); + items.push({ + kind: "assistant", + key, + at, + text: text(a["response"]), + length: num(a["response_length"]), + model: text(a["model"]), + }); + break; + case "tool_result": { + flushSystem(); + const id = text(a["tool_use_id"]); + const d = id ? decisions.get(id) : undefined; + const success = a["success"]; + items.push({ + kind: "tool", + key, + at, + name: text(a["tool_name"]) ?? "(unknown)", + success: + success === "true" || success === true + ? true + : success === "false" || success === false + ? false + : null, + durationMs: num(a["duration_ms"]), + input: text(a["tool_input"]) ?? text(a["tool_parameters"]), + error: text(a["error"]), + decision: text(d?.attributes["decision"]) ?? text(a["decision_type"]), + decisionSource: + text(d?.attributes["source"]) ?? text(a["decision_source"]), + }); + break; + } + case "tool_decision": { + const id = text(a["tool_use_id"]); + if (id && resulted.has(id)) break; + if (text(a["decision"]) !== "reject") break; + flushSystem(); + items.push({ + kind: "tool", + key, + at, + name: text(a["tool_name"]) ?? "(unknown)", + success: false, + durationMs: null, + input: null, + error: null, + decision: "reject", + decisionSource: text(a["source"]), + }); + break; + } + case "api_request": + flushSystem(); + items.push({ + kind: "api", + key, + at, + model: text(a["model"]), + inputTokens: num(a["input_tokens"]) ?? 0, + outputTokens: num(a["output_tokens"]) ?? 0, + cacheReadTokens: num(a["cache_read_tokens"]) ?? 0, + costUsd: num(a["cost_usd"]) ?? 0, + durationMs: num(a["duration_ms"]), + }); + break; + case "api_error": + flushSystem(); + items.push({ + kind: "error", + key, + at, + message: text(a["error"]), + status: text(a["status_code"]), + model: text(a["model"]), + }); + break; + default: + if (!system) system = { kind: "system", key, at, events: [] }; + system.events.push({ + id: e.id, + name: e.event_name ?? "(none)", + detail: systemDetail(e), + }); + } + } + flushSystem(); + return items; +}