import { SpanStatusCode, trace, type Attributes, type Span, } from '@opentelemetry/api'; import { getServiceName } from '../config.js'; function compactAttributes(attributes?: Attributes): Attributes { if (!attributes) { return {}; } return Object.fromEntries( Object.entries(attributes).filter(([, value]) => value !== undefined), ); } export async function withSpan( name: string, attributes: Attributes | undefined, fn: (span: Span) => Promise | T, ): Promise { const tracer = trace.getTracer(getServiceName()); return tracer.startActiveSpan(name, async (span) => { span.setAttributes(compactAttributes(attributes)); try { const result = await fn(span); span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error), }); span.recordException(error instanceof Error ? error : new Error(String(error))); throw error; } finally { span.end(); } }); } export function withSkillSpan( skillName: string, attributes: Attributes | undefined, fn: (span: Span) => Promise | T, ): Promise { return withSpan(`skill.${skillName}.handle`, attributes, fn); } export function withClassifierSpan( attributes: Attributes | undefined, fn: (span: Span) => Promise | T, ): Promise { return withSpan('classifier.run', attributes, fn); } export function withToolSpan( toolName: string, attributes: Attributes | undefined, fn: (span: Span) => Promise | T, ): Promise { return withSpan(`tool.${toolName}`, attributes, fn); } export function withLlmSpan( attributes: Attributes | undefined, fn: (span: Span) => Promise | T, ): Promise { return withSpan('llm.chat_completion', attributes, fn); }