Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
feat: add a dimension registry for trace analysis (#1354)
Morgan Carr7895ff73b935
diff --git a/src/client/src/__tests__/lib/platform/chat/trace-analysis-registry.test.ts b/src/client/src/__tests__/lib/platform/chat/trace-analysis-registry.test.tsnew file mode 100644index 00000000..8c0608de--- /dev/null+++ b/src/client/src/__tests__/lib/platform/chat/trace-analysis-registry.test.ts@@ -0,0 +1,195 @@+import {+ TRACE_ANALYSIS_DIMENSION_DEFINITIONS,+ TRACE_ANALYSIS_DIMENSION_REGISTRY,+ getTraceAnalysisDimensionDefinition,+ selectTraceAnalysisMetrics,+ selectTraceAnalysisSpan,+} from "@/lib/platform/chat/trace-analysis-registry";+import {+ TRACE_ANALYSIS_DIMENSION_LABELS,+ TRACE_ANALYSIS_DIMENSIONS,+} from "@/types/trace-analysis";++const expectedDimensions = [+ "strengths",+ "improvements",+ "wrong_turns",+ "cost",+ "token_efficiency",+ "path_analysis",+];++const expectedUiLabels = {+ strengths: "Strengths",+ improvements: "Improvements",+ wrong_turns: "Wrong turns",+ cost: "Cost",+ token_efficiency: "Token efficiency",+ path_analysis: "Path",+};++const expectedStreamLabels = {+ strengths: "Strengths",+ improvements: "Improvements",+ wrong_turns: "Wrong turns",+ cost: "Cost",+ token_efficiency: "Token efficiency",+ path_analysis: "Path analysis",+};++describe("trace analysis dimension registry", () => {+ it("keeps the six existing dimensions in their stored and streamed order", () => {+ expect(TRACE_ANALYSIS_DIMENSION_DEFINITIONS).toHaveLength(6);+ expect(TRACE_ANALYSIS_DIMENSION_DEFINITIONS.map(({ key }) => key)).toEqual(+ expectedDimensions+ );+ expect(Object.keys(TRACE_ANALYSIS_DIMENSION_REGISTRY)).toEqual(+ expectedDimensions+ );+ expect(TRACE_ANALYSIS_DIMENSIONS).toEqual(expectedDimensions);+ });++ it("derives both legacy label maps without collapsing their path label difference", () => {+ expect(TRACE_ANALYSIS_DIMENSION_LABELS).toEqual(expectedUiLabels);+ expect(+ Object.fromEntries(+ TRACE_ANALYSIS_DIMENSION_DEFINITIONS.map(({ key, streamLabel }) => [+ key,+ streamLabel,+ ])+ )+ ).toEqual(expectedStreamLabels);+ expect(TRACE_ANALYSIS_DIMENSION_LABELS.path_analysis).toBe("Path");+ expect(+ TRACE_ANALYSIS_DIMENSION_REGISTRY.path_analysis.streamLabel+ ).toBe("Path analysis");+ });++ it("freezes the ordered registry and each definition", () => {+ expect(Object.isFrozen(TRACE_ANALYSIS_DIMENSION_DEFINITIONS)).toBe(true);+ expect(Object.isFrozen(TRACE_ANALYSIS_DIMENSION_REGISTRY)).toBe(true);+ for (const definition of TRACE_ANALYSIS_DIMENSION_DEFINITIONS) {+ expect(Object.isFrozen(definition)).toBe(true);+ expect(Object.isFrozen(definition.spanFields)).toBe(true);+ expect(Object.isFrozen(definition.metricFields)).toBe(true);+ expect(Object.isFrozen(definition.emptyStateCopy)).toBe(true);+ }+ });++ it("falls back safely when a persisted dimension key is unknown", () => {+ expect(getTraceAnalysisDimensionDefinition("future_dimension")).toBe(+ TRACE_ANALYSIS_DIMENSION_DEFINITIONS[0]+ );+ });++ it("selects the same focused span and metric fields as the legacy branches", () => {+ const child = {+ spanId: "child-span",+ spanName: "tool.search",+ role: "tool",+ statusCode: "STATUS_CODE_OK",+ statusMessage: "ok",+ durationMs: 4,+ error: undefined,+ model: "gpt-4o-mini",+ provider: "openai",+ cost: 0.001,+ promptTokens: 10,+ completionTokens: 5,+ totalTokens: 15,+ cacheReadTokens: 2,+ cacheCreationTokens: 1,+ reasoningTokens: 3,+ systemPrompt: "system",+ prompt: "prompt",+ response: "response",+ toolArgs: "args",+ toolResult: "result",+ children: [],+ };+ const span = {+ ...child,+ spanId: "root-span",+ spanName: "agent.root",+ children: [child],+ };++ expect(selectTraceAnalysisSpan(span, "token_efficiency")).toEqual({+ spanId: "root-span",+ spanName: "agent.root",+ role: "tool",+ statusCode: "STATUS_CODE_OK",+ statusMessage: "ok",+ durationMs: 4,+ error: undefined,+ children: [+ {+ spanId: "child-span",+ spanName: "tool.search",+ role: "tool",+ statusCode: "STATUS_CODE_OK",+ statusMessage: "ok",+ durationMs: 4,+ error: undefined,+ children: [],+ model: "gpt-4o-mini",+ promptTokens: 10,+ completionTokens: 5,+ totalTokens: 15,+ cacheReadTokens: 2,+ cacheCreationTokens: 1,+ reasoningTokens: 3,+ systemPrompt: "system",+ prompt: "prompt",+ response: "response",+ toolArgs: "args",+ toolResult: "result",+ },+ ],+ model: "gpt-4o-mini",+ promptTokens: 10,+ completionTokens: 5,+ totalTokens: 15,+ cacheReadTokens: 2,+ cacheCreationTokens: 1,+ reasoningTokens: 3,+ systemPrompt: "system",+ prompt: "prompt",+ response: "response",+ toolArgs: "args",+ toolResult: "result",+ });++ const metrics = {+ spanCount: 3,+ maxDepth: 2,+ errorCount: 1,+ llmCallCount: 1,+ toolCallCount: 1,+ retrievalCallCount: 1,+ modelsUsed: ["gpt-4o-mini"],+ toolsUsed: ["search"],+ totalDurationMs: 12,+ repeatedSpanNames: [{ name: "tool.search", count: 2, spanIds: ["a", "b"] }],+ potentialRetrySequences: [{ reason: "same sibling", spanIds: ["a", "b"] }],+ databaseCallCount: 0,+ httpCallCount: 1,+ };++ expect(selectTraceAnalysisMetrics(metrics, "path_analysis")).toEqual({+ spanCount: 3,+ maxDepth: 2,+ errorCount: 1,+ llmCallCount: 1,+ toolCallCount: 1,+ retrievalCallCount: 1,+ modelsUsed: ["gpt-4o-mini"],+ toolsUsed: ["search"],+ totalDurationMs: 12,+ repeatedSpanNames: [{ name: "tool.search", count: 2, spanIds: ["a", "b"] }],+ potentialRetrySequences: [{ reason: "same sibling", spanIds: ["a", "b"] }],+ databaseCallCount: 0,+ httpCallCount: 1,+ });+ });+});diff --git a/src/client/src/components/(playground)/request/components/trace-improvement-view.tsx b/src/client/src/components/(playground)/request/components/trace-improvement-view.tsxindex c92d5774..126bf6c2 100644--- a/src/client/src/components/(playground)/request/components/trace-improvement-view.tsx+++ b/src/client/src/components/(playground)/request/components/trace-improvement-view.tsx@@ -32,6 +32,7 @@ import {TraceAnalysisFinding,emptyTraceAnalysis,} from "@/types/trace-analysis";+import { TRACE_ANALYSIS_DIMENSION_REGISTRY } from "@/lib/platform/chat/trace-analysis-registry";import { useRequest } from "../request-context";import getMessage from "@/constants/messages";import { CLIENT_EVENTS } from "@/constants/events";@@ -168,33 +169,6 @@ function AnalysisProgress({);}-const EMPTY_DIMENSION_COPY: Record<TraceAnalysisDimension, { summary: string; detail: string }> = {- strengths: {- summary: "No explicit strengths were identified in this run.",- detail: "The analysis did not find a concrete positive pattern worth calling out. This does not mean the trace failed; it means the model did not see a specific strength with enough evidence.",- },- improvements: {- summary: "No general improvements are required right now.",- detail: "The trace did not show a broad improvement opportunity outside the more specific cost, token, path, or wrong-turn categories.",- },- wrong_turns: {- summary: "No wrong turns were detected.",- detail: "The trace did not show clear retries, off-task branches, unnecessary rework, or agent decisions that caused a detour.",- },- cost: {- summary: "Cost looks acceptable for this trace.",- detail: "No span stood out as clearly over budget or using a model that was obviously too expensive for the observed subtask.",- },- token_efficiency: {- summary: "Token usage looks acceptable for this trace.",- detail: "The analysis did not find obvious prompt bloat, repeated context, oversized tool outputs, or duplicate retrieval payloads.",- },- path_analysis: {- summary: "The execution path looks reasonable.",- detail: "The trace did not show clear routing loops, missed branches, unnecessary tool hops, or inappropriate tool choices.",- },-};-function MarkdownText({ content }: { content: string }) {return (<div className="chat-markdown">@@ -879,7 +853,7 @@ export default function TraceImprovementView({</p></div>- <Tabs defaultValue="strengths" className="w-full">+ <Tabs defaultValue={TRACE_ANALYSIS_DIMENSIONS[0]} className="w-full"><TabsList className="h-auto flex w-full justify-start overflow-auto rounded-none bg-transparent p-0 dark:bg-transparent shrink-0 openlit-scrollbar">{TRACE_ANALYSIS_DIMENSIONS.map((dimension) => (<TabsTrigger@@ -899,7 +873,7 @@ export default function TraceImprovementView({{getDimensionFindings(parsedAnalysis, dimension).length === 0 ? (<div className="rounded-md border border-stone-200 bg-stone-50 p-4 dark:border-stone-800 dark:bg-stone-900/60"><div className="text-sm font-semibold text-stone-800 dark:text-stone-100">- {EMPTY_DIMENSION_COPY[dimension].summary}+ {TRACE_ANALYSIS_DIMENSION_REGISTRY[dimension].emptyStateCopy.summary}</div><Accordion type="single" collapsible className="mt-2"><AccordionItem value="detail" className="border-0">@@ -907,7 +881,7 @@ export default function TraceImprovementView({{m.TRACE_AI_DETAILS}</AccordionTrigger><AccordionContent className="pb-0 text-sm text-stone-600 dark:text-stone-300">- {EMPTY_DIMENSION_COPY[dimension].detail}+ {TRACE_ANALYSIS_DIMENSION_REGISTRY[dimension].emptyStateCopy.detail}</AccordionContent></AccordionItem></Accordion>diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.tsindex e9c1061c..9eaeef54 100644--- a/src/client/src/constants/messages/en.ts+++ b/src/client/src/constants/messages/en.ts@@ -1724,6 +1724,54 @@ export const TRACE_AI_DURATION_MS = (duration: number | string) => `${duration}mexport const TRACE_AI_EMPTY_TITLE = "No analysis yet";export const TRACE_AI_EMPTY_DESCRIPTION ="Run an AI improvement analysis to review prompts, responses, cost, tokens, latency, and hierarchy-level failure patterns.";+export const TRACE_AI_STRENGTHS_UI_LABEL = "Strengths";+export const TRACE_AI_STRENGTHS_STREAM_LABEL = "Strengths";+export const TRACE_AI_STRENGTHS_GUIDANCE =+ "Find concrete things that worked well: efficient prompts, good model choice, useful tool use, clean path, low cost, fast execution, useful context handling. Do not put problems here.";+export const TRACE_AI_STRENGTHS_EMPTY_SUMMARY =+ "No explicit strengths were identified in this run.";+export const TRACE_AI_STRENGTHS_EMPTY_DETAIL =+ "The analysis did not find a concrete positive pattern worth calling out. This does not mean the trace failed; it means the model did not see a specific strength with enough evidence.";+export const TRACE_AI_IMPROVEMENTS_UI_LABEL = "Improvements";+export const TRACE_AI_IMPROVEMENTS_STREAM_LABEL = "Improvements";+export const TRACE_AI_IMPROVEMENTS_GUIDANCE =+ "Find concrete general improvements that do not belong in cost, token_efficiency, wrong_turns, or path_analysis. Avoid generic advice; cite spans.";+export const TRACE_AI_IMPROVEMENTS_EMPTY_SUMMARY =+ "No general improvements are required right now.";+export const TRACE_AI_IMPROVEMENTS_EMPTY_DETAIL =+ "The trace did not show a broad improvement opportunity outside the more specific cost, token, path, or wrong-turn categories.";+export const TRACE_AI_WRONG_TURNS_UI_LABEL = "Wrong turns";+export const TRACE_AI_WRONG_TURNS_STREAM_LABEL = "Wrong turns";+export const TRACE_AI_WRONG_TURNS_GUIDANCE =+ "Find retries, rework, off-task branches, tool failures followed by repeated work, user-blocked steps, self-correction, or decisions that created unnecessary work.";+export const TRACE_AI_WRONG_TURNS_EMPTY_SUMMARY =+ "No wrong turns were detected.";+export const TRACE_AI_WRONG_TURNS_EMPTY_DETAIL =+ "The trace did not show clear retries, off-task branches, unnecessary rework, or agent decisions that caused a detour.";+export const TRACE_AI_COST_UI_LABEL = "Cost";+export const TRACE_AI_COST_STREAM_LABEL = "Cost";+export const TRACE_AI_COST_GUIDANCE =+ "Analyze absolute spend, cost concentration, model choice, expensive spans, cost per call, and whether cheaper routing would have been appropriate. Do not discuss token waste unless it directly explains spend.";+export const TRACE_AI_COST_EMPTY_SUMMARY =+ "Cost looks acceptable for this trace.";+export const TRACE_AI_COST_EMPTY_DETAIL =+ "No span stood out as clearly over budget or using a model that was obviously too expensive for the observed subtask.";+export const TRACE_AI_TOKEN_EFFICIENCY_UI_LABEL = "Token efficiency";+export const TRACE_AI_TOKEN_EFFICIENCY_STREAM_LABEL = "Token efficiency";+export const TRACE_AI_TOKEN_EFFICIENCY_GUIDANCE =+ "Analyze input/output/cache/reasoning token waste, repeated context, repeated prompts, oversized tool results, duplicate retrieval/tool inputs, and largest context spans. This is about waste, not absolute spend.";+export const TRACE_AI_TOKEN_EFFICIENCY_EMPTY_SUMMARY =+ "Token usage looks acceptable for this trace.";+export const TRACE_AI_TOKEN_EFFICIENCY_EMPTY_DETAIL =+ "The analysis did not find obvious prompt bloat, repeated context, oversized tool outputs, or duplicate retrieval payloads.";+export const TRACE_AI_PATH_ANALYSIS_UI_LABEL = "Path";+export const TRACE_AI_PATH_ANALYSIS_STREAM_LABEL = "Path analysis";+export const TRACE_AI_PATH_ANALYSIS_GUIDANCE =+ "Analyze routing and execution path: whether the trace picked the right tools, avoided loops, used the right branches, and kept orchestration efficient.";+export const TRACE_AI_PATH_ANALYSIS_EMPTY_SUMMARY =+ "The execution path looks reasonable.";+export const TRACE_AI_PATH_ANALYSIS_EMPTY_DETAIL =+ "The trace did not show clear routing loops, missed branches, unnecessary tool hops, or inappropriate tool choices.";export const TRACE_AI_TOKENS_SAVED = (tokens: number | string) =>`${tokens} tokens saved`;export const TRACE_AI_USD_SAVED = (usd: number | string) => `$${usd} saved`;diff --git a/src/client/src/lib/platform/chat/improvement.ts b/src/client/src/lib/platform/chat/improvement.tsindex 1ef37572..5bfa0706 100644--- a/src/client/src/lib/platform/chat/improvement.ts+++ b/src/client/src/lib/platform/chat/improvement.ts@@ -13,6 +13,11 @@ import {TraceAnalysisFinding,emptyTraceAnalysis,} from "@/types/trace-analysis";+import {+ TRACE_ANALYSIS_DIMENSION_REGISTRY,+ selectTraceAnalysisMetrics,+ selectTraceAnalysisSpan,+} from "./trace-analysis-registry";import Sanitizer from "@/utils/sanitizer";type ImprovementSpanSummary = {@@ -134,29 +139,23 @@ type TraceAnalysis = {};};`;-const DIMENSION_GUIDANCE: Record<TraceAnalysisDimension, string> = {- strengths:- "Find concrete things that worked well: efficient prompts, good model choice, useful tool use, clean path, low cost, fast execution, useful context handling. Do not put problems here.",- improvements:- "Find concrete general improvements that do not belong in cost, token_efficiency, wrong_turns, or path_analysis. Avoid generic advice; cite spans.",- wrong_turns:- "Find retries, rework, off-task branches, tool failures followed by repeated work, user-blocked steps, self-correction, or decisions that created unnecessary work.",- cost:- "Analyze absolute spend, cost concentration, model choice, expensive spans, cost per call, and whether cheaper routing would have been appropriate. Do not discuss token waste unless it directly explains spend.",- token_efficiency:- "Analyze input/output/cache/reasoning token waste, repeated context, repeated prompts, oversized tool results, duplicate retrieval/tool inputs, and largest context spans. This is about waste, not absolute spend.",- path_analysis:- "Analyze routing and execution path: whether the trace picked the right tools, avoided loops, used the right branches, and kept orchestration efficient.",-};--const DIMENSION_LABELS: Record<TraceAnalysisDimension, string> = {- strengths: "Strengths",- improvements: "Improvements",- wrong_turns: "Wrong turns",- cost: "Cost",- token_efficiency: "Token efficiency",- path_analysis: "Path analysis",-};+const DIMENSION_GUIDANCE = Object.freeze(+ Object.fromEntries(+ TRACE_ANALYSIS_DIMENSIONS.map((dimension) => [+ dimension,+ TRACE_ANALYSIS_DIMENSION_REGISTRY[dimension].guidance,+ ])+ )+) as Record<TraceAnalysisDimension, string>;++const DIMENSION_LABELS = Object.freeze(+ Object.fromEntries(+ TRACE_ANALYSIS_DIMENSIONS.map((dimension) => [+ dimension,+ TRACE_ANALYSIS_DIMENSION_REGISTRY[dimension].streamLabel,+ ])+ )+) as Record<TraceAnalysisDimension, string>;function computeWorstSeverity(analysis: TraceAnalysis): string {for (const severity of ["critical", "major", "minor", "info"] as const) {@@ -1019,179 +1018,6 @@ function contextForLogs(summary: ImprovementSpanSummary, metrics: TraceAnalysisM};}-function spanForDimension(span: ImprovementSpanSummary, dimension: TraceAnalysisDimension): Record<string, unknown> {- const base = {- spanId: span.spanId,- spanName: span.spanName,- role: span.role,- statusCode: span.statusCode,- statusMessage: span.statusMessage,- durationMs: span.durationMs,- error: span.error,- children: span.children.map((child) => spanForDimension(child, dimension)),- };-- if (dimension === "cost") {- return {- ...base,- model: span.model,- provider: span.provider,- cost: span.cost,- promptTokens: span.promptTokens,- completionTokens: span.completionTokens,- totalTokens: span.totalTokens,- };- }-- if (dimension === "token_efficiency") {- return {- ...base,- model: span.model,- promptTokens: span.promptTokens,- completionTokens: span.completionTokens,- totalTokens: span.totalTokens,- cacheReadTokens: span.cacheReadTokens,- cacheCreationTokens: span.cacheCreationTokens,- reasoningTokens: span.reasoningTokens,- systemPrompt: span.systemPrompt,- prompt: span.prompt,- response: span.response,- toolArgs: span.toolArgs,- toolResult: span.toolResult,- };- }-- if (dimension === "wrong_turns") {- return {- ...base,- toolName: span.toolName,- toolArgs: span.toolArgs,- toolResult: span.toolResult,- prompt: span.prompt,- response: span.response,- reasoning: span.reasoning,- eventSummary: span.eventSummary,- };- }-- if (dimension === "path_analysis") {- return {- ...base,- serviceName: span.serviceName,- toolName: span.toolName,- toolCallId: span.toolCallId,- toolArgs: span.toolArgs,- dbQuery: span.dbQuery,- httpUrl: span.httpUrl,- resource: span.resource,- };- }-- if (dimension === "strengths") {- return {- ...base,- model: span.model,- provider: span.provider,- cost: span.cost,- totalTokens: span.totalTokens,- toolName: span.toolName,- prompt: span.prompt,- response: span.response,- };- }-- return {- ...base,- model: span.model,- provider: span.provider,- cost: span.cost,- totalTokens: span.totalTokens,- prompt: span.prompt,- response: span.response,- toolName: span.toolName,- toolArgs: span.toolArgs,- toolResult: span.toolResult,- dbQuery: span.dbQuery,- httpUrl: span.httpUrl,- resource: span.resource,- };-}--function metricsForDimension(metrics: TraceAnalysisMetrics, dimension: TraceAnalysisDimension): Record<string, unknown> {- const common = {- spanCount: metrics.spanCount,- maxDepth: metrics.maxDepth,- errorCount: metrics.errorCount,- llmCallCount: metrics.llmCallCount,- toolCallCount: metrics.toolCallCount,- retrievalCallCount: metrics.retrievalCallCount,- modelsUsed: metrics.modelsUsed,- toolsUsed: metrics.toolsUsed,- };-- if (dimension === "cost") {- return {- ...common,- totalCostUsd: metrics.totalCostUsd,- costPerCall: metrics.costPerCall,- avgCostPerLlm: metrics.avgCostPerLlm,- mostExpensiveSpanId: metrics.mostExpensiveSpanId,- mostExpensiveCostUsd: metrics.mostExpensiveCostUsd,- totalTokens: metrics.totalTokens,- };- }-- if (dimension === "token_efficiency") {- return {- ...common,- totalInputTokens: metrics.totalInputTokens,- totalOutputTokens: metrics.totalOutputTokens,- totalTokens: metrics.totalTokens,- totalCacheReadTokens: metrics.totalCacheReadTokens,- totalCacheCreationTokens: metrics.totalCacheCreationTokens,- totalReasoningTokens: metrics.totalReasoningTokens,- cacheHitRate: metrics.cacheHitRate,- largestContextSpanId: metrics.largestContextSpanId,- largestContextTokens: metrics.largestContextTokens,- duplicateToolInputs: metrics.duplicateToolInputs,- duplicateRetrievalInputs: metrics.duplicateRetrievalInputs,- repeatedSpanNames: metrics.repeatedSpanNames,- };- }-- if (dimension === "wrong_turns") {- return {- ...common,- potentialRetrySequences: metrics.potentialRetrySequences,- repeatedSpanNames: metrics.repeatedSpanNames,- slowestSpanId: metrics.slowestSpanId,- slowestDurationMs: metrics.slowestDurationMs,- };- }-- if (dimension === "path_analysis") {- return {- ...common,- totalDurationMs: metrics.totalDurationMs,- maxDepth: metrics.maxDepth,- repeatedSpanNames: metrics.repeatedSpanNames,- potentialRetrySequences: metrics.potentialRetrySequences,- databaseCallCount: metrics.databaseCallCount,- httpCallCount: metrics.httpCallCount,- };- }-- return {- ...common,- totalCostUsd: metrics.totalCostUsd,- totalTokens: metrics.totalTokens,- totalDurationMs: metrics.totalDurationMs,- slowestSpanId: metrics.slowestSpanId,- mostExpensiveSpanId: metrics.mostExpensiveSpanId,- largestContextSpanId: metrics.largestContextSpanId,- };-}-function buildDimensionSystemPrompt(dimension: TraceAnalysisDimension) {return `You are analyzing one dimension of a single OpenTelemetry trace from an LLM application.@@ -1227,7 +1053,7 @@ Source span id: ${spanId}Focused deterministic metrics:\`\`\`json-${JSON.stringify(metricsForDimension(metrics, dimension), null, 2)}+${JSON.stringify(selectTraceAnalysisMetrics(metrics, dimension), null, 2)}\`\`\`Rule-engine context:@@ -1241,7 +1067,7 @@ ${JSON.stringify({Focused trace tree:\`\`\`json-${JSON.stringify(spanForDimension(summary, dimension), null, 2)}+${JSON.stringify(selectTraceAnalysisSpan(summary, dimension), null, 2)}\`\`\`Return strict JSON: {"summary": string, "findings": Finding[]}.`;@@ -1293,7 +1119,7 @@ ${JSON.stringify(firstPass, null, 2)}Focused deterministic metrics:\`\`\`json-${JSON.stringify(metricsForDimension(metrics, dimension), null, 2)}+${JSON.stringify(selectTraceAnalysisMetrics(metrics, dimension), null, 2)}\`\`\`Rule-engine context:@@ -1307,7 +1133,7 @@ ${JSON.stringify({Focused trace tree:\`\`\`json-${JSON.stringify(spanForDimension(summary, dimension), null, 2)}+${JSON.stringify(selectTraceAnalysisSpan(summary, dimension), null, 2)}\`\`\`Return the improved final JSON only: {"summary": string, "findings": Finding[]}.`;diff --git a/src/client/src/lib/platform/chat/trace-analysis-registry.ts b/src/client/src/lib/platform/chat/trace-analysis-registry.tsnew file mode 100644index 00000000..83e0c7f4--- /dev/null+++ b/src/client/src/lib/platform/chat/trace-analysis-registry.ts@@ -0,0 +1,383 @@+import {+ TRACE_AI_COST_EMPTY_DETAIL,+ TRACE_AI_COST_EMPTY_SUMMARY,+ TRACE_AI_COST_GUIDANCE,+ TRACE_AI_COST_STREAM_LABEL,+ TRACE_AI_COST_UI_LABEL,+ TRACE_AI_IMPROVEMENTS_EMPTY_DETAIL,+ TRACE_AI_IMPROVEMENTS_EMPTY_SUMMARY,+ TRACE_AI_IMPROVEMENTS_GUIDANCE,+ TRACE_AI_IMPROVEMENTS_STREAM_LABEL,+ TRACE_AI_IMPROVEMENTS_UI_LABEL,+ TRACE_AI_PATH_ANALYSIS_EMPTY_DETAIL,+ TRACE_AI_PATH_ANALYSIS_EMPTY_SUMMARY,+ TRACE_AI_PATH_ANALYSIS_GUIDANCE,+ TRACE_AI_PATH_ANALYSIS_STREAM_LABEL,+ TRACE_AI_PATH_ANALYSIS_UI_LABEL,+ TRACE_AI_STRENGTHS_EMPTY_DETAIL,+ TRACE_AI_STRENGTHS_EMPTY_SUMMARY,+ TRACE_AI_STRENGTHS_GUIDANCE,+ TRACE_AI_STRENGTHS_STREAM_LABEL,+ TRACE_AI_STRENGTHS_UI_LABEL,+ TRACE_AI_TOKEN_EFFICIENCY_EMPTY_DETAIL,+ TRACE_AI_TOKEN_EFFICIENCY_EMPTY_SUMMARY,+ TRACE_AI_TOKEN_EFFICIENCY_GUIDANCE,+ TRACE_AI_TOKEN_EFFICIENCY_STREAM_LABEL,+ TRACE_AI_TOKEN_EFFICIENCY_UI_LABEL,+ TRACE_AI_WRONG_TURNS_EMPTY_DETAIL,+ TRACE_AI_WRONG_TURNS_EMPTY_SUMMARY,+ TRACE_AI_WRONG_TURNS_GUIDANCE,+ TRACE_AI_WRONG_TURNS_STREAM_LABEL,+ TRACE_AI_WRONG_TURNS_UI_LABEL,+} from "@/constants/messages/en";++type TraceAnalysisSpanSource = {+ spanId: string;+ spanName: string;+ role?: string;+ serviceName?: string;+ resource?: Record<string, string | number>;+ statusCode?: string;+ statusMessage?: string;+ durationMs: number;+ error?: string;+ model?: string;+ provider?: string;+ cost?: number;+ promptTokens?: number;+ completionTokens?: number;+ totalTokens?: number;+ cacheReadTokens?: number;+ cacheCreationTokens?: number;+ reasoningTokens?: number;+ systemPrompt?: string;+ prompt?: string;+ response?: string;+ reasoning?: string;+ toolName?: string;+ toolCallId?: string;+ toolArgs?: string;+ toolResult?: string;+ dbQuery?: string;+ httpUrl?: string;+ eventSummary?: Array<{+ name?: string;+ attributes: Record<string, string | number>;+ }>;+ children: TraceAnalysisSpanSource[];+};++type TraceAnalysisMetricSource = {+ spanCount: number;+ maxDepth: number;+ errorCount: number;+ llmCallCount: number;+ toolCallCount: number;+ retrievalCallCount: number;+ modelsUsed: string[];+ toolsUsed: string[];+ totalCostUsd?: number;+ costPerCall?: number;+ avgCostPerLlm?: number;+ mostExpensiveSpanId?: string;+ mostExpensiveCostUsd?: number;+ totalInputTokens?: number;+ totalOutputTokens?: number;+ totalTokens?: number;+ totalCacheReadTokens?: number;+ totalCacheCreationTokens?: number;+ totalReasoningTokens?: number;+ cacheHitRate?: number;+ largestContextSpanId?: string;+ largestContextTokens?: number;+ duplicateToolInputs?: Array<{ key: string; count: number; spanIds: string[] }>;+ duplicateRetrievalInputs?: Array<{ key: string; count: number; spanIds: string[] }>;+ repeatedSpanNames?: Array<{ name: string; count: number; spanIds: string[] }>;+ potentialRetrySequences?: Array<{ reason: string; spanIds: string[] }>;+ slowestSpanId?: string;+ slowestDurationMs?: number;+ totalDurationMs?: number;+ databaseCallCount?: number;+ httpCallCount?: number;+};++type TraceAnalysisSpanField = Exclude<keyof TraceAnalysisSpanSource, "children">;+type TraceAnalysisMetricField = keyof TraceAnalysisMetricSource;++type DimensionDefinitionSource = {+ key: string;+ uiLabel: string;+ streamLabel: string;+ guidance: string;+ emptyStateCopy: { summary: string; detail: string };+ spanFields: readonly TraceAnalysisSpanField[];+ metricFields: readonly TraceAnalysisMetricField[];+};++function defineDimension<const T extends DimensionDefinitionSource>(definition: T) {+ return Object.freeze({+ ...definition,+ emptyStateCopy: Object.freeze(definition.emptyStateCopy),+ spanFields: Object.freeze(definition.spanFields),+ metricFields: Object.freeze(definition.metricFields),+ });+}++export const TRACE_ANALYSIS_DIMENSION_DEFINITIONS = Object.freeze([+ defineDimension({+ key: "strengths",+ uiLabel: TRACE_AI_STRENGTHS_UI_LABEL,+ streamLabel: TRACE_AI_STRENGTHS_STREAM_LABEL,+ guidance: TRACE_AI_STRENGTHS_GUIDANCE,+ emptyStateCopy: {+ summary: TRACE_AI_STRENGTHS_EMPTY_SUMMARY,+ detail: TRACE_AI_STRENGTHS_EMPTY_DETAIL,+ },+ spanFields: [+ "model",+ "provider",+ "cost",+ "totalTokens",+ "toolName",+ "prompt",+ "response",+ ],+ metricFields: [+ "totalCostUsd",+ "totalTokens",+ "totalDurationMs",+ "slowestSpanId",+ "mostExpensiveSpanId",+ "largestContextSpanId",+ ],+ }),+ defineDimension({+ key: "improvements",+ uiLabel: TRACE_AI_IMPROVEMENTS_UI_LABEL,+ streamLabel: TRACE_AI_IMPROVEMENTS_STREAM_LABEL,+ guidance: TRACE_AI_IMPROVEMENTS_GUIDANCE,+ emptyStateCopy: {+ summary: TRACE_AI_IMPROVEMENTS_EMPTY_SUMMARY,+ detail: TRACE_AI_IMPROVEMENTS_EMPTY_DETAIL,+ },+ spanFields: [+ "model",+ "provider",+ "cost",+ "totalTokens",+ "prompt",+ "response",+ "toolName",+ "toolArgs",+ "toolResult",+ "dbQuery",+ "httpUrl",+ "resource",+ ],+ metricFields: [+ "totalCostUsd",+ "totalTokens",+ "totalDurationMs",+ "slowestSpanId",+ "mostExpensiveSpanId",+ "largestContextSpanId",+ ],+ }),+ defineDimension({+ key: "wrong_turns",+ uiLabel: TRACE_AI_WRONG_TURNS_UI_LABEL,+ streamLabel: TRACE_AI_WRONG_TURNS_STREAM_LABEL,+ guidance: TRACE_AI_WRONG_TURNS_GUIDANCE,+ emptyStateCopy: {+ summary: TRACE_AI_WRONG_TURNS_EMPTY_SUMMARY,+ detail: TRACE_AI_WRONG_TURNS_EMPTY_DETAIL,+ },+ spanFields: [+ "toolName",+ "toolArgs",+ "toolResult",+ "prompt",+ "response",+ "reasoning",+ "eventSummary",+ ],+ metricFields: [+ "potentialRetrySequences",+ "repeatedSpanNames",+ "slowestSpanId",+ "slowestDurationMs",+ ],+ }),+ defineDimension({+ key: "cost",+ uiLabel: TRACE_AI_COST_UI_LABEL,+ streamLabel: TRACE_AI_COST_STREAM_LABEL,+ guidance: TRACE_AI_COST_GUIDANCE,+ emptyStateCopy: {+ summary: TRACE_AI_COST_EMPTY_SUMMARY,+ detail: TRACE_AI_COST_EMPTY_DETAIL,+ },+ spanFields: [+ "model",+ "provider",+ "cost",+ "promptTokens",+ "completionTokens",+ "totalTokens",+ ],+ metricFields: [+ "totalCostUsd",+ "costPerCall",+ "avgCostPerLlm",+ "mostExpensiveSpanId",+ "mostExpensiveCostUsd",+ "totalTokens",+ ],+ }),+ defineDimension({+ key: "token_efficiency",+ uiLabel: TRACE_AI_TOKEN_EFFICIENCY_UI_LABEL,+ streamLabel: TRACE_AI_TOKEN_EFFICIENCY_STREAM_LABEL,+ guidance: TRACE_AI_TOKEN_EFFICIENCY_GUIDANCE,+ emptyStateCopy: {+ summary: TRACE_AI_TOKEN_EFFICIENCY_EMPTY_SUMMARY,+ detail: TRACE_AI_TOKEN_EFFICIENCY_EMPTY_DETAIL,+ },+ spanFields: [+ "model",+ "promptTokens",+ "completionTokens",+ "totalTokens",+ "cacheReadTokens",+ "cacheCreationTokens",+ "reasoningTokens",+ "systemPrompt",+ "prompt",+ "response",+ "toolArgs",+ "toolResult",+ ],+ metricFields: [+ "totalInputTokens",+ "totalOutputTokens",+ "totalTokens",+ "totalCacheReadTokens",+ "totalCacheCreationTokens",+ "totalReasoningTokens",+ "cacheHitRate",+ "largestContextSpanId",+ "largestContextTokens",+ "duplicateToolInputs",+ "duplicateRetrievalInputs",+ "repeatedSpanNames",+ ],+ }),+ defineDimension({+ key: "path_analysis",+ uiLabel: TRACE_AI_PATH_ANALYSIS_UI_LABEL,+ streamLabel: TRACE_AI_PATH_ANALYSIS_STREAM_LABEL,+ guidance: TRACE_AI_PATH_ANALYSIS_GUIDANCE,+ emptyStateCopy: {+ summary: TRACE_AI_PATH_ANALYSIS_EMPTY_SUMMARY,+ detail: TRACE_AI_PATH_ANALYSIS_EMPTY_DETAIL,+ },+ spanFields: [+ "serviceName",+ "toolName",+ "toolCallId",+ "toolArgs",+ "dbQuery",+ "httpUrl",+ "resource",+ ],+ metricFields: [+ "totalDurationMs",+ "maxDepth",+ "repeatedSpanNames",+ "potentialRetrySequences",+ "databaseCallCount",+ "httpCallCount",+ ],+ }),+] as const);++export type TraceAnalysisDimensionKey =+ (typeof TRACE_ANALYSIS_DIMENSION_DEFINITIONS)[number]["key"];++export type TraceAnalysisDimensionDefinition =+ (typeof TRACE_ANALYSIS_DIMENSION_DEFINITIONS)[number];++export const TRACE_ANALYSIS_DIMENSION_REGISTRY = Object.freeze(+ Object.fromEntries(+ TRACE_ANALYSIS_DIMENSION_DEFINITIONS.map((definition) => [+ definition.key,+ definition,+ ])+ )+) as Readonly<+ Record<TraceAnalysisDimensionKey, TraceAnalysisDimensionDefinition>+>;++export function getTraceAnalysisDimensionDefinition(+ dimension: string+): TraceAnalysisDimensionDefinition {+ return (+ TRACE_ANALYSIS_DIMENSION_REGISTRY[+ dimension as TraceAnalysisDimensionKey+ ] ?? TRACE_ANALYSIS_DIMENSION_DEFINITIONS[0]+ );+}++function selectFields(+ source: object,+ fields: readonly string[]+): Record<string, unknown> {+ const values = source as Record<string, unknown>;+ return Object.fromEntries(fields.map((field) => [field, values[field]]));+}++export function selectTraceAnalysisSpan(+ span: TraceAnalysisSpanSource,+ dimension: TraceAnalysisDimensionKey+): Record<string, unknown> {+ const definition = TRACE_ANALYSIS_DIMENSION_REGISTRY[dimension];+ const base = {+ spanId: span.spanId,+ spanName: span.spanName,+ role: span.role,+ statusCode: span.statusCode,+ statusMessage: span.statusMessage,+ durationMs: span.durationMs,+ error: span.error,+ children: span.children.map((child) =>+ selectTraceAnalysisSpan(child, dimension)+ ),+ };++ return {+ ...base,+ ...selectFields(span, definition.spanFields),+ };+}++export function selectTraceAnalysisMetrics(+ metrics: TraceAnalysisMetricSource,+ dimension: TraceAnalysisDimensionKey+): Record<string, unknown> {+ const definition = TRACE_ANALYSIS_DIMENSION_REGISTRY[dimension];+ const common = {+ spanCount: metrics.spanCount,+ maxDepth: metrics.maxDepth,+ errorCount: metrics.errorCount,+ llmCallCount: metrics.llmCallCount,+ toolCallCount: metrics.toolCallCount,+ retrievalCallCount: metrics.retrievalCallCount,+ modelsUsed: metrics.modelsUsed,+ toolsUsed: metrics.toolsUsed,+ };++ return {+ ...common,+ ...selectFields(metrics, definition.metricFields),+ };+}diff --git a/src/client/src/types/trace-analysis.ts b/src/client/src/types/trace-analysis.tsindex 04004bcf..c9d2a64c 100644--- a/src/client/src/types/trace-analysis.ts+++ b/src/client/src/types/trace-analysis.ts@@ -1,22 +1,22 @@-export const TRACE_ANALYSIS_DIMENSIONS = [- "strengths",- "improvements",- "wrong_turns",- "cost",- "token_efficiency",- "path_analysis",-] as const;+import {+ TRACE_ANALYSIS_DIMENSION_DEFINITIONS,+ TraceAnalysisDimensionKey,+} from "@/lib/platform/chat/trace-analysis-registry";-export type TraceAnalysisDimension = (typeof TRACE_ANALYSIS_DIMENSIONS)[number];+export const TRACE_ANALYSIS_DIMENSIONS = Object.freeze(+ TRACE_ANALYSIS_DIMENSION_DEFINITIONS.map(({ key }) => key)+) as readonly TraceAnalysisDimensionKey[];-export const TRACE_ANALYSIS_DIMENSION_LABELS: Record<TraceAnalysisDimension, string> = {- strengths: "Strengths",- improvements: "Improvements",- wrong_turns: "Wrong turns",- cost: "Cost",- token_efficiency: "Token efficiency",- path_analysis: "Path",-};+export type TraceAnalysisDimension = TraceAnalysisDimensionKey;++export const TRACE_ANALYSIS_DIMENSION_LABELS = Object.freeze(+ Object.fromEntries(+ TRACE_ANALYSIS_DIMENSION_DEFINITIONS.map(({ key, uiLabel }) => [+ key,+ uiLabel,+ ])+ )+) as Record<TraceAnalysisDimension, string>;export type TraceAnalysisSeverity = "info" | "minor" | "major" | "critical";@@ -58,25 +58,18 @@ export type TraceAnalysisTotals = {export type TraceAnalysis = {trace_id: string;summary: string;- strengths: TraceAnalysisFinding[];- improvements: TraceAnalysisFinding[];- wrong_turns: TraceAnalysisFinding[];- cost: TraceAnalysisFinding[];- token_efficiency: TraceAnalysisFinding[];- path_analysis: TraceAnalysisFinding[];totals: TraceAnalysisTotals;-};+} & Record<TraceAnalysisDimension, TraceAnalysisFinding[]>;export function emptyTraceAnalysis(traceId: string): TraceAnalysis {+ const emptyDimensions = Object.fromEntries(+ TRACE_ANALYSIS_DIMENSIONS.map((dimension) => [dimension, []])+ ) as unknown as Record<TraceAnalysisDimension, TraceAnalysisFinding[]>;+return {trace_id: traceId,summary: "",- strengths: [],- improvements: [],- wrong_turns: [],- cost: [],- token_efficiency: [],- path_analysis: [],+ ...emptyDimensions,totals: {span_count: 0,total_tokens: 0,