Skip to content
TypeScript
5.7 KB
Raw Blame
/**
 * 방어적 파서 (opencode / openclaw / hermes).
 * 이 도구들의 출력 스키마는 부분적으로만 문서화돼 있어, 알려진 형태(JSONL 이벤트, 단일 JSON
 * 객체, 평문)를 모두 견디도록 재귀 스캔으로 토큰/도구/세션을 best-effort 추출한다.
 * 실제 codex 처럼 in-process 서브에이전트는 명시 마커가 없으면 0.
 */
import { readFileSync } from "node:fs";
import type { ParsedTranscript, TranscriptEvent } from "../models";
import { type TranscriptParser, compressTools, isMcp, truncate } from "./base";

interface Acc {
  in: number;
  out: number;
  cr: number;
  cc: number;
  toolCalls: number;
  subagents: number;
  mcp: number;
  tools: string[];
  steps: string[];
  logs: string[];
  session: string;
}

const TOKEN_KEYS: Record<string, keyof Pick<Acc, "in" | "out" | "cr" | "cc">> = {
  input_tokens: "in",
  prompt_tokens: "in",
  output_tokens: "out",
  completion_tokens: "out",
  cache_read_input_tokens: "cr",
  cached_input_tokens: "cr",
  cache_creation_input_tokens: "cc",
};

const TOOL_TYPE_RE = /tool|command|item\.completed|file_change|step/i;
const SUBAGENT_RE = /\b(task|subagent)\b/i;

/**
 * anc — 조상 노드가 이미 도구 이벤트로 집계됐는지. 래퍼({type:"item.completed", item:{type:"command_…"}})
 * 안의 중첩 객체는 같은 논리 이벤트의 상세이므로 toolCalls 를 다시 세지 않는다(이중 집계 방지).
 * 단, 조상이 서브에이전트로 안 잡힌 경우 중첩 마커의 subagent 판정은 1회 허용(포착 누락 방지).
 */
function scan(
  node: unknown,
  acc: Acc,
  depth = 0,
  anc: { counted: boolean; sub: boolean } = { counted: false, sub: false },
): void {
  if (depth > 8 || node === null || typeof node !== "object") return;
  if (Array.isArray(node)) {
    for (const v of node) scan(v, acc, depth + 1, anc);
    return;
  }
  const obj = node as Record<string, unknown>;
  for (const [k, v] of Object.entries(obj)) {
    if (typeof v === "number" && k in TOKEN_KEYS) acc[TOKEN_KEYS[k]!] += v;
  }
  // 세션 id
  for (const k of ["session_id", "thread_id", "sessionId", "threadId"]) {
    if (typeof obj[k] === "string" && !acc.session) acc.session = obj[k] as string;
  }
  // payloads[].text (openclaw) / text (opencode/hermes)
  if (typeof obj.text === "string") acc.logs.push(obj.text as string);
  // 이벤트/아이템 타입 → 도구·서브에이전트
  const type = typeof obj.type === "string" ? (obj.type as string) : "";
  const name = typeof obj.name === "string" ? (obj.name as string) : "";
  const isSub = SUBAGENT_RE.test(type) || SUBAGENT_RE.test(name);
  const matched = (type !== "" && TOOL_TYPE_RE.test(type)) || isSub;
  let next = anc;
  if (matched && !anc.counted) {
    acc.toolCalls += 1;
    acc.tools.push(name || type);
    acc.steps.push(name || type);
    if (isSub) acc.subagents += 1;
    if (isMcp(name) || isMcp(type)) acc.mcp += 1;
    next = { counted: true, sub: isSub };
  } else if (matched && anc.counted && isSub && !anc.sub) {
    // 래퍼는 일반 도구로 집계됐지만 안쪽이 서브에이전트 마커 — 판정만 승격(중복 toolCall 없음).
    acc.subagents += 1;
    next = { counted: true, sub: true };
  }
  for (const v of Object.values(obj)) scan(v, acc, depth + 1, next);
}

export class DefensiveParser implements TranscriptParser {
  // 멀티모델 에이전트는 cc/codex 둘 다 아니므로 타입상 'codex' 로 분류(평탄 구조).
  agent = "codex" as const;
  constructor(private displayAgent: string) {}

  parse(transcriptPath: string, opts?: { model?: string }): ParsedTranscript {
    let raw = "";
    try {
      raw = readFileSync(transcriptPath, "utf8");
    } catch {
      // ignore
    }
    const acc: Acc = {
      in: 0,
      out: 0,
      cr: 0,
      cc: 0,
      toolCalls: 0,
      subagents: 0,
      mcp: 0,
      tools: [],
      steps: [],
      logs: [],
      session: "",
    };

    // JSONL 또는 단일 JSON 객체 모두 처리
    const lines = raw
      .split("\n")
      .map((l) => l.trim())
      .filter(Boolean);
    let parsedAny = false;
    for (const line of lines) {
      try {
        scan(JSON.parse(line), acc);
        parsedAny = true;
      } catch {
        // 평문 라인(hermes -z) — 로그로만 수집
        acc.logs.push(line);
      }
    }
    if (!parsedAny && raw.trim()) {
      try {
        scan(JSON.parse(raw), acc);
      } catch {
        // 전체가 평문
      }
    }

    const total = acc.in + acc.out + acc.cr + acc.cc;
    const rootEvent: TranscriptEvent = {
      idx: 0,
      tsMs: 0,
      endMs: 0,
      durationMs: 0,
      kind: "assistant",
      name: "main",
      parentIdx: null,
      inputTokens: acc.in,
      outputTokens: acc.out,
      cacheReadTokens: acc.cr,
      cacheCreationTokens: acc.cc,
      summaryIn: truncate(acc.logs[0] ?? ""),
      summaryOut: truncate(acc.logs[acc.logs.length - 1] ?? ""),
      status: "success",
      isSidechain: false,
      toolCalls: acc.toolCalls,
      skillFires: 0,
      toolsUsed: compressTools(acc.tools),
      skillsUsed: [],
      steps: acc.steps,
      logText: truncate(acc.logs.join("\n"), 1000),
    };

    return {
      agent: "codex",
      events: [rootEvent],
      sessionId: acc.session || `${this.displayAgent}-session`,
      model: opts?.model ?? "unknown",
      numTurns: Math.max(1, acc.toolCalls),
      toolCalls: acc.toolCalls,
      subagentCount: acc.subagents,
      skillFires: 0,
      mcpCalls: acc.mcp,
      inputTokens: acc.in,
      outputTokens: acc.out,
      cacheReadTokens: acc.cr,
      cacheCreationTokens: acc.cc,
      totalTokens: total,
      latencyMs: 0,
      skillsUsed: [],
      toolsUsed: compressTools(acc.tools),
      steps: acc.steps,
    };
  }
}