/** * Per-turn inference latency tracing. * * A turn-scoped span/mark recorder that answers one question: "where did the * wall-clock time of this response go?" It is the text/cloud sibling of the * voice loop's `EndToEndLatencyTracer` (plugin-local-inference) — same intent, * different shape: voice has a fixed ordered checkpoint set; a text turn has an * open-ended set of named spans (composeState, the model round-trip, the HTTP * fetch, the concurrency-limiter wait, evaluators) that every layer of the * stack contributes to without threading a recorder reference. * * Threading model (mirrors `streaming-context.ts`): the message handler opens a * timer with {@link runWithInferenceTiming} for the turn; any code running * inside that async scope — `AgentRuntime.useModel`, `composeState`, the * elizaOS Cloud HTTP handler, the evaluator service — calls the context-free * helpers ({@link timeInferenceSpan}, {@link recordInferenceSpan}, * {@link markInference}). When no timer is active the helpers are zero-cost * no-ops, so instrumentation is safe to leave on every code path. * * Each turn also carries a `traceId` — a bounded 32-lowercase-hex id, minted * here or adopted from an upstream hop — that outbound callers propagate so a * turn's local spans join the records of downstream services (e.g. the elizaOS * Cloud gateway) that key their own events to the same id. The format doubles * as a W3C `traceparent` trace-id so a hop can forward it without re-minting. * * A missing measurement is recorded as missing, never synthesized (AGENTS.md * §3 / §8): derived metrics whose endpoint mark was never recorded stay `null`. * The same rule governs the trace id: a summary rehydrated from a log written * before correlation existed reports `traceId: null` rather than a fresh id. * * Logger only, `[InferenceTiming]` prefix (AGENTS.md §9). */ export type InferenceTimingMeta = Record; export interface InferenceSpan { /** Stage name, e.g. `composeState`, `model:RESPONSE_HANDLER`, * `cloud.http:/chat/completions`, `cloud.semaphore-wait`, `evaluators`. */ name: string; /** Wall-clock ms since the turn's `t0` when the span opened. */ startMs: number; /** Wall-clock ms since `t0` when the span closed. */ endMs: number; /** `endMs - startMs`. */ durationMs: number; meta?: InferenceTimingMeta; } export interface InferenceMark { name: string; /** Wall-clock ms since the turn's `t0`. */ tMs: number; } /** Canonical point-in-time marks the summary derives headline metrics from. */ export declare const INFERENCE_MARKS: { /** First streamed token/char delivered to the caller (streaming only). */ readonly firstToken: "first-token"; /** First user-visible reply text committed by the host delivery path. */ readonly firstVisibleReply: "first-visible-reply"; /** The user-visible reply was handed to the delivery callback. */ readonly replyDelivered: "reply-delivered"; /** Host response normalization and all synchronous turn work completed. */ readonly responseFinalized: "response-finalized"; }; export interface InferenceTurnSummary { turnId: string; /** * Gateway correlation ID, sent as X-Eliza-Trace-Id. Null denotes a stored summary without * correlation evidence; never invent an ID. */ traceId: string | null; label: string; roomId: string | null; modelProvider: string | null; t0EpochMs: number; closedAtEpochMs: number | null; /** `t0` → turn close. Null while the turn is still open. */ totalMs: number | null; /** `t0` → `first-token` mark; null when nothing streamed. */ timeToFirstTokenMs: number | null; /** `t0` → first host-visible reply text; null when no text was emitted. */ timeToFirstVisibleMs: number | null; /** `t0` → `reply-delivered` mark; null when no reply was delivered. */ timeToReplyMs: number | null; /** `t0` → host response finalization; null outside host-owned chat turns. */ timeToResponseFinalizedMs: number | null; spans: InferenceSpan[]; marks: InferenceMark[]; /** * Per-span-name roll-up: total ms and count within this turn. Durations can * sum past wall-clock time because sibling spans (e.g. parallel providers) * overlap — this is a contribution view, not a timeline partition. */ byName: Record; anomalies: string[]; } export declare const INFERENCE_FLOW_STAGES: readonly ["document-augmentation", "providers", "embedding", "model-queue", "model-routing", "model-preprocess", "llm-inference", "model-postprocess", "actions", "evaluators", "planner-overhead", "response-finalization", "message-ingress", "message-delivery", "message-lifecycle", "message-service-overhead", "unattributed"]; export type InferenceFlowStage = (typeof INFERENCE_FLOW_STAGES)[number]; export interface InferenceFlowStageBreakdown { stage: InferenceFlowStage; /** Exclusive wall time: overlapping child/parent spans are counted once. */ totalMs: number; /** Exclusive wall time before the first visible reply, when available. */ toFirstVisibleMs: number | null; percentOfTotal: number | null; } export interface InferenceFlowBreakdown { turnId: string; totalMs: number | null; timeToFirstVisibleMs: number | null; stages: InferenceFlowStageBreakdown[]; } /** * Partitions the request timeline into exclusive stages. Nested model/provider * spans and parallel providers therefore never inflate the wall-clock total. */ export declare function buildInferenceFlowBreakdown(summary: InferenceTurnSummary): InferenceFlowBreakdown; export { INFERENCE_TRACE_ID_PATTERN, isInferenceTraceId, mintInferenceTraceId, } from "./inference-trace.js"; export declare class InferenceTurnTimer { readonly turnId: string; readonly traceId: string; readonly label: string; readonly roomId: string | null; readonly t0EpochMs: number; modelProvider: string | null; private readonly spans; private readonly marks; private readonly anomalies; private readonly maxSpans; private closedAtEpochMs; constructor(args: { turnId: string; /** Caller-propagated id (e.g. from an upstream hop); minted when absent. * Must match {@link INFERENCE_TRACE_ID_PATTERN}. */ traceId?: string; label: string; roomId?: string | null; t0EpochMs?: number; maxSpans?: number; }); private rel; /** Open a span; returns a function that closes it. Safe to call the closer * more than once (subsequent calls are ignored). */ openSpan(name: string, meta?: InferenceTimingMeta): () => void; /** Record a span whose duration was already measured by the caller. */ recordSpan(name: string, durationMs: number, meta?: InferenceTimingMeta): void; private recordSpanAbsolute; /** Record a once-per-turn point mark. A duplicate keeps the first. */ mark(name: string, atEpochMs?: number): void; /** Attribute the turn to a model provider (first writer wins). */ setModelProvider(provider: string | null | undefined): void; close(): InferenceTurnSummary; summary(): InferenceTurnSummary; } /** Run `fn` with `timer` as the active turn timer for all nested async work. */ export declare function runWithInferenceTiming(timer: InferenceTurnTimer | undefined, fn: () => T): T; /** The active turn timer, or undefined when no turn is being timed. */ export declare function getInferenceTimer(): InferenceTurnTimer | undefined; /** Time `fn` as a span on the active timer (no-op-times when none active). */ export declare function timeInferenceSpan(name: string, fn: () => Promise, meta?: InferenceTimingMeta): Promise; /** Record a pre-measured span on the active timer (no-op when none active). */ export declare function recordInferenceSpan(name: string, durationMs: number, meta?: InferenceTimingMeta): void; /** Record a point mark on the active timer (no-op when none active). */ export declare function markInference(name: string, atEpochMs?: number): void; /** Attribute the active turn to a model provider (no-op when none active). */ export declare function setInferenceModelProvider(provider: string | null | undefined): void; export interface InferenceHistogramSummary { count: number; p50: number | null; p90: number | null; p95: number | null; p99: number | null; min: number | null; max: number | null; mean: number | null; } declare class InferenceTimingRegistry { private readonly ring; private readonly spanHistograms; private readonly ttft; private readonly firstVisible; private readonly ttreply; private readonly finalized; private readonly total; record(summary: InferenceTurnSummary): void; recentTurns(limit: number): InferenceTurnSummary[]; spanSummaries(): Record; derivedSummaries(): Record; reset(): void; } export declare const inferenceTimingRegistry: InferenceTimingRegistry; export interface InferenceTimingDevPayload { generatedAtEpochMs: number; turns: InferenceTurnSummary[]; flows: InferenceFlowBreakdown[]; spanHistograms: Record; derivedHistograms: Record; providers: ProviderInferenceTelemetry[]; } export interface ProviderInferenceTelemetry { providerName: string; execution: InferenceHistogramSummary; cacheHits: number; successes: number; errors: number; aborted: number; coalesced: number; unknown: number; } /** JSON body for a dev endpoint (e.g. `GET /api/dev/inference-timing`). */ export declare function buildInferenceTimingDevPayload(limit?: number, persistedTurns?: readonly InferenceTurnSummary[]): InferenceTimingDevPayload; /** A compact `name=ms` breakdown sorted by descending contribution. */ export declare function formatInferenceTimingSummary(s: InferenceTurnSummary): string; /** * Close the timer, fold it into the process registry, and emit the breakdown. * Call once at the end of a turn. No-op-safe for an undefined timer. */ export declare function emitInferenceTiming(timer: InferenceTurnTimer | undefined): InferenceTurnSummary | null; /** Allocate a process-unique turn id for a new inference timer. */ export declare function nextInferenceTurnId(): string;