Skip to content
TypeScript
3.9 KB
Raw Blame
/**
 * Codex transcript 파서 (PRD §8).
 * `codex exec --json` thread-event: thread.started(session) / turn.started(numTurns) /
 * turn.completed.usage(토큰) / item.completed(도구). 실제 codex 는 in-process 서브에이전트 없음(평탄).
 * mock/구 스키마의 명시 parent_idx 만 중첩으로 인정.
 */
import { readFileSync } from "node:fs";
import { CodexEventSchema } from "../models";
import type { ParsedTranscript, TranscriptEvent } from "../models";
import { type TranscriptParser, compressTools, isMcp, truncate } from "./base";

function readEvents(path: string): any[] {
  let raw: string;
  try {
    raw = readFileSync(path, "utf8");
  } catch {
    return [];
  }
  const out: any[] = [];
  for (const line of raw.split("\n")) {
    const s = line.trim();
    if (!s) continue;
    try {
      const obj = JSON.parse(s);
      if (CodexEventSchema.safeParse(obj).success) out.push(obj);
    } catch {
      // skip
    }
  }
  return out;
}

function eventType(o: any): string {
  if (typeof o.type === "string") return o.type;
  if (o.msg && typeof o.msg.type === "string") return o.msg.type;
  return "";
}

export class CodexParser implements TranscriptParser {
  agent = "codex" as const;

  parse(transcriptPath: string, opts?: { model?: string }): ParsedTranscript {
    const events = readEvents(transcriptPath);
    let sessionId = "";
    let numTurns = 0;
    let inputTokens = 0;
    let outputTokens = 0;
    let cacheReadTokens = 0;
    let cacheCreationTokens = 0;
    let toolCalls = 0;
    let mcpCalls = 0;
    const tools: string[] = [];
    const steps: string[] = [];
    const logs: string[] = [];
    // 명시 parent_idx 가 있는 평탄-외 중첩(구 스키마/mock)
    let explicitSubagents = 0;

    for (const o of events) {
      const t = eventType(o);
      if (t === "thread.started") sessionId = o.thread_id ?? o.thread?.id ?? sessionId;
      else if (t === "turn.started") numTurns += 1;
      else if (t === "turn.completed") {
        const u = o.usage ?? o.msg?.usage ?? {};
        inputTokens += u.input_tokens ?? 0;
        outputTokens += u.output_tokens ?? 0;
        cacheReadTokens += u.cached_input_tokens ?? u.cache_read_input_tokens ?? 0;
        cacheCreationTokens += u.cache_creation_input_tokens ?? 0;
      } else if (t === "item.completed") {
        const item = o.item ?? o.msg?.item ?? {};
        const name = item.type ?? "item";
        toolCalls += 1;
        tools.push(name);
        if (isMcp(name) || isMcp(item.name)) mcpCalls += 1;
        steps.push(String(item.command ?? name));
        if (typeof item.text === "string") logs.push(item.text);
        if (typeof o.parent_idx === "number" || typeof item.parent_idx === "number")
          explicitSubagents += 1;
      }
    }

    if (!sessionId) sessionId = "codex-session";
    const model = opts?.model ?? "unknown";

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

    return {
      agent: "codex",
      events: [rootEvent],
      sessionId,
      model,
      numTurns,
      toolCalls,
      subagentCount: explicitSubagents, // 실제 codex=0
      skillFires: 0,
      mcpCalls,
      inputTokens,
      outputTokens,
      cacheReadTokens,
      cacheCreationTokens,
      totalTokens: inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens,
      latencyMs: 0,
      skillsUsed: [],
      toolsUsed: compressTools(tools),
      steps,
    };
  }
}