import { createRequire } from "node:module";
var __defProp = Object.defineProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: (newValue) => all[name] = () => newValue
    });
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = /* @__PURE__ */ createRequire(import.meta.url);

// src/telemetry/adapter.ts
function parseAgentId(agentId) {
  const match = agentId.match(/^(.+)\.v(\d+)$/);
  if (match) {
    return { name: match[1], version: match[2] };
  }
  return { name: agentId, version: "1.0.0" };
}
function getRecord(value) {
  return value && typeof value === "object" ? value : undefined;
}
function getStepResponse(step) {
  const response = getRecord(step.response);
  if (!response)
    return;
  return {
    id: response["id"],
    modelId: response["modelId"],
    timestamp: response["timestamp"],
    headers: response["headers"],
    body: response["body"],
    messages: response["messages"]
  };
}
function getRequestBodyValue(request, key) {
  const body = request?.["body"];
  if (!body)
    return;
  if (typeof body === "string") {
    try {
      const parsed = JSON.parse(body);
      return typeof parsed[key] === "string" ? parsed[key] : undefined;
    } catch {
      return;
    }
  }
  const record = getRecord(body);
  return typeof record?.[key] === "string" ? record[key] : undefined;
}
async function trackAgentStep(collector, agentId, step, durationMs, context) {
  const { name, version } = parseAgentId(agentId);
  const response = getStepResponse(step);
  const providerMetadata = step.providerMetadata;
  const warnings = step.warnings;
  const rawFinishReason = step.rawFinishReason;
  const request = getRecord(step.request);
  const traceId = context?.traceId ?? getRequestBodyValue(request, "$ai_trace_id");
  const sessionId = context?.sessionId ?? getRequestBodyValue(request, "$ai_session_id");
  const parentSpanId = response?.id;
  for (const toolCall of step.toolCalls ?? []) {
    const toolResult = step.toolResults?.find((r) => r.toolCallId === toolCall.toolCallId);
    const toolError = getRecord(toolResult?.output)?.["error"];
    const toolSample = {
      operation: { name: `${name}.${toolCall.toolName}`, version },
      durationMs: durationMs ?? 0,
      success: step.toolResults?.some((r) => r.toolCallId === toolCall.toolCallId && r.output !== undefined) ?? false,
      timestamp: new Date,
      metadata: {
        telemetryEvent: "span",
        traceId,
        sessionId,
        spanId: toolCall.toolCallId,
        parentSpanId,
        spanName: `tool.${toolCall.toolName}`,
        agentId,
        actorId: context?.actorId,
        tenantId: context?.tenantId,
        stepIndex: context?.stepIndex,
        toolName: toolCall.toolName,
        toolCallArgs: toolCall.input,
        toolResultOutput: toolResult?.output,
        errorMessage: typeof toolError === "string" ? toolError : typeof toolResult?.output === "string" ? toolResult.output : undefined,
        finishReason: step.finishReason,
        rawFinishReason
      }
    };
    await collector.collect(toolSample);
  }
  const stepSample = {
    operation: { name, version },
    durationMs: durationMs ?? 0,
    success: step.finishReason !== "error",
    timestamp: new Date,
    metadata: {
      telemetryEvent: "generation",
      traceId,
      sessionId,
      spanId: response?.id,
      spanName: `agent.${name}.step`,
      agentId,
      actorId: context?.actorId,
      tenantId: context?.tenantId,
      stepIndex: context?.stepIndex,
      stepStartedAt: context?.stepStartedAt,
      finishReason: step.finishReason,
      rawFinishReason,
      tokenUsage: step.usage,
      totalUsage: step.totalUsage,
      providerMetadata,
      warnings,
      stepText: step.text,
      stepReasoningText: step.reasoningText,
      responseId: response?.id,
      responseModelId: response?.modelId,
      responseTimestamp: response?.timestamp,
      responseHeaders: response?.headers,
      responseBody: response?.body,
      responseMessages: response?.messages,
      requestBody: request?.["body"],
      requestHeaders: request?.["headers"],
      toolCallCount: step.toolCalls?.length ?? 0,
      toolCalls: step.toolCalls,
      toolResults: step.toolResults,
      errorMessage: step.finishReason === "error" ? step.text : undefined
    }
  };
  await collector.collect(stepSample);
}

class InMemoryTelemetryCollector {
  samples = [];
  async collect(sample) {
    this.samples.push(sample);
  }
  getSamples() {
    return [...this.samples];
  }
  getSamplesForOperation(operationName) {
    return this.samples.filter((s) => s.operation.name === operationName);
  }
  clear() {
    this.samples.length = 0;
  }
}
function createInMemoryTelemetryCollector() {
  return new InMemoryTelemetryCollector;
}
var noopTelemetryCollector;
var init_adapter = __esm(() => {
  noopTelemetryCollector = {
    collect: async () => {}
  };
});
init_adapter();

export {
  trackAgentStep,
  noopTelemetryCollector,
  createInMemoryTelemetryCollector,
  InMemoryTelemetryCollector
};
