Skip to navigation

Generated from crates/node/dist/index.d.ts.

Import from nemo-relay-node.

Main runtime lifecycle, scope, middleware, subscriber, and exporter APIs.

Namespaces

codecs

Selection, typed content snapshots, and text extraction over normalized annotations.

export * as codecs from './codecs.js';

Interfaces

ApplicationExecutionContext

Concrete invocation context; application-owned JSON belongs inside data.

export interface ApplicationExecutionContext {
/** Opaque application fields. Middleware validates their schema and meaning. */
data?: JsonObject;
}

ResourceMetricsPollingConfig

export interface ResourceMetricsPollingConfig {
enabled?: boolean;
interval_millis?: number;
}

ResourceMemoryInspectionConfig

export interface ResourceMemoryInspectionConfig {
enabled?: boolean;
stale_after_millis?: number;
}

ResourceMetricsCpuConfig

export interface ResourceMetricsCpuConfig {
enabled?: boolean;
}

ResourceMetricsMemoryConfig

export interface ResourceMetricsMemoryConfig {
enabled?: boolean;
}

ResourceMetricsProcessConfig

export interface ResourceMetricsProcessConfig {
enabled?: boolean;
}

ResourceMetricsDiskConfig

export interface ResourceMetricsDiskConfig {
enabled?: boolean;
process_io?: boolean;
filesystem_paths?: string[];
}

ResourceMetricsGpuConfig

export interface ResourceMetricsGpuConfig {
enabled?: boolean;
devices?: string[];
device_metrics?: boolean;
process_metrics?: boolean;
}

ResourceMetricsNetworkConfig

export interface ResourceMetricsNetworkConfig {
enabled?: boolean;
interfaces?: string[];
}

ResourceMetricsCpuUnits

export interface ResourceMetricsCpuUnits {
user_time?: ResourceUnit<DurationUnit>;
system_time?: ResourceUnit<DurationUnit>;
total_time?: ResourceUnit<DurationUnit>;
throttled_time?: ResourceUnit<DurationUnit>;
some_pressure_stall_time?: ResourceUnit<DurationUnit>;
full_pressure_stall_time?: ResourceUnit<DurationUnit>;
consumption_rate?: ResourceUnit<CpuUnit>;
effective_limit?: ResourceUnit<CpuUnit>;
}

ResourceMetricsMemoryUnits

export interface ResourceMetricsMemoryUnits {
system_used?: ResourceUnit<CapacityUnit>;
system_total?: ResourceUnit<CapacityUnit>;
system_available?: ResourceUnit<CapacityUnit>;
resident?: ResourceUnit<CapacityUnit>;
private?: ResourceUnit<CapacityUnit>;
physical_footprint?: ResourceUnit<CapacityUnit>;
virtual_memory?: ResourceUnit<CapacityUnit>;
peak_resident?: ResourceUnit<CapacityUnit>;
limit?: ResourceUnit<CapacityUnit>;
environment_accounted?: ResourceUnit<CapacityUnit>;
some_pressure_stall_time?: ResourceUnit<DurationUnit>;
full_pressure_stall_time?: ResourceUnit<DurationUnit>;
}

ResourceMetricsDiskUnits

export interface ResourceMetricsDiskUnits {
read_data?: ResourceUnit<DataUnit>;
write_data?: ResourceUnit<DataUnit>;
filesystem_total_capacity?: ResourceUnit<CapacityUnit>;
filesystem_available_capacity?: ResourceUnit<CapacityUnit>;
filesystem_free_capacity?: ResourceUnit<CapacityUnit>;
read_throughput?: ResourceUnit<BandwidthUnit>;
write_throughput?: ResourceUnit<BandwidthUnit>;
}

ResourceMetricsGpuUnits

export interface ResourceMetricsGpuUnits {
device_memory_used?: ResourceUnit<CapacityUnit>;
process_memory_used?: ResourceUnit<CapacityUnit>;
device_compute_utilization?: ResourceUnit<UtilizationUnit>;
process_compute_utilization?: ResourceUnit<UtilizationUnit>;
}

ResourceMetricsNetworkTrafficUnits

export interface ResourceMetricsNetworkTrafficUnits {
received_data?: ResourceUnit<DataUnit>;
transmitted_data?: ResourceUnit<DataUnit>;
receive_throughput?: ResourceUnit<BandwidthUnit>;
transmit_throughput?: ResourceUnit<BandwidthUnit>;
}

ResourceMetricsNetworkUnits

export interface ResourceMetricsNetworkUnits {
system?: ResourceMetricsNetworkTrafficUnits;
interface?: ResourceMetricsNetworkTrafficUnits;
}

ResourceMetricsUnits

export interface ResourceMetricsUnits {
cpu?: ResourceMetricsCpuUnits;
memory?: ResourceMetricsMemoryUnits;
disk?: ResourceMetricsDiskUnits;
gpu?: ResourceMetricsGpuUnits;
network?: ResourceMetricsNetworkUnits;
}

ResourceMetricsConfig

export interface ResourceMetricsConfig {
measurement_scope?: ResourceMetricsMeasurementScope;
polling?: ResourceMetricsPollingConfig;
memory_inspection?: ResourceMemoryInspectionConfig;
cpu?: ResourceMetricsCpuConfig;
memory?: ResourceMetricsMemoryConfig;
process?: ResourceMetricsProcessConfig;
disk?: ResourceMetricsDiskConfig;
gpu?: ResourceMetricsGpuConfig;
network?: ResourceMetricsNetworkConfig;
units?: ResourceMetricsUnits;
}

ResourceMeasurement

export interface ResourceMeasurement<T extends ResourceNumeric, U extends ResourceUnitKind> {
readonly value: T;
readonly unit: U;
}

ResourceLimitEventCount

export interface ResourceLimitEventCount {
readonly resource: 'cpu' | 'memory' | 'processes';
readonly event: 'throttled' | 'high' | 'maximum' | 'out_of_memory' | 'terminated';
readonly count: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
}

AcceleratorDeviceMetrics

export interface AcceleratorDeviceMetrics {
readonly vendor: AcceleratorVendor;
readonly deviceIdentifier: string;
readonly deviceIndex: number | null;
readonly memoryUsed: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly computeUtilization: ResourceMeasurement<number, UtilizationUnit> | null;
}

AcceleratorProcessMetrics

export interface AcceleratorProcessMetrics {
readonly vendor: AcceleratorVendor;
readonly deviceIdentifier: string;
readonly deviceIndex: number | null;
readonly processId: number;
readonly memoryUsed: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly computeUtilization: ResourceMeasurement<number, UtilizationUnit> | null;
}

FilesystemCapacityMetrics

export interface FilesystemCapacityMetrics {
readonly path: string;
readonly totalCapacity: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly availableCapacity: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly freeCapacity: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
}

CpuMetrics

export interface CpuMetrics {
readonly userTime: ResourceMeasurement<ResourceNumeric, DurationUnit> | null;
readonly systemTime: ResourceMeasurement<ResourceNumeric, DurationUnit> | null;
readonly totalTime: ResourceMeasurement<ResourceNumeric, DurationUnit> | null;
readonly consumptionRate: ResourceMeasurement<number, CpuUnit> | null;
readonly throttledTime: ResourceMeasurement<ResourceNumeric, DurationUnit> | null;
readonly effectiveLimit: ResourceMeasurement<number, CpuUnit> | null;
readonly somePressureStallTime: ResourceMeasurement<ResourceNumeric, DurationUnit> | null;
readonly fullPressureStallTime: ResourceMeasurement<ResourceNumeric, DurationUnit> | null;
readonly limitEvents: readonly ResourceLimitEventCount[];
}

MemoryMetrics

export interface MemoryMetrics {
readonly systemUsed: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly systemTotal: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly systemAvailable: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly resident: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly private: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly physicalFootprint: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly virtualMemory: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly peakResident: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly limit: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly environmentAccounted: ResourceMeasurement<ResourceNumeric, CapacityUnit> | null;
readonly somePressureStallTime: ResourceMeasurement<ResourceNumeric, DurationUnit> | null;
readonly fullPressureStallTime: ResourceMeasurement<ResourceNumeric, DurationUnit> | null;
readonly outOfMemoryEventCount: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly limitEvents: readonly ResourceLimitEventCount[];
}

ProcessMetrics

export interface ProcessMetrics {
readonly activeCount: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly descendantCount: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly threadCount: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly lifetimeCreationCount: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly openFileDescriptorCount: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly windowsHandleCount: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly limitEvents: readonly ResourceLimitEventCount[];
}

DiskMetrics

export interface DiskMetrics {
readonly readData: ResourceMeasurement<ResourceNumeric, DataUnit> | null;
readonly writeData: ResourceMeasurement<ResourceNumeric, DataUnit> | null;
readonly readThroughput: ResourceMeasurement<number, BandwidthUnit> | null;
readonly writeThroughput: ResourceMeasurement<number, BandwidthUnit> | null;
readonly readOperations: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly writeOperations: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly filesystems: readonly FilesystemCapacityMetrics[];
}

GpuMetrics

export interface GpuMetrics {
readonly deviceMetrics: readonly AcceleratorDeviceMetrics[] | null;
readonly processMetrics: readonly AcceleratorProcessMetrics[] | null;
}

NetworkTrafficMetrics

export interface NetworkTrafficMetrics {
readonly receivedData: ResourceMeasurement<ResourceNumeric, DataUnit> | null;
readonly transmittedData: ResourceMeasurement<ResourceNumeric, DataUnit> | null;
readonly receiveThroughput: ResourceMeasurement<number, BandwidthUnit> | null;
readonly transmitThroughput: ResourceMeasurement<number, BandwidthUnit> | null;
readonly receivedPackets: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly transmittedPackets: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly receiveErrors: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
readonly transmitErrors: ResourceMeasurement<ResourceNumeric, CountUnit> | null;
}

NetworkInterfaceMetrics

export interface NetworkInterfaceMetrics {
readonly name: string;
readonly traffic: NetworkTrafficMetrics;
}

NetworkMetrics

export interface NetworkMetrics {
readonly measurementScope: 'global';
readonly system: NetworkTrafficMetrics;
readonly interfaces: readonly NetworkInterfaceMetrics[];
}

ProcessSamplingMetadata

export interface ProcessSamplingMetadata {
readonly visibleProcesses: ResourceNumeric;
readonly sampledProcesses: ResourceNumeric;
/** Process counts keyed by snake_case measurement path. */
readonly fieldSampledProcesses: Readonly<Record<string, ResourceNumeric>>;
}

ResourceMetricsSnapshot

export interface ResourceMetricsSnapshot {
readonly timestamp: string;
readonly operatingSystem: ResourceOperatingSystem;
readonly measurementScope: ResourceMeasurementScope;
readonly processSampling: ProcessSamplingMetadata | null;
readonly cpu: CpuMetrics | null;
readonly memory: MemoryMetrics | null;
readonly process: ProcessMetrics | null;
readonly disk: DiskMetrics | null;
readonly gpu: GpuMetrics | null;
readonly network: NetworkMetrics | null;
}

LlmCodec

export interface LlmCodec<
TAnnotated extends JsonCompatible<TAnnotated> = JsonValue,
TEncoded extends LlmRequestCompatible<TEncoded> = LlmRequestShape,
> {
decode: (request: LlmRequestShape) => TAnnotated;
encode: (annotated: JsonValue, original: LlmRequestShape) => TEncoded;
}

LlmResponseCodec

export interface LlmResponseCodec<TDecoded extends JsonCompatible<TDecoded> = JsonValue> {
decodeResponse: (response: JsonValue) => TDecoded;
}

LlmSanitizeRequestContext

Request codec context for sanitizer and execution callbacks.

export interface LlmSanitizeRequestContext {
codec: LlmCodecIdentity;
/** Active codec, valid until the callback returns. */
resolveCodec(): LlmCodec | null;
}

LlmSanitizeResponseContext

Response codec context for sanitizer and execution callbacks.

export interface LlmSanitizeResponseContext {
codec: LlmCodecIdentity;
/** Active codec, valid until the callback returns. */
resolveCodec(): LlmResponseCodec | null;
}

LlmApplicationExecutionContext

Invocation-local application payload for LLM execution intercepts.

export interface LlmApplicationExecutionContext {
data?: { [key: string]: Json };
}

LlmExecutionContext

Codecs and application data available to one LLM execution intercept call.

export interface LlmExecutionContext {
/** Request codec, with decode and encode when available. */
requestCodec: LlmRequestContext;
/** Response codec, with decode when available; `null` for streaming. */
responseCodec: LlmResponseContext | null;
executionContext: LlmApplicationExecutionContext | null;
}

LlmOptimizationDataSchema

Schema tag for an optimization payload.

export interface LlmOptimizationDataSchema {
name: string;
version: string;
}

LlmOptimizationModel

Model identity kept for repricing.

export interface LlmOptimizationModel {
model: string;
provider?: string;
}

LlmOptimizationModelTransition

Baseline and effective models of a routing optimization.

export interface LlmOptimizationModelTransition {
baseline?: LlmOptimizationModel;
effective?: LlmOptimizationModel;
}

LlmOptimizationTokens

Token counts reported directly.

export interface LlmOptimizationTokens {
/** Non-negative safe integer. */
prompt_tokens?: number;
/** Non-negative safe integer. */
completion_tokens?: number;
/** Non-negative safe integer. */
cache_read_tokens?: number;
/** Non-negative safe integer. */
cache_write_tokens?: number;
/** Non-negative safe integer. */
total_tokens?: number;
}

LlmOptimizationTokenImpact

Baseline, effective, and saved tokens of one optimization.

export interface LlmOptimizationTokenImpact {
baseline?: LlmOptimizationTokens;
effective?: LlmOptimizationTokens;
saved?: LlmOptimizationTokens;
quality?: 'observed' | 'estimated';
estimation_method?: string;
}

LlmOptimizationContribution

One plugin’s optimization evidence. kind accepts any string and unknown fields are kept.

export interface LlmOptimizationContribution {
id?: string;
/** Safe integer. */
sequence?: number;
producer: string;
kind: 'input_compression' | 'model_routing' | (string & {});
applied: boolean;
model_transition?: LlmOptimizationModelTransition;
token_impact?: LlmOptimizationTokenImpact;
payload_schema?: LlmOptimizationDataSchema;
payload?: Json;
[key: string]:
| Json
| LlmOptimizationModelTransition
| LlmOptimizationTokenImpact
| LlmOptimizationDataSchema
| undefined;
}

LlmRequestInterceptOutcome

Result of an LLM request intercept.

export interface LlmRequestInterceptOutcome {
request: LlmRequestShape;
annotated?: Json | null;
pendingMarks?: PendingMarkSpec[];
optimizationContributions?: LlmOptimizationContribution[];
[key: string]: JsonValue | PendingMarkSpec[] | LlmOptimizationContribution[] | undefined;
}

ConfigDiagnostic

export interface ConfigDiagnostic {
level: 'warning' | 'error';
code: string;
component?: string;
field?: string;
message: string;
}

ToolExecutionInterceptOutcome

export interface ToolExecutionInterceptOutcome extends ToolExecutionResult {
pendingMarks?: PendingMarkSpec[];
[key: string]: JsonValue | PendingMarkSpec[] | undefined;
}

PluginContext

export interface PluginContext {
registerConditionalMiddlewareGuardrail(
name: string,
kinds: Array<RuntimeRegistrationKind | RuntimeRegistrationKindName>,
registrationName: string,
guardrail: (kinds: RuntimeRegistrationKind[], registrationName: string) => string | null,
): void;
registerSubscriber(name: string, callback: (event: JsonObject) => void | Promise<void>): void;
registerEventMetadataInjector<TMetadata extends EventMetadataCompatible<TMetadata>>(
name: string,
priority: number,
callback: (event: JsonObject) => TMetadata | Promise<TMetadata>,
): void;
registerMarkSanitizeGuardrail<TFields extends EventSanitizeFieldsCompatible<TFields>>(
name: string,
priority: number,
callback: (event: JsonObject, fields: EventSanitizeFields) => TFields | Promise<TFields>,
): void;
registerScopeSanitizeStartGuardrail<TFields extends EventSanitizeFieldsCompatible<TFields>>(
name: string,
priority: number,
callback: (event: JsonObject, fields: EventSanitizeFields) => TFields | Promise<TFields>,
): void;
registerScopeSanitizeEndGuardrail<TFields extends EventSanitizeFieldsCompatible<TFields>>(
name: string,
priority: number,
callback: (event: JsonObject, fields: EventSanitizeFields) => TFields | Promise<TFields>,
): void;
registerToolSanitizeRequestGuardrail<TValue extends JsonCompatible<TValue>>(
name: string,
priority: number,
callback: (name: string, args: Json) => TValue | Promise<TValue>,
): void;
registerToolSanitizeResponseGuardrail<TValue extends JsonCompatible<TValue>>(
name: string,
priority: number,
callback: (name: string, result: Json) => TValue | Promise<TValue>,
): void;
registerToolConditionalExecutionGuardrail(
name: string,
priority: number,
callback: (name: string, args: Json) => string | null | Promise<string | null>,
): void;
registerLlmSanitizeRequestGuardrail<TRequest extends LlmRequestCompatible<TRequest> = LlmRequestShape>(
name: string,
priority: number,
callback: (
request: LlmRequestShape,
context: LlmSanitizeRequestContext,
) => TRequest | null | Promise<TRequest | null>,
): void;
registerLlmSanitizeResponseGuardrail<TResponse extends JsonCompatible<TResponse> = Json>(
name: string,
priority: number,
callback: (response: Json, context: LlmSanitizeResponseContext) => TResponse | null | Promise<TResponse | null>,
): void;
registerLlmConditionalExecutionGuardrail(
name: string,
priority: number,
callback: (request: LlmRequestShape) => string | null | Promise<string | null>,
): void;
registerLlmRequestIntercept<TOutcome extends LlmRequestInterceptOutcomeCompatible<TOutcome>>(
name: string,
priority: number,
breakChain: boolean,
callback: (args: {
name: string;
request: LlmRequestShape;
annotated: Json | null;
}) => TOutcome | Promise<TOutcome>,
): void;
registerLlmExecutionIntercept<TResponse extends JsonCompatible<TResponse>>(
name: string,
priority: number,
callback: (
request: LlmRequestShape,
context: LlmExecutionContext,
next: <TNextRequest extends LlmRequestCompatible<TNextRequest>>(request: TNextRequest) => Json | Promise<Json>,
) => TResponse | Promise<TResponse>,
): void;
registerLlmStreamExecutionIntercept<TChunk extends JsonCompatible<TChunk>>(
name: string,
priority: number,
callback: (
request: LlmRequestShape,
context: LlmExecutionContext,
next: <TNextRequest extends LlmRequestCompatible<TNextRequest>>(
request: TNextRequest,
) => Promise<AsyncIterable<Json>>,
) => AsyncIterable<TChunk> | Promise<AsyncIterable<TChunk>>,
): void;
registerToolRequestIntercept<TArgs extends JsonCompatible<TArgs>>(
name: string,
priority: number,
breakChain: boolean,
callback: (name: string, args: Json) => TArgs | Promise<TArgs>,
): void;
registerToolExecutionIntercept<TOutcome extends ToolExecutionInterceptOutcomeCompatible<TOutcome>>(
name: string,
priority: number,
callback: (
context: ToolExecutionContext,
next: <TNextArgs extends JsonCompatible<TNextArgs>>(
args: TNextArgs,
) => ToolExecutionResult | Promise<ToolExecutionResult>,
) => TOutcome | Promise<TOutcome>,
): void;
}

ConfigReport

Validation or activation report for a plugin config.

export interface ConfigReport {
diagnostics: ConfigDiagnostic[];
runtime_diagnostics?: RuntimeDiagnostic[];
}

RuntimeDiagnostic

One aggregated runtime plugin failure.

export interface RuntimeDiagnostic {
code: string;
component: string;
field?: string;
message: string;
session_id?: string;
count: number;
}

PluginHostReport

export interface PluginHostReport {
config: ConfigReport;
dynamic_plugins: DynamicPluginValidationReport[];
/** `plugins.toml` files merged into the resolved config. */
config_paths: string[];
/** Merged plugin config with sensitive values redacted. */
resolved_config: Json;
}

DynamicPluginValidationStatus

export interface DynamicPluginValidationStatus {
manifest: DynamicPluginCheckState;
compatibility: DynamicPluginCheckState;
integrity: DynamicPluginCheckState;
environment: DynamicPluginCheckState;
authenticity: DynamicPluginCheckState;
policy_satisfied: DynamicPluginCheckState;
checked_at?: string | null;
message?: string | null;
}

DynamicPluginFailure

export interface DynamicPluginFailure {
phase: string;
code: string;
message: string;
}

DynamicPluginValidationReport

export interface DynamicPluginValidationReport {
plugin_id: string;
manifest_ref: string;
kind: DynamicPluginKind;
status: DynamicPluginValidationStatus;
failure?: DynamicPluginFailure | null;
selected: boolean;
}

CacheWriteTokenCounts

Prompt-cache write tokens for one cache duration.

export interface CacheWriteTokenCounts {
count: number;
/** Cache duration in seconds, when the provider reports it. */
duration?: number;
}

CacheUsage

Token usage for cache telemetry.

export interface CacheUsage {
prompt_tokens?: number;
completion_tokens?: number;
total_tokens?: number;
cache_read_tokens?: number;
cache_write_tokens?: CacheWriteTokenCounts[];
cost?: Json;
}

AgentIdentity

Agent identity in cache telemetry.

export interface AgentIdentity {
agent_id: string;
template_version: string;
toolset_hash: string;
model_family: string;
tenant_scope: string;
}

CacheRequestFactsOptions

Input to buildCacheRequestFacts.

export interface CacheRequestFactsOptions {
provider: string;
requestId: string;
annotatedRequest: Json;
agentId: string;
timestamp?: string;
}

CacheRequestFacts

Request facts that classify cache misses.

export interface CacheRequestFacts {
provider: string;
stable_prefix_length: number;
stable_prefix_tokens?: number;
required_min_tokens?: number;
first_mismatch_span_id?: string;
first_mismatch_sequence_index?: number;
expected_hash_prefix?: string;
actual_hash_prefix?: string;
retention_window_secs?: number;
observed_gap_secs?: number;
missing_facts?: string[];
}

CacheTelemetryEventOptions

Input to buildCacheTelemetryEvent.

export interface CacheTelemetryEventOptions {
provider: 'anthropic' | 'openai' | string;
requestId: string;
usage?: CacheUsage | null;
requestFacts?: CacheRequestFacts | null;
agentId: string;
templateVersion: string;
toolsetHash: string;
modelFamily: string;
tenantScope: string;
timestamp?: string;
}

CacheTelemetryEvent

Cache telemetry event.

export interface CacheTelemetryEvent {
request_id: string;
agent_identity: AgentIdentity;
cache_read_tokens: number;
cache_creation_tokens: number;
total_prompt_tokens: number;
hit_rate: number;
miss_reason?: Record<string, Json>;
miss_diagnosis?: Record<string, Json>;
provider: string;
timestamp: string;
}

SourceIdentity

Producer of the evidence.

export interface SourceIdentity {
/** Unique id of this process run. */
instanceId: string;
/** Operating system process ID, not an identity key. */
processId: number | null;
/** Role, such as gateway or worker. */
processRole: string;
/** Relay version that produced the evidence. */
relayVersion: string;
}

ComponentIdentity

Component registration.

export interface ComponentIdentity {
/** Logical name without request or session ids. */
key: string;
/** Unique id of this registration. */
instanceId: string;
/** Generation, increased when a logical key is replaced. */
generation: bigint;
}

ComponentOwnership

Owner and configuration of a component.

export interface ComponentOwnership {
/** Subscriber registration, when applicable. */
subscriberInstanceId: string | null;
/** Plugin registration, when applicable. */
pluginInstanceId: string | null;
/** Id of the committed configuration. */
configurationId: string | null;
/** Runtime responsibility of the owner. */
responsibility: string | null;
}

DiagnosticOrigin

Where an observation came from.

export interface DiagnosticOrigin {
/** Refresh generation of the observation. */
refreshGeneration: bigint;
/** Original owner and configuration. */
ownership: ComponentOwnership;
}

DiagnosticCorrelation

Session and request of an observation.

export interface DiagnosticCorrelation {
/** Trajectory session, when known. */
sessionId?: string | null;
/** Request, when known. */
requestId?: string | null;
}

Classification

Code and cause of an observation.

export interface Classification {
/** Built-in name or registered extension name. */
canonicalCode: string;
/** Cause name, absent for successes and notices. */
failureClass: string | null;
}

DiagnosticDetail

Text attached to an observation.

export interface DiagnosticDetail {
/** Unsanitized text cut to the byte capacity. */
message: string;
/** Whether the text was cut. */
truncated: boolean;
}

DiagnosticEvent

One retained observation.

export interface DiagnosticEvent {
/** Unique update sequence, not an occurrence count. */
sequence: bigint;
/** Observation time at the source. */
observedAt: string;
/** Registration that made the observation. */
component: ComponentIdentity;
/** Configuration at observation time. */
origin: DiagnosticOrigin;
/** Remote submission origin, absent for local observations. */
remote?: RemoteDiagnosticOrigin | null;
/** Event classification. */
classification: Classification;
/** Plugin operation facts, excluded from aggregation keys. */
context: PluginObservationContext;
/** Severity, independent of outcome. */
severity: string;
/** Operation outcome. */
outcome: string;
/** Message attached to the observation, or `null`. */
detail: DiagnosticDetail | null;
/** Occurrences added by this recording. */
count: bigint;
/** Caller correlation, excluded from aggregation identity. */
correlation: DiagnosticCorrelation;
}

RemoteDiagnosticOrigin

Origin of a remote submission.

export interface RemoteDiagnosticOrigin {
/** Host-issued session id. */
sourceInstanceId: string;
/** Host-issued plugin activation id. */
activationInstanceId: string;
/** Submission sequence, not the host event sequence. */
submissionSequence: bigint;
/** Producer-reported wall time, if any. */
observedAt: string | null;
/** Host wall time at acceptance, used as the event observation time. */
receivedAt: string;
/** Host monotonic time at acceptance since context startup. */
acceptedElapsedMillis: bigint;
}

DiagnosticCount

Count that may saturate.

export interface DiagnosticCount {
/** Exact count unless saturated. */
value: bigint;
/** Whether overflow made the value a lower bound. */
saturated: boolean;
}

DiagnosticTotals

Occurrence totals by outcome.

export interface DiagnosticTotals {
/** Accepted recording calls. */
recordedEventsTotal: DiagnosticCount;
/** Accepted occurrences across outcomes and codes. */
occurrencesTotal: DiagnosticCount;
/** Retained events later evicted. */
historyEvictionsTotal: DiagnosticCount;
/** Occurrences with a successful outcome. */
successesTotal: DiagnosticCount;
/** Occurrences with a failed outcome. */
failuresTotal: DiagnosticCount;
/** Occurrences with no outcome. */
unspecifiedTotal: DiagnosticCount;
}

DiagnosticLifetimeSummary

Totals over a lifetime.

export interface DiagnosticLifetimeSummary {
/** Totals for the context or component. */
totals: DiagnosticTotals;
/** Elapsed lifetime at capture. */
elapsedMillis: bigint;
/** Wall-clock time of the latest failure. */
lastFailureAt: string | null;
/** Elapsed time since the latest failure, or `null` when none was observed. */
sinceLastFailureMillis: bigint | null;
}

DiagnosticRefreshSummary

Totals since the last refresh.

export interface DiagnosticRefreshSummary {
/** Generation, increased by a successful refresh. */
generation: bigint;
/** Wall-clock time of the refresh. */
startedAt: string;
/** Elapsed time since the refresh. */
elapsedMillis: bigint;
/** Configuration and owner for this period. */
ownership: ComponentOwnership;
/** Counts for this period, separate from lifetime totals. */
totals: DiagnosticTotals;
}

DiagnosticCounter

Occurrences of one code.

export interface DiagnosticCounter {
/** Canonical code of the counted observations. */
code: string;
/** Accepted occurrences. */
occurrences: DiagnosticCount;
/** Time of the last update. */
lastObservedAt: string;
}

DiagnosticWindowBucket

One time bucket of outcomes.

export interface DiagnosticWindowBucket {
/** Inclusive start offset from component start. */
startElapsedMillis: bigint;
/** Exclusive end offset of the bucket. */
endElapsedMillis: bigint;
/** Successful occurrences in this interval. */
successes: DiagnosticCount;
/** Failed occurrences in this interval. */
failures: DiagnosticCount;
/** Occurrences with no outcome in this interval. */
unspecified: DiagnosticCount;
}

DiagnosticWindowCoverage

Interval covered by a window.

export interface DiagnosticWindowCoverage {
/** Availability of the window series. */
availability: string;
/** Earliest covered offset. */
startElapsedMillis: bigint;
/** Latest covered offset at capture. */
endElapsedMillis: bigint;
/** First bucket is only partly covered. */
partialStart: boolean;
/** Last bucket is still open or partly selected. */
partialEnd: boolean;
/** Known loss makes the interval incomplete. */
incomplete: boolean;
}

DiagnosticWindow

Fixed-bucket outcome series.

export interface DiagnosticWindow {
/** Bucket duration. */
resolutionMillis: bigint;
/** Configured bucket count. */
bucketCapacity: number;
/** Selected buckets, zero when idle. */
buckets: Array<DiagnosticWindowBucket>;
/** Covered interval and edge limits. */
coverage: DiagnosticWindowCoverage;
}

DiagnosticCursor

Position for the next page.

export interface DiagnosticCursor {
/** Source run whose state was selected. */
sourceInstanceId: string;
/** Source revision at the time the cursor was issued. */
sequence: bigint;
/** Next component position. */
componentOffset: bigint;
/** Next event position. */
eventOffset: bigint;
/** Fingerprint of the query scope. */
scope: bigint;
}

DiagnosticQuery

Selection for a snapshot.

export interface DiagnosticQuery {
/** Snapshot schema version to request. */
schemaVersion?: number | null;
/** Selects one component key. */
componentKey?: string | null;
/** Selects one registration instance. */
componentInstanceId?: string | null;
/** Selects recent events by refresh generation. */
originGeneration?: bigint | null;
/** Selects one code. */
code?: string | null;
/** Selects a catalogue domain. */
domain?: string | null;
/** Selects a plugin catalogue family. */
pluginFamily?: string | null;
/** Selects event causes. */
failureClass?: string | null;
/** Selects components by current ownership and events by original ownership. */
ownership?: Partial<ComponentOwnership>;
/** Selects events after this sequence. */
afterSequence?: bigint | null;
/** Maximum number of component rows to return. */
maxComponents?: number | null;
/** Maximum number of events to return. */
maxEvents?: number | null;
/** Maximum encoded response size in bytes. */
maxResponseBytes?: number | null;
/** Resumes a selection with the same scope. */
continuation?: DiagnosticCursor | null;
}

DiagnosticRetention

History bounds of a selection.

export interface DiagnosticRetention {
/** Oldest selected event sequence, if any. */
oldestEventSequence: bigint | null;
/** Latest selected event sequence, if any. */
latestEventSequence: bigint | null;
/** Returned event count. */
eventsRetained: bigint;
/** Returned component count. */
componentsRetained: bigint;
/** Whether query limits cut matching evidence. */
queryTruncated: boolean;
}

DiagnosticLoss

Cumulative loss counters.

export interface DiagnosticLoss {
/** Events evicted from history. */
eventsEvicted: DiagnosticCount;
/** Observations accepted without retaining the event. */
eventsOmitted: DiagnosticCount;
/** Closed components evicted with their evidence. */
componentsEvicted: DiagnosticCount;
/** Component registrations rejected by limits. */
componentsRejected: DiagnosticCount;
/** Code registrations rejected by limits. */
keysRejected: DiagnosticCount;
/** Observations rejected before counting. */
observationsRejected: DiagnosticCount;
/** Detail cut to its byte limit. */
messagesTruncated: DiagnosticCount;
/** Detail dropped without evicting an event. */
detailsOmitted: DiagnosticCount;
/** Correlation fields cut to their byte limit. */
correlationsTruncated: DiagnosticCount;
/** Correlation fields dropped for lack of space. */
correlationsOmitted: DiagnosticCount;
/** Metadata registrations rejected by budget. */
metadataRejected: DiagnosticCount;
/** Counted occurrences whose classification was not admitted. */
classificationsOverflowed: DiagnosticCount;
/** Window series rejected by budget. */
windowsRejected: DiagnosticCount;
/** Queries rejected for lack of workspace. */
queriesRejected: DiagnosticCount;
/** Recordings for closed or replaced registrations. */
staleObservations: DiagnosticCount;
/** Projection deliveries dropped for lack of workspace. */
projectionDeliveriesOmitted: DiagnosticCount;
/** Projection callbacks that panicked. */
projectionsPanicked: DiagnosticCount;
/** Projection chains suppressed for cycles or depth. */
projectionsSuppressed: DiagnosticCount;
/** Sequence numbers are exhausted. */
sequenceSaturated: boolean;
}

DiagnosticCapability

One producer integration.

export interface DiagnosticCapability {
/** Capability name, such as `otel`. */
name: string;
/** Availability of this capability's evidence. */
availability: string;
/** Reason, such as `not_integrated`. */
reason: string | null;
}

DiagnosticCoverage

Limits of a snapshot.

export interface DiagnosticCoverage {
/** Availability of this diagnostic source. */
availability: string;
/** Scope of component summaries and windows. */
summaryScope: string;
/** Selected history bounds and query cuts. */
retention: DiagnosticRetention;
/** Cumulative loss counters. */
loss: DiagnosticLoss;
/** Producer integrations and whether each is supported. */
capabilities: Array<DiagnosticCapability>;
}

ComponentSnapshot

One component row.

export interface ComponentSnapshot {
/** Logical name and registration instance. */
identity: ComponentIdentity;
/** Registration time. */
registeredAt: string;
/** Time the registration closed, or `null` while it is open. */
closedAt: string | null;
/** Lifetime totals and elapsed time. */
lifetime: DiagnosticLifetimeSummary;
/** Current refresh period with its owner. */
sinceRefresh: DiagnosticRefreshSummary;
/** Selected lifetime counters by code. */
counters: Array<DiagnosticCounter>;
/** Outcome windows of the component. */
windows: Array<DiagnosticWindow>;
}

DiagnosticSnapshot

One diagnostics page.

export interface DiagnosticSnapshot {
/** Schema version of this snapshot. */
schemaVersion: number;
/** Revision of the code catalogue. */
catalogueVersion: number;
/** Process that produced the snapshot. */
source: SourceIdentity;
/** Capture time at the source. */
capturedAt: string;
/** Latest update revision. */
sequence: bigint;
/** Lifetime totals for the whole context, ignoring selectors. */
lifetime: DiagnosticLifetimeSummary;
/** One row per selected component. */
components: Array<ComponentSnapshot>;
/** Selected recent events. */
events: Array<DiagnosticEvent>;
/** Availability, scope, integration, and loss limits. */
coverage: DiagnosticCoverage;
/** Cursor for the next page, or `null` when there is none. */
continuation: DiagnosticCursor | null;
}

PluginObservationContext

Plugin operation facts.

export interface PluginObservationContext {
/** Execution name, when known. */
execution: string | null;
/** Lifecycle phase or policy gate, when known. */
phase: string | null;
}

DiagnosticDiscovery

Capabilities of the diagnostics core.

export interface DiagnosticDiscovery {
discoveryVersion: number;
snapshotVersion: number;
catalogueVersion: number;
source: SourceIdentity;
collectionEnabled: boolean;
queriesEnabled: boolean;
maxComponents: bigint;
maxEvents: bigint;
detailPoolBytes: bigint;
maxQueries: bigint;
maxSnapshotBytes: bigint;
maxOwnedBytes: bigint;
maxQueryComponents: bigint;
maxQueryEvents: bigint;
memoryInspection: boolean;
restrictedDetail: boolean;
producerSupport: Array<{ name: string; supported: boolean }>;
detailedMemoryInspection: boolean;
resourceCorrelation: boolean;
}

DiagnosticsInfo

export interface DiagnosticsInfo {
discovery: DiagnosticDiscovery;
limits: Record<string, number>;
memory: DiagnosticMemoryUsage;
bindingCopyConcurrency: number;
bindingMaxPageBytes: number;
bindingReservedBytes: number;
loggingCoverage: string;
}

ResourceMemoryUnit

export interface ResourceMemoryUnit {
dimension: 'capacity' | 'duration' | 'count';
name: string;
}

DiagnosticMemoryUsage

Reserved bytes and occupancy gauges.

export interface DiagnosticMemoryUsage {
reservedBytes: bigint;
components: bigint;
counters: bigint;
events: bigint;
eventSlotBytes: bigint;
eventCapacity: bigint;
historyReservedBytes: bigint;
historyOccupiedBytes: bigint;
detailBytes: bigint;
detailCapacityBytes: bigint;
detailReservedBytes: bigint;
detailMetadataBytes: bigint;
detailLogicalBytes: bigint;
detailSlackBytes: bigint;
metadataBytes: bigint;
windowBuckets: bigint;
extensions: bigint;
queryWorkspaces: bigint;
projections: bigint;
projectionWorkspaces: bigint;
}

EntryMemoryFootprint

One event header and its text.

export interface EntryMemoryFootprint {
headerBytes: bigint;
detailPayloadBytes: bigint;
detailMetadataBytes: bigint;
logicalTextBytes: bigint;
detailSlackBytes: bigint;
occupiedBytes: bigint;
}

ComponentMemoryFootprint

Storage owned by one registration, excluding plugin heap.

export interface ComponentMemoryFootprint {
registrationBytes: bigint;
counterBytes: bigint;
windowBytes: bigint;
extensionBytes: bigint;
retainedEventCount: bigint;
retainedEventBytes: bigint;
occupiedBytes: bigint;
}

EntryMemoryUsage

One event and its footprint.

export interface EntryMemoryUsage extends EntryMemoryFootprint {
sequence: bigint;
component: ComponentIdentity;
}

ComponentMemoryUsage

One registration and its footprint.

export interface ComponentMemoryUsage extends ComponentMemoryFootprint {
component: ComponentIdentity;
}

MemorySelectionTotals

Row counts and byte totals.

export interface MemorySelectionTotals {
components: bigint;
events: bigint;
componentOccupiedBytes: bigint;
entryOccupiedBytes: bigint;
}

DiagnosticMemoryPage

One memory page with resource context.

export interface DiagnosticMemoryPage {
schemaVersion: number;
source: SourceIdentity;
capturedAt: string;
sequence: bigint;
aggregate: DiagnosticMemoryUsage;
loss: DiagnosticLoss;
componentOccupiedBytes: bigint;
sharedOrUnassignedReservedBytes: bigint;
selection: MemorySelectionTotals;
page: MemorySelectionTotals;
components: Array<ComponentMemoryUsage>;
entries: Array<EntryMemoryUsage>;
resource: ResourceMemoryView;
continuation: DiagnosticCursor | null;
}

ResourceMemoryMeasurement

Resource value with its number kind, unit, scope, and coverage.

export interface ResourceMemoryMeasurement {
value: ResourceMemoryNumber;
unit: ResourceMemoryUnit;
measurementScope: string;
sampledProcesses: bigint | null;
}

MemoryLimitEvent

One cumulative limit event.

export interface MemoryLimitEvent {
resource: string;
event: string;
count: ResourceMemoryMeasurement | null;
}

ResourceMemoryMetrics

Memory measurements and up to eight limit events.

export interface ResourceMemoryMetrics {
systemUsed: ResourceMemoryMeasurement | null;
systemTotal: ResourceMemoryMeasurement | null;
systemAvailable: ResourceMemoryMeasurement | null;
resident: ResourceMemoryMeasurement | null;
private: ResourceMemoryMeasurement | null;
physicalFootprint: ResourceMemoryMeasurement | null;
virtualMemory: ResourceMemoryMeasurement | null;
peakResident: ResourceMemoryMeasurement | null;
limit: ResourceMemoryMeasurement | null;
environmentAccounted: ResourceMemoryMeasurement | null;
somePressureStallTime: ResourceMemoryMeasurement | null;
fullPressureStallTime: ResourceMemoryMeasurement | null;
outOfMemoryEventCount: ResourceMemoryMeasurement | null;
limitEvents: Array<MemoryLimitEvent | null>;
}

ResourceProcessIdentity

Root process identity checked during collection.

export interface ResourceProcessIdentity {
processId: number;
startIdentity: bigint;
}

ResourceMemorySample

One collection and its memory result.

export interface ResourceMemorySample {
collectorInstanceId: string;
runtimeGeneration: bigint;
targetGeneration: bigint;
stream: string;
ordinal: bigint;
startedAt: string;
completedAt: string;
collectionMillis: bigint;
operatingSystem: string;
measurementScope: string;
root: ResourceProcessIdentity | null;
visibleProcesses: bigint | null;
sampledProcesses: bigint | null;
memory: ResourceMemoryMetrics;
}

ResourceMemoryView

Collection availability, association, and freshness.

export interface ResourceMemoryView {
availability: string;
sample: ResourceMemorySample | null;
association: string;
ageMillis: bigint | null;
stale: boolean;
projectionSlotBytes: bigint;
}

AtofExporterConfig

One tagged sink configuration for AtofExporter.

export interface AtofExporterConfig {
/** Sink type: `"file"` (default) or `"stream"`. */
type?: string
/** Output directory. Defaults to the current working directory. */
outputDirectory?: string
/** `"append"` (default) or `"overwrite"`. */
mode?: string
/** Output filename. Defaults to `nemo-relay-events-YYYY-MM-DD-HH.MM.SS.jsonl`. */
filename?: string
/** Stream endpoint URL. Required when `type` is `"stream"`. */
url?: string
/** `"http_post"` (default), `"websocket"`, or `"ndjson"`. */
transport?: string
/** Extra stream headers as string key/value pairs. */
headers?: Json
/** Header names mapped to environment variables that supply their values. */
headerEnv?: Json
/** Per-stream timeout in milliseconds. */
timeoutMillis?: number
/** Field name policy applied before sending stream events. */
fieldNamePolicy?: string
/** Allow `http://` or `ws://` to any host; events and configured headers travel unencrypted. */
allowInsecure?: boolean
}

DataSchema

Schema identifier attached to an event’s opaque data payload.

export interface DataSchema {
name: string
version: string
}

DiagnosticsQueryContract

export interface DiagnosticsQueryContract {
maxQueryBytes: number
numericQueryFields: Array<string>
}

EventSanitizeFields

Observability fields returned by mark and scope event sanitizers.

export interface EventSanitizeFields {
data?: Json
categoryProfile?: Json
metadata?: Json
}

ExecutionOptions

Choose which middleware stages run for one call. Omitted fields run their stages. Relay still sanitizes event data, uses codecs, and handles call completion. Nested calls use their own options.

export interface ExecutionOptions {
conditionalExecution?: boolean
requestIntercepts?: boolean
executionIntercepts?: boolean
}

MetricMeasurement

One typed recording operation emitted by metric.

export interface MetricMeasurement {
name: string
kind: MetricKind
valueType: MetricValueType
value: number
unit?: string
description?: string
attributes?: Json
boundaries?: Array<number>
}

OpenTelemetryConfig

Mutable configuration object for OpenTelemetrySubscriber.

export interface OpenTelemetryConfig {
/** `"full"`, `"gen_ai"`, or `"openinference"`. */
type: "full" | "gen_ai" | "openinference"
/** `"http_binary"` (default) or `"grpc"`. */
transport?: string
/** OTLP endpoint, such as `http://localhost:4318/v1/traces`. */
endpoint: string
/** TLS certificate and private key file paths for this endpoint. */
tls?: OpenTelemetryTlsConfig
/** Extra exporter headers/metadata as string key/value pairs. */
headers?: Json
/** Header names mapped to environment variables resolved during subscriber activation. */
headerEnv?: Record<string, string>
/** Allow plain HTTP to any host; data and configured headers travel unencrypted. */
allowInsecure?: boolean
/** Extra OpenTelemetry resource attributes as string key/value pairs. */
resourceAttributes?: Json
/** `service.name` resource attribute. Defaults to `"unknown_service"`. */
serviceName?: string
/** Optional `service.namespace` resource attribute. */
serviceNamespace?: string
/** Optional `service.version` resource attribute. */
serviceVersion?: string
/** Instrumentation scope name. Defaults to `"opentelemetry"`. */
instrumentationScope?: string
/** Export timeout in milliseconds. Defaults to `3000`. */
timeoutMillis?: number
/** Completed scope lineage retention in milliseconds as a `bigint`. Defaults to `60000`. */
completedSpanContextTtlMillis?: bigint
/** Mark projection for full and OpenInference exporters. Defaults to `"inherit"`. */
markProjection?: "inherit" | "event" | "tool"
/** Mark names excluded from full and OpenInference projections. */
markExcludeNames?: Array<string>
/** Attribute aliases for full and OpenInference projections. */
attributeMappings?: Json
/** Literal Event metadata prefixes copied to top-level OTLP attributes. */
promoteMetadataPrefixes?: Array<string>
/** Literal root-scope Event metadata prefixes copied to OTLP resource attributes. */
promoteResourceMetadataPrefixes?: Array<string>
}

OpenTelemetryFileSinkConfig

Configuration for a subscriber that writes OTLP to a local file.

Carries no endpoint, transport, headers, or timeout: a file destination has no use for them.

export interface OpenTelemetryFileSinkConfig {
/** `"full"`, `"gen_ai"`, or `"openinference"`. */
type: "full" | "gen_ai" | "openinference"
/** Directory containing the output file. */
outputDirectory: string
/** Output filename. Defaults to a name derived from `format`. */
filename?: string
/** `"json_lines"` (default) or `"proto"`. */
format?: "json_lines" | "proto"
/** `"overwrite"` (default) or `"append"`. */
mode?: "append" | "overwrite"
/** Extra OpenTelemetry resource attributes as string key/value pairs. */
resourceAttributes?: Json
/** `service.name` resource attribute. Defaults to `"unknown_service"`. */
serviceName?: string
/** Optional `service.namespace` resource attribute. */
serviceNamespace?: string
/** Optional `service.version` resource attribute. */
serviceVersion?: string
/** Instrumentation scope name. Defaults to `"opentelemetry"`. */
instrumentationScope?: string
/** Completed scope lineage retention in milliseconds as a `bigint`. Defaults to `60000`. */
completedSpanContextTtlMillis?: bigint
/** Mark projection for full and OpenInference exporters. Defaults to `"inherit"`. */
markProjection?: "inherit" | "event" | "tool"
/** Mark names excluded from full and OpenInference projections. */
markExcludeNames?: Array<string>
/** Attribute aliases for full and OpenInference projections. */
attributeMappings?: Json
/** Literal Event metadata prefixes copied to top-level OTLP attributes. */
promoteMetadataPrefixes?: Array<string>
/** Literal root-scope Event metadata prefixes copied to OTLP resource attributes. */
promoteResourceMetadataPrefixes?: Array<string>
}

OpenTelemetryLogConfig

Configuration object for OpenTelemetryLogSubscriber.

export interface OpenTelemetryLogConfig {
/** OTLP endpoint. Bare HTTP origins append `/v1/logs`. */
endpoint: string
/** TLS certificate and private key file paths for this endpoint. */
tls?: OpenTelemetryTlsConfig
/** `"http_binary"` (default) or `"grpc"`. */
transport?: "http_binary" | "grpc"
/** Extra exporter headers/metadata as string key/value pairs. */
headers?: Record<string, string>
/** Header names mapped to environment variables resolved during subscriber activation. */
headerEnv?: Record<string, string>
/** Allow plain HTTP to any host; data and configured headers travel unencrypted. */
allowInsecure?: boolean
/** Extra OpenTelemetry resource attributes as string key/value pairs. */
resourceAttributes?: Record<string, string>
/** `service.name` resource attribute. Defaults to `"unknown_service"`. */
serviceName?: string
/** Optional `service.namespace` resource attribute. */
serviceNamespace?: string
/** Optional `service.version` resource attribute. */
serviceVersion?: string
/** Instrumentation scope name. Defaults to `"opentelemetry"`. */
instrumentationScope?: string
/** Export timeout in milliseconds. Defaults to `3000`. */
timeoutMillis?: number
/** Minimum severity exported. Defaults to `LogSeverity.Info`. */
minimumSeverity?: LogSeverity
/** Maximum queued log records. Defaults to `2048`. */
maxQueueSize?: number
/** Maximum records per export batch. Defaults to `512`. */
maxExportBatchSize?: number
/** Maximum delay before a partial batch is exported. Defaults to `1000`. */
scheduledDelayMillis?: number
/** Completed scope lineage retention in milliseconds as a `bigint`. Defaults to `60000`. */
completedSpanContextTtlMillis?: bigint
}

OpenTelemetryMetricConfig

Configuration object for OpenTelemetryMetricSubscriber.

export interface OpenTelemetryMetricConfig {
/** OTLP endpoint. Bare HTTP origins append `/v1/metrics`. */
endpoint: string
/** TLS certificate and private key file paths for this endpoint. */
tls?: OpenTelemetryTlsConfig
/** `"http_binary"` (default) or `"grpc"`. */
transport?: "http_binary" | "grpc"
/** Extra exporter headers/metadata as string key/value pairs. */
headers?: Record<string, string>
/** Header names mapped to environment variables resolved during subscriber activation. */
headerEnv?: Record<string, string>
/** Allow plain HTTP to any host; data and configured headers travel unencrypted. */
allowInsecure?: boolean
/** Extra OpenTelemetry resource attributes as string key/value pairs. */
resourceAttributes?: Record<string, string>
/** `service.name` resource attribute. Defaults to `"unknown_service"`. */
serviceName?: string
/** Optional `service.namespace` resource attribute. */
serviceNamespace?: string
/** Optional `service.version` resource attribute. */
serviceVersion?: string
/** Instrumentation scope name. Defaults to `"opentelemetry"`. */
instrumentationScope?: string
/** Export timeout in milliseconds. Defaults to `3000`. */
timeoutMillis?: number
/** Collection interval in milliseconds. Defaults to `60000`. */
exportIntervalMillis?: number
/** Preferred aggregation temporality. Defaults to cumulative. */
temporality?: MetricTemporality
/** Maximum number of retained instrument descriptors. Defaults to `256`. */
maxInstruments?: number
/** Maximum series cardinality per instrument. Defaults to `2000`. */
cardinalityLimit?: number
}

OpenTelemetryTlsConfig

Paths to PEM certificate and private key files for one OTLP endpoint.

export interface OpenTelemetryTlsConfig {
/** CA bundle that replaces the system's trusted CAs. */
certificate?: string
/** Client certificate chain. Also set `privateKey`. */
clientCertificate?: string
/** Client private key. Also set `clientCertificate`. */
privateKey?: string
}

PendingMarkSpec

A mark Relay materializes under a managed lifecycle.

export interface PendingMarkSpec {
name: string
category?: string | null
categoryProfile?: Json
data?: Json
dataSchema?: { name: string; version: string } | null
metadata?: Json
severity?: 'trace' | 'debug' | 'info' | 'warn' | 'warning' | 'error' | null
}

PropagationContext

Transport-neutral Relay causal context for application-managed transport.

export interface PropagationContext {
version: number
rootUuid?: string
parentUuid: string
traceparent?: string
tracestate?: string
}

RuntimeRegistrationIdentity

Structured identity for one global gateable runtime registration.

export interface RuntimeRegistrationIdentity {
kind: RuntimeRegistrationKind
localName: string
effectiveName: string
owner: RuntimeRegistrationOwner
}

RuntimeRegistrationOwner

Discovery metadata describing the owner of a runtime registration.

export interface RuntimeRegistrationOwner {
kind: RuntimeRegistrationOwnerKind
pluginKind?: string
componentOrdinal?: number
}

ScopeStackEntry

Identity of one visible Relay scope.

export interface ScopeStackEntry {
/** Canonical UUID of the scope handle. */
scopeId: string
/** Existing Relay scope category. */
scopeType: ScopeType
}

ScopeStackSnapshot

Detached root-to-top values including implicit and synthetic roots.

export interface ScopeStackSnapshot {
/** Ordered owned entries from one coherent read. */
scopes: Array<ScopeStackEntry>
}

ToolExecutionContext

Per-call context delivered to a tool execution intercept.

toolCallId is the provider-issued correlation identifier recorded on the managed tool call, or null when the call did not record one. It lets an intercept that completes execution without invoking the remaining chain associate its result with the originating tool call.

export interface ToolExecutionContext {
toolName: string
args: Json
toolCallId: string | null
/** Host-supplied invocation-local JSON object; absent is null. Not event metadata or authority. */
executionContext: ApplicationExecutionContext | null
}

ToolExecutionResult

Canonical application-visible result of tool execution.

result is application-owned JSON. annotation is optional opaque adjacent metadata that Relay transports without interpretation.

export interface ToolExecutionResult {
result: Json
annotation?: Json
}

codecs.ContentLocation

Read-time location in a normalized snapshot; not an edit handle or provider-wire offset.

export interface ContentLocation {
readonly root: 'request_message' | 'message' | 'response' | 'content';
readonly messageIndex: number | null;
readonly field: 'content' | 'message' | 'tool_calls' | 'tool_call_item' | 'output' | 'value' | 'native_content' | 'native_refusal' | 'native_tool_calls';
readonly index: number | null;
}

codecs.ToolCallView

Tool invocation backed by selected Rust snapshot storage.

export interface ToolCallView {
readonly id: string | null;
readonly callId: string | null;
readonly name: string;
readonly arguments: PayloadView;
}

codecs.ToolResultView

Complete tool result, excluded from default text extraction.

export interface ToolResultView {
readonly id: string | null;
readonly callId: string | null;
readonly name: string | null;
readonly isError: boolean | null;
readonly payload: PayloadView;
}

codecs.TextEntry

Explicit normalized text or refusal.

export interface TextEntry {
readonly kind: 'text' | 'refusal';
readonly location: ContentLocation;
readonly text: string;
}

codecs.ToolCallEntry

A typed tool-call entry.

export interface ToolCallEntry {
readonly kind: 'tool_call';
readonly location: ContentLocation;
readonly toolCall: ToolCallView;
}

codecs.ToolResultEntry

A typed tool-result entry.

export interface ToolResultEntry {
readonly kind: 'tool_result';
readonly location: ContentLocation;
readonly toolResult: ToolResultView;
}

codecs.MediaEntry

Media retained as an independent JavaScript value when value is accessed.

export interface MediaEntry {
readonly kind: 'image_url' | 'image' | 'audio' | 'file';
readonly location: ContentLocation;
readonly value: JsonValue;
}

codecs.ProviderNativeEntry

Opaque provider-native content; default text permits only supported shallow fallbacks.

export interface ProviderNativeEntry {
readonly kind: 'provider_native';
readonly location: ContentLocation;
readonly provider: string;
readonly nativeKind: string;
readonly value: JsonValue;
}

Classes

LlmRequest

export declare class LlmRequest<THeaders extends JsonObjectCompatible<THeaders> = JsonObject, TContent extends JsonCompatible<TContent> = Json> {
readonly headers: THeaders;
readonly content: TContent;
constructor(headers: THeaders, content: TContent);
}

AdaptiveRuntime

Owned adaptive runtime that can register adaptive features outside the plugin system.

export declare class AdaptiveRuntime {
/**
* Create an adaptive runtime wrapper from config.
*
* The runtime is constructed lazily when `register()` is awaited.
*/
static create<TConfig extends JsonCompatible<TConfig>>(config: TConfig): AdaptiveRuntime
/**
* Register all configured adaptive runtime features.
*
* `register()` and `shutdown()` calls run one at a time in call order.
*/
register(): Promise<void>
/** Deregister all previously registered adaptive runtime features. */
deregister(): void
/** Shut down the adaptive runtime and consume its Rust runtime state. */
shutdown(): Promise<void>
/** Block until the telemetry drain has processed pending events. */
waitForIdle(): void
/** Return the validation report captured during runtime construction. */
report(): ConfigReport
/** Bind the runtime's ACG request rewrite to a scope. */
bindScope(scopeHandle: ScopeHandle): void
/** Build cache request facts for an annotated LLM request. */
buildCacheRequestFacts<TOptions extends JsonCompatible<TOptions>>(options: TOptions): CacheRequestFacts | null
}

AnthropicMessagesCodec

Built-in codec for the Anthropic Messages API.

Implements both request codec (decode/encode) and response codec (decodeResponse). Construct with new AnthropicMessagesCodec().

export declare class AnthropicMessagesCodec {
constructor()
/** Decode an opaque LLM request into structured form. */
decode<TRequest extends LlmRequestCompatible<TRequest>>(request: TRequest): Json
/** Encode structured changes back into an opaque LLM request. */
encode<TAnnotated extends JsonCompatible<TAnnotated>, TOriginal extends LlmRequestCompatible<TOriginal>>(annotated: TAnnotated, original: TOriginal): LlmRequestShape
/** Decode a raw LLM response into structured form. */
decodeResponse<TResponse extends JsonCompatible<TResponse>>(response: TResponse): Json
}

AtifExporter

An Agent Trajectory Interchange Format (ATIF) exporter that collects lifecycle events and exports them as a structured trajectory.

Create an instance with session and agent metadata, then register it as an event subscriber. When ready, call exportJson() to serialize the collected trajectory.

export declare class AtifExporter {
/**
* Create a new ATIF exporter.
*
* `sessionId` identifies the session. `agentName` and `agentVersion` describe the agent.
* Optional `modelName` records the LLM model used.
*/
constructor(sessionId: string, agentName: string, agentVersion: string, modelName?: string | undefined | null)
/**
* Register this exporter as an event subscriber with the given name.
*
* Throws if a subscriber with the same `name` already exists.
*/
register(name: string): void
/**
* Deregister this exporter's event subscriber by name.
*
* Returns `true` if a subscriber with that name was found and removed.
*/
deregister(name: string): boolean
/**
* Export the collected trajectory as a JSON string.
*
* Returns a JSON-serialized `AtifTrajectory`.
*/
exportJson(): string
/** Clear all collected events from the exporter. */
clear(): void
}

AtofExporter

Single-sink Agent Trajectory Observability Format (ATOF) exporter.

export declare class AtofExporter {
/**
* Create a new Agent Trajectory Observability Format (ATOF) JSONL exporter
* from a config object.
*/
constructor(config?: AtofExporterConfig | undefined | null)
/** Return the JSONL output path, or `null` for a stream sink. */
get path(): string | null
/** Register this exporter globally with the given name. */
register(name: string): void
/** Deregister a subscriber by name. */
deregister(name: string): boolean
/**
* Outside subscriber and middleware callbacks, wait for queued subscriber delivery, then
* flush the file sink or ask the stream sink to drain for up to its timeout. A stream timeout
* is logged and does not by itself return an error.
*/
forceFlush(): void
/**
* Outside subscriber and middleware callbacks, wait for queued subscriber delivery, then
* flush the file sink or ask the stream sink to drain and close up to its timeout. A stream
* timeout is logged and does not by itself return an error.
*/
shutdown(): void
/** Return delivery diagnostics recorded by this exporter's stream sink. */
runtimeDiagnostics(): Array<{ code: string; message: string; count: number }>
}

DiagnosticsReader

Authority to inspect restricted diagnostic evidence in the current process.

export declare class DiagnosticsReader {
/** Return canonical snake_case JSON with decimal-string diagnostic integers. */
snapshotJson(queryJson?: string | undefined | null): string
/**
* Return a caller-owned camelCase object. Diagnostic u64 fields are always bigint.
* Use snapshotJson for portable serialization; JSON.stringify cannot encode bigint.
*/
snapshot(queryJson?: string | undefined | null): DiagnosticSnapshot
/** Return canonical snake_case JSON with decimal-string diagnostic integers. */
inspectMemoryJson(queryJson?: string | undefined | null): string
/**
* Return a caller-owned camelCase object. Diagnostic u64 fields are always bigint.
* Use inspectMemoryJson for portable serialization; JSON.stringify cannot encode bigint.
*/
inspectMemory(queryJson?: string | undefined | null): DiagnosticMemoryPage
/** Return independent core/adapter budgets, occupancy, and logging coverage. */
info(): DiagnosticsInfo
}

GeminiGenerateContentCodec

Built-in codec for the Gemini generateContent API.

Implements both request codec (decode/encode) and response codec (decodeResponse). Construct with new GeminiGenerateContentCodec().

export declare class GeminiGenerateContentCodec {
constructor()
/** Decode an opaque LLM request into structured form. */
decode<TRequest extends LlmRequestCompatible<TRequest>>(request: TRequest): Json
/** Encode structured changes back into an opaque LLM request. */
encode<TAnnotated extends JsonCompatible<TAnnotated>, TOriginal extends LlmRequestCompatible<TOriginal>>(annotated: TAnnotated, original: TOriginal): LlmRequestShape
/**
* Decode a raw LLM response into structured form.
* Throws a TypeError if the response contains a BigInt value.
*/
decodeResponse<TResponse extends JsonCompatible<TResponse>>(response: TResponse): Json
}

LlmHandle

A handle representing an in-progress LLM call.

Returned by llmCall() and used to signal completion via llmCallEnd().

export declare class LlmHandle {
/** The unique identifier for this LLM call. */
get uuid(): string
/** The name of the LLM provider being called. */
get name(): string
/** Bitfield of LLM attributes (e.g., STATELESS, STREAMING). */
get attributes(): number
/** The UUID of the parent scope that initiated this LLM call, or `null`. */
get parentUuid(): string | null
}

LlmStream

An async iterator over chunks from a streaming LLM response.

Obtained from llmStreamCallExecute(). Call next() repeatedly to consume response chunks. Returns null when the stream is fully consumed.

export declare class LlmStream {
/**
* Retrieve the next chunk from the stream.
*
* Returns the next JSON chunk, or `null` when the stream is exhausted.
* Throws if the underlying stream encountered an error.
*/
next(): Promise<Json | null>
/**
* Stop the producer and wait for its cleanup to complete.
*
* Throws a stream error that `next()` has not yet thrown, then a cleanup
* error, then a finalizer failure. A cleanup failure after a stream error
* is logged. Further calls return the same result.
*/
close(): Promise<void>
}

OCIGenAIChatCodec

Built-in codec for the OCI Generative AI chat API.

Implements both request codec (decode/encode) and response codec (decodeResponse). Construct with new OCIGenAIChatCodec().

export declare class OCIGenAIChatCodec {
constructor()
/** Decode an opaque LLM request into structured form. */
decode<TRequest extends LlmRequestCompatible<TRequest>>(request: TRequest): Json
/** Encode structured changes back into an opaque LLM request. */
encode<TAnnotated extends JsonCompatible<TAnnotated>, TOriginal extends LlmRequestCompatible<TOriginal>>(annotated: TAnnotated, original: TOriginal): LlmRequestShape
/** Decode a raw LLM response into structured form. */
decodeResponse<TResponse extends JsonCompatible<TResponse>>(response: TResponse): Json
}

OpenAIChatCodec

Built-in codec for the OpenAI Chat Completions API.

Implements both request codec (decode/encode) and response codec (decodeResponse). Construct with new OpenAIChatCodec().

export declare class OpenAIChatCodec {
constructor()
/** Decode an opaque LLM request into structured form. */
decode<TRequest extends LlmRequestCompatible<TRequest>>(request: TRequest): Json
/** Encode structured changes back into an opaque LLM request. */
encode<TAnnotated extends JsonCompatible<TAnnotated>, TOriginal extends LlmRequestCompatible<TOriginal>>(annotated: TAnnotated, original: TOriginal): LlmRequestShape
/** Decode a raw LLM response into structured form. */
decodeResponse<TResponse extends JsonCompatible<TResponse>>(response: TResponse): Json
}

OpenAIResponsesCodec

Built-in codec for the OpenAI Responses API.

Implements both request codec (decode/encode) and response codec (decodeResponse). Construct with new OpenAIResponsesCodec().

export declare class OpenAIResponsesCodec {
constructor()
/** Decode an opaque LLM request into structured form. */
decode<TRequest extends LlmRequestCompatible<TRequest>>(request: TRequest): Json
/** Encode structured changes back into an opaque LLM request. */
encode<TAnnotated extends JsonCompatible<TAnnotated>, TOriginal extends LlmRequestCompatible<TOriginal>>(annotated: TAnnotated, original: TOriginal): LlmRequestShape
/** Decode a raw LLM response into structured form. */
decodeResponse<TResponse extends JsonCompatible<TResponse>>(response: TResponse): Json
}

OpenTelemetryLogSubscriber

Subscriber that exports severity-tagged marks through OTLP logs.

export declare class OpenTelemetryLogSubscriber {
/** Create a log subscriber from a config object. */
constructor(config: OpenTelemetryLogConfig)
/** Register this subscriber globally with the given name. */
register(name: string): void
/** Deregister a subscriber by name. */
deregister(name: string): boolean
/**
* Flush queued Relay events and the OTLP log processor.
*
* A successful flush updates `runtimeDiagnostics()` with queue drops observed so far.
*/
forceFlush(): void
/** Return bounded runtime diagnostics recorded by this subscriber. */
runtimeDiagnostics(): Array<{ code: string; message: string; count: number }>
/** Shut down the underlying logger provider. */
shutdown(): void
}

OpenTelemetryMetricSubscriber

Subscriber that records metric marks and exports them through OTLP metrics.

export declare class OpenTelemetryMetricSubscriber {
/** Create a metric subscriber from a config object. */
constructor(config: OpenTelemetryMetricConfig)
/** Register this subscriber globally with the given name. */
register(name: string): void
/** Deregister a subscriber by name. */
deregister(name: string): boolean
/** Collect and export current metric aggregates immediately. */
forceFlush(): void
/** Return bounded runtime diagnostics recorded by this subscriber. */
runtimeDiagnostics(): Array<{ code: string; message: string; count: number }>
/** Shut down the underlying meter provider. */
shutdown(): void
}

OpenTelemetrySubscriber

OpenTelemetry-backed event subscriber.

export declare class OpenTelemetrySubscriber {
/** Create a new OpenTelemetry subscriber from a config object. */
constructor(config: OpenTelemetryConfig)
/** Create a subscriber that writes OTLP to a local file. */
static fileSink(config: OpenTelemetryFileSinkConfig): OpenTelemetrySubscriber
/** Register this subscriber globally with the given name. */
register(name: string): void
/** Deregister a subscriber by name. */
deregister(name: string): boolean
/**
* Force a flush of finished spans through the exporter.
*
* A successful flush updates `runtimeDiagnostics()` with queue drops observed so far.
*/
forceFlush(): void
/** Return bounded runtime diagnostics recorded by this subscriber. */
runtimeDiagnostics(): Array<{ code: string; message: string; count: number }>
/** Shut down the underlying tracer provider. */
shutdown(): void
}

PluginHostActivation

Owned dynamic plugin activation.

Keep this object alive while code may invoke callbacks registered by the dynamic plugins. Call close() for deterministic cleanup; garbage collection performs the same cleanup as a defensive fallback.

export declare class PluginHostActivation {
/** Return the validation report produced by activation. */
get report(): PluginHostReport
/**
* Return whether this activation handle has not begun teardown.
*
* Failed teardown leaves the activation active so `close()` can retry.
*/
get isActive(): boolean
/**
* Clear plugin callbacks before unloading libraries and workers.
*
* This method is idempotent, including when concurrent callers race to
* close the same activation.
*/
close(): Promise<void>
/** Delegate structured `await using` cleanup to `close()`. */
[globalThis.Symbol.asyncDispose](): Promise<void>
}

ScopeHandle

A handle to an execution scope in the agent runtime.

Scopes form a hierarchical stack representing the current execution context (e.g., agent -> function -> tool). Use this handle to reference a specific scope when pushing child scopes, emitting events, or making tool/LLM calls.

export declare class ScopeHandle {
/** The unique identifier for this scope. */
get uuid(): string
/** The human-readable name of this scope. */
get name(): string
/** The type of this scope (Agent, Tool, Llm, etc.). */
get scopeType(): ScopeType
/** Bitfield of scope attributes (e.g., PARALLEL, RELOCATABLE). */
get attributes(): number
/** The UUID of this scope's parent, or `null` if this is the root scope. */
get parentUuid(): string | null
/** Optional user-defined data associated with this scope. */
get data(): Json | null
/** Optional metadata associated with this scope. */
get metadata(): Json | null
}

ScopeStack

Handle to an isolated scope stack for per-request/per-task isolation.

export declare class ScopeStack {
/** Creates a new isolated scope stack with its own root scope. */
constructor()
}

ToolHandle

A handle representing an in-progress tool call.

Returned by toolCall() and used to signal completion via toolCallEnd().

export declare class ToolHandle {
/** The unique identifier for this tool call. */
get uuid(): string
/** The name of the tool being called. */
get name(): string
/** Bitfield of tool attributes (e.g., LOCAL). */
get attributes(): number
/** The UUID of the parent scope that initiated this tool call, or `null`. */
get parentUuid(): string | null
}

codecs.MessageView

Read-only Rust-owned snapshot. Iterators, entries, and payload views retain selected storage.

export declare class MessageView {
#private;
private constructor();
/** Snapshot a normalized message, preserving its role and tool-result semantics. */
static fromMessage<T extends JsonCompatible<T>>(value: T): MessageView;
/** Snapshot standalone normalized content: a string or content-part array. */
static fromContent<T extends JsonCompatible<T>>(value: T): MessageView;
/** Iterate typed parts in normalized order, followed by separate tool-call fields. */
parts(): IterableIterator<ContentEntry>;
/** Iterate text/refusal strings, including supported native fallbacks and excluding tool payloads. */
textParts(): IterableIterator<string>;
/** Return null for absent text; otherwise preserve whitespace and newline-join empty/text/refusal parts. */
text(): string | null;
/** @internal Read direct selections in place and delegate role matching to Rust. */
static _selectRequest(request: unknown, selection: string, index?: number): MessageView | null;
/** @internal Snapshot current output without retaining unrelated response metadata. */
static _output(value: JsonValue): MessageView;
}

Enums

BandwidthUnit

Units for bandwidth measurements.

export declare enum BandwidthUnit {
/** Bytes per second. */
BytesPerSecond = 'bytes_per_second',
/** Kibibytes per second. */
KibibytesPerSecond = 'kibibytes_per_second',
/** Mebibytes per second. */
MebibytesPerSecond = 'mebibytes_per_second',
/** Gibibytes per second. */
GibibytesPerSecond = 'gibibytes_per_second',
/** Bits per second. */
BitsPerSecond = 'bits_per_second',
/** Megabits per second. */
MegabitsPerSecond = 'megabits_per_second',
/** Gigabits per second. */
GigabitsPerSecond = 'gigabits_per_second',
}

CapacityUnit

Units for capacity measurements.

export declare enum CapacityUnit {
/** Bytes. */
Bytes = 'bytes',
/** Kilobytes. */
Kilobytes = 'kilobytes',
/** Megabytes. */
Megabytes = 'megabytes',
/** Gigabytes. */
Gigabytes = 'gigabytes',
/** Terabytes. */
Terabytes = 'terabytes',
/** Kibibytes. */
Kibibytes = 'kibibytes',
/** Mebibytes. */
Mebibytes = 'mebibytes',
/** Gibibytes. */
Gibibytes = 'gibibytes',
/** Tebibytes. */
Tebibytes = 'tebibytes',
}

CountUnit

Units for count measurements.

export declare enum CountUnit {
/** Processes. */
Processes = 'processes',
/** Threads. */
Threads = 'threads',
/** File descriptors. */
FileDescriptors = 'file_descriptors',
/** Handles. */
Handles = 'handles',
/** Events. */
Events = 'events',
/** Operations. */
Operations = 'operations',
/** Packets. */
Packets = 'packets',
/** Errors. */
Errors = 'errors',
}

CpuUnit

Units for CPU measurements.

export declare enum CpuUnit {
/** Logical processors. */
LogicalProcessors = 'logical_processors',
/** Millicores. */
Millicores = 'millicores',
}

DataUnit

Units for data measurements.

export declare enum DataUnit {
/** Bytes. */
Bytes = 'bytes',
/** Kilobytes. */
Kilobytes = 'kilobytes',
/** Megabytes. */
Megabytes = 'megabytes',
/** Gigabytes. */
Gigabytes = 'gigabytes',
/** Terabytes. */
Terabytes = 'terabytes',
/** Kibibytes. */
Kibibytes = 'kibibytes',
/** Mebibytes. */
Mebibytes = 'mebibytes',
/** Gibibytes. */
Gibibytes = 'gibibytes',
/** Tebibytes. */
Tebibytes = 'tebibytes',
}

DurationUnit

Units for duration measurements.

export declare enum DurationUnit {
/** Microseconds. */
Microseconds = 'microseconds',
/** Milliseconds. */
Milliseconds = 'milliseconds',
/** Seconds. */
Seconds = 'seconds',
/** Minutes. */
Minutes = 'minutes',
}

LogSeverity

Severity attached to a mark projected as an OpenTelemetry log.

export declare enum LogSeverity {
Trace = 0,
Debug = 1,
Info = 2,
Warn = 3,
Error = 4,
}

MetricKind

OpenTelemetry instrument kind recorded by a metric measurement.

export declare enum MetricKind {
Counter = 0,
UpDownCounter = 1,
Gauge = 2,
Histogram = 3,
}

MetricTemporality

Preferred aggregation temporality for OTLP metric export.

export declare enum MetricTemporality {
Cumulative = 0,
Delta = 1,
LowMemory = 2,
}

MetricValueType

Explicit numeric representation used by a metric measurement.

export declare enum MetricValueType {
U64 = 0,
I64 = 1,
F64 = 2,
}

RuntimeRegistrationKind

A global runtime registration surface that a conditional middleware guardrail can select.

export declare enum RuntimeRegistrationKind {
Subscriber = 'subscriber',
EventMetadataInjector = 'event_metadata_injector',
MarkSanitizeGuardrail = 'mark_sanitize_guardrail',
ScopeSanitizeStartGuardrail = 'scope_sanitize_start_guardrail',
ScopeSanitizeEndGuardrail = 'scope_sanitize_end_guardrail',
ToolSanitizeRequestGuardrail = 'tool_sanitize_request_guardrail',
ToolSanitizeResponseGuardrail = 'tool_sanitize_response_guardrail',
ToolConditionalExecutionGuardrail = 'tool_conditional_execution_guardrail',
ToolRequestIntercept = 'tool_request_intercept',
ToolExecutionIntercept = 'tool_execution_intercept',
LlmSanitizeRequestGuardrail = 'llm_sanitize_request_guardrail',
LlmSanitizeResponseGuardrail = 'llm_sanitize_response_guardrail',
LlmConditionalExecutionGuardrail = 'llm_conditional_execution_guardrail',
LlmRequestIntercept = 'llm_request_intercept',
LlmExecutionIntercept = 'llm_execution_intercept',
LlmStreamExecutionIntercept = 'llm_stream_execution_intercept',
}

RuntimeRegistrationOwnerKind

The owner category reported for a global runtime registration.

export declare enum RuntimeRegistrationOwnerKind {
Core = 'core',
GlobalApi = 'global_api',
Plugin = 'plugin',
}

ScopeType

The type of an execution scope in the agent runtime hierarchy.

export declare enum ScopeType {
/** An autonomous agent scope. */
Agent = 0,
/** A generic function invocation scope. */
Function = 1,
/** A tool execution scope. */
Tool = 2,
/** A large language model call scope. */
Llm = 3,
/** A retriever (vector search / RAG) scope. */
Retriever = 4,
/** An embedding model scope. */
Embedder = 5,
/** A reranker model scope. */
Reranker = 6,
/** A guardrail evaluation scope. */
Guardrail = 7,
/** An evaluator / scoring scope. */
Evaluator = 8,
/** A user-defined custom scope type. */
Custom = 9,
/** An unknown or unclassified scope type. */
Unknown = 10,
}

UtilizationUnit

Units for utilization measurements.

export declare enum UtilizationUnit {
/** Percentage. */
Percentage = 'percentage',
/** Fraction. */
Fraction = 'fraction',
}

Functions

buildCacheTelemetryEvent

Build one adaptive cache telemetry event from normalized usage.

export declare function buildCacheTelemetryEvent<TOptions extends JsonCompatible<TOptions>>(options: TOptions): CacheTelemetryEvent | null

capturePropagationContext

Capture the current Relay causal parent for application-managed transport.

export declare function capturePropagationContext(): PropagationContext

capturePropagationContextWithRoot

Capture the current parent with an optional stable application session root.

export declare function capturePropagationContextWithRoot(rootUuid?: string | undefined | null): PropagationContext

captureRootlessPropagationContext

Capture the current Relay causal parent without a propagation root.

export declare function captureRootlessPropagationContext(): PropagationContext

captureTraceparent

Capture the current Relay context as a W3C traceparent value.

export declare function captureTraceparent(): string

clearLastCallbackError

Clears the most recent callback error recorded by the Node binding.

export declare function clearLastCallbackError(): void

collectResourceMetrics

Acquire a fresh resource metrics snapshot without requiring polling. Collection runs outside the JavaScript event loop.

export declare function collectResourceMetrics(): Promise<ResourceMetricsSnapshot>

createScopeStack

Creates a new isolated scope stack.

export declare function createScopeStack(): ScopeStack

createScopeStackFromPropagation

Create an isolated scope stack seeded from a received propagation context.

export declare function createScopeStackFromPropagation(context: PropagationContext): ScopeStack

currentScopeStack

Returns the current execution context’s scope stack handle.

export declare function currentScopeStack(): ScopeStack

currentScopeStackSnapshot

Return owned scope identities, or null without an explicitly active binding.

export declare function currentScopeStackSnapshot(): ScopeStackSnapshot | null

debug

Emit a debug-level operational log record through Relay’s configured sinks.

export declare function debug<TFields extends JsonObjectCompatible<TFields> = JsonObject>(message: string, target?: string | undefined | null, fields?: TFields | null): void

deregisterConditionalMiddlewareGuardrail

Deregister a global runtime-registration eligibility gate by name.

export declare function deregisterConditionalMiddlewareGuardrail(name: string): boolean

deregisterEventMetadataInjector

Deregister a global event metadata injector by name.

export declare function deregisterEventMetadataInjector(name: string): boolean

deregisterLlmConditionalExecutionGuardrail

Deregister an LLM conditional execution guardrail by name.

Returns true if a guardrail with that name was found and removed.

export declare function deregisterLlmConditionalExecutionGuardrail(name: string): boolean

deregisterLlmExecutionIntercept

Deregister an LLM execution intercept by name.

Returns true if an intercept with that name was found and removed.

export declare function deregisterLlmExecutionIntercept(name: string): boolean

deregisterLlmRequestIntercept

Deregister an LLM request intercept by name.

Returns true if an intercept with that name was found and removed.

export declare function deregisterLlmRequestIntercept(name: string): boolean

deregisterLlmSanitizeRequestGuardrail

Deregister an LLM request sanitization guardrail by name.

Returns true if a guardrail with that name was found and removed.

export declare function deregisterLlmSanitizeRequestGuardrail(name: string): boolean

deregisterLlmSanitizeResponseGuardrail

Deregister an LLM response sanitization guardrail by name.

Returns true if a guardrail with that name was found and removed.

export declare function deregisterLlmSanitizeResponseGuardrail(name: string): boolean

deregisterLlmStreamExecutionIntercept

Deregister an LLM stream execution intercept by name.

Returns true if an intercept with that name was found and removed.

export declare function deregisterLlmStreamExecutionIntercept(name: string): boolean

deregisterMarkSanitizeGuardrail

export declare function deregisterMarkSanitizeGuardrail(name: string): boolean

deregisterPlugin

Deregister a plugin by kind.

export declare function deregisterPlugin(pluginKind: string): boolean

deregisterScopeSanitizeEndGuardrail

export declare function deregisterScopeSanitizeEndGuardrail(name: string): boolean

deregisterScopeSanitizeStartGuardrail

export declare function deregisterScopeSanitizeStartGuardrail(name: string): boolean

deregisterSubscriber

Deregister an event subscriber by name.

Future emissions stop seeing the subscriber. Already queued event snapshots may still run. Returns true if a subscriber with that name was found and removed.

export declare function deregisterSubscriber(name: string): boolean

deregisterToolConditionalExecutionGuardrail

Deregister a tool conditional execution guardrail by name.

Returns true if a guardrail with that name was found and removed.

export declare function deregisterToolConditionalExecutionGuardrail(name: string): boolean

deregisterToolExecutionIntercept

Deregister a tool execution intercept by name.

Removes an intercept registered through either registration shape. Returns true if an intercept with that name was found and removed.

export declare function deregisterToolExecutionIntercept(name: string): boolean

deregisterToolRequestIntercept

Deregister a tool request intercept by name.

Returns true if an intercept with that name was found and removed.

export declare function deregisterToolRequestIntercept(name: string): boolean

deregisterToolSanitizeRequestGuardrail

Deregister a tool request sanitization guardrail by name.

Returns true if a guardrail with that name was found and removed.

export declare function deregisterToolSanitizeRequestGuardrail(name: string): boolean

deregisterToolSanitizeResponseGuardrail

Deregister a tool response sanitization guardrail by name.

Returns true if a guardrail with that name was found and removed.

export declare function deregisterToolSanitizeResponseGuardrail(name: string): boolean

diagnosticsReader

Inspect the configured service without starting it. Errors use a stable reason message.

export declare function diagnosticsReader(): DiagnosticsReader

error

Emit an error-level operational log record through Relay’s configured sinks.

export declare function error<TFields extends JsonObjectCompatible<TFields> = JsonObject>(message: string, target?: string | undefined | null, fields?: TFields | null): void

event

Emit a custom mark event on the current scope.

Emits a named event with optional data and metadata payloads. If handle is provided, the event is associated with that scope; otherwise it uses the current top scope. Optional timestamp is a Unix timestamp in microseconds recorded on the mark event. It must be a safe integer number; omit it to use the current runtime time. Optional dataSchema identifies the shape of data; severity supplies the typed severity used by OpenTelemetry log exporters.

export declare function event<TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json>(name: string, handle?: ScopeHandle | undefined | null, data?: TData | null, metadata?: TMetadata | null, timestamp?: number | undefined | null, dataSchema?: DataSchema | undefined | null, severity?: LogSeverity | undefined | null): void

flushSubscribers

Return a Promise that resolves when native and JavaScript subscriber callbacks and managed terminal publications registered before this call finish.

Call this function outside subscribers, event sanitizers, conditional guardrails, and request or execution intercepts. A queued tool or LLM observability sanitizer may call it, but the Promise resolves without waiting for its own publication.

Awaiting this Promise does not block the Node event loop while Promise-returning event sanitizers settle or queued JavaScript subscriber callbacks run. Native events emitted by a JavaScript subscriber are separate publications and may require another flush.

The Promise rejects if the blocking task fails or the core subscriber flush returns an error. Callers should handle errors when awaiting it.

export declare function flushSubscribers(): Promise<void>

forkScopeStack

Copy the active Relay scope stack without changing the caller’s binding.

Preserves scope UUIDs/types, scope-local registrations, and managed event, trace, and publication context. Use one fork per concurrent operation with withScopeStack, and finish the operation before its inherited scopes close.

export declare function forkScopeStack(): ScopeStack

getHandle

Get the handle for the current top-of-stack execution scope.

Returns the ScopeHandle for the innermost active scope on the current task’s scope stack. Throws if the scope stack is empty.

export declare function getHandle(): ScopeHandle

getLastCallbackError

Returns the most recent callback error that could not be surfaced through a direct exception.

This is primarily used for sanitize callback paths that omit observability payloads and cannot surface their errors directly.

export declare function getLastCallbackError(): string | null

info

Emit an info-level operational log record through Relay’s configured sinks.

export declare function info<TFields extends JsonObjectCompatible<TFields> = JsonObject>(message: string, target?: string | undefined | null, fields?: TFields | null): void

initialize

Initialize the core-owned static and dynamic plugin host from layered files.

export declare function initialize<TConfig extends JsonCompatible<TConfig>>(config: TConfig, additionalPluginsToml?: string | undefined | null): Promise<PluginHostActivation>

listPluginKinds

List registered plugin kinds.

export declare function listPluginKinds(): Array<string>

listRuntimeRegistrations

List global gateable runtime registrations.

export declare function listRuntimeRegistrations<K extends RuntimeRegistrationKind | RuntimeRegistrationKindName = RuntimeRegistrationKind>(kinds?: Array<K> | undefined | null): Array<RuntimeRegistrationIdentity & { kind: K extends RuntimeRegistrationKind ? K : Extract<RuntimeRegistrationKind, K> }>

llmCall

Begin a manual LLM call lifecycle span.

Registers an LLM invocation with the given provider name and request payload. The request should be a JSON object with headers and content fields matching the LlmRequest schema. Returns an LlmHandle that must be passed to llmCallEnd() when the response is received. Sanitize-request guardrails are applied to the emitted start-event payload; request and execution intercepts run only through llmCallExecute. Optional handle specifies the parent scope; attributes is a bitfield; data is stored on the handle; metadata is recorded on the start event; and modelName is recorded in the LLM event category profile. Optional timestamp is a Unix timestamp in microseconds recorded as the handle start time and start event timestamp. It must be a safe integer number; omit it to use the current runtime time. Optional codecDecode and codecEncode callbacks help sanitize and annotate the telemetry copy. Supply both callbacks together. The caller’s request stays unchanged. codecEncode receives an object with annotated and original fields. If codecDecode throws or returns an invalid value, Relay skips the annotation, still publishes the event, and records the error for getLastCallbackError().

export declare function llmCall<TRequest extends LlmRequestCompatible<TRequest>, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json, TAnnotated extends JsonCompatible<TAnnotated> = Json, TEncoded extends LlmRequestCompatible<TEncoded> = LlmRequestShape>(name: string, request: TRequest, handle?: ScopeHandle | undefined | null, attributes?: number | undefined | null, data?: TData | null, metadata?: TMetadata | null, modelName?: string | undefined | null, timestamp?: number | undefined | null, codecDecode?: (request: LlmRequestShape) => TAnnotated, codecEncode?: (arg: { annotated: Json; original: LlmRequestShape }) => TEncoded): LlmHandle

llmCallEnd

End a manual LLM call lifecycle span.

Signals that the LLM call identified by handle has completed with the given response. Sanitize-response guardrails are applied to the emitted end-event payload; response intercepts run only through llmCallExecute. Optional data is used when the sanitized response is JSON null, and optional metadata is recorded on the end event. Optional timestamp is a Unix timestamp in microseconds recorded on the end event. It must be a safe integer number; omit it to use the runtime default end timestamp.

export declare function llmCallEnd<TResponse extends JsonCompatible<TResponse>, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json>(handle: LlmHandle, response: TResponse, data?: TData | null, metadata?: TMetadata | null, timestamp?: number | undefined | null): void

llmCallExecute

Execute an LLM call end-to-end with full lifecycle management.

By default, this call runs these stages:

  1. Check conditional-execution guardrails on the original input. 2. Apply request intercepts. 3. Sanitize the request copy in the Start event. 4. Run execution intercepts around func. 5. Sanitize the response copy in the End event.

If a guardrail rejects the call, Relay emits a standalone Mark event. It does not emit a Start/End pair. The call returns GuardrailRejected. Sanitizers change event data. They do not change the result returned to the caller. Pass a JSON object with headers and content fields in request. Supply codecDecode and codecEncode together or omit both. Use executionOptions to choose which stages run for this call. Optional executionContext passes application data to execution intercepts for this call. The data stays separate from provider input and event metadata.

export declare function llmCallExecute<TRequest extends LlmRequestCompatible<TRequest>, TResponse extends JsonCompatible<TResponse>, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json, TAnnotated extends JsonCompatible<TAnnotated> = Json, TEncoded extends LlmRequestCompatible<TEncoded> = LlmRequestShape, TDecodedResponse extends JsonCompatible<TDecodedResponse> = Json>(name: string, request: TRequest, func: (request: LlmRequestShape) => TResponse, handle?: ScopeHandle | undefined | null, attributes?: number | undefined | null, data?: TData | null, metadata?: TMetadata | null, modelName?: string | undefined | null, codecDecode?: (request: LlmRequestShape) => TAnnotated, codecEncode?: (arg: { annotated: Json; original: LlmRequestShape }) => TEncoded, responseCodecDecode?: (response: Json) => TDecodedResponse, executionOptions?: ExecutionOptions | undefined | null, executionContext?: LlmApplicationExecutionContext | null): Promise<Json>

llmCallExecuteAsync

Execute an LLM call end-to-end with a callback that returns a value or a Promise.

Runs the same lifecycle as llmCallExecute. Supply codecDecode and codecEncode together or omit both. Use executionOptions to choose which stages run for this call. Optional executionContext passes application data to execution intercepts for this call. The data stays separate from provider input and event metadata.

export declare function llmCallExecuteAsync<TRequest extends LlmRequestCompatible<TRequest>, TResponse extends JsonCompatible<TResponse>, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json, TAnnotated extends JsonCompatible<TAnnotated> = Json, TEncoded extends LlmRequestCompatible<TEncoded> = LlmRequestShape, TDecodedResponse extends JsonCompatible<TDecodedResponse> = Json>(name: string, request: TRequest, func: (request: LlmRequestShape, signal: AbortSignal) => TResponse | Promise<TResponse>, handle?: ScopeHandle | undefined | null, attributes?: number | undefined | null, data?: TData | null, metadata?: TMetadata | null, modelName?: string | undefined | null, codecDecode?: (request: LlmRequestShape) => TAnnotated, codecEncode?: (arg: { annotated: Json; original: LlmRequestShape }) => TEncoded, responseCodecDecode?: (response: Json) => TDecodedResponse, executionOptions?: ExecutionOptions | undefined | null, executionContext?: LlmApplicationExecutionContext | null): Promise<Json>

llmConditionalExecution

Run the registered LLM conditional execution guardrail chain. Throws if any guardrail rejects. The request should be a JSON object with headers and content fields matching the LlmRequest schema.

export declare function llmConditionalExecution<TRequest extends LlmRequestCompatible<TRequest>>(request: TRequest): Promise<void>

llmRequestIntercepts

Run the registered LLM request intercept chain on the given request. The request should be a JSON object with headers and content fields matching the LlmRequest schema. Returns the transformed request as JSON.

export declare function llmRequestIntercepts<TRequest extends LlmRequestCompatible<TRequest>>(name: string, request: TRequest): Promise<LlmRequestInterceptOutcome>

llmStreamCallExecute

Execute a streaming LLM call end-to-end with full lifecycle management.

By default, conditional-execution guardrails run first on the raw request. Sanitize-request guardrails only affect the emitted Start event payload, and sanitize-response guardrails only affect the aggregated End event payload. Returns an LlmStream whose next() method yields response chunks incrementally. The func callback receives the intercepted request as JSON and an AbortSignal, and returns an AsyncIterable of JSON chunks. Stream-level intercepts are applied to each chunk. The request should be a JSON object with headers and content fields matching the LlmRequest schema.

The optional collector callback is invoked with each intercepted chunk as JSON, allowing the caller to accumulate chunks for aggregation. The optional finalizer callback is invoked once when the stream is exhausted or closed early and must return a JSON value representing the aggregated response. Both may return a Promise. If the collector throws or rejects, the stream fails with that error. If the finalizer throws or rejects, the aggregated response is null. Consumers that stop reading early must await stream.close(), which aborts the signal and waits for producer cleanup. Supply codecDecode and codecEncode together or omit both. Use executionOptions to choose which stages run for this call. Optional executionContext passes application data to execution intercepts for this call. The data stays separate from provider input and event metadata.

export declare function llmStreamCallExecute<TRequest extends LlmRequestCompatible<TRequest>, TChunk extends JsonCompatible<TChunk>, TAggregate extends JsonCompatible<TAggregate> = Json, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json, TAnnotated extends JsonCompatible<TAnnotated> = Json, TEncoded extends LlmRequestCompatible<TEncoded> = LlmRequestShape, TDecodedResponse extends JsonCompatible<TDecodedResponse> = Json>(name: string, request: TRequest, func: (request: LlmRequestShape, signal: AbortSignal) => AsyncIterable<TChunk> | Promise<AsyncIterable<TChunk>>, collector?: (chunk: Json) => void | Promise<void>, finalizer?: () => TAggregate | Promise<TAggregate>, handle?: ScopeHandle | undefined | null, attributes?: number | undefined | null, data?: TData | null, metadata?: TMetadata | null, modelName?: string | undefined | null, codecDecode?: (request: LlmRequestShape) => TAnnotated, codecEncode?: (arg: { annotated: Json; original: LlmRequestShape }) => TEncoded, responseCodecDecode?: (response: Json) => TDecodedResponse, executionOptions?: ExecutionOptions | undefined | null, executionContext?: LlmApplicationExecutionContext | null): Promise<LlmStream>

log

Emit a structured operational log record through Relay’s configured sinks.

export declare function log<TFields extends JsonObjectCompatible<TFields> = JsonObject>(level: string, message: string, target?: string | undefined | null, fields?: TFields | null): void

metric

Emit an atomic, validated group of OpenTelemetry metric recording operations.

name is the metric mark name. Every measurement is validated before any event is published. Optional handle, metadata, and microsecond timestamp have the same behavior as the corresponding event parameters.

export declare function metric<TMeasurements extends MetricMeasurementsCompatible<TMeasurements>, TMetadata extends JsonCompatible<TMetadata> = Json>(name: string, measurements: TMeasurements, handle?: ScopeHandle | undefined | null, metadata?: TMetadata | null, timestamp?: number | undefined | null): void

popScope

Pop an execution scope from the scope stack.

Removes the scope identified by handle from the stack and emits an end event. Optional output is a semantic JSON payload exported on the scope end event. Optional timestamp is a Unix timestamp in microseconds recorded on the end event. It must be a safe integer number; omit it to use the runtime default end timestamp. Optional metadata is a JSON metadata payload recorded on the scope end event. Throws if the handle does not match the current top scope.

export declare function popScope<TOutput extends JsonCompatible<TOutput> = Json, TMetadata extends JsonCompatible<TMetadata> = Json>(handle: ScopeHandle, output?: TOutput | null, timestamp?: number | undefined | null, metadata?: TMetadata | null): void

propagationContextFromJson

Deserialize and validate a Relay causal context from the JSON wire format.

export declare function propagationContextFromJson(value: string): PropagationContext

propagationContextToJson

Serialize a Relay causal context to the JSON wire format.

export declare function propagationContextToJson(context: PropagationContext): string

propagationContextToTraceparent

Convert a Relay propagation context to a W3C traceparent value.

export declare function propagationContextToTraceparent(context: PropagationContext): string

pushScope

Push a new execution scope onto the scope stack.

Creates a child scope with the given name and scopeType. If handle is provided, the new scope is parented to that scope; otherwise it is parented to the current top scope. Optional attributes is a bitfield of scope attribute flags. Optional data is a JSON application payload stored on the scope handle. Optional metadata is a JSON metadata payload recorded on the scope start event. Optional input is a semantic JSON payload exported on the scope start event. Optional timestamp is a Unix timestamp in microseconds recorded as the handle start time and start event timestamp. It must be a safe integer number; omit it to use the current runtime time. Returns the handle for the newly created scope.

export declare function pushScope<TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json, TInput extends JsonCompatible<TInput> = Json>(name: string, scopeType: ScopeType, handle?: ScopeHandle | undefined | null, attributes?: number | undefined | null, data?: TData | null, metadata?: TMetadata | null, input?: TInput | null, timestamp?: number | undefined | null): ScopeHandle

registerConditionalMiddlewareGuardrail

Register a global eligibility gate for runtime registrations matching kind and name.

export declare function registerConditionalMiddlewareGuardrail(name: string, kinds: Array<RuntimeRegistrationKind | RuntimeRegistrationKindName>, registrationName: string, guardrail: (kinds: RuntimeRegistrationKind[], registrationName: string) => string | null): void

registerEventMetadataInjector

Register a global event metadata injector.

The callback receives an immutable event snapshot and may return additions directly or in a Promise. Relay validates and merges accepted additions before event sanitizers run.

export declare function registerEventMetadataInjector<TMetadata extends EventMetadataCompatible<TMetadata>>(name: string, priority: number, injector: (event: JsonObject) => TMetadata | Promise<TMetadata>): void

registerLlmConditionalExecutionGuardrail

Register a guardrail that conditionally gates LLM execution.

The guardrail callback receives the LLM request as JSON and must return null to allow execution or a rejection reason string to block it. Higher priority values run first. If the callback throws, the managed call rejects and the protected callback does not run.

export declare function registerLlmConditionalExecutionGuardrail(name: string, priority: number, guardrail: (request: LlmRequestShape) => string | null | Promise<string | null>): void

registerLlmExecutionIntercept

Register an LLM execution intercept following the middleware chain pattern.

The callable receives the request, codec context, and a next function. Call next(request) to invoke the next intercept or original implementation; skip calling next to short-circuit the chain. next may be called repeatedly or concurrently while callable is pending; each call receives an isolated scope-stack branch, and unfinished or later calls reject after callable settles.

export declare function registerLlmExecutionIntercept<TResponse extends JsonCompatible<TResponse>>(name: string, priority: number, callable: (request: LlmRequestShape, context: LlmExecutionContext, next: <TNextRequest extends LlmRequestCompatible<TNextRequest>>(request: TNextRequest) => Json | Promise<Json>) => TResponse | Promise<TResponse>): void

registerLlmRequestIntercept

Register an intercept that transforms LLM request data.

The callable receives the LlmRequest (as JSON) and returns a transformed request. If breakChain is true, no lower-priority intercepts run after this one. Higher priority values run first. If the callback throws, the managed call rejects and later middleware does not run.

export declare function registerLlmRequestIntercept<TOutcome extends LlmRequestInterceptOutcomeCompatible<TOutcome>>(name: string, priority: number, breakChain: boolean, callable: (args: { name: string; request: LlmRequestShape; annotated: Json | null }) => TOutcome | Promise<TOutcome>): void

registerLlmSanitizeRequestGuardrail

Register a guardrail that sanitizes LLM request data before execution.

The guardrail callback receives (request, context) and must return the sanitized request, or null to omit the observability payload. Lower priority values run first. Throws if a guardrail with the same name already exists. If the callback throws, Relay omits the payload and annotation, continues publication, and records the error for getLastCallbackError().

export declare function registerLlmSanitizeRequestGuardrail<TRequest extends LlmRequestCompatible<TRequest> = LlmRequestShape>(name: string, priority: number, guardrail: (request: LlmRequestShape, context: LlmSanitizeRequestContext) => TRequest | null | Promise<TRequest | null>): void

registerLlmSanitizeResponseGuardrail

Register a guardrail that sanitizes LLM response data after execution.

The guardrail callback receives (response, context) and must return the sanitized response, or null to omit the observability payload. Lower priority values run first. Throws if a guardrail with the same name already exists. If the callback throws, Relay omits the payload and annotation, continues publication, and records the error for getLastCallbackError().

export declare function registerLlmSanitizeResponseGuardrail<TResponse extends JsonCompatible<TResponse> = Json>(name: string, priority: number, guardrail: (response: Json, context: LlmSanitizeResponseContext) => TResponse | null | Promise<TResponse | null>): void

registerLlmStreamExecutionIntercept

Register a streaming LLM execution intercept following the middleware chain pattern.

The callable receives the request, request-codec context, and a next function. The response codec is null because streaming execution has no complete-response codec. Call next(request) to invoke the next intercept or original streaming implementation; in Node the returned promise resolves to a lazy AsyncIterable. Return it directly or wrap it next to short-circuit the chain. next may be called repeatedly or concurrently while callable is pending; each call receives an isolated scope-stack branch, and unfinished or later calls reject after the returned interceptor stream settles. A downstream stream returned successfully by next keeps its normal lifetime.

export declare function registerLlmStreamExecutionIntercept<TChunk extends JsonCompatible<TChunk>>(name: string, priority: number, callable: (request: LlmRequestShape, context: LlmExecutionContext, next: <TNextRequest extends LlmRequestCompatible<TNextRequest>>(request: TNextRequest) => Promise<AsyncIterable<Json>>) => AsyncIterable<TChunk> | Promise<AsyncIterable<TChunk>>): void

registerMarkSanitizeGuardrail

Register an event sanitize guardrail.

The callback may return fields directly or in a Promise. Scope and mark calls queue the event and return synchronously; publication resumes after the Promise settles. Callback, serialization, conversion, or invalid-result failures clear the emitted event fields and record the error for getLastCallbackError(). Await flushSubscribers() before inspecting either the delivered event or that error.

export declare function registerMarkSanitizeGuardrail<TFields extends EventSanitizeFieldsCompatible<TFields>>(name: string, priority: number, guardrail: (event: JsonObject, fields: EventSanitizeFields) => TFields | Promise<TFields>): void

registerPlugin

Register a plugin backed by JavaScript callbacks.

validate receives (pluginConfig) and should return a diagnostics array. register receives (pluginConfig, context) and should use the context methods to attach subscribers or intercepts. Both callbacks must be synchronous.

export declare function registerPlugin(pluginKind: string, validate: ((pluginConfig: JsonObject) => ConfigDiagnostic[] | null | undefined) | undefined | null, register: (pluginConfig: JsonObject, context: PluginContext) => void): void

registerScopeSanitizeEndGuardrail

Register an event sanitize guardrail.

The callback may return fields directly or in a Promise. Scope and mark calls queue the event and return synchronously; publication resumes after the Promise settles. Callback, serialization, conversion, or invalid-result failures clear the emitted event fields and record the error for getLastCallbackError(). Await flushSubscribers() before inspecting either the delivered event or that error.

export declare function registerScopeSanitizeEndGuardrail<TFields extends EventSanitizeFieldsCompatible<TFields>>(name: string, priority: number, guardrail: (event: JsonObject, fields: EventSanitizeFields) => TFields | Promise<TFields>): void

registerScopeSanitizeStartGuardrail

Register an event sanitize guardrail.

The callback may return fields directly or in a Promise. Scope and mark calls queue the event and return synchronously; publication resumes after the Promise settles. Callback, serialization, conversion, or invalid-result failures clear the emitted event fields and record the error for getLastCallbackError(). Await flushSubscribers() before inspecting either the delivered event or that error.

export declare function registerScopeSanitizeStartGuardrail<TFields extends EventSanitizeFieldsCompatible<TFields>>(name: string, priority: number, guardrail: (event: JsonObject, fields: EventSanitizeFields) => TFields | Promise<TFields>): void

registerSubscriber

Register a named event subscriber that receives all lifecycle events.

The callback receives each event as the canonical JSON event object and may return a Promise. Events are delivered asynchronously and non-blocking. Callback failures are isolated, reported to stderr and getLastCallbackError(), and do not reject flushSubscribers(). Throws if a subscriber with the same name already exists.

export declare function registerSubscriber(name: string, callback: (event: JsonObject) => void | Promise<void>): void

registerToolConditionalExecutionGuardrail

Register a guardrail that conditionally gates tool execution.

The guardrail callback receives (toolName, args) and must return null to allow execution or a rejection reason string to block it. Higher priority values run first. If the callback throws, the managed call rejects and the protected callback does not run.

export declare function registerToolConditionalExecutionGuardrail(name: string, priority: number, guardrail: (toolName: string, args: Json) => string | null | Promise<string | null>): void

registerToolExecutionIntercept

Register a tool execution intercept following the middleware chain pattern.

The callable receives ToolExecutionContext and next. The context exposes toolName, args, toolCallId, and executionContext. The latter is a host-supplied JSON object or null, separate from event metadata and tool arguments; it grants no authorization. toolCallId is null when the call has no provider-issued correlation identifier. Call next(context.args) to continue the chain, or return an outcome directly to short-circuit execution.

export declare function registerToolExecutionIntercept<TOutcome extends ToolExecutionInterceptOutcomeCompatible<TOutcome>>(name: string, priority: number, callable: (context: ToolExecutionContext, next: <TNextArgs extends JsonCompatible<TNextArgs>>(args: TNextArgs) => ToolExecutionResult | Promise<ToolExecutionResult>) => TOutcome | Promise<TOutcome>): void

registerToolRequestIntercept

Register an intercept that transforms tool request arguments.

The callable receives (toolName, args) and returns transformed args. If breakChain is true, no lower-priority intercepts run after this one. Higher priority values run first. If the callback throws, the managed call rejects and later middleware does not run.

export declare function registerToolRequestIntercept<TArgs extends JsonCompatible<TArgs>>(name: string, priority: number, breakChain: boolean, callable: (toolName: string, args: Json) => TArgs | Promise<TArgs>): void

registerToolSanitizeRequestGuardrail

Register a guardrail that sanitizes tool request arguments before execution.

The guardrail callback receives (toolName, args) and must return sanitized args. Higher priority values run first. Throws if a guardrail with the same name already exists. If the callback throws, Relay omits the emitted payload and records the error for getLastCallbackError().

export declare function registerToolSanitizeRequestGuardrail<TValue extends JsonCompatible<TValue>>(name: string, priority: number, guardrail: (toolName: string, value: Json) => TValue | Promise<TValue>): void

registerToolSanitizeResponseGuardrail

Register a guardrail that sanitizes tool response data after execution.

The guardrail callback receives (toolName, result) and must return sanitized result. Higher priority values run first. Throws if a guardrail with the same name already exists. If the callback throws, Relay omits the emitted payload and records the error for getLastCallbackError().

export declare function registerToolSanitizeResponseGuardrail<TValue extends JsonCompatible<TValue>>(name: string, priority: number, guardrail: (toolName: string, value: Json) => TValue | Promise<TValue>): void

scopeDeregisterEventMetadataInjector

Deregister a scope-local event metadata injector by name.

export declare function scopeDeregisterEventMetadataInjector(scopeUuid: string, name: string): boolean

scopeDeregisterLlmConditionalExecutionGuardrail

Deregister a scope-local LLM conditional execution guardrail by name.

Returns true if a guardrail with that name was found and removed from the specified scope.

export declare function scopeDeregisterLlmConditionalExecutionGuardrail(scopeUuid: string, name: string): boolean

scopeDeregisterLlmExecutionIntercept

Deregister a scope-local LLM execution intercept by name.

Returns true if an intercept with that name was found and removed from the specified scope.

export declare function scopeDeregisterLlmExecutionIntercept(scopeUuid: string, name: string): boolean

scopeDeregisterLlmRequestIntercept

Deregister a scope-local LLM request intercept by name.

Returns true if an intercept with that name was found and removed from the specified scope.

export declare function scopeDeregisterLlmRequestIntercept(scopeUuid: string, name: string): boolean

scopeDeregisterLlmSanitizeRequestGuardrail

Deregister a scope-local LLM request sanitization guardrail by name.

Returns true if a guardrail with that name was found and removed from the specified scope.

export declare function scopeDeregisterLlmSanitizeRequestGuardrail(scopeUuid: string, name: string): boolean

scopeDeregisterLlmSanitizeResponseGuardrail

Deregister a scope-local LLM response sanitization guardrail by name.

Returns true if a guardrail with that name was found and removed from the specified scope.

export declare function scopeDeregisterLlmSanitizeResponseGuardrail(scopeUuid: string, name: string): boolean

scopeDeregisterLlmStreamExecutionIntercept

Deregister a scope-local LLM stream execution intercept by name.

Returns true if an intercept with that name was found and removed from the specified scope.

export declare function scopeDeregisterLlmStreamExecutionIntercept(scopeUuid: string, name: string): boolean

scopeDeregisterMarkSanitizeGuardrail

export declare function scopeDeregisterMarkSanitizeGuardrail(scopeUuid: string, name: string): boolean

scopeDeregisterScopeSanitizeEndGuardrail

export declare function scopeDeregisterScopeSanitizeEndGuardrail(scopeUuid: string, name: string): boolean

scopeDeregisterScopeSanitizeStartGuardrail

export declare function scopeDeregisterScopeSanitizeStartGuardrail(scopeUuid: string, name: string): boolean

scopeDeregisterSubscriber

Deregister a scope-local event subscriber by name.

Returns true if a subscriber with that name was found and removed from the specified scope.

export declare function scopeDeregisterSubscriber(scopeUuid: string, name: string): boolean

scopeDeregisterToolConditionalExecutionGuardrail

Deregister a scope-local tool conditional execution guardrail by name.

Returns true if a guardrail with that name was found and removed from the specified scope.

export declare function scopeDeregisterToolConditionalExecutionGuardrail(scopeUuid: string, name: string): boolean

scopeDeregisterToolExecutionIntercept

Deregister a scope-local tool execution intercept by name.

Removes an intercept registered through either registration shape. Returns true if an intercept with that name was found and removed from the specified scope.

export declare function scopeDeregisterToolExecutionIntercept(scopeUuid: string, name: string): boolean

scopeDeregisterToolRequestIntercept

Deregister a scope-local tool request intercept by name.

Returns true if an intercept with that name was found and removed from the specified scope.

export declare function scopeDeregisterToolRequestIntercept(scopeUuid: string, name: string): boolean

scopeDeregisterToolSanitizeRequestGuardrail

Deregister a scope-local tool request sanitization guardrail by name.

Returns true if a guardrail with that name was found and removed from the specified scope.

export declare function scopeDeregisterToolSanitizeRequestGuardrail(scopeUuid: string, name: string): boolean

scopeDeregisterToolSanitizeResponseGuardrail

Deregister a scope-local tool response sanitization guardrail by name.

Returns true if a guardrail with that name was found and removed from the specified scope.

export declare function scopeDeregisterToolSanitizeResponseGuardrail(scopeUuid: string, name: string): boolean

scopeRegisterEventMetadataInjector

Register an event metadata injector owned by an active scope.

export declare function scopeRegisterEventMetadataInjector<TMetadata extends EventMetadataCompatible<TMetadata>>(scopeUuid: string, name: string, priority: number, injector: (event: JsonObject) => TMetadata | Promise<TMetadata>): void

scopeRegisterLlmConditionalExecutionGuardrail

Register a scope-local guardrail that conditionally gates LLM execution.

The guardrail callback receives the LLM request as JSON and must return null to allow execution or a rejection reason string to block it. Higher priority values run first. If the callback throws, the managed call rejects and the protected callback does not run.

export declare function scopeRegisterLlmConditionalExecutionGuardrail(scopeUuid: string, name: string, priority: number, guardrail: (request: LlmRequestShape) => string | null | Promise<string | null>): void

scopeRegisterLlmExecutionIntercept

Register a scope-local LLM execution intercept following the middleware chain pattern.

The callable receives the request, codec context, and a next function. Call next(request) to invoke the next intercept or original implementation; skip calling next to short-circuit the chain. next may be called repeatedly or concurrently while callable is pending; each call receives an isolated scope-stack branch, and unfinished or later calls reject after callable settles.

export declare function scopeRegisterLlmExecutionIntercept<TResponse extends JsonCompatible<TResponse>>(scopeUuid: string, name: string, priority: number, callable: (request: LlmRequestShape, context: LlmExecutionContext, next: <TNextRequest extends LlmRequestCompatible<TNextRequest>>(request: TNextRequest) => Json | Promise<Json>) => TResponse | Promise<TResponse>): void

scopeRegisterLlmRequestIntercept

Register a scope-local intercept that transforms LLM request data.

The callable receives the LlmRequest (as JSON) and returns a transformed request. If breakChain is true, no lower-priority intercepts run after this one. Higher priority values run first. If the callback throws, the managed call rejects and later middleware does not run.

export declare function scopeRegisterLlmRequestIntercept<TOutcome extends LlmRequestInterceptOutcomeCompatible<TOutcome>>(scopeUuid: string, name: string, priority: number, breakChain: boolean, callable: (args: { name: string; request: LlmRequestShape; annotated: Json | null }) => TOutcome | Promise<TOutcome>): void

scopeRegisterLlmSanitizeRequestGuardrail

Register a scope-local guardrail that sanitizes LLM request data before execution.

The guardrail callback receives (request, context) and must return the sanitized request, or null to omit the observability payload. Lower priority values run first. Throws if a guardrail with the same name already exists on the specified scope. If the callback throws, Relay omits the payload and annotation, continues publication, and records the error for getLastCallbackError().

export declare function scopeRegisterLlmSanitizeRequestGuardrail<TRequest extends LlmRequestCompatible<TRequest> = LlmRequestShape>(scopeUuid: string, name: string, priority: number, guardrail: (request: LlmRequestShape, context: LlmSanitizeRequestContext) => TRequest | null | Promise<TRequest | null>): void

scopeRegisterLlmSanitizeResponseGuardrail

Register a scope-local guardrail that sanitizes LLM response data after execution.

The guardrail callback receives (response, context) and must return the sanitized response, or null to omit the observability payload. Lower priority values run first. Throws if a guardrail with the same name already exists on the specified scope. If the callback throws, Relay omits the payload and annotation, continues publication, and records the error for getLastCallbackError().

export declare function scopeRegisterLlmSanitizeResponseGuardrail<TResponse extends JsonCompatible<TResponse> = Json>(scopeUuid: string, name: string, priority: number, guardrail: (response: Json, context: LlmSanitizeResponseContext) => TResponse | null | Promise<TResponse | null>): void

scopeRegisterLlmStreamExecutionIntercept

Register a scope-local streaming LLM execution intercept following the middleware chain pattern.

The callable receives the request, request-codec context, and a next function. The response codec is null because streaming execution has no complete-response codec. Call next(request) to invoke the next intercept or original streaming implementation; in Node the returned promise resolves to a lazy AsyncIterable. Return it directly or wrap it next to short-circuit the chain. next may be called repeatedly or concurrently while callable is pending; each call receives an isolated scope-stack branch, and unfinished or later calls reject after the returned interceptor stream settles. A downstream stream returned successfully by next keeps its normal lifetime.

export declare function scopeRegisterLlmStreamExecutionIntercept<TChunk extends JsonCompatible<TChunk>>(scopeUuid: string, name: string, priority: number, callable: (request: LlmRequestShape, context: LlmExecutionContext, next: <TNextRequest extends LlmRequestCompatible<TNextRequest>>(request: TNextRequest) => Promise<AsyncIterable<Json>>) => AsyncIterable<TChunk> | Promise<AsyncIterable<TChunk>>): void

scopeRegisterMarkSanitizeGuardrail

Register a scope-local event sanitize guardrail.

The callback may return fields directly or in a Promise. Scope and mark calls queue the event and return synchronously; publication resumes after the Promise settles. Callback, serialization, conversion, or invalid-result failures clear the emitted event fields and record the error for getLastCallbackError(). Await flushSubscribers() before inspecting either the delivered event or that error.

export declare function scopeRegisterMarkSanitizeGuardrail<TFields extends EventSanitizeFieldsCompatible<TFields>>(scopeUuid: string, name: string, priority: number, guardrail: (event: JsonObject, fields: EventSanitizeFields) => TFields | Promise<TFields>): void

scopeRegisterScopeSanitizeEndGuardrail

Register a scope-local event sanitize guardrail.

The callback may return fields directly or in a Promise. Scope and mark calls queue the event and return synchronously; publication resumes after the Promise settles. Callback, serialization, conversion, or invalid-result failures clear the emitted event fields and record the error for getLastCallbackError(). Await flushSubscribers() before inspecting either the delivered event or that error.

export declare function scopeRegisterScopeSanitizeEndGuardrail<TFields extends EventSanitizeFieldsCompatible<TFields>>(scopeUuid: string, name: string, priority: number, guardrail: (event: JsonObject, fields: EventSanitizeFields) => TFields | Promise<TFields>): void

scopeRegisterScopeSanitizeStartGuardrail

Register a scope-local event sanitize guardrail.

The callback may return fields directly or in a Promise. Scope and mark calls queue the event and return synchronously; publication resumes after the Promise settles. Callback, serialization, conversion, or invalid-result failures clear the emitted event fields and record the error for getLastCallbackError(). Await flushSubscribers() before inspecting either the delivered event or that error.

export declare function scopeRegisterScopeSanitizeStartGuardrail<TFields extends EventSanitizeFieldsCompatible<TFields>>(scopeUuid: string, name: string, priority: number, guardrail: (event: JsonObject, fields: EventSanitizeFields) => TFields | Promise<TFields>): void

scopeRegisterSubscriber

Register a scope-local named event subscriber that receives lifecycle events for the specified scope.

The callback receives each event as the canonical JSON event object and may return a Promise. Events are delivered asynchronously and non-blocking. Callback failures are isolated, reported to stderr and getLastCallbackError(), and do not reject flushSubscribers(). Throws if a subscriber with the same name already exists on the specified scope.

export declare function scopeRegisterSubscriber(scopeUuid: string, name: string, callback: (event: JsonObject) => void | Promise<void>): void

scopeRegisterToolConditionalExecutionGuardrail

Register a scope-local guardrail that conditionally gates tool execution.

The guardrail callback receives (toolName, args) and must return null to allow execution or a rejection reason string to block it. Higher priority values run first. If the callback throws, the managed call rejects and the protected callback does not run.

export declare function scopeRegisterToolConditionalExecutionGuardrail(scopeUuid: string, name: string, priority: number, guardrail: (toolName: string, args: Json) => string | null | Promise<string | null>): void

scopeRegisterToolExecutionIntercept

Register a scope-local tool execution intercept following the middleware chain pattern.

The callable receives ToolExecutionContext and next. The context exposes toolName, args, toolCallId, and executionContext. The latter is a host-supplied JSON object or null, separate from event metadata and tool arguments; it grants no authorization. toolCallId is null when the call has no provider-issued correlation identifier. Call next(context.args) to continue the chain, or return an outcome directly to short-circuit execution.

export declare function scopeRegisterToolExecutionIntercept<TOutcome extends ToolExecutionInterceptOutcomeCompatible<TOutcome>>(scopeUuid: string, name: string, priority: number, callable: (context: ToolExecutionContext, next: <TNextArgs extends JsonCompatible<TNextArgs>>(args: TNextArgs) => ToolExecutionResult | Promise<ToolExecutionResult>) => TOutcome | Promise<TOutcome>): void

scopeRegisterToolRequestIntercept

Register a scope-local intercept that transforms tool request arguments.

The callable receives (toolName, args) and returns transformed args. If breakChain is true, no lower-priority intercepts run after this one. Higher priority values run first. If the callback throws, the managed call rejects and later middleware does not run.

export declare function scopeRegisterToolRequestIntercept<TArgs extends JsonCompatible<TArgs>>(scopeUuid: string, name: string, priority: number, breakChain: boolean, callable: (toolName: string, args: Json) => TArgs | Promise<TArgs>): void

scopeRegisterToolSanitizeRequestGuardrail

Register a scope-local guardrail that sanitizes tool request arguments before execution.

The guardrail callback receives (toolName, args) and must return sanitized args. Higher priority values run first. Throws if a guardrail with the same name already exists on the specified scope. If the callback throws, Relay omits the emitted payload and records the error for getLastCallbackError().

export declare function scopeRegisterToolSanitizeRequestGuardrail<TValue extends JsonCompatible<TValue>>(scopeUuid: string, name: string, priority: number, guardrail: (toolName: string, value: Json) => TValue | Promise<TValue>): void

scopeRegisterToolSanitizeResponseGuardrail

Register a scope-local guardrail that sanitizes tool response data after execution.

The guardrail callback receives (toolName, result) and must return sanitized result. Higher priority values run first. Throws if a guardrail with the same name already exists on the specified scope. If the callback throws, Relay omits the emitted payload and records the error for getLastCallbackError().

export declare function scopeRegisterToolSanitizeResponseGuardrail<TValue extends JsonCompatible<TValue>>(scopeUuid: string, name: string, priority: number, guardrail: (toolName: string, value: Json) => TValue | Promise<TValue>): void

scopeStackActive

Returns whether the current execution context has an explicitly-initialized scope stack.

Returns true if setThreadScopeStack has been called on the current thread, or the caller is inside a task-local scope. Returns false when only the auto-created default is present.

export declare function scopeStackActive(): boolean

setLatencySensitivity

Set manual latency sensitivity on the current scope.

export declare function setLatencySensitivity(value: number): void

setThreadScopeStack

Binds a scope stack to the current thread or async resource.

This mutates the current execution resource. Use withScopeStack when concurrent asynchronous branches need isolated stack replacements. Captured stacks require an active JavaScript callback context; otherwise this returns an error and callers must use withScopeStack.

export declare function setThreadScopeStack(stack: ScopeStack): void

toolCall

Begin a manual tool call lifecycle span.

Registers a tool invocation with the given name and args. Sanitize-request guardrails are applied to the emitted start-event payload; request and execution intercepts run only through toolCallExecute. Returns a ToolHandle that must be passed to toolCallEnd() when the tool finishes. Optional handle specifies the parent scope; attributes is a bitfield; data is stored on the handle; metadata is recorded on the start event; and toolCallId is recorded in the tool event category profile. Optional timestamp is a Unix timestamp in microseconds recorded as the handle start time and start event timestamp. It must be a safe integer number; omit it to use the current runtime time.

export declare function toolCall<TArgs extends JsonCompatible<TArgs>, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json>(name: string, args: TArgs, handle?: ScopeHandle | undefined | null, attributes?: number | undefined | null, data?: TData | null, metadata?: TMetadata | null, toolCallId?: string | undefined | null, timestamp?: number | undefined | null): ToolHandle

toolCallEnd

End a manual tool call lifecycle span.

Signals that the tool call identified by handle has completed with the given result. Sanitize-response guardrails are applied to the emitted end-event payload; response intercepts run only through toolCallExecute. Optional data is used when the sanitized result is JSON null, and optional metadata is recorded on the end event. Optional timestamp is a Unix timestamp in microseconds recorded on the end event. It must be a safe integer number; omit it to use the runtime default end timestamp.

export declare function toolCallEnd<TResult extends ToolExecutionResultCompatible<TResult>, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json>(handle: ToolHandle, result: TResult, data?: TData | null, metadata?: TMetadata | null, timestamp?: number | undefined | null): void

toolCallExecute

Execute a tool call end-to-end with full lifecycle management.

By default, this call runs these stages:

  1. Check conditional-execution guardrails on the original input. 2. Apply request intercepts. 3. Sanitize the request copy in the Start event. 4. Run execution intercepts around func. 5. Sanitize the response copy in the End event.

If a guardrail rejects the call, Relay emits a standalone Mark event. It does not emit a Start/End pair. The call returns GuardrailRejected. Sanitizers change event data. They do not change the result returned to the caller. An optional toolCallId is recorded in both lifecycle events. Use executionOptions to choose which stages run for this call. Optional executionContext is a host-supplied JSON object (at most 16 KiB) exposed only to execution intercepts. It is not arguments or event metadata, grants no authorization, and is not inherited by nested calls.

export declare function toolCallExecute<TArgs extends JsonCompatible<TArgs>, TResult extends ToolExecutionResultCompatible<TResult>, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json>(name: string, args: TArgs, func: (arg: Json) => TResult, handle?: ScopeHandle | undefined | null, attributes?: number | undefined | null, data?: TData | null, metadata?: TMetadata | null, toolCallId?: string | undefined | null, executionOptions?: ExecutionOptions | undefined | null, executionContext?: ApplicationExecutionContext | null): Promise<ToolExecutionResult>

toolCallExecuteAsync

Execute a tool call end-to-end with a callback that returns a value or a Promise.

Runs the same lifecycle as toolCallExecute. An optional toolCallId is recorded in both lifecycle events. Use executionOptions to choose which stages run for this call. Optional executionContext is a host-supplied JSON object (at most 16 KiB) exposed only to execution intercepts. It is not arguments or event metadata, grants no authorization, and is not inherited by nested calls.

export declare function toolCallExecuteAsync<TArgs extends JsonCompatible<TArgs>, TResult extends ToolExecutionResultCompatible<TResult>, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json>(name: string, args: TArgs, func: (arg: Json, signal: AbortSignal) => TResult | Promise<TResult>, handle?: ScopeHandle | undefined | null, attributes?: number | undefined | null, data?: TData | null, metadata?: TMetadata | null, toolCallId?: string | undefined | null, executionOptions?: ExecutionOptions | undefined | null, executionContext?: ApplicationExecutionContext | null): Promise<ToolExecutionResult>

toolConditionalExecution

Run the registered tool conditional execution guardrail chain. Throws if any guardrail rejects.

export declare function toolConditionalExecution<TArgs extends JsonCompatible<TArgs>>(name: string, args: TArgs): Promise<void>

toolRequestIntercepts

Run the registered tool request intercept chain on the given arguments. Returns the transformed arguments.

export declare function toolRequestIntercepts<TArgs extends JsonCompatible<TArgs>>(name: string, args: TArgs): Promise<Json>

trace

Emit a trace-level operational log record through Relay’s configured sinks.

export declare function trace<TFields extends JsonObjectCompatible<TFields> = JsonObject>(message: string, target?: string | undefined | null, fields?: TFields | null): void

validate

Validate dynamic plugins without loading any plugin code.

export declare function validate<TConfig extends JsonCompatible<TConfig>>(config: TConfig, additionalPluginsToml?: string | undefined | null): PluginHostReport

validateAdaptiveConfig

Validate an adaptive config document without constructing a runtime.

export declare function validateAdaptiveConfig<TConfig extends JsonCompatible<TConfig>>(config: TConfig): ConfigReport

validateExact

Validate only the supplied static plugin configuration.

export declare function validateExact<TConfig extends JsonCompatible<TConfig>>(config: TConfig): PluginHostReport

warn

Emit a warn-level operational log record through Relay’s configured sinks.

export declare function warn<TFields extends JsonObjectCompatible<TFields> = JsonObject>(message: string, target?: string | undefined | null, fields?: TFields | null): void

withScope

Push a scope, run a callback, then pop the scope automatically.

Creates a child scope with the given name and scopeType, invokes the callback with the new scope handle, and guarantees that the scope is popped when the callback completes (whether it returns normally, throws, or returns a rejected Promise). Supports both synchronous and async (Promise-returning) callbacks.

Optional handle sets the parent scope; attributes is a bitfield of scope attribute flags; data is stored on the scope handle; metadata is recorded on the start event; and input is exported as the semantic start-event payload.

Returns a Promise that resolves with the callback’s return value.

export declare function withScope<T extends JsonCompatible<T> | void = Json, TData extends JsonCompatible<TData> = Json, TMetadata extends JsonCompatible<TMetadata> = Json, TInput extends JsonCompatible<TInput> = Json>(name: string, scopeType: ScopeType, callback: (handle: ScopeHandle) => T | Promise<T>, handle?: ScopeHandle | undefined | null, attributes?: number | undefined | null, data?: TData | null, metadata?: TMetadata | null, input?: TInput | null): Promise<T extends void ? null : T>

withScopeStack

Run a callback with an isolated scope stack installed.

The caller’s stack is restored immediately after callback invocation. When the callback returns a Promise, the requested stack remains active for that Promise until it settles and is then expired for inherited detached work. Use this helper instead of setThreadScopeStack to isolate concurrent async branches.

export declare function withScopeStack<T>(stack: ScopeStack, callback: () => T): T

codecs.message

Snapshot any normalized request item by integer index; negative indices count from the end.

export declare function message<T extends JsonCompatible<T>>(request: T, index: number): MessageView;

codecs.lastMessage

Snapshot exactly the final supplied item, or null for empty history; never search backward for text.

export declare function lastMessage<T extends JsonCompatible<T>>(request: T): MessageView | null;

codecs.instructionsView

Snapshot only top-level instructions, without falling back to history.

export declare function instructionsView<T extends JsonCompatible<T>>(request: T): MessageView | null;

codecs.output

Snapshot current normalized message and separate tool calls, excluding response metadata.

export declare function output<T extends JsonCompatible<T>>(response: T): MessageView;

codecs.systemPrompt

Extract instructions, otherwise the first portable/native system/developer item, including textless selections.

export declare function systemPrompt<T extends JsonCompatible<T>>(request: T): string | null;

codecs.lastUserMessage

Extract the final portable/native user item without skipping a selected item that has no text.

export declare function lastUserMessage<T extends JsonCompatible<T>>(request: T): string | null;

codecs.responseText

Extract current normalized response text/refusals, excluding tool payloads, reasoning, and media.

export declare function responseText<T extends JsonCompatible<T>>(response: T): string | null;

Type Aliases

JsonPrimitive

export type JsonPrimitive = string | number | boolean | null;

JsonObject

export type JsonObject = { [Key in string]: JsonValue };

JsonArray

export type JsonArray = JsonValue[] | readonly JsonValue[];

JsonValue

export type JsonValue = JsonPrimitive | JsonObject | JsonArray;

Json

export type Json = JsonValue;

LlmRequestShape

export type LlmRequestShape = {
headers: JsonObject;
content: Json;
};

JsonCompatible

export type JsonCompatible<T> =
| JsonValue
| ([T] extends [{} | null] ? Shaped<T, { [K in keyof T]: JsonProperty<T[K]> }> : never);

JsonObjectCompatible

export type JsonObjectCompatible<T> =
| JsonObject
| ([T] extends [object]
? Shaped<T, { [K in keyof T]: JsonProperty<T[K]> }, NonJsonValue | readonly unknown[]>
: never);

LlmRequestCompatible

export type LlmRequestCompatible<T> =
| LlmRequestOpen
| ([T] extends [object]
? Shaped<
T,
{ [K in keyof T]: K extends 'headers' ? JsonObjectProperty<T[K]> : JsonProperty<T[K]> } & Record<
'headers' | 'content',
unknown
>
>
: never);

ToolExecutionResultCompatible

export type ToolExecutionResultCompatible<T> =
| ToolExecutionResultOpen
| ([T] extends [object] ? Shaped<T, { [K in keyof T]: JsonProperty<T[K]> } & Record<'result', unknown>> : never);

ToolExecutionInterceptOutcomeCompatible

export type ToolExecutionInterceptOutcomeCompatible<T> =
| ToolExecutionInterceptOutcome
| ([T] extends [object]
? Shaped<
T,
{ [K in keyof T]: K extends 'pendingMarks' ? PendingMarksProperty<T[K]> : JsonProperty<T[K]> } & Record<
'result',
unknown
>
>
: never);

LlmRequestInterceptOutcomeCompatible

export type LlmRequestInterceptOutcomeCompatible<T> =
| LlmRequestInterceptOutcome
| ([T] extends [object]
? Shaped<
T,
{
[K in keyof T]: K extends 'request'
? LlmRequestProperty<T[K]>
: K extends 'pendingMarks'
? PendingMarksProperty<T[K]>
: K extends 'optimizationContributions'
? LlmOptimizationContribution[]
: JsonProperty<T[K]>;
} & Record<'request', unknown>
>
: never);

EventSanitizeFieldsCompatible

export type EventSanitizeFieldsCompatible<T> =
| EventSanitizeFieldsOpen
| ([T] extends [object] ? Shaped<T, { [K in keyof T]: JsonProperty<T[K]> }> : never);

EventMetadataCompatible

export type EventMetadataCompatible<T> =
| EventMetadata
| ([T] extends [object] ? Shaped<T, { [K in keyof T]: EventMetadataProperty<T[K]> }> : never);

MetricMeasurementsCompatible

export type MetricMeasurementsCompatible<T> =
| readonly MetricMeasurement[]
| ([T] extends [readonly unknown[]] ? { [I in keyof T]: MetricMeasurementProperty<T[I]> } : never);

RuntimeRegistrationKindName

export type RuntimeRegistrationKindName = `${RuntimeRegistrationKind}`;

ResourceMetricsMeasurementScope

export type ResourceMetricsMeasurementScope = 'runtime_default' | ResourceMeasurementScope;

ResourceUnitKind

export type ResourceUnitKind =
| DurationUnit
| CapacityUnit
| DataUnit
| BandwidthUnit
| CpuUnit
| UtilizationUnit
| CountUnit;

ResourceUnit

export type ResourceUnit<U extends ResourceUnitKind> = U | `${U}`;

ResourceOperatingSystem

export type ResourceOperatingSystem = 'linux' | 'macos' | 'windows' | 'unsupported';

ResourceMeasurementScope

export type ResourceMeasurementScope = 'global' | 'application_process' | 'process_tree';

ResourceNumeric

bigint above JavaScript’s safe integer range.

export type ResourceNumeric = number | bigint;

AcceleratorVendor

export type AcceleratorVendor = 'nvidia' | 'amd' | 'intel' | 'apple' | 'other';

LlmCodecIdentity

Codec identity during LLM event sanitization.

export type LlmCodecIdentity =
| { kind: 'none' }
| {
kind: 'builtin';
id: 'openai_chat' | 'openai_responses' | 'anthropic_messages' | 'oci_genai' | 'gemini_generate_content';
}
| { kind: 'runtime'; id: string }
| { kind: 'opaque' };

LlmRequestContext

Request codec context for an LLM execution intercept.

export type LlmRequestContext = LlmSanitizeRequestContext;

LlmResponseContext

Response codec context for an LLM execution intercept.

export type LlmResponseContext = LlmSanitizeResponseContext;

EventMetadataScalar

Scalar accepted in event metadata.

export type EventMetadataScalar = string | number | boolean;

EventMetadataValue

Value accepted in event metadata; numeric arrays are all integers or all floats.

export type EventMetadataValue = EventMetadataScalar | readonly string[] | readonly number[] | readonly boolean[];

EventMetadata

Metadata returned by an event metadata injector.

export type EventMetadata = Record<string, EventMetadataValue>;

DynamicPluginKind

How a dynamic plugin runs.

export type DynamicPluginKind = 'rust_dynamic' | 'worker';

DynamicPluginCheckState

export type DynamicPluginCheckState = 'unknown' | 'valid' | 'invalid';

DiagnosticNumber

Diagnostic integer, written as a decimal string in canonical JSON.

export type DiagnosticNumber = bigint;

ResourceMemoryNumber

Resource number with explicit precision.

export type ResourceMemoryNumber =
| { kind: 'integer'; value: bigint }
| { kind: 'decimal'; value: number }
| { kind: 'non_finite' };

ContentEntrySnapshot

export type ContentEntrySnapshot = _ContentEntry

ContentIterator

export type ContentIterator = _ContentIterator

ContentSnapshot

export type ContentSnapshot = _ContentSnapshot

codecs.PayloadView

Tool payload in its original normalized representation; value materializes an independent JavaScript value.

export type PayloadView = {
readonly kind: 'null';
readonly value: null;
} | {
readonly kind: 'string';
readonly value: string;
} | {
readonly kind: 'json' | 'content';
readonly value: JsonValue;
};

codecs.ContentEntry

Discriminated content union; checking kind narrows the available fields.

export type ContentEntry = TextEntry | ToolCallEntry | ToolResultEntry | MediaEntry | ProviderNativeEntry;