Skip to content
TypeScript
11.5 KB
Raw Blame
/**
 * Claude Code transcript 파서 (PRD §8). 두 레이아웃 모두 지원:
 *  (A) 인라인 sidechain (구버전/mock): isSidechain:true 이벤트가 서브에이전트 내부, parentUuid 체인.
 *  (B) 별도 파일 (현행 cc): <session>/subagents/agent-<id>.jsonl + meta.json(toolUseId 로 멀티레벨 부모 링크).
 *      러너가 subagents/ 를 work_dir 의 transcript_subagents/ 로 복사 → 파서가 sibling 으로 읽어 토큰/도구 총합 합산.
 */
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { CcLineSchema, CcSubagentMetaSchema } from "../models";
import type { ParsedTranscript, TranscriptEvent } from "../models";
import {
  SKILL_NAMES,
  SUBAGENT_NAMES,
  type TranscriptParser,
  compressTools,
  isMcp,
  truncate,
  tsToMs,
} from "./base";

interface ToolUse {
  id: string;
  name: string;
  input: any;
}
interface Entry {
  uuid: string;
  parentUuid: string | null;
  isSidechain: boolean;
  tsMs: number | null;
  model: string | null;
  usage: { in: number; out: number; cr: number; cc: number };
  toolUses: ToolUse[];
  texts: string[];
  isResult: boolean;
  sessionId: string | null;
}

interface Agg {
  key: string;
  label: string;
  tIn: number;
  tOut: number;
  tCr: number;
  tCc: number;
  toolCalls: number;
  skillFires: number;
  mcpCalls: number;
  tools: string[];
  skills: string[];
  steps: string[];
  logs: string[];
  startMs: number | null;
  endMs: number | null;
  parentKey: string | null; // root 면 null
  status: "success" | "fail";
}

function readLines(path: string): Entry[] {
  let raw: string;
  try {
    raw = readFileSync(path, "utf8");
  } catch {
    return [];
  }
  const entries: Entry[] = [];
  for (const line of raw.split("\n")) {
    const s = line.trim();
    if (!s) continue;
    let obj: any;
    try {
      obj = JSON.parse(s);
    } catch {
      continue;
    }
    const parsed = CcLineSchema.safeParse(obj);
    if (!parsed.success) continue;
    const o: any = obj;
    const msg: any = o.message ?? {};
    const usage: any = msg.usage ?? {};
    const content: any[] = Array.isArray(msg.content) ? msg.content : [];
    const toolUses: ToolUse[] = [];
    const texts: string[] = [];
    for (const c of content) {
      if (c && c.type === "tool_use")
        toolUses.push({ id: c.id ?? "", name: c.name ?? "", input: c.input ?? {} });
      else if (c && c.type === "text" && typeof c.text === "string") texts.push(c.text);
    }
    entries.push({
      uuid: o.uuid ?? "",
      parentUuid: o.parentUuid ?? null,
      isSidechain: o.isSidechain === true,
      tsMs: tsToMs(o.timestamp),
      model: msg.model ?? null,
      usage: {
        in: usage.input_tokens ?? 0,
        out: usage.output_tokens ?? 0,
        cr: usage.cache_read_input_tokens ?? 0,
        cc: usage.cache_creation_input_tokens ?? 0,
      },
      toolUses,
      texts,
      isResult: o.type === "result",
      sessionId: o.session_id ?? msg.session_id ?? null,
    });
  }
  return entries;
}

function newAgg(key: string, label: string, parentKey: string | null): Agg {
  return {
    key,
    label,
    tIn: 0,
    tOut: 0,
    tCr: 0,
    tCc: 0,
    toolCalls: 0,
    skillFires: 0,
    mcpCalls: 0,
    tools: [],
    skills: [],
    steps: [],
    logs: [],
    startMs: null,
    endMs: null,
    parentKey,
    status: "success",
  };
}

function attribute(agg: Agg, e: Entry): void {
  agg.tIn += e.usage.in;
  agg.tOut += e.usage.out;
  agg.tCr += e.usage.cr;
  agg.tCc += e.usage.cc;
  if (e.tsMs !== null) {
    if (agg.startMs === null || e.tsMs < agg.startMs) agg.startMs = e.tsMs;
    if (agg.endMs === null || e.tsMs > agg.endMs) agg.endMs = e.tsMs;
  }
  for (const tu of e.toolUses) {
    agg.toolCalls += 1;
    agg.tools.push(tu.name);
    if (SKILL_NAMES.has(tu.name)) {
      agg.skillFires += 1;
      const cmd = tu.input?.command ?? tu.input?.name;
      if (cmd) agg.skills.push(String(cmd));
    }
    if (isMcp(tu.name)) agg.mcpCalls += 1;
    agg.steps.push(SUBAGENT_NAMES.has(tu.name) ? `spawn ${tu.name}` : tu.name);
  }
  for (const t of e.texts) agg.logs.push(t);
}

export class ClaudeCodeParser implements TranscriptParser {
  agent = "cc" as const;

  parse(transcriptPath: string, opts?: { model?: string }): ParsedTranscript {
    const entries = readLines(transcriptPath);
    const byUuid = new Map<string, Entry>();
    for (const e of entries) if (e.uuid) byUuid.set(e.uuid, e);

    const root = newAgg("__root__", "main loop", null);
    const subs = new Map<string, Agg>(); // key = 컨테이너 메시지 uuid (Task tool_use 보유)
    const toolUseOwner = new Map<string, string>(); // Task tool_use id → 소유 agg key

    // 레이아웃 판정: 별도 파일이 있으면 그 파일들이 권위(인라인 Task 는 spawn 으로만 취급).
    const subDir = join(dirname(transcriptPath), "transcript_subagents");
    const hasSeparate = existsSync(subDir);

    // 1) Task/Agent tool_use 처리
    if (!hasSeparate) {
      // 레이아웃 A: 인라인 Task → subagent agg (컨테이너 메시지 uuid 로 키)
      for (const e of entries) {
        for (const tu of e.toolUses) {
          if (SUBAGENT_NAMES.has(tu.name)) {
            if (!subs.has(e.uuid)) subs.set(e.uuid, newAgg(e.uuid, `sub ${subs.size + 1}`, null));
            if (tu.id) toolUseOwner.set(tu.id, e.uuid);
          }
        }
      }
    } else {
      // 레이아웃 B: 메인 transcript 의 Task spawn 은 root 소유로만 기록(파일이 실 서브에이전트)
      for (const e of entries)
        for (const tu of e.toolUses)
          if (SUBAGENT_NAMES.has(tu.name) && tu.id) toolUseOwner.set(tu.id, "__root__");
    }

    // owner(entry) — sidechain 은 parentUuid climb 으로 소속 subagent 결정
    const ownerOf = (e: Entry): Agg => {
      if (!e.isSidechain) {
        return subs.get(e.uuid) ?? root;
      }
      let cur: Entry | undefined = e;
      const guard = new Set<string>();
      while (cur && !guard.has(cur.uuid)) {
        guard.add(cur.uuid);
        if (subs.has(cur.uuid)) return subs.get(cur.uuid)!;
        cur = cur.parentUuid ? byUuid.get(cur.parentUuid) : undefined;
      }
      return root;
    };

    // 2) 각 entry 토큰/도구 귀속. Task 메시지 자체(spawn)는 root 의 tool call.
    for (const e of entries) {
      const owner = ownerOf(e);
      attribute(owner, e);
    }

    // 3) subagent 부모 링크 — 컨테이너 메시지의 owner(= 그 entry 의 부모 agg)
    for (const [uuid, agg] of subs) {
      const container = byUuid.get(uuid);
      if (!container) {
        agg.parentKey = "__root__";
        continue;
      }
      // 컨테이너가 sidechain 이면 그 owner subagent, 아니면 root
      if (container.isSidechain) {
        // climb 시작은 부모부터(자기 자신 제외)
        let cur: Entry | undefined = container.parentUuid
          ? byUuid.get(container.parentUuid)
          : undefined;
        const guard = new Set<string>();
        let parentKey = "__root__";
        while (cur && !guard.has(cur.uuid)) {
          guard.add(cur.uuid);
          if (subs.has(cur.uuid)) {
            parentKey = cur.uuid;
            break;
          }
          cur = cur.parentUuid ? byUuid.get(cur.parentUuid) : undefined;
        }
        agg.parentKey = parentKey;
      } else {
        agg.parentKey = "__root__";
      }
    }

    // 4) 레이아웃 B — transcript_subagents/agent-*.jsonl + meta.json
    if (hasSeparate) {
      this.parseSeparateFiles(subDir, subs, toolUseOwner);
    }

    const sessionId =
      entries.find((e) => e.sessionId)?.sessionId ??
      `cc-${Math.abs(hashStr(transcriptPath)) % 100000}`;
    const model = opts?.model ?? entries.find((e) => e.model)?.model ?? "unknown";

    return assemble("cc", root, subs, sessionId, model, entries.length);
  }

  private parseSeparateFiles(
    subDir: string,
    subs: Map<string, Agg>,
    toolUseOwner: Map<string, string>,
  ): void {
    let files: string[];
    try {
      files = readdirSync(subDir).filter((f) => f.endsWith(".jsonl"));
    } catch {
      return;
    }
    // 1차 패스: 모든 파일 attribute + toolUseOwner 채우기(부모-자식 순서 무관)
    const fileAggs: { id: string; agg: Agg }[] = [];
    for (const file of files.sort()) {
      const id = file.replace(/\.jsonl$/, "");
      const entries = readLines(join(subDir, file));
      const agg = newAgg(`file:${id}`, id, "__root__");
      for (const e of entries) {
        attribute(agg, e);
        for (const tu of e.toolUses)
          if (SUBAGENT_NAMES.has(tu.name) && tu.id) toolUseOwner.set(tu.id, `file:${id}`);
      }
      fileAggs.push({ id, agg });
    }
    // 2차 패스: meta.toolUseId → 부모 결정 (멀티레벨)
    for (const { id, agg } of fileAggs) {
      let parentKey = "__root__";
      try {
        const metaRaw = readFileSync(join(subDir, `${id}.meta.json`), "utf8");
        const meta = CcSubagentMetaSchema.parse(JSON.parse(metaRaw));
        if (meta.toolUseId && toolUseOwner.has(meta.toolUseId)) {
          parentKey = toolUseOwner.get(meta.toolUseId)!;
        }
      } catch {
        // meta 없으면 root
      }
      agg.parentKey = parentKey;
      subs.set(`file:${id}`, agg);
    }
  }
}

function hashStr(s: string): number {
  let h = 0;
  for (let i = 0; i < s.length; i++) h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;
  return h;
}

function assemble(
  agent: "cc",
  root: Agg,
  subs: Map<string, Agg>,
  sessionId: string,
  model: string,
  rawCount: number,
): ParsedTranscript {
  // 이벤트 배열: [root, ...subs]. 부모는 events 인덱스로 링크.
  const aggList = [root, ...subs.values()];
  const keyToIdx = new Map<string, number>();
  aggList.forEach((a, i) => keyToIdx.set(a.key, i));

  const events: TranscriptEvent[] = aggList.map((a, idx) => {
    const parentIdx = a.parentKey ? (keyToIdx.get(a.parentKey) ?? 0) : null;
    const dur = a.startMs !== null && a.endMs !== null ? Math.max(0, a.endMs - a.startMs) : 0;
    return {
      idx,
      tsMs: a.startMs ?? 0,
      endMs: a.endMs ?? 0,
      durationMs: dur,
      kind: idx === 0 ? "assistant" : "subagent",
      name: idx === 0 ? "main" : a.label,
      parentIdx,
      inputTokens: a.tIn,
      outputTokens: a.tOut,
      cacheReadTokens: a.tCr,
      cacheCreationTokens: a.tCc,
      summaryIn: truncate(a.logs[0] ?? ""),
      summaryOut: truncate(a.logs[a.logs.length - 1] ?? ""),
      status: a.status,
      isSidechain: idx !== 0,
      toolCalls: a.toolCalls,
      skillFires: a.skillFires,
      toolsUsed: compressTools(a.tools),
      skillsUsed: [...new Set(a.skills)],
      steps: a.steps,
      logText: truncate(a.logs.join("\n"), 1000),
    };
  });

  const sum = (f: (a: Agg) => number) => aggList.reduce((acc, a) => acc + f(a), 0);
  const inputTokens = sum((a) => a.tIn);
  const outputTokens = sum((a) => a.tOut);
  const cacheReadTokens = sum((a) => a.tCr);
  const cacheCreationTokens = sum((a) => a.tCc);
  const subagentCount = subs.size;
  const toolCalls = sum((a) => a.toolCalls);
  const skillFires = sum((a) => a.skillFires);
  const mcpCalls = sum((a) => a.mcpCalls);
  const latency =
    root.startMs !== null && root.endMs !== null ? Math.max(0, root.endMs - root.startMs) : 0;

  return {
    agent,
    events,
    sessionId,
    model,
    numTurns: rawCount,
    toolCalls,
    subagentCount,
    skillFires,
    mcpCalls,
    inputTokens,
    outputTokens,
    cacheReadTokens,
    cacheCreationTokens,
    totalTokens: inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens,
    latencyMs: latency,
    skillsUsed: [...new Set(root.skills)],
    toolsUsed: compressTools(root.tools),
    steps: root.steps,
  };
}