All files / src/util traceUtils.ts

94.38% Statements 84/89
87.5% Branches 84/96
100% Functions 12/12
97.43% Lines 76/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310                                                                                22x     84x                                         41x         41x     41x   41x 162x 48x 48x                     48x 48x 114x 44x 44x 44x 44x 44x 44x 44x 44x       70x       59x 59x 59x 58x               11x 5x 5x 5x 5x   6x 6x       41x           7x                           4x                                                       9x 9x 5x 5x 5x 5x         4x 5x 5x 4x 4x               253x 253x 8x 2x 6x 1x     253x                       22x                 22x           22x       5x                                               6x 6x 7x 13x   13x 13x 13x             13x 13x 13x     6x                                 3x 3x 4x 2x 2x     3x 2x 5x      
import { HitlPause, HitlResume, NodeHitl } from "@/objects/Hitl";
import { NodeExecution, SystemNodeResult, TraceEvent } from "@/objects/Model";
import { SYSTEM_NODES } from "@/objects/systemNodes";
import type { SearchReport } from "@/objects/WebSearch";
 
// ─── Types ────────────────────────────────────────────────────────────────────
 
export type NodeTraceData = {
  node_id: string;
  is_system_node: boolean;
  tokens: { input: number; output: number };
  duration_ms: number;
  output_preview: string;
  system_result?: SystemNodeResult;
  /** Input context passed to this system node's LLM call (from system_node_result.input). */
  system_input?: Record<string, unknown>;
  /** LLM model name used for this node. */
  model_name?: string;
  /** LLM provider used for this node. */
  provider?: string;
  tools: {
    tool: string;
    params?: Record<string, unknown>;
    output_preview: string;
    status: "success" | "error";
    /** A web search's report (`objects/WebSearch.ts`). */
    report?: SearchReport;
  }[];
  /** Set when this execution stopped for a person. */
  hitl?: NodeHitl;
  /** When it started and ended, in ms from the stream's start, and the
   *  graph pass it ran on; absent on traces stored before them. */
  started_ms?: number;
  ended_ms?: number;
  pass?: number;
};
 
// ─── System node identity ─────────────────────────────────────────────────────
 
/** Every system node the registry names (`objects/systemNodes.ts`). */
const SYSTEM_NODE_ID_SET: ReadonlySet<string> = new Set(Object.keys(SYSTEM_NODES));
 
export function isSystemNodeId(nodeId: string): boolean {
  return (
    SYSTEM_NODE_ID_SET.has(nodeId) ||
    (nodeId.startsWith("__") && nodeId.endsWith("__"))
  );
}
 
// ─── Trace grouping ───────────────────────────────────────────────────────────
 
/**
 * Groups a flat list of TraceEvents into per-node summaries.
 *
 * Robustness guarantees:
 * - `tool_call` events that arrive after their node's `node_end` are still
 *   attributed correctly — the node map is never cleared between start and end.
 * - `tool_call` events with an empty `node_id` (emitted when the backend
 *   cannot resolve a parent chain) fall back to the most recently started
 *   node, which is the overwhelmingly common case for system-node tools.
 * - `system_node_result` uses the same permanent map as tool attribution,
 *   so all three event types share one lookup path.
 */
export function groupTraceByNode(trace: TraceEvent[]): NodeTraceData[] {
  const result: NodeTraceData[] = [];
  // Permanent map: node_id → index in result.
  // Updated on every node_start (last-wins for repeated node IDs) but NEVER
  // deleted, so late-arriving tool_call / system_node_result events always
  // find their node.
  const nodeMap = new Map<string, number>();
  // Tracks the most recent node_id seen in a node_start event.  Used as a
  // fallback when a tool_call carries an empty node_id.
  let lastStartedNodeId = "";
 
  for (const ev of trace) {
    if (ev.type === "node_start") {
      const idx = result.length;
      result.push({
        node_id: ev.node_id,
        is_system_node:
          Boolean(ev.is_system_node) || isSystemNodeId(ev.node_id),
        tokens: { input: 0, output: 0 },
        duration_ms: 0,
        output_preview: "",
        tools: [],
        ...(typeof ev.t_ms === "number" ? { started_ms: ev.t_ms } : {}),
        ...(typeof ev.pass === "number" ? { pass: ev.pass } : {}),
      });
      nodeMap.set(ev.node_id, idx);
      lastStartedNodeId = ev.node_id;
    } else if (ev.type === "node_end") {
      const idx = nodeMap.get(ev.node_id);
      Eif (idx !== undefined) {
        result[idx].tokens = ev.tokens ?? { input: 0, output: 0 };
        result[idx].duration_ms = ev.duration_ms ?? 0;
        result[idx].output_preview = ev.output_preview ?? "";
        Iif (ev.model_name) result[idx].model_name = String(ev.model_name);
        Iif (ev.provider) result[idx].provider = String(ev.provider);
        if (typeof ev.t_ms === "number") result[idx].ended_ms = ev.t_ms;
        // Deliberately NOT deleting from nodeMap — late tool_call events must
        // still resolve to this node after its end event is processed.
      }
    } else if (ev.type === "tool_call" && ev.tool) {
      // Primary lookup by node_id; fall back to the most recently started
      // node when node_id is absent or empty (backend couldn't resolve parent).
      const targetNodeId =
        ev.node_id !== "" ? ev.node_id : lastStartedNodeId;
      const idx = nodeMap.get(targetNodeId);
      if (idx !== undefined) {
        result[idx].tools.push({
          tool: ev.tool,
          params: ev.params,
          output_preview: ev.output_preview ?? "",
          status: ev.status ?? "success",
          ...(ev.report ? { report: ev.report } : {}),
        });
      }
    } else if (ev.type === "system_node_result") {
      const idx = nodeMap.get(ev.node_id);
      Eif (idx !== undefined) {
        if (ev.result) result[idx].system_result = ev.result;
        Iif (ev.input) result[idx].system_input = ev.input as Record<string, unknown>;
      }
    } else Eif (ev.type === "hitl_pause" || ev.type === "hitl_resume") {
      attachHitl(result, ev, lastStartedNodeId);
    }
  }
 
  return result;
}
 
// ─── Human in the loop ────────────────────────────────────────────────────────
 
export function pauseFromTrace(ev: TraceEvent): HitlPause {
  return {
    interrupt_type: ev.interrupt_type ?? "approval_request",
    source: ev.source,
    title: ev.title,
    intro: ev.intro,
    reason: ev.reason,
    questions: ev.questions,
    task: ev.task,
    output: ev.output,
    paused_at: ev.paused_at,
  };
}
 
export function resumeFromTrace(ev: TraceEvent): HitlResume {
  return {
    outcome: ev.outcome ?? "answered",
    answers: ev.answers,
    approved: ev.approved,
    feedback: ev.feedback,
    answered_at: ev.answered_at,
    answered_by: ev.answered_by,
    waited_ms: ev.waited_ms,
    redacted: ev.redacted,
  };
}
 
/**
 * Attach a `hitl_pause` / `hitl_resume` frame to the execution it concerns.
 *
 * A pause belongs to the latest execution of its node (or the latest one
 * started, when the node is unknown). A resume closes the latest *open*
 * pause on its node: the run replays the paused node after an answer, so by
 * the time a later frame arrives there may be a newer execution of the same
 * node that never paused. Works on any list of `{node_id, hitl?}`, so the
 * live chat and a persisted trace fold frames the same way. Returns the
 * index it changed, or -1.
 */
export function attachHitl<T extends { node_id: string; hitl?: NodeHitl }>(
  executions: T[],
  ev: TraceEvent,
  fallbackNodeId = "",
): number {
  const nodeId = ev.node_id || fallbackNodeId;
  if (ev.type === "hitl_pause") {
    for (let i = executions.length - 1; i >= 0; i--) {
      Eif (!nodeId || executions[i].node_id === nodeId) {
        executions[i].hitl = { pause: pauseFromTrace(ev) };
        return i;
      }
    }
    return -1;
  }
  for (let i = executions.length - 1; i >= 0; i--) {
    const hitl = executions[i].hitl;
    if (hitl && !hitl.resume && (!nodeId || executions[i].node_id === nodeId)) {
      executions[i].hitl = { ...hitl, resume: resumeFromTrace(ev) };
      return i;
    }
  }
  return -1;
}
 
/** Every pause in a trace, paired with how it ended, in order. */
export function hitlFromTrace(trace: TraceEvent[]): NodeHitl[] {
  const found: { node_id: string; hitl?: NodeHitl }[] = [];
  for (const ev of trace) {
    if (ev.type === "hitl_pause") {
      found.push({ node_id: ev.node_id, hitl: { pause: pauseFromTrace(ev) } });
    } else if (ev.type === "hitl_resume") {
      attachHitl(found, ev);
    }
  }
  return found.flatMap((f) => (f.hitl ? [f.hitl] : []));
}
 
// ─── Tools queried ────────────────────────────────────────────────────────────
 
/**
 * The tools that search or read an agent's knowledge, by exact name (svc-ai
 * `source_ledger.TOOL_KINDS`). A name prefix (`search_`, `explore_`) made any
 * tool so named — `search_flights` — read as a knowledge search, and missed
 * `read_document`. `list_documents` lists names, not content, so it is not
 * one.
 */
const KB_TOOLS: ReadonlySet<string> = new Set([
  "search_knowledge",
  "read_document",
  "explore_graph",
  "query_knowledge_base",
  "query_knowledge_graph",
]);
 
/** The knowledge tools that read a graph rather than passages. */
const GRAPH_TOOLS: ReadonlySet<string> = new Set([
  "explore_graph",
  "query_knowledge_graph",
]);
 
export function isKbTool(name: string): boolean {
  return KB_TOOLS.has(name);
}
 
export function isGraphTool(name: string): boolean {
  return GRAPH_TOOLS.has(name);
}
 
/** One tool a turn called, and how often — per knowledge base, for a
 *  knowledge tool whose call named one. */
export type QueriedTool = {
  tool: string;
  /** The knowledge base the calls named (`params.knowledge_base`), if any. */
  knowledgeBase?: string;
  isKnowledge: boolean;
  calls: number;
  /** Calls that came back as an error. */
  errors: number;
};
 
/**
 * Every tool a turn called, in the order first called, with counts.
 *
 * What was *asked*, not what the answer rests on: a search that returned
 * the wrong thing, or nothing the answer used, counts the same. The answer's
 * own sources are `meta.cited_sources`; this is what a turn stored before
 * them can still say truthfully.
 */
export function queriedTools(nodes: NodeTraceData[]): QueriedTool[] {
  const found = new Map<string, QueriedTool>();
  for (const node of nodes) {
    for (const tc of node.tools) {
      const named = tc.params?.knowledge_base;
      const knowledgeBase =
        typeof named === "string" && named.trim() ? named.trim() : undefined;
      const key = `${tc.tool}\u0000${knowledgeBase ?? ""}`;
      const entry = found.get(key) ?? {
        tool: tc.tool,
        ...(knowledgeBase ? { knowledgeBase } : {}),
        isKnowledge: isKbTool(tc.tool),
        calls: 0,
        errors: 0,
      };
      entry.calls++;
      if (tc.status === "error") entry.errors++;
      found.set(key, entry);
    }
  }
  return Array.from(found.values());
}
 
// ─── Live results ─────────────────────────────────────────────────────────────
 
/**
 * ``executions`` with ``result`` on the newest execution of ``nodeId`` — the
 * one it reports on, since a result follows its node's end. Applied to every
 * execution of the node, a corrective pass's knowledge plan overwrote the
 * first pass's.
 */
export function withNodeResult(
  executions: NodeExecution[],
  nodeId: string,
  result: SystemNodeResult,
  input?: Record<string, unknown>,
): NodeExecution[] {
  let newest = -1;
  for (let i = executions.length - 1; i >= 0; i--) {
    if (executions[i].node_id === nodeId) {
      newest = i;
      break;
    }
  }
  if (newest < 0) return executions;
  return executions.map((n, i) =>
    i === newest ? { ...n, system_result: result, system_input: input } : n,
  );
}