Runtime
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.
Interfaces
ApplicationExecutionContext
Concrete invocation context; application-owned JSON belongs inside data.
ResourceMetricsPollingConfig
ResourceMemoryInspectionConfig
ResourceMetricsCpuConfig
ResourceMetricsMemoryConfig
ResourceMetricsProcessConfig
ResourceMetricsDiskConfig
ResourceMetricsGpuConfig
ResourceMetricsNetworkConfig
ResourceMetricsCpuUnits
ResourceMetricsMemoryUnits
ResourceMetricsDiskUnits
ResourceMetricsGpuUnits
ResourceMetricsNetworkTrafficUnits
ResourceMetricsNetworkUnits
ResourceMetricsUnits
ResourceMetricsConfig
ResourceMeasurement
ResourceLimitEventCount
AcceleratorDeviceMetrics
AcceleratorProcessMetrics
FilesystemCapacityMetrics
CpuMetrics
MemoryMetrics
ProcessMetrics
DiskMetrics
GpuMetrics
NetworkTrafficMetrics
NetworkInterfaceMetrics
NetworkMetrics
ProcessSamplingMetadata
ResourceMetricsSnapshot
LlmCodec
LlmResponseCodec
LlmSanitizeRequestContext
Request codec context for sanitizer and execution callbacks.
LlmSanitizeResponseContext
Response codec context for sanitizer and execution callbacks.
LlmApplicationExecutionContext
Invocation-local application payload for LLM execution intercepts.
LlmExecutionContext
Codecs and application data available to one LLM execution intercept call.
LlmOptimizationDataSchema
Schema tag for an optimization payload.
LlmOptimizationModel
Model identity kept for repricing.
LlmOptimizationModelTransition
Baseline and effective models of a routing optimization.
LlmOptimizationTokens
Token counts reported directly.
LlmOptimizationTokenImpact
Baseline, effective, and saved tokens of one optimization.
LlmOptimizationContribution
One plugin’s optimization evidence. kind accepts any string and unknown fields are kept.
LlmRequestInterceptOutcome
Result of an LLM request intercept.
ConfigDiagnostic
ToolExecutionInterceptOutcome
PluginContext
ConfigReport
Validation or activation report for a plugin config.
RuntimeDiagnostic
One aggregated runtime plugin failure.
PluginHostReport
DynamicPluginValidationStatus
DynamicPluginFailure
DynamicPluginValidationReport
CacheWriteTokenCounts
Prompt-cache write tokens for one cache duration.
CacheUsage
Token usage for cache telemetry.
AgentIdentity
Agent identity in cache telemetry.
CacheRequestFactsOptions
Input to buildCacheRequestFacts.
CacheRequestFacts
Request facts that classify cache misses.
CacheTelemetryEventOptions
Input to buildCacheTelemetryEvent.
CacheTelemetryEvent
Cache telemetry event.
SourceIdentity
Producer of the evidence.
ComponentIdentity
Component registration.
ComponentOwnership
Owner and configuration of a component.
DiagnosticOrigin
Where an observation came from.
DiagnosticCorrelation
Session and request of an observation.
Classification
Code and cause of an observation.
DiagnosticDetail
Text attached to an observation.
DiagnosticEvent
One retained observation.
RemoteDiagnosticOrigin
Origin of a remote submission.
DiagnosticCount
Count that may saturate.
DiagnosticTotals
Occurrence totals by outcome.
DiagnosticLifetimeSummary
Totals over a lifetime.
DiagnosticRefreshSummary
Totals since the last refresh.
DiagnosticCounter
Occurrences of one code.
DiagnosticWindowBucket
One time bucket of outcomes.
DiagnosticWindowCoverage
Interval covered by a window.
DiagnosticWindow
Fixed-bucket outcome series.
DiagnosticCursor
Position for the next page.
DiagnosticQuery
Selection for a snapshot.
DiagnosticRetention
History bounds of a selection.
DiagnosticLoss
Cumulative loss counters.
DiagnosticCapability
One producer integration.
DiagnosticCoverage
Limits of a snapshot.
ComponentSnapshot
One component row.
DiagnosticSnapshot
One diagnostics page.
PluginObservationContext
Plugin operation facts.
DiagnosticDiscovery
Capabilities of the diagnostics core.
DiagnosticsInfo
ResourceMemoryUnit
DiagnosticMemoryUsage
Reserved bytes and occupancy gauges.
EntryMemoryFootprint
One event header and its text.
ComponentMemoryFootprint
Storage owned by one registration, excluding plugin heap.
EntryMemoryUsage
One event and its footprint.
ComponentMemoryUsage
One registration and its footprint.
MemorySelectionTotals
Row counts and byte totals.
DiagnosticMemoryPage
One memory page with resource context.
ResourceMemoryMeasurement
Resource value with its number kind, unit, scope, and coverage.
MemoryLimitEvent
One cumulative limit event.
ResourceMemoryMetrics
Memory measurements and up to eight limit events.
ResourceProcessIdentity
Root process identity checked during collection.
ResourceMemorySample
One collection and its memory result.
ResourceMemoryView
Collection availability, association, and freshness.
AtofExporterConfig
One tagged sink configuration for AtofExporter.
DataSchema
Schema identifier attached to an event’s opaque data payload.
DiagnosticsQueryContract
EventSanitizeFields
Observability fields returned by mark and scope event sanitizers.
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.
MetricMeasurement
One typed recording operation emitted by metric.
OpenTelemetryConfig
Mutable configuration object for OpenTelemetrySubscriber.
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.
OpenTelemetryLogConfig
Configuration object for OpenTelemetryLogSubscriber.
OpenTelemetryMetricConfig
Configuration object for OpenTelemetryMetricSubscriber.
OpenTelemetryTlsConfig
Paths to PEM certificate and private key files for one OTLP endpoint.
PendingMarkSpec
A mark Relay materializes under a managed lifecycle.
PropagationContext
Transport-neutral Relay causal context for application-managed transport.
RuntimeRegistrationIdentity
Structured identity for one global gateable runtime registration.
RuntimeRegistrationOwner
Discovery metadata describing the owner of a runtime registration.
ScopeStackEntry
Identity of one visible Relay scope.
ScopeStackSnapshot
Detached root-to-top values including implicit and synthetic roots.
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.
ToolExecutionResult
Canonical application-visible result of tool execution.
result is application-owned JSON. annotation is optional opaque adjacent metadata that Relay transports without interpretation.
codecs.ContentLocation
Read-time location in a normalized snapshot; not an edit handle or provider-wire offset.
codecs.ToolCallView
Tool invocation backed by selected Rust snapshot storage.
codecs.ToolResultView
Complete tool result, excluded from default text extraction.
codecs.TextEntry
Explicit normalized text or refusal.
codecs.ToolCallEntry
A typed tool-call entry.
codecs.ToolResultEntry
A typed tool-result entry.
codecs.MediaEntry
Media retained as an independent JavaScript value when value is accessed.
codecs.ProviderNativeEntry
Opaque provider-native content; default text permits only supported shallow fallbacks.
Classes
LlmRequest
AdaptiveRuntime
Owned adaptive runtime that can register adaptive features outside the plugin system.
AnthropicMessagesCodec
Built-in codec for the Anthropic Messages API.
Implements both request codec (decode/encode) and response codec (decodeResponse). Construct with new AnthropicMessagesCodec().
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.
AtofExporter
Single-sink Agent Trajectory Observability Format (ATOF) exporter.
DiagnosticsReader
Authority to inspect restricted diagnostic evidence in the current process.
GeminiGenerateContentCodec
Built-in codec for the Gemini generateContent API.
Implements both request codec (decode/encode) and response codec (decodeResponse). Construct with new GeminiGenerateContentCodec().
LlmHandle
A handle representing an in-progress LLM call.
Returned by llmCall() and used to signal completion via llmCallEnd().
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.
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().
OpenAIChatCodec
Built-in codec for the OpenAI Chat Completions API.
Implements both request codec (decode/encode) and response codec (decodeResponse). Construct with new OpenAIChatCodec().
OpenAIResponsesCodec
Built-in codec for the OpenAI Responses API.
Implements both request codec (decode/encode) and response codec (decodeResponse). Construct with new OpenAIResponsesCodec().
OpenTelemetryLogSubscriber
Subscriber that exports severity-tagged marks through OTLP logs.
OpenTelemetryMetricSubscriber
Subscriber that records metric marks and exports them through OTLP metrics.
OpenTelemetrySubscriber
OpenTelemetry-backed event subscriber.
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.
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.
ScopeStack
Handle to an isolated scope stack for per-request/per-task isolation.
ToolHandle
A handle representing an in-progress tool call.
Returned by toolCall() and used to signal completion via toolCallEnd().
codecs.MessageView
Read-only Rust-owned snapshot. Iterators, entries, and payload views retain selected storage.
Enums
BandwidthUnit
Units for bandwidth measurements.
CapacityUnit
Units for capacity measurements.
CountUnit
Units for count measurements.
CpuUnit
Units for CPU measurements.
DataUnit
Units for data measurements.
DurationUnit
Units for duration measurements.
LogSeverity
Severity attached to a mark projected as an OpenTelemetry log.
MetricKind
OpenTelemetry instrument kind recorded by a metric measurement.
MetricTemporality
Preferred aggregation temporality for OTLP metric export.
MetricValueType
Explicit numeric representation used by a metric measurement.
RuntimeRegistrationKind
A global runtime registration surface that a conditional middleware guardrail can select.
RuntimeRegistrationOwnerKind
The owner category reported for a global runtime registration.
ScopeType
The type of an execution scope in the agent runtime hierarchy.
UtilizationUnit
Units for utilization measurements.
Functions
buildCacheTelemetryEvent
Build one adaptive cache telemetry event from normalized usage.
capturePropagationContext
Capture the current Relay causal parent for application-managed transport.
capturePropagationContextWithRoot
Capture the current parent with an optional stable application session root.
captureRootlessPropagationContext
Capture the current Relay causal parent without a propagation root.
captureTraceparent
Capture the current Relay context as a W3C traceparent value.
clearLastCallbackError
Clears the most recent callback error recorded by the Node binding.
collectResourceMetrics
Acquire a fresh resource metrics snapshot without requiring polling. Collection runs outside the JavaScript event loop.
createScopeStack
Creates a new isolated scope stack.
createScopeStackFromPropagation
Create an isolated scope stack seeded from a received propagation context.
currentScopeStack
Returns the current execution context’s scope stack handle.
currentScopeStackSnapshot
Return owned scope identities, or null without an explicitly active binding.
debug
Emit a debug-level operational log record through Relay’s configured sinks.
deregisterConditionalMiddlewareGuardrail
Deregister a global runtime-registration eligibility gate by name.
deregisterEventMetadataInjector
Deregister a global event metadata injector by name.
deregisterLlmConditionalExecutionGuardrail
Deregister an LLM conditional execution guardrail by name.
Returns true if a guardrail with that name was found and removed.
deregisterLlmExecutionIntercept
Deregister an LLM execution intercept by name.
Returns true if an intercept with that name was found and removed.
deregisterLlmRequestIntercept
Deregister an LLM request intercept by name.
Returns true if an intercept with that name was found and removed.
deregisterLlmSanitizeRequestGuardrail
Deregister an LLM request sanitization guardrail by name.
Returns true if a guardrail with that name was found and removed.
deregisterLlmSanitizeResponseGuardrail
Deregister an LLM response sanitization guardrail by name.
Returns true if a guardrail with that name was found and removed.
deregisterLlmStreamExecutionIntercept
Deregister an LLM stream execution intercept by name.
Returns true if an intercept with that name was found and removed.
deregisterMarkSanitizeGuardrail
deregisterPlugin
Deregister a plugin by kind.
deregisterScopeSanitizeEndGuardrail
deregisterScopeSanitizeStartGuardrail
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.
deregisterToolConditionalExecutionGuardrail
Deregister a tool conditional execution guardrail by name.
Returns true if a guardrail with that name was found and removed.
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.
deregisterToolRequestIntercept
Deregister a tool request intercept by name.
Returns true if an intercept with that name was found and removed.
deregisterToolSanitizeRequestGuardrail
Deregister a tool request sanitization guardrail by name.
Returns true if a guardrail with that name was found and removed.
deregisterToolSanitizeResponseGuardrail
Deregister a tool response sanitization guardrail by name.
Returns true if a guardrail with that name was found and removed.
diagnosticsReader
Inspect the configured service without starting it. Errors use a stable reason message.
error
Emit an error-level operational log record through Relay’s configured sinks.
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.
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.
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.
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.
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.
info
Emit an info-level operational log record through Relay’s configured sinks.
initialize
Initialize the core-owned static and dynamic plugin host from layered files.
listPluginKinds
List registered plugin kinds.
listRuntimeRegistrations
List global gateable runtime registrations.
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().
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.
llmCallExecute
Execute an LLM call end-to-end with full lifecycle management.
By default, this call runs these stages:
- Check conditional-execution guardrails on the original input. 2. Apply request intercepts. 3. Sanitize the request copy in the
Startevent. 4. Run execution intercepts aroundfunc. 5. Sanitize the response copy in theEndevent.
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.
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.
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.
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.
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.
log
Emit a structured operational log record through Relay’s configured sinks.
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.
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.
propagationContextFromJson
Deserialize and validate a Relay causal context from the JSON wire format.
propagationContextToJson
Serialize a Relay causal context to the JSON wire format.
propagationContextToTraceparent
Convert a Relay propagation context to a W3C traceparent value.
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.
registerConditionalMiddlewareGuardrail
Register a global eligibility gate for runtime registrations matching kind and name.
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.
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.
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.
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.
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().
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().
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.
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.
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.
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.
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.
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.
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.
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.
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.
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().
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().
scopeDeregisterEventMetadataInjector
Deregister a scope-local event metadata injector by name.
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.
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.
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.
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.
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.
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.
scopeDeregisterMarkSanitizeGuardrail
scopeDeregisterScopeSanitizeEndGuardrail
scopeDeregisterScopeSanitizeStartGuardrail
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.
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.
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.
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.
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.
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.
scopeRegisterEventMetadataInjector
Register an event metadata injector owned by an active scope.
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.
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.
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.
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().
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().
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.
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.
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.
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.
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.
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.
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.
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.
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().
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().
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.
setLatencySensitivity
Set manual latency sensitivity on the current scope.
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.
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.
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.
toolCallExecute
Execute a tool call end-to-end with full lifecycle management.
By default, this call runs these stages:
- Check conditional-execution guardrails on the original input. 2. Apply request intercepts. 3. Sanitize the request copy in the
Startevent. 4. Run execution intercepts aroundfunc. 5. Sanitize the response copy in theEndevent.
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.
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.
toolConditionalExecution
Run the registered tool conditional execution guardrail chain. Throws if any guardrail rejects.
toolRequestIntercepts
Run the registered tool request intercept chain on the given arguments. Returns the transformed arguments.
trace
Emit a trace-level operational log record through Relay’s configured sinks.
validate
Validate dynamic plugins without loading any plugin code.
validateAdaptiveConfig
Validate an adaptive config document without constructing a runtime.
validateExact
Validate only the supplied static plugin configuration.
warn
Emit a warn-level operational log record through Relay’s configured sinks.
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.
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.
codecs.message
Snapshot any normalized request item by integer index; negative indices count from the end.
codecs.lastMessage
Snapshot exactly the final supplied item, or null for empty history; never search backward for text.
codecs.instructionsView
Snapshot only top-level instructions, without falling back to history.
codecs.output
Snapshot current normalized message and separate tool calls, excluding response metadata.
codecs.systemPrompt
Extract instructions, otherwise the first portable/native system/developer item, including textless selections.
codecs.lastUserMessage
Extract the final portable/native user item without skipping a selected item that has no text.
codecs.responseText
Extract current normalized response text/refusals, excluding tool payloads, reasoning, and media.
Type Aliases
JsonPrimitive
JsonObject
JsonArray
JsonValue
Json
LlmRequestShape
JsonCompatible
JsonObjectCompatible
LlmRequestCompatible
ToolExecutionResultCompatible
ToolExecutionInterceptOutcomeCompatible
LlmRequestInterceptOutcomeCompatible
EventSanitizeFieldsCompatible
EventMetadataCompatible
MetricMeasurementsCompatible
RuntimeRegistrationKindName
ResourceMetricsMeasurementScope
ResourceUnitKind
ResourceUnit
ResourceOperatingSystem
ResourceMeasurementScope
ResourceNumeric
bigint above JavaScript’s safe integer range.
AcceleratorVendor
LlmCodecIdentity
Codec identity during LLM event sanitization.
LlmRequestContext
Request codec context for an LLM execution intercept.
LlmResponseContext
Response codec context for an LLM execution intercept.
EventMetadataScalar
Scalar accepted in event metadata.
EventMetadataValue
Value accepted in event metadata; numeric arrays are all integers or all floats.
EventMetadata
Metadata returned by an event metadata injector.
DynamicPluginKind
How a dynamic plugin runs.
DynamicPluginCheckState
DiagnosticNumber
Diagnostic integer, written as a decimal string in canonical JSON.
ResourceMemoryNumber
Resource number with explicit precision.
ContentEntrySnapshot
ContentIterator
ContentSnapshot
codecs.PayloadView
Tool payload in its original normalized representation; value materializes an independent JavaScript value.
codecs.ContentEntry
Discriminated content union; checking kind narrows the available fields.