|
| 1 | +import { |
| 2 | + AxJSRuntime, |
| 3 | + agent, |
| 4 | + type AxActorTurn, |
| 5 | + type AxAIService, |
| 6 | + type AxFunction, |
| 7 | +} from '@ax-llm/ax' |
| 8 | + |
| 9 | +import { TraceFileMissingError } from './store-otlp' |
| 10 | +import { |
| 11 | + TRACE_ANALYST_ACTOR_DESCRIPTION, |
| 12 | + TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION, |
| 13 | + TRACE_ANALYST_SUBAGENT_DESCRIPTION, |
| 14 | +} from './prompts' |
| 15 | +import { buildTraceAnalystTools } from './tools' |
| 16 | +import type { TraceAnalysisStore } from './store' |
| 17 | +import { OtlpFileTraceStore } from './store-otlp' |
| 18 | + |
| 19 | +export interface AnalyzeTracesInput { |
| 20 | + /** The user-facing question. Domain framing belongs here, not in the |
| 21 | + * actor description. */ |
| 22 | + question: string |
| 23 | +} |
| 24 | + |
| 25 | +export interface AnalyzeTracesResult { |
| 26 | + /** The responder's prose answer. */ |
| 27 | + answer: string |
| 28 | + /** Bulleted findings extracted from the responder's structured output. */ |
| 29 | + findings: string[] |
| 30 | + /** Per-actor-turn snapshots captured via `actorTurnCallback`. */ |
| 31 | + turns: AnalyzeTracesTurnSnapshot[] |
| 32 | + /** Total turns the actor took. */ |
| 33 | + turnCount: number |
| 34 | + /** Token usage by role. */ |
| 35 | + usage: { actor: unknown[]; responder: unknown[] } |
| 36 | + /** Full system + assistant + tool message log by role. */ |
| 37 | + chatLog: { actor: unknown[]; responder: unknown[] } |
| 38 | + /** Prompt version that produced this run. */ |
| 39 | + actorPromptVersion: string |
| 40 | +} |
| 41 | + |
| 42 | +export interface AnalyzeTracesTurnSnapshot { |
| 43 | + turn: number |
| 44 | + isError: boolean |
| 45 | + /** The JS code the actor produced for this turn. */ |
| 46 | + code: string |
| 47 | + /** The formatted action-log entry the actor sees on the next turn. */ |
| 48 | + output: string |
| 49 | + /** Provider thought (when `actorOptions.showThoughts` is true and the |
| 50 | + * provider returns it). */ |
| 51 | + thought?: string |
| 52 | +} |
| 53 | + |
| 54 | +export interface AnalyzeTracesOptions { |
| 55 | + /** Trace data source. Pass either an OTLP-JSONL path or a custom store. */ |
| 56 | + source: string | TraceAnalysisStore |
| 57 | + /** Caller-provided AxAIService. */ |
| 58 | + ai: AxAIService |
| 59 | + /** Model id forwarded to actor + responder. */ |
| 60 | + model?: string |
| 61 | + /** Recursion depth. 0 = no sub-agent dispatch. Default 1. */ |
| 62 | + maxDepth?: number |
| 63 | + /** Maximum actor turns. Default 12. */ |
| 64 | + maxTurns?: number |
| 65 | + /** Maximum parallel sub-agent calls in batched llmQuery. Default 2. */ |
| 66 | + maxParallelSubagents?: number |
| 67 | + /** Override the actor description. */ |
| 68 | + actorDescription?: string |
| 69 | + /** Override the subagent description. */ |
| 70 | + subagentDescription?: string |
| 71 | + /** Per-turn observability hook. */ |
| 72 | + onTurn?: (turn: AnalyzeTracesTurnSnapshot) => void | Promise<void> |
| 73 | + /** Override max runtime characters per turn. Default 6000. */ |
| 74 | + maxRuntimeChars?: number |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Run the trace analyst. |
| 79 | + * |
| 80 | + * Throws: |
| 81 | + * - `TraceFileMissingError` if `source` is a path and doesn't exist. |
| 82 | + * - `AxAgentClarificationError` if the analyst asks for clarification. |
| 83 | + * - Provider errors (auth, rate limits) propagate from the AI service. |
| 84 | + */ |
| 85 | +export async function analyzeTraces( |
| 86 | + input: AnalyzeTracesInput, |
| 87 | + options: AnalyzeTracesOptions, |
| 88 | +): Promise<AnalyzeTracesResult> { |
| 89 | + if (!input.question || typeof input.question !== 'string') { |
| 90 | + throw new TypeError('analyzeTraces: input.question must be a non-empty string') |
| 91 | + } |
| 92 | + |
| 93 | + const store: TraceAnalysisStore = |
| 94 | + typeof options.source === 'string' |
| 95 | + ? new OtlpFileTraceStore({ path: options.source }) |
| 96 | + : options.source |
| 97 | + |
| 98 | + // Pre-warm file stores so missing inputs fail before the RLM starts. |
| 99 | + if (store instanceof OtlpFileTraceStore) { |
| 100 | + await store.ensureIndexed() |
| 101 | + } |
| 102 | + |
| 103 | + const tools: AxFunction[] = buildTraceAnalystTools({ store }) |
| 104 | + const turns: AnalyzeTracesTurnSnapshot[] = [] |
| 105 | + |
| 106 | + const actorTurnCallback = async (turn: AxActorTurn): Promise<void> => { |
| 107 | + const snap: AnalyzeTracesTurnSnapshot = { |
| 108 | + turn: turn.turn, |
| 109 | + isError: turn.isError, |
| 110 | + code: turn.code, |
| 111 | + output: turn.output, |
| 112 | + thought: turn.thought, |
| 113 | + } |
| 114 | + turns.push(snap) |
| 115 | + if (options.onTurn) await options.onTurn(snap) |
| 116 | + } |
| 117 | + |
| 118 | + const maxDepth = options.maxDepth ?? 1 |
| 119 | + const maxTurns = options.maxTurns ?? 12 |
| 120 | + const maxParallelSubagents = options.maxParallelSubagents ?? 2 |
| 121 | + const maxRuntimeChars = options.maxRuntimeChars ?? 6000 |
| 122 | + |
| 123 | + const analyst = agent<{ question: string }, { answer: string; findings: string[] }>( |
| 124 | + 'question:string -> answer:string, findings:string[]', |
| 125 | + { |
| 126 | + agentIdentity: { |
| 127 | + name: 'TraceAnalyst', |
| 128 | + description: |
| 129 | + 'Analyzes OTLP-shaped JSONL traces using bounded discovery tools to identify systemic failure modes.', |
| 130 | + }, |
| 131 | + contextFields: ['question'], |
| 132 | + runtime: new AxJSRuntime({ |
| 133 | + permissions: [], |
| 134 | + blockDynamicImport: true, |
| 135 | + allowedModules: [], |
| 136 | + freezeIntrinsics: true, |
| 137 | + blockShadowRealm: true, |
| 138 | + preventGlobalThisExtensions: true, |
| 139 | + }), |
| 140 | + mode: maxDepth > 0 ? 'advanced' : 'simple', |
| 141 | + recursionOptions: maxDepth > 0 ? { maxDepth } : undefined, |
| 142 | + maxTurns, |
| 143 | + maxRuntimeChars, |
| 144 | + maxBatchedLlmQueryConcurrency: maxParallelSubagents, |
| 145 | + promptLevel: 'detailed', |
| 146 | + contextPolicy: { preset: 'checkpointed', budget: 'balanced' }, |
| 147 | + functions: { local: tools }, |
| 148 | + actorOptions: { |
| 149 | + description: options.actorDescription ?? TRACE_ANALYST_ACTOR_DESCRIPTION, |
| 150 | + ...(options.model ? { model: options.model } : {}), |
| 151 | + }, |
| 152 | + responderOptions: { |
| 153 | + ...(options.model ? { model: options.model } : {}), |
| 154 | + description: |
| 155 | + options.subagentDescription ?? TRACE_ANALYST_SUBAGENT_DESCRIPTION, |
| 156 | + }, |
| 157 | + actorTurnCallback, |
| 158 | + bubbleErrors: [TraceFileMissingError], |
| 159 | + }, |
| 160 | + ) |
| 161 | + |
| 162 | + const result = await analyst.forward(options.ai, { question: input.question }) |
| 163 | + |
| 164 | + return { |
| 165 | + answer: typeof result.answer === 'string' ? result.answer : String(result.answer ?? ''), |
| 166 | + findings: Array.isArray(result.findings) |
| 167 | + ? result.findings.filter((s): s is string => typeof s === 'string') |
| 168 | + : [], |
| 169 | + turns, |
| 170 | + turnCount: turns.length, |
| 171 | + usage: analyst.getUsage(), |
| 172 | + chatLog: analyst.getChatLog(), |
| 173 | + actorPromptVersion: TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION, |
| 174 | + } |
| 175 | +} |
0 commit comments