Skip to content

The platform for continuously improving AI agents.

8.9 KB
Raw Blame
/**
 * @overmind-lab/trace-sdk
 *
 * Thin wrapper over the OpenTelemetry JS SDK. `init()` builds one tracer
 * provider, one meter provider, and one logger provider, registers them as
 * the process globals, and exports OTLP/HTTP protobuf. It requires Node:
 * reading configuration throws when `process` is missing.
 *
 * ```ts
 * import { init } from "@overmind-lab/trace-sdk";
 *
 * const { tracer, meter, logger, flush, shutdown } = init({
 *   serviceName: "support-copilot",
 * });
 *
 * tracer.startActiveSpan("answer", (span) => {
 *   span.setAttribute("overmind.capability.id", "support-copilot");
 *   span.end();
 * });
 *
 * await flush();
 * await shutdown();
 * ```
 *
 * A second `init()` returns the same handle. Call `shutdown()` before
 * starting again.
 *
 * Credentials, endpoint, and environment come from the process environment.
 * `init()` only sets the service identity and extra headers.
 *
 * | `init()` option       | Effect                                                                 |
 * | --------------------- | ---------------------------------------------------------------------- |
 * | `serviceName`         | Resource attribute `service.name`, when set                           |
 * | `serviceDescription`  | Resource attribute `service.description`, when set                    |
 * | `serviceVersion`      | Accepted. Not written onto the resource                               |
 * | `headers`             | Extra export headers, under the auth headers                          |
 *
 * | Environment                              | Default                     |
 * | ---------------------------------------- | --------------------------- |
 * | `OVERMIND_API_KEY`                       | empty, so no auth headers   |
 * | `OVERMIND_PROJECT_ID`                    | empty                       |
 * | `OVERMIND_ENVIRONMENT`                   | `production`                |
 * | `OTEL_EXPORTER_OTLP_ENDPOINT`            | `https://api.overmindlab.ai`|
 * | `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`     | `/api/v1/traces`            |
 * | `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`    | `/api/v1/metrics`           |
 * | `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`       | `/api/v1/logs`              |
 *
 * The export URL is the endpoint plus the signal path. A trailing slash on
 * the endpoint is removed, so the defaults export to
 * `https://api.overmindlab.ai/api/v1/traces` and the matching metrics and
 * logs paths. A local collector is
 * `OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318` with paths
 * `/v1/traces`, `/v1/metrics`, and `/v1/logs`.
 *
 * A non-empty `OVERMIND_API_KEY` (an `om_live_…` key or an `eyJ…` JWT) sends
 * `Authorization: Bearer <token>`, `x-api-key`, and `x-overmind-api-key`.
 * A non-empty `OVERMIND_PROJECT_ID` also sends `x-project-id` and
 * `x-overmind-project-id`.
 *
 * Resource attributes always include `overmind.sdk.name` and
 * `overmind.sdk.version`. `deployment.environment.name` and
 * `overmind.project.id` are set when those environment values are non-empty.
 *
 * The returned `tracer`, `meter`, and `logger` are the standard
 * OpenTelemetry objects. Spans, metrics, and logs started from the global
 * `trace`, `metrics`, and `logs` APIs use the same providers. `flush()`
 * sends the buffered batch. `shutdown()` flushes, then deregisters the
 * globals.
 */
import { context, metrics, trace, type Meter, type Tracer } from "@opentelemetry/api";
import { logs, type Logger } from "@opentelemetry/api-logs";
import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { BatchLogRecordProcessor, LoggerProvider } from "@opentelemetry/sdk-logs";
import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
import { BatchSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";

const SDK_NAME = "overmind-js";
const SDK_VERSION = "0.1.0";


export type Overmind = {
  flush: () => Promise<void>;
  logger: Logger;
  meter: Meter;
  shutdown: () => Promise<void>;
  tracer: Tracer;
};

type Providers = {
  loggerProvider: LoggerProvider;
  meterProvider: MeterProvider;
  tracerProvider: TracerProvider;
};

let current: Overmind | undefined;
let providers: Providers | undefined;


export type OvermindOptions = {
  serviceName?: string;
  serviceVersion?: string;
  serviceDescription?: string;
  headers?: Record<string, string>;
};

function signalPath(signal: "logs" | "metrics" | "traces"): string {
  switch (signal) {
    case "logs":
      return config.pathLogs;
    case "metrics":
      return config.pathMetrics;
    case "traces":
      return config.pathTraces;
  }
}


function getEnv<T>(name: string, defaultValue: T): T {
  if (typeof process === "undefined") throw new Error('process is not defined, this is likely running in a browser environment');
  return process.env[name] as T ?? defaultValue;
}

const config = {
  apiKey: getEnv("OVERMIND_API_KEY", ""),
  environment: getEnv("OVERMIND_ENVIRONMENT", "production"),
  projectId: getEnv("OVERMIND_PROJECT_ID", ""),

  // remove trailing slash from baseUrl if any
  baseUrl: getEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "https://api.overmindlab.ai").replace(/\/+$/, ""),
  pathTraces: getEnv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "/api/v1/traces"),
  pathMetrics: getEnv("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", "/api/v1/metrics"),
  pathLogs: getEnv("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "/api/v1/logs"),
}


function headersFor(options: OvermindOptions): Record<string, string> {
  const headers: Record<string, string> = { ...options.headers };

  if (!config.apiKey && !options.headers?.Authorization) {
    throw new Error('OVERMIND_API_KEY is not set and no Authorization header is provided');
  }

  if (config.apiKey) {
    headers.Authorization = `Bearer ${config.apiKey}`;
    headers["x-api-key"] = config.apiKey;
    headers["x-overmind-api-key"] = config.apiKey;
  }
  if (config.projectId) {
    headers["x-project-id"] = config.projectId;
    headers["x-overmind-project-id"] = config.projectId;
  }
  return headers;
}

function attributesFor(options: OvermindOptions): Record<string, string> {
  const attributes: Record<string, string> = {
    "overmind.sdk.name": SDK_NAME,
    "overmind.sdk.version": SDK_VERSION,
  }
  if (options.serviceName) {
    attributes["service.name"] = options.serviceName;
  }
  if (options.serviceDescription) {
    attributes["service.description"] = options.serviceDescription;
  }

  if (config.environment) {
    attributes["deployment.environment.name"] = config.environment;
  }
  if (config.projectId) {
    attributes["overmind.project.id"] = config.projectId;
  }
  return attributes;
}

export function init(options: OvermindOptions = {}): Overmind {
  if (current) return current;

  const headers = headersFor(options);
  const attributes = attributesFor(options);
  const resource = resourceFromAttributes(attributes);

  const exporterConfig = (signal: "logs" | "metrics" | "traces") => ({
    headers,
    url: `${config.baseUrl}${signalPath(signal)}`,
  });

  const tracerProvider = new TracerProvider({
    resource,
    spanProcessors: [new BatchSpanProcessor({ exporter: new OTLPTraceExporter(exporterConfig("traces")) })],
  });

  const meterProvider = new MeterProvider({
    readers: [
      new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter(exporterConfig("metrics")) }),
    ],
    resource,
  });

  const loggerProvider = new LoggerProvider({
    processors: [new BatchLogRecordProcessor({ exporter: new OTLPLogExporter(exporterConfig("logs")) })],
    resource,
  });

  const manager = new AsyncLocalStorageContextManager();
  manager.enable();
  context.setGlobalContextManager(manager);
  trace.setGlobalTracerProvider(tracerProvider);
  metrics.setGlobalMeterProvider(meterProvider);
  logs.setGlobalLoggerProvider(loggerProvider);

  providers = { loggerProvider, meterProvider, tracerProvider };

  current = {
    flush,
    logger: logs.getLogger(SDK_NAME, SDK_VERSION),
    meter: metrics.getMeter(SDK_NAME, SDK_VERSION),
    shutdown,
    tracer: trace.getTracer(SDK_NAME, SDK_VERSION),
  };
  return current;
}

export async function flush(): Promise<void> {
  if (!providers) return;
  await Promise.all([
    providers.tracerProvider.forceFlush(),
    providers.meterProvider.forceFlush(),
    providers.loggerProvider.forceFlush(),
  ]);
}

export async function shutdown(): Promise<void> {
  const active = providers;
  current = undefined;
  providers = undefined;
  if (!active) return;
  await Promise.all([
    active.tracerProvider.shutdown(),
    active.meterProvider.shutdown(),
    active.loggerProvider.shutdown(),
  ]);
  trace.disable();
  metrics.disable();
  logs.disable();
  context.disable();
}

export default init;