import {
  buildLoopOtelSpans,
  createOtelExporter
} from "./chunk-UD4BHQMI.js";

// src/mcp/trace-propagation.ts
function readTraceContextFromEnv() {
  const traceId = process.env.TRACE_ID || generateTraceId();
  const parentSpanId = process.env.PARENT_SPAN_ID || void 0;
  return { traceId, parentSpanId };
}
function createPropagatingTraceEmitter(ctx) {
  const exporter = createOtelExporter();
  const buffers = /* @__PURE__ */ new Map();
  const emitter = {
    emit(event) {
      if (!exporter) return;
      const buf = buffers.get(event.runId);
      if (buf) buf.push(event);
      else buffers.set(event.runId, [event]);
      if (event.kind === "loop.ended") {
        const events = buffers.get(event.runId) ?? [event];
        buffers.delete(event.runId);
        for (const span of buildLoopOtelSpans(events, ctx.traceId, ctx.parentSpanId)) {
          exporter.exportSpan(span);
        }
      }
    }
  };
  return { emitter, exporter, context: ctx };
}
function traceContextToEnv(ctx) {
  const env = { TRACE_ID: ctx.traceId };
  if (ctx.parentSpanId) env.PARENT_SPAN_ID = ctx.parentSpanId;
  return env;
}
function generateTraceId() {
  const bytes = new Uint8Array(16);
  if (typeof globalThis.crypto?.getRandomValues === "function") {
    globalThis.crypto.getRandomValues(bytes);
  } else {
    for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
  }
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
}

export {
  readTraceContextFromEnv,
  createPropagatingTraceEmitter,
  traceContextToEnv
};
//# sourceMappingURL=chunk-4WXGK6GV.js.map