import type { Request, Response } from "express"; import { RunTree } from "langsmith"; import { createHash } from "crypto"; export const LANGSMITH_PROJECT = process.env.LANGSMITH_PROJECT?.trim() || "legal-mike-oss"; const LANGSMITH_ENABLED = !!process.env.LANGSMITH_API_KEY?.trim(); const SENSITIVE_KEY_RE = /(?:^|[_-])(authorization|auth|cookie|set-cookie|api[_-]?key|secret|token|password|session|refresh[_-]?token|access[_-]?token|client[_-]?secret|private[_-]?key)(?:$|[_-])/i; const BINARY_KEY_RE = /(?:bytes|blob|buffer|file|document_bytes_b64|content_b64|data_url)$/i; const SURFACE_CHUNK_SIZE = 18000; export function sha256(text: string): string { return createHash("sha256").update(text).digest("hex"); } export function chunkSurfaceForTrace(text: string): { index: number; start: number; end: number; text: string }[] { const chunks: { index: number; start: number; end: number; text: string }[] = []; let start = 0; let index = 0; while (start < text.length) { const end = Math.min(start + SURFACE_CHUNK_SIZE, text.length); chunks.push({ index, start, end, text: text.slice(start, end) }); start = end; index++; } return chunks; } export function buildDocumentSurfaceTracePayload(params: { docLabel: string; documentId?: string; filename?: string; surfaceId?: string; text: string; }): Record { const { docLabel, documentId, filename, surfaceId, text } = params; const blockCount = (text.match(/\[\[(?:P_\d+|BMK_[PT]_[a-z0-9]+)/g) || []).length; const chunks = chunkSurfaceForTrace(text); return { doc_id: docLabel, document_id: documentId ?? null, filename: filename ?? null, surface_id: surfaceId ?? null, block_count: blockCount, char_count: text.length, surface_sha256: sha256(text), chunks_count: chunks.length, surface_chunks: chunks.map((c) => ({ index: c.index, start: c.start, end: c.end, text: c.text, })), }; } export type TraceRun = RunTree; type TraceContext = { run: RunTree; startedAt: number; streamed: boolean; responseBytes: number; responseChunks: number; responseBody?: unknown; finished: boolean; originalJson: Response["json"]; originalSend: Response["send"]; originalWrite: Response["write"]; originalEnd: Response["end"]; isHighSignal: boolean; }; function toSafeString(value: string): string { if (value.length <= 20000) return value; return `${value.slice(0, 20000)}…[truncated]`; } export function sanitizeTraceValue( value: unknown, key?: string, depth = 0, ): unknown { if (depth > 8) return "[max-depth]"; if (value == null) return value; if (value instanceof Date) return value.toISOString(); if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) { return `[binary ${value.length} bytes redacted]`; } if (ArrayBuffer.isView(value)) { return `[binary ${value.byteLength} bytes redacted]`; } if (value instanceof ArrayBuffer) { return `[binary ${value.byteLength} bytes redacted]`; } if (typeof value === "string") { if (key && BINARY_KEY_RE.test(key)) return "[binary redacted]"; if (key && SENSITIVE_KEY_RE.test(key)) return "[redacted]"; return toSafeString(value); } if ( typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" ) { return value; } if (Array.isArray(value)) { return value.slice(0, 200).map((item) => sanitizeTraceValue(item, key, depth + 1), ); } if (typeof value === "object") { const obj = value as Record; const out: Record = {}; for (const [k, v] of Object.entries(obj)) { if (SENSITIVE_KEY_RE.test(k)) { out[k] = "[redacted]"; continue; } if (BINARY_KEY_RE.test(k)) { out[k] = "[binary redacted]"; continue; } out[k] = sanitizeTraceValue(v, k, depth + 1); } return out; } return String(value); } function safeHeaderValue(value: string | string[] | undefined): string | undefined { if (!value) return undefined; const raw = Array.isArray(value) ? value.join(",") : value; return raw ? toSafeString(raw) : undefined; } function pickSafeHeaders(headers: Request["headers"]): Record { const safeKeys = [ "content-type", "accept", "user-agent", "x-request-id", "x-vercel-id", "x-forwarded-for", "origin", "referer", ]; const out: Record = {}; for (const key of safeKeys) { const value = headers[key]; const safe = safeHeaderValue(value); if (safe) out[key] = safe; } return out; } function classifySurface(path: string): string[] { const tags = ["request"]; if (path.startsWith("/tabular-review")) { tags.push("tabular"); } else if (path.startsWith("/playbook-review") || path.startsWith("/playbooks") || path.startsWith("/workflows")) { tags.push("workflow"); } else if (path.startsWith("/chat") || /\/projects\/[^/]+\/chat/.test(path)) { tags.push("chat"); } else if (path.startsWith("/single-documents") || path.startsWith("/download")) { tags.push("documents"); } else if (path.startsWith("/projects")) { tags.push("project"); } return [...new Set(tags)]; } function requestPath(req: Request): string { return (req.originalUrl || `${req.baseUrl || ""}${req.path}` || req.path) .split("?")[0] .trim(); } function requestInputs(req: Request, res: Response): Record { const body = req.body || {}; // Focus inputs on the actual content (messages, text, etc.) if (body.messages) return { messages: sanitizeTraceValue(body.messages) }; if (body.message) return { message: sanitizeTraceValue(body.message) }; if (body.document_name) return { document: body.document_name, ...(sanitizeTraceValue(body) as Record), }; return sanitizeTraceValue(body) as Record; } function getContext(res: Response): TraceContext | undefined { return (res.locals as Record).langsmithTrace as | TraceContext | undefined; } function getContextOrNull(res: Response): TraceContext | null { return getContext(res) ?? null; } async function finalizeContext( res: Response, ctx: TraceContext, reason: "finish" | "close", ): Promise { if (ctx.finished) return; ctx.finished = true; const durationMs = Date.now() - ctx.startedAt; const statusCode = res.statusCode; const isError = statusCode >= 400 || reason === "close"; if (!ctx.isHighSignal && !isError) { // Drop low-signal traces completely if they succeed return; } if (!ctx.isHighSignal && isError) { // Late post for low-signal traces that errored out try { await ctx.run.postRun(); } catch (err) { console.warn("[langsmith] failed to post deferred error trace", err); } } const outputs: Record = { statusCode, durationMs, streamed: ctx.streamed, responseBytes: ctx.responseBytes, responseChunks: ctx.responseChunks, reason, }; if (!ctx.streamed && ctx.responseBody !== undefined) { outputs.response = sanitizeTraceValue(ctx.responseBody); } const error = statusCode >= 500 ? `HTTP ${statusCode}` : reason === "close" && !res.writableEnded ? "Request closed before completion" : undefined; try { await ctx.run.end(outputs, error); await ctx.run.patchRun(); } catch (err) { console.warn("[langsmith] failed to finalize trace", err); } } export function getRequestTrace(res: Response): TraceRun | null { return getContextOrNull(res)?.run ?? null; } export function createTraceChild( parent: TraceRun | null | undefined, config: { name: string; run_type?: string; inputs?: Record; tags?: string[]; metadata?: Record; }, ): TraceRun | null { if (!LANGSMITH_ENABLED || !parent) return null; try { const tags = [ ...new Set([...(parent.tags ?? []), ...(config.tags ?? [])]), ]; const metadata = { ...(parent.metadata ?? {}), ...(config.metadata ?? {}), }; const child = parent.createChild({ name: config.name, run_type: config.run_type ?? "chain", inputs: sanitizeTraceValue(config.inputs ?? {}) as Record< string, unknown >, tags, metadata, project_name: parent.project_name || LANGSMITH_PROJECT, }); void child.postRun().catch((err) => { console.warn("[langsmith] failed to post child trace", err); }); return child; } catch (err) { console.warn("[langsmith] failed to create child trace", err); return null; } } export async function endTrace( run: TraceRun | null | undefined, opts?: { outputs?: Record; error?: string | null; metadata?: Record; }, ): Promise { if (!run) return; try { await run.end( sanitizeTraceValue(opts?.outputs ?? {}) as Record, opts?.error ?? undefined, Date.now(), opts?.metadata ? sanitizeTraceValue(opts.metadata) as Record : undefined, ); await run.patchRun(); } catch (err) { console.warn("[langsmith] failed to end trace", err); } } export function traceHeaders( run: TraceRun | null | undefined, ): Record { if (!run) return {}; try { return run.toHeaders(); } catch (err) { console.warn("[langsmith] failed to build trace headers", err); return {}; } } export function startRequestTrace( req: Request, res: Response, ): TraceRun | null { if (!LANGSMITH_ENABLED) return null; const existing = getContextOrNull(res); if (existing?.run) return existing.run; try { const path = requestPath(req); // Filter out low-signal CRUD operations to keep LangSmith clean. // We only want to actively trace actual AI generations. // However, we DO want to trace low-signal endpoints if they error! // We handle this by deferring the postRun() call. const isHighSignal = (req.method === "POST" && path === "/chat") || (req.method === "POST" && /^\/projects\/[^/]+\/chat$/.test(path)) || (req.method === "POST" && path.startsWith("/tabular-review")) || (req.method === "POST" && path.startsWith("/playbook-review")); const tags = classifySurface(path); const locals = res.locals as Record; const trace = new RunTree({ name: `${req.method} ${path}`, run_type: "chain", project_name: LANGSMITH_PROJECT, inputs: requestInputs(req, res), tags, metadata: { path, method: req.method, query: sanitizeTraceValue(req.query), params: sanitizeTraceValue(req.params), headers: pickSafeHeaders(req.headers), user_id: typeof locals.userId === "string" ? locals.userId : undefined, user_email: typeof locals.userEmail === "string" ? locals.userEmail : undefined, surface: tags.filter((tag) => tag !== "request"), }, }); const ctx: TraceContext = { run: trace, isHighSignal, startedAt: Date.now(), streamed: false, responseBytes: 0, responseChunks: 0, finished: false, originalJson: res.json.bind(res), originalSend: res.send.bind(res), originalWrite: res.write.bind(res), originalEnd: res.end.bind(res), }; locals.langsmithTrace = ctx; res.json = ((body: unknown) => { ctx.responseBody = body; return ctx.originalJson(body as never); }) as Response["json"]; res.send = ((body: unknown) => { if (body instanceof Buffer) { ctx.responseBody = `[binary ${body.length} bytes redacted]`; } else if (typeof body === "string") { ctx.responseBody = toSafeString(body); } else if (body !== undefined) { ctx.responseBody = body; } return ctx.originalSend(body as never); }) as Response["send"]; res.write = ((chunk: unknown, encoding?: BufferEncoding, cb?: (error?: Error | null) => void) => { const contentType = String(res.getHeader("content-type") ?? ""); const isEventStream = contentType.includes("text/event-stream"); if (isEventStream) { ctx.streamed = true; if (typeof chunk === "string") { ctx.responseBytes += Buffer.byteLength(chunk); } else if (chunk instanceof Buffer) { ctx.responseBytes += chunk.length; } else if (chunk instanceof Uint8Array) { ctx.responseBytes += chunk.byteLength; } ctx.responseChunks += 1; } if (typeof encoding === "string") { return cb ? ctx.originalWrite(chunk as never, encoding, cb) : ctx.originalWrite(chunk as never, encoding); } return cb ? ctx.originalWrite(chunk as never, cb) : ctx.originalWrite(chunk as never); }) as Response["write"]; res.end = ((chunk?: unknown, encoding?: BufferEncoding, cb?: () => void) => { const contentType = String(res.getHeader("content-type") ?? ""); if (contentType.includes("text/event-stream")) { ctx.streamed = true; if (typeof chunk === "string") { ctx.responseBytes += Buffer.byteLength(chunk); } else if (chunk instanceof Buffer) { ctx.responseBytes += chunk.length; } else if (chunk instanceof Uint8Array) { ctx.responseBytes += chunk.byteLength; } if (chunk !== undefined) ctx.responseChunks += 1; } if (typeof encoding === "string") { return cb ? ctx.originalEnd(chunk as never, encoding, cb) : ctx.originalEnd(chunk as never, encoding); } return cb ? ctx.originalEnd(chunk as never, cb) : ctx.originalEnd(chunk as never); }) as Response["end"]; if (isHighSignal) { void trace.postRun().catch((err) => { console.warn("[langsmith] failed to post root trace", err); }); } trace.addEvent({ name: "request_started", kwargs: { method: req.method, path, tags, }, }); const finalize = (reason: "finish" | "close") => { void finalizeContext(res, ctx, reason); }; res.once("finish", () => finalize("finish")); res.once("close", () => finalize("close")); return trace; } catch (err) { console.warn("[langsmith] failed to start request trace", err); return null; } }