Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/trace.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Trace and provenance of a generation (contract: docs/next/CONTRACT.md §2.4).47 *48 * Trace: what the agent team did — the plan as last shown, each sub-agent with its role, status and duration, the49 * tool calls recorded by the tool runtime (table tool_calls) and the usage rows. Stored in vq_generation_trace50 * while the generation runs and when it ends.51 *52 * Provenance: where the figures of an answer can have come from, built ONLY from tool calls that really ran in53 * that generation. Nothing is inferred from the text of the answer and nothing is reconstructed afterwards.54 */55import type { Express, Request, Response } from "express";56import type Database from "better-sqlite3";57import { isSqlite, pool } from "../db";58import { currentUser } from "../access";59import { usageOfGeneration } from "./usage";6061// ─── Provenance ──────────────────────────────────────────────────────────────62export type ProvenanceProvider = "fmp" | "findata" | "eodhd" | "web" | "python" | "quant-engine" | "other";6364export interface ProvenanceSource {65 tool: string;66 provider: ProvenanceProvider;67 symbols: string[];68 /** epoch ms of the last call of this tool on these symbols */69 retrievedAt: number;70 ok: boolean;71 /** how many calls this line stands for */72 calls: number;73}7475export interface ToolRun {76 tool: string;77 input?: unknown;78 ok: boolean;79 at: number;80 /** the raw result when the call succeeded (only its `source` field is read) */81 result?: unknown;82}8384const PYTHON_TOOLS = new Set([85 "execute_custom_python_analysis", "run_monte_carlo_simulation", "calculate_options_price", "estimate_garch_volatility", "calculate_var",86 "optimize_portfolio", "analyze_risk_metrics", "create_plot", "create_volatility_surface",87]);88const EODHD_TOOLS = new Set(["search_eodhd", "get_option_chain", "get_option_prices", "get_option_greeks"]);89const WEB_TOOLS = new Set([90 "web_search_exa", "get_contents_exa", "search_images", "get_map_directions", "search_google_shopping", "search_finance", "search_jobs",91 "search_flights", "search_hotels", "search_videos", "search_google_trends", "search_google_scholar", "search_app_store",92]);93/** Orchestration and workspace tools: they produce no market data, so they never appear as a source. */94const NOT_A_SOURCE = /^(update_plan|delegate_research|audit_analysis|memory_|recall_conversations|portfolio_|schedule_watch|create_diagram|workspace_files|research_runs|research_memory|log_experiment|list_experiments|code_library|request_approval)/;9596/**97 * The data provider behind a tool. A result that names its own source wins (get_historical_price answers98 * `source: "FinData"` when FMP failed and the lake served the series). Returns null for tools that are not sources.99 */100export function toolProvider(tool: string, result?: unknown): ProvenanceProvider | null {101 if (NOT_A_SOURCE.test(tool)) return null;102 const declared = typeof (result as any)?.source === "string" ? String((result as any).source).toLowerCase() : "";103 if (declared.startsWith("findata")) return "findata";104 if (declared.startsWith("fmp")) return "fmp";105 if (declared.startsWith("eodhd")) return "eodhd";106 if (tool === "run_quant_engine") return "quant-engine";107 if (tool.startsWith("findata_")) return "findata";108 if (tool.startsWith("eodhd_") || tool.startsWith("get_eodhd_") || EODHD_TOOLS.has(tool)) return "eodhd";109 if (tool.startsWith("firecrawl_") || tool.startsWith("tavily_") || WEB_TOOLS.has(tool)) return "web";110 if (PYTHON_TOOLS.has(tool) || tool === "research_run" || tool === "inspect_dataset") return "python";111 // Everything else in the data toolset is an FMP endpoint (server/services/fmpService.ts).112 if (/^(get_|search_)/.test(tool) || tool === "extract_sec_filings" || tool === "download_fmp_data") return "fmp";113 return "other";114}115116const SYMBOL_RE = /^[A-Z0-9^][A-Z0-9.\-=^]{0,14}$/;117const SYMBOL_KEYS = ["symbol", "symbols", "ticker", "tickers", "pair", "benchmark_symbol", "benchmark"];118119/** Ticker symbols named in a tool input (top level, and inside `params` for run_quant_engine). Never guessed from free text. */120export function extractSymbols(input: unknown): string[] {121 const out = new Set<string>();122 const take = (v: unknown) => {123 // A string is one ticker or a comma-separated list of tickers; a phrase is not split into pretend tickers.124 const list = Array.isArray(v) ? v : typeof v === "string" ? v.split(/\s*[,;]\s*/) : [];125 for (const x of list) {126 const s = String(x ?? "").trim().toUpperCase();127 if (s && SYMBOL_RE.test(s)) out.add(s);128 }129 };130 const scan = (o: unknown) => {131 if (!o || typeof o !== "object" || Array.isArray(o)) return;132 for (const k of SYMBOL_KEYS) take((o as Record<string, unknown>)[k]);133 };134 scan(input);135 scan((input as any)?.params);136 return [...out].sort().slice(0, 40);137}138139/** One line per (tool, provider, symbols): the last time it ran, whether any call succeeded, how many calls. Pure. */140export function buildProvenance(runs: ToolRun[]): ProvenanceSource[] {141 const lines = new Map<string, ProvenanceSource>();142 for (const r of runs) {143 const provider = toolProvider(r.tool, r.ok ? r.result : undefined);144 if (!provider) continue;145 const symbols = extractSymbols(r.input);146 const key = `${r.tool}|${provider}|${symbols.join(",")}`;147 const line = lines.get(key);148 if (!line) lines.set(key, { tool: r.tool, provider, symbols, retrievedAt: r.at, ok: r.ok, calls: 1 });149 else {150 line.calls++;151 line.ok = line.ok || r.ok;152 line.retrievedAt = Math.max(line.retrievedAt, r.at);153 }154 }155 return [...lines.values()].sort((a, b) => a.retrievedAt - b.retrievedAt).slice(0, 300);156}157158// ─── Trace ───────────────────────────────────────────────────────────────────159type Db = Database.Database;160const sqlite = (db?: Db): Db | null => db ?? (isSqlite ? (pool as Db) : null);161162export interface TraceAgent {163 id: string;164 name: string;165 kind: string;166 role: string | null;167 status: "running" | "done" | "failed";168 startedAt: number;169 durationMs: number | null;170 tools: number;171}172173export interface TraceData {174 startedAt: number;175 finishedAt: number | null;176 mode: string | null;177 model: string | null;178 requestedModel: string | null;179 plan: Array<{ title: string; status: string }>;180 agents: TraceAgent[];181 budget: Array<{ kind: string; limit: number; spent: number; at: number }>;182 /** the limits the generation started with and where they came from */183 budgetApplied?: { maxCostUsd: number | null; maxMinutes: number | null; source: string } | null;184}185186/** Follows one generation through the events it emits and keeps vq_generation_trace current. */187export class GenerationTrace {188 readonly runs: ToolRun[] = [];189 private data: TraceData;190 private status = "running";191192 constructor(private scope: { owner: string; sessionId: string; generationId: string; mode?: string; model?: string; requestedModel?: string }, private db?: Db) {193 this.data = { startedAt: Date.now(), finishedAt: null, mode: scope.mode ?? null, model: scope.model ?? null, requestedModel: scope.requestedModel ?? null, plan: [], agents: [], budget: [] };194 this.save();195 }196197 /** Feeds an event of the generation stream; only plan, agent and budget events change the trace. */198 observe(event: Record<string, unknown>): void {199 const type = event.type;200 if (type === "plan" && Array.isArray(event.steps)) {201 this.data.plan = (event.steps as any[]).map((s) => ({ title: String(s?.title ?? ""), status: String(s?.status ?? "pending") }));202 } else if (type === "agent_start") {203 this.data.agents.push({ id: String(event.agentId), name: String(event.name ?? ""), kind: String(event.kind ?? "analyst"), role: typeof event.role === "string" ? event.role : null, status: "running", startedAt: Date.now(), durationMs: null, tools: 0 });204 } else if (type === "agent_done") {205 const a = this.data.agents.find((x) => x.id === event.agentId);206 if (!a) return;207 a.status = event.ok === false ? "failed" : "done";208 a.durationMs = typeof event.durationMs === "number" ? event.durationMs : Date.now() - a.startedAt;209 a.tools = typeof event.tools === "number" ? event.tools : a.tools;210 } else if (type === "budget_applied") {211 this.data.budgetApplied = { maxCostUsd: (event.maxCostUsd as number | null) ?? null, maxMinutes: (event.maxMinutes as number | null) ?? null, source: String(event.source) };212 } else if (type === "budget") {213 this.data.budget.push({ kind: String(event.kind), limit: Number(event.limit), spent: Number(event.spent), at: Date.now() });214 } else return;215 this.save();216 }217218 /** Records a data-tool run for the provenance of this generation. */219 noteTool(run: ToolRun): void {220 this.runs.push(run);221 }222223 provenance(): ProvenanceSource[] {224 return buildProvenance(this.runs);225 }226227 finish(status: "done" | "error" | "cancelled"): void {228 if (this.status !== "running") return;229 this.status = status;230 this.data.finishedAt = Date.now();231 // An agent still marked running when the generation ends did not finish.232 for (const a of this.data.agents) if (a.status === "running") a.status = "failed";233 this.save();234 }235236 snapshot(): TraceData & { status: string } {237 return { ...this.data, status: this.status };238 }239240 private save(): void {241 try {242 sqlite(this.db)243 ?.prepare(244 "INSERT INTO vq_generation_trace (generation_id, owner, session_id, at, status, data) VALUES (?, ?, ?, ?, ?, ?) " +245 "ON CONFLICT(generation_id) DO UPDATE SET status = excluded.status, data = excluded.data",246 )247 .run(this.scope.generationId, this.scope.owner, this.scope.sessionId, this.data.startedAt, this.status, JSON.stringify(this.data));248 } catch (e) {249 console.error("[trace] could not save the trace:", (e as Error).message);250 }251 }252}253254interface TraceRow {255 generation_id: string;256 session_id: string | null;257 at: number;258 status: string | null;259 data: string;260}261262/** The stored trace of a generation, by its id or (latest of) its conversation; null when there is none for this person. */263export function readTrace(owner: string, by: { generationId?: string; sessionId?: string }, db?: Db) {264 const s = sqlite(db);265 if (!s) return null;266 const row = (by.sessionId267 ? s.prepare("SELECT * FROM vq_generation_trace WHERE owner = ? AND session_id = ? ORDER BY at DESC LIMIT 1").get(owner, by.sessionId)268 : s.prepare("SELECT * FROM vq_generation_trace WHERE owner = ? AND generation_id = ?").get(owner, by.generationId ?? "")) as TraceRow | undefined;269 if (!row) return null;270 let data: Partial<TraceData> = {};271 try {272 data = JSON.parse(row.data);273 } catch {274 /* an unreadable trace still returns its tool calls and usage */275 }276 const toolCalls = (s.prepare("SELECT at, agent, tool, ok, ms, error FROM tool_calls WHERE generation_id = ? AND owner = ? ORDER BY at, id LIMIT 2000").all(row.generation_id, owner) as Array<{ at: number; agent: string; tool: string; ok: number; ms: number; error: string | null }>).map((t) => ({ at: t.at, agent: t.agent, tool: t.tool, ok: t.ok === 1, ms: t.ms, error: t.error }));277 return {278 generationId: row.generation_id,279 sessionId: row.session_id,280 status: row.status,281 startedAt: data.startedAt ?? row.at,282 finishedAt: data.finishedAt ?? null,283 mode: data.mode ?? null,284 model: data.model ?? null,285 requestedModel: data.requestedModel ?? null,286 plan: data.plan ?? [],287 agents: data.agents ?? [],288 budget: data.budget ?? [],289 budgetApplied: data.budgetApplied ?? null,290 toolCalls,291 usage: usageOfGeneration(owner, row.generation_id, s),292 };293}294295/** After a restart: an analysis still marked running was cut by it (generations live in memory). */296export function interruptStaleTraces(db?: Db): number {297 try {298 return sqlite(db)?.prepare("UPDATE vq_generation_trace SET status = 'interrupted' WHERE status = 'running'").run().changes ?? 0;299 } catch {300 return 0;301 }302}303304/** The generations of a conversation as last traced (oldest first): what a reopened study shows of each analysis. */305export function listTraces(owner: string, sessionId: string, db?: Db): Array<{ generationId: string; sessionId: string; status: string | null; startedAt: number; finishedAt: number | null; mode: string | null; model: string | null; plan: Array<{ title: string; status: string }>; budgetApplied: TraceData["budgetApplied"] | null; budget: TraceData["budget"] }> {306 const s = sqlite(db);307 if (!s) return [];308 return (s.prepare("SELECT * FROM vq_generation_trace WHERE owner = ? AND session_id = ? ORDER BY at LIMIT 200").all(owner, sessionId) as TraceRow[]).map((row) => {309 let data: Partial<TraceData> = {};310 try {311 data = JSON.parse(row.data);312 } catch {313 /* listed with what the row itself says */314 }315 return { generationId: row.generation_id, sessionId, status: row.status, startedAt: data.startedAt ?? row.at, finishedAt: data.finishedAt ?? null, mode: data.mode ?? null, model: data.model ?? null, plan: data.plan ?? [], budgetApplied: data.budgetApplied ?? null, budget: data.budget ?? [] };316 });317}318319export function registerTraceRoutes(app: Express): void {320 // `?sessionId=` asks for the latest generation of a conversation (the path id is then ignored: use "latest").321 app.get("/api/v2/generations/:id/trace", (req: Request, res: Response) => {322 const sessionId = typeof req.query.sessionId === "string" && req.query.sessionId ? req.query.sessionId : undefined;323 const trace = readTrace(currentUser(req).id, sessionId ? { sessionId } : { generationId: req.params.id });324 if (!trace) return res.status(404).json({ error: "No trace for this analysis." });325 res.set("Cache-Control", "private, no-store").json(trace);326 });327}328