Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent-tracing): tool-result feedback quality analysis (tq command) (#15508)

Arvin Xuad87e43b2ead
diff --git a/packages/agent-tracing/src/analysis/toolFeedback.ts b/packages/agent-tracing/src/analysis/toolFeedback.ts
new file mode 100644
index 00000000000..d9a2eecac5f
--- /dev/null
+++ b/packages/agent-tracing/src/analysis/toolFeedback.ts
@@ -0,0 +1,262 @@
+import { encode } from 'gpt-tokenizer';
+
+import type { ExecutionSnapshot } from '../types';
+
+/**
+ * Objective (no-LLM) quality metrics for a single tool result β€” the "environment feedback"
+ * an agent receives. These are the Phase-1 signals that can be computed over the whole
+ * snapshot corpus to rank which tools pollute the context window.
+ *
+ * Semantic metrics that genuinely need a judge (feedback utility, actionability, failure
+ * clarity, compressibility) are intentionally NOT here β€” they belong to a later phase.
+ */
+export interface ToolResultMetrics {
+ apiName: string;
+ /** Character length of the (unwrapped) content. */
+ chars: number;
+ format: 'json' | 'xml' | 'markdown' | 'text';
+ identifier: string;
+ /** `isSuccess === false`, or an error/stack signal in the head of the content. */
+ isError: boolean;
+ /** 0..1 β€” fraction of fixed-size shingles that are exact repeats (degenerate dumps). */
+ selfRedundancy: number;
+ stepIndex: number;
+ /** 0..1 β€” for xml/html, share of chars living inside `<...>` tags (node ids, markup). */
+ structuralNoiseRatio: number;
+ /** gpt-tokenizer count of the unwrapped content. */
+ tokens: number;
+ /** `${identifier}/${apiName}` */
+ tool: string;
+}
+
+const SHINGLE = 80;
+const ERROR_HEAD = 2000;
+const ERROR_RE = /\b(?:error|failed|failure|exception|enoent|econn|traceback|status\s+5\d\d)\b/i;
+
+/** Tool outputs are frequently JSON-wrapped as `{"content":"..."}` β€” score the payload, not the envelope. */
+function unwrapContent(output: string): string {
+ const t = output.trimStart();
+ if (t.startsWith('{')) {
+ try {
+ const o = JSON.parse(output);
+ if (o && typeof o.content === 'string') return o.content;
+ } catch {
+ // not JSON β€” score as-is
+ }
+ }
+ return output;
+}
+
+function detectFormat(s: string): ToolResultMetrics['format'] {
+ const h = s.trimStart();
+ if (h.startsWith('{') || h.startsWith('[')) return 'json';
+ if (h.startsWith('<')) return 'xml';
+ if (/^[#*\-|>]/.test(h)) return 'markdown';
+ return 'text';
+}
+
+function selfRedundancy(s: string): number {
+ if (s.length < SHINGLE * 4) return 0;
+ const shingles: string[] = [];
+ for (let i = 0; i + SHINGLE <= s.length; i += SHINGLE) shingles.push(s.slice(i, i + SHINGLE));
+ if (shingles.length === 0) return 0;
+ return 1 - new Set(shingles).size / shingles.length;
+}
+
+function structuralNoiseRatio(s: string, format: ToolResultMetrics['format']): number {
+ if (format !== 'xml' || s.length === 0) return 0;
+ let inside = 0;
+ const tags = s.match(/<[^>]*>/g);
+ if (tags) for (const tag of tags) inside += tag.length;
+ return inside / s.length;
+}
+
+/** Pure: score one raw tool output string. The shared core reused by CLI / DC ingestion / backfill. */
+export function analyzeToolResult(
+ rawOutput: string,
+ isSuccess: boolean | undefined,
+): Pick<
+ ToolResultMetrics,
+ 'chars' | 'tokens' | 'format' | 'isError' | 'selfRedundancy' | 'structuralNoiseRatio'
+> {
+ const content = unwrapContent(rawOutput ?? '');
+ const format = detectFormat(content);
+ return {
+ chars: content.length,
+ format,
+ isError: isSuccess === false || ERROR_RE.test(content.slice(0, ERROR_HEAD)),
+ selfRedundancy: selfRedundancy(content),
+ structuralNoiseRatio: structuralNoiseRatio(content, format),
+ tokens: content ? encode(content).length : 0,
+ };
+}
+
+/** Flatten every tool result in a snapshot into per-result metrics. */
+export function collectToolResults(snapshot: ExecutionSnapshot): ToolResultMetrics[] {
+ const out: ToolResultMetrics[] = [];
+ for (const step of snapshot.steps) {
+ const results = step.toolsResult;
+ if (!Array.isArray(results)) continue;
+ for (const r of results) {
+ if (!r || typeof r.output !== 'string') continue;
+ const identifier = r.identifier ?? '?';
+ const apiName = r.apiName ?? '?';
+ out.push({
+ ...analyzeToolResult(r.output, r.isSuccess),
+ apiName,
+ identifier,
+ stepIndex: step.stepIndex,
+ tool: `${identifier}/${apiName}`,
+ });
+ }
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Aggregation
+// ---------------------------------------------------------------------------
+
+/** Tokens of a result estimated to carry no useful signal β€” the basis for the dirty leaderboard. */
+const ERROR_TOKEN_BUDGET = 200;
+export function estWasteTokens(m: ToolResultMetrics): number {
+ let noise = m.selfRedundancy + m.structuralNoiseRatio;
+ if (m.isError) noise += Math.min(1, m.tokens / ERROR_TOKEN_BUDGET) * 0.5;
+ return m.tokens * Math.min(1, noise);
+}
+
+function percentile(sorted: number[], p: number): number {
+ if (sorted.length === 0) return 0;
+ const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));
+ return sorted[idx];
+}
+
+/** Op-level rollup β€” the candidate shape for the `agent_operations` analytics column (lobehub side). */
+export interface OpToolFeedbackRollup {
+ errorResultCount: number;
+ errorResultTokens: number;
+ operationId: string;
+ resultCount: number;
+ selfRedundancyMax: number;
+ structuralNoiseAvg: number;
+ tokensMax: number;
+ tokensP50: number;
+ tokensP90: number;
+ tokensP99: number;
+ tokensTotal: number;
+ wasteTokensTotal: number;
+ worstOffenders: Array<{
+ selfRedundancy: number;
+ stepIndex: number;
+ structuralNoiseRatio: number;
+ tokens: number;
+ tool: string;
+ }>;
+}
+
+export function rollupOperation(snapshot: ExecutionSnapshot): OpToolFeedbackRollup {
+ const results = collectToolResults(snapshot);
+ const tokens = results.map((r) => r.tokens).sort((a, b) => a - b);
+ const errors = results.filter((r) => r.isError);
+ const offenders = [...results]
+ .sort((a, b) => estWasteTokens(b) - estWasteTokens(a))
+ .slice(0, 3)
+ .map((r) => ({
+ selfRedundancy: r.selfRedundancy,
+ stepIndex: r.stepIndex,
+ structuralNoiseRatio: r.structuralNoiseRatio,
+ tokens: r.tokens,
+ tool: r.tool,
+ }));
+
+ return {
+ errorResultCount: errors.length,
+ errorResultTokens: errors.reduce((s, r) => s + r.tokens, 0),
+ operationId: snapshot.operationId,
+ resultCount: results.length,
+ selfRedundancyMax: results.reduce((m, r) => Math.max(m, r.selfRedundancy), 0),
+ structuralNoiseAvg: results.length
+ ? results.reduce((s, r) => s + r.structuralNoiseRatio, 0) / results.length
+ : 0,
+ tokensMax: percentile(tokens, 100),
+ tokensP50: percentile(tokens, 50),
+ tokensP90: percentile(tokens, 90),
+ tokensP99: percentile(tokens, 99),
+ tokensTotal: tokens.reduce((s, t) => s + t, 0),
+ wasteTokensTotal: results.reduce((s, r) => s + estWasteTokens(r), 0),
+ worstOffenders: offenders,
+ };
+}
+
+/** Per-tool aggregate across a corpus β€” drives the dirty leaderboard. */
+export interface ToolAggregate {
+ calls: number;
+ errRate: number;
+ errTokens: number;
+ noiseAvg: number;
+ redundAvg: number;
+ tokensP99: number;
+ tokensTotal: number;
+ tool: string;
+ wasteTokens: number;
+}
+
+export interface CorpusReport {
+ buckets: Array<{ count: number; label: string; tokens: number; upper: number }>;
+ leaderboard: ToolAggregate[];
+ ops: number;
+ resultCount: number;
+ tokensTotal: number;
+ wasteTokensTotal: number;
+}
+
+const HIST_BUCKETS = [128, 512, 2048, 8192, 32_768, Infinity];
+
+export function buildCorpusReport(perResult: ToolResultMetrics[], ops: number): CorpusReport {
+ // histogram
+ const buckets = HIST_BUCKETS.map((upper, i) => {
+ const lower = i === 0 ? 0 : HIST_BUCKETS[i - 1];
+ const label = upper === Infinity ? `β‰₯${lower}` : `<${upper}`;
+ return { count: 0, label, tokens: 0, upper };
+ });
+ for (const r of perResult) {
+ const b = buckets.find((x) => r.tokens < x.upper) ?? buckets.at(-1);
+ if (!b) continue;
+ b.count += 1;
+ b.tokens += r.tokens;
+ }
+
+ // per-tool aggregate
+ const byTool = new Map<string, ToolResultMetrics[]>();
+ for (const r of perResult) {
+ const arr = byTool.get(r.tool) ?? [];
+ arr.push(r);
+ byTool.set(r.tool, arr);
+ }
+ const leaderboard: ToolAggregate[] = [...byTool.entries()]
+ .map(([tool, rs]) => {
+ const toks = rs.map((r) => r.tokens).sort((a, b) => a - b);
+ const errs = rs.filter((r) => r.isError);
+ return {
+ calls: rs.length,
+ errRate: errs.length / rs.length,
+ errTokens: errs.reduce((s, r) => s + r.tokens, 0),
+ noiseAvg: rs.reduce((s, r) => s + r.structuralNoiseRatio, 0) / rs.length,
+ redundAvg: rs.reduce((s, r) => s + r.selfRedundancy, 0) / rs.length,
+ tokensP99: percentile(toks, 99),
+ tokensTotal: toks.reduce((s, t) => s + t, 0),
+ tool,
+ wasteTokens: rs.reduce((s, r) => s + estWasteTokens(r), 0),
+ };
+ })
+ .sort((a, b) => b.wasteTokens - a.wasteTokens);
+
+ return {
+ buckets,
+ leaderboard,
+ ops,
+ resultCount: perResult.length,
+ tokensTotal: perResult.reduce((s, r) => s + r.tokens, 0),
+ wasteTokensTotal: perResult.reduce((s, r) => s + estWasteTokens(r), 0),
+ };
+}
diff --git a/packages/agent-tracing/src/cli/index.ts b/packages/agent-tracing/src/cli/index.ts
index 25c4d129d47..abdd5c0dcae 100755
--- a/packages/agent-tracing/src/cli/index.ts
+++ b/packages/agent-tracing/src/cli/index.ts
@@ -5,6 +5,7 @@ import { Command } from 'commander';
import { registerInspectCommand } from './inspect';
import { registerListCommand } from './list';
import { registerPartialCommand } from './partial';
+import { registerToolQualityCommand } from './tool-quality';
const program = new Command();
@@ -13,5 +14,6 @@ program.name('agent-tracing').description('Local agent execution snapshot viewer
registerInspectCommand(program);
registerListCommand(program);
registerPartialCommand(program);
+registerToolQualityCommand(program);
program.parse();
diff --git a/packages/agent-tracing/src/cli/tool-quality.ts b/packages/agent-tracing/src/cli/tool-quality.ts
new file mode 100644
index 00000000000..d42dfb70d9d
--- /dev/null
+++ b/packages/agent-tracing/src/cli/tool-quality.ts
@@ -0,0 +1,220 @@
+import { readdir, readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { Command } from 'commander';
+
+import {
+ buildCorpusReport,
+ collectToolResults,
+ type CorpusReport,
+ rollupOperation,
+ type ToolResultMetrics,
+} from '../analysis/toolFeedback';
+import type { ExecutionSnapshot } from '../types';
+
+const dim = (s: string) => `\x1B[2m${s}\x1B[22m`;
+const bold = (s: string) => `\x1B[1m${s}\x1B[22m`;
+const red = (s: string) => `\x1B[31m${s}\x1B[39m`;
+const yellow = (s: string) => `\x1B[33m${s}\x1B[39m`;
+const green = (s: string) => `\x1B[32m${s}\x1B[39m`;
+const cyan = (s: string) => `\x1B[36m${s}\x1B[39m`;
+
+function fmtTokens(n: number): string {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
+ return String(Math.round(n));
+}
+function pct(n: number): string {
+ return `${Math.round(n * 100)}%`;
+}
+function pad(s: string, w: number): string {
+ // eslint-disable-next-line no-control-regex
+ const len = s.replaceAll(/\x1B\[[0-9;]*m/g, '').length;
+ return s + ' '.repeat(Math.max(0, w - len));
+}
+function bar(frac: number, width = 24): string {
+ const n = Math.round(frac * width);
+ return 'β–ˆ'.repeat(n) + dim('Β·'.repeat(width - n));
+}
+function heat(frac: number, s: string): string {
+ if (frac >= 0.5) return red(s);
+ if (frac >= 0.2) return yellow(s);
+ return s;
+}
+
+async function loadSnapshots(dir: string, limit?: number): Promise<ExecutionSnapshot[]> {
+ let files: string[];
+ try {
+ files = (await readdir(dir)).filter((f) => f.endsWith('.json'));
+ } catch {
+ console.error(red(`Cannot read snapshot dir: ${dir}`));
+ process.exit(1);
+ }
+ if (limit) files = files.slice(0, limit);
+ const out: ExecutionSnapshot[] = [];
+ for (const f of files) {
+ try {
+ out.push(JSON.parse(await readFile(path.join(dir, f), 'utf8')));
+ } catch {
+ // skip unreadable / non-snapshot json
+ }
+ }
+ return out;
+}
+
+function renderCorpus(report: CorpusReport, top: number): string {
+ const wasteFrac = report.tokensTotal ? report.wasteTokensTotal / report.tokensTotal : 0;
+ const L: string[] = [
+ '',
+ bold('Tool-result feedback quality ') +
+ dim(
+ `(${report.ops} ops Β· ${report.resultCount} results Β· ${fmtTokens(report.tokensTotal)} tokens)`,
+ ),
+ dim(' est. wasted β‰ˆ ') +
+ heat(wasteFrac, bold(`${fmtTokens(report.wasteTokensTotal)} (${pct(wasteFrac)})`)) +
+ dim(' of all tool-result tokens'),
+ '',
+ // histogram
+ bold(' token-size distribution') + dim(' bar = % of results Β· right = % of tokens'),
+ ];
+ const maxCount = Math.max(...report.buckets.map((b) => b.count), 1);
+ for (const b of report.buckets) {
+ const cFrac = report.resultCount ? b.count / report.resultCount : 0;
+ const tFrac = report.tokensTotal ? b.tokens / report.tokensTotal : 0;
+ L.push(
+ ' ' +
+ pad(b.label, 7) +
+ bar(b.count / maxCount, 20) +
+ ' ' +
+ pad(dim(pct(cFrac)), 5) +
+ heat(tFrac, ` ${pct(tFrac)} tok`),
+ );
+ }
+
+ // leaderboard
+ L.push('');
+ L.push(bold(' dirty leaderboard') + dim(' (ranked by token-weighted waste)'));
+ L.push(
+ dim(
+ ' ' +
+ pad('tool', 38) +
+ pad('calls', 6) +
+ pad('p99', 7) +
+ pad('redund', 7) +
+ pad('noise', 6) +
+ pad('err%', 6) +
+ 'waste',
+ ),
+ );
+ for (const t of report.leaderboard.slice(0, top)) {
+ L.push(
+ ' ' +
+ pad(t.tool.length > 36 ? t.tool.slice(0, 35) + '…' : t.tool, 38) +
+ pad(String(t.calls), 6) +
+ pad(fmtTokens(t.tokensP99), 7) +
+ pad(heat(t.redundAvg, pct(t.redundAvg)), 7) +
+ pad(heat(t.noiseAvg, pct(t.noiseAvg)), 6) +
+ pad(heat(t.errRate, pct(t.errRate)), 6) +
+ heat(
+ t.tokensTotal ? t.wasteTokens / t.tokensTotal : 0,
+ bold(`β‰ˆ${fmtTokens(t.wasteTokens)}`),
+ ),
+ );
+ }
+ L.push('');
+ L.push(dim(' drill into one op: agent-tracing tq <opId>'));
+ L.push('');
+ return L.join('\n');
+}
+
+function renderOp(snapshot: ExecutionSnapshot): string {
+ const results = collectToolResults(snapshot).sort((a, b) => a.stepIndex - b.stepIndex);
+ const roll = rollupOperation(snapshot);
+ const L: string[] = [
+ '',
+ bold(`Op ${snapshot.operationId}`) + dim(` ${results.length} tool results`),
+ dim(' total ') +
+ cyan(fmtTokens(roll.tokensTotal)) +
+ dim(' tok Β· p99 ') +
+ fmtTokens(roll.tokensP99) +
+ dim(' Β· max ') +
+ fmtTokens(roll.tokensMax) +
+ dim(' Β· errors ') +
+ (roll.errorResultCount
+ ? red(`${roll.errorResultCount} (${fmtTokens(roll.errorResultTokens)} tok)`)
+ : green('0')),
+ '',
+ dim(
+ ' ' +
+ pad('step', 5) +
+ pad('tool', 40) +
+ pad('fmt', 6) +
+ pad('tokens', 8) +
+ pad('redund', 7) +
+ pad('noise', 6) +
+ 'err',
+ ),
+ ];
+ for (const r of results) {
+ L.push(
+ ' ' +
+ pad(String(r.stepIndex), 5) +
+ pad(r.tool.length > 38 ? r.tool.slice(0, 37) + '…' : r.tool, 40) +
+ pad(r.format, 6) +
+ pad(heat(Math.min(1, r.tokens / 8192), fmtTokens(r.tokens)), 8) +
+ pad(heat(r.selfRedundancy, pct(r.selfRedundancy)), 7) +
+ pad(heat(r.structuralNoiseRatio, pct(r.structuralNoiseRatio)), 6) +
+ (r.isError ? red('βœ—') : green('Β·')),
+ );
+ }
+ L.push('');
+ return L.join('\n');
+}
+
+export function registerToolQualityCommand(program: Command) {
+ program
+ .command('tool-quality')
+ .alias('tq')
+ .description('Analyze tool-result feedback quality (size distribution + dirty leaderboard)')
+ .argument('[opId]', 'Operation id β€” drill into one op instead of corpus stats')
+ .option('-d, --dir <path>', 'Snapshot directory to scan', '.agent-tracing/_remote')
+ .option('-l, --limit <n>', 'Max snapshots to scan')
+ .option('-t, --top <n>', 'Leaderboard rows to show', '15')
+ .option('-j, --json', 'Output JSON')
+ .action(
+ async (
+ opId: string | undefined,
+ opts: { dir: string; json?: boolean; limit?: string; top: string },
+ ) => {
+ const dir = path.resolve(process.cwd(), opts.dir);
+
+ if (opId) {
+ const file = path.join(dir, opId.endsWith('.json') ? opId : `${opId}.json`);
+ let snapshot: ExecutionSnapshot;
+ try {
+ snapshot = JSON.parse(await readFile(file, 'utf8'));
+ } catch {
+ console.error(red(`Snapshot not found: ${file}`));
+ process.exit(1);
+ }
+ if (opts.json) {
+ console.log(JSON.stringify(rollupOperation(snapshot), null, 2));
+ } else {
+ console.log(renderOp(snapshot));
+ }
+ return;
+ }
+
+ const limit = opts.limit ? Number.parseInt(opts.limit, 10) : undefined;
+ const snapshots = await loadSnapshots(dir, limit);
+ const perResult: ToolResultMetrics[] = snapshots.flatMap((s) => collectToolResults(s));
+ const report = buildCorpusReport(perResult, snapshots.length);
+
+ if (opts.json) {
+ console.log(JSON.stringify(report, null, 2));
+ } else {
+ console.log(renderCorpus(report, Number.parseInt(opts.top, 10) || 15));
+ }
+ },
+ );
+}