Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

2.2 KB
Raw Blame
import { createHash } from "node:crypto";

/**
 * ID generator installed by the host OTel provider for reserved-ID emission. A span
 * whose lifetime crosses durable worker boundaries (`invoke_agent`) is emitted
 * at its terminal; priming the next span id lets that span carry the
 * pre-allocated id its descendants already parented to.
 */
export class AgentSpanIdGenerator {
  #primedSpanId: string | undefined;
  #primedTraceId: string | undefined;

  /** Reserves a span id for a span emitted later via {@link withSpanId}. */
  allocateSpanId(): string {
    return randomHexId(16);
  }

  /** Derives one span id for a replay-stable instrumentation event. */
  deriveSpanId(key: string): string {
    return deriveAgentSpanId(key);
  }

  deriveTraceId(key: string): string {
    const traceId = createHash("sha256").update(key).digest("hex").slice(0, 32);
    return /^0+$/u.test(traceId) ? "00000000000000000000000000000001" : traceId;
  }

  generateSpanId(): string {
    const primed = this.#primedSpanId;
    if (primed !== undefined) {
      this.#primedSpanId = undefined;
      return primed;
    }
    return randomHexId(16);
  }

  generateTraceId(): string {
    const primed = this.#primedTraceId;
    if (primed !== undefined) {
      this.#primedTraceId = undefined;
      return primed;
    }
    return randomHexId(32);
  }

  /** Runs `startSpan` so the next span started carries `spanId`. */
  withSpanId<T>(spanId: string, startSpan: () => T): T {
    this.#primedSpanId = spanId;
    try {
      return startSpan();
    } finally {
      this.#primedSpanId = undefined;
    }
  }

  withTraceId<T>(traceId: string, startSpan: () => T): T {
    this.#primedTraceId = traceId;
    try {
      return startSpan();
    } finally {
      this.#primedTraceId = undefined;
    }
  }
}

function deriveAgentSpanId(key: string): string {
  const spanId = createHash("sha256").update(key).digest("hex").slice(0, 16);
  return /^0+$/u.test(spanId) ? "0000000000000001" : spanId;
}

const HEX_DIGITS = "0123456789abcdef";

function randomHexId(length: number): string {
  let id: string;
  do {
    id = "";
    for (let index = 0; index < length; index += 1) {
      id += HEX_DIGITS[Math.trunc(Math.random() * 16)];
    }
  } while (!/[1-9a-f]/u.test(id));
  return id;
}