OpenTelemetry-native tracing for AI agents and LLM applications.
Rius wraps the OpenTelemetry SDK with agent-shaped primitives: spans for
tool calls and chains, generations for LLM calls, and a function wrapper
that turns a plain async function into an instrumented one. Traces are
sent as OTLP over HTTP, so any OTLP-compatible backend can receive them.
Docs · TypeScript reference · Console · Changelog · Issues
Releases follow Conventional Commits: a breaking change ships as a new major version. The changelog lists what changed in each release.
npm install @glassflow-ai/rius @opentelemetry/api@opentelemetry/api is a peer dependency and is never bundled. Install
it alongside @glassflow-ai/rius at a version satisfying ^1.9.0.
The package ships an ES module build and a CommonJS build. If one process
loads both, say your code uses import while a dependency calls
require("@glassflow-ai/rius"), Node loads two separate copies of the SDK
with separate state. init() configures only the copy it was imported from:
the other copy's spans reach Rius only through the OpenTelemetry global
provider (so not at all when another SDK holds it), its AGENT and TOOL spans
lack the agent name init() was given, and registerWorkspace() on it is
skipped with a warning because it sees no client. Sessions and users
(withSession, withUser) ride OpenTelemetry context and work across both.
Load the SDK one way throughout, or call every Rius function through the copy
you called init() on.
import {
init,
observe,
startAsCurrentSpan,
startAsCurrentGeneration,
SpanKind,
} from "@glassflow-ai/rius";
const client = init({
apiKey: process.env.RIUS_API_KEY, // or set RIUS_API_KEY
});
// Optional: wait for auto-instrumentations to finish attaching before the
// first span is created.
await client.ready;
// 1. Function wrapper — trace a whole call. Use a named function expression
// (or pass { name }): an arrow function has no inferrable name and its
// span would fall back to "anonymous". The wrapper always returns a
// Promise, even for a synchronous function.
const handle = observe(async function handle(query: string) {
return await callModel(query);
});
// 2. Scoped span — trace a block
await startAsCurrentSpan(
"retrieve",
{ kind: SpanKind.RETRIEVER, input: query },
async (obs) => {
const docs = await retrieveDocuments(query);
obs.setOutput(docs);
return docs;
},
);
// 3. LLM generations — gen_ai-native
await startAsCurrentGeneration(
"chat",
{ model: "gpt-4o", input: messages },
async (gen) => {
const reply = await callModel(messages);
gen.setOutput(reply);
gen.setUsage({ inputTokens: 42, outputTokens: 17 });
return reply;
},
);Each surface has more detail below: observe for the function wrapper,
startSpan/startAsCurrentSpan for manual and scoped spans, and
startGeneration/startAsCurrentGeneration for LLM calls.
observe wraps a function so every call becomes a span. It returns a
promise, even when the wrapped function is synchronous. The exception is
a generator function (function* or async function*): its wrapper returns
a generator, and the span covers the whole iteration (see below).
Use a named function expression (or pass { name }) so the span gets a
real name. An arrow function has no inferrable name, and its span falls
back to "anonymous":
import { observe } from "@glassflow-ai/rius";
const handleQuery = observe(async function handleQuery(query: string) {
return await callModel(query);
});
// Equivalent, with an explicit name:
const handleQuery2 = observe(
async (query: string) => callModel(query),
{ name: "handleQuery" },
);
await handleQuery("hello");That is the CHAIN case, the default. On every other kind the span is named
the way the GenAI conventions say to, {operation} {target}, and the
wrapped function's name is used as the target only where it IS the target,
a tool:
const getWeather = observe(async function getWeather(city: string) { ... }, {
kind: SpanKind.TOOL,
});
await getWeather("Berlin"); // span "execute_tool getWeather", gen_ai.tool.name "getWeather"An AGENT wrapper is named after the agent it invokes (agentName, or the
one init() was given), a RETRIEVER after its dataSourceId. A function
name is not an agent or an index, so it is never used as one. Pass { name }
to override any of this.
A wrapped generator function stays a generator. Its span opens on the first
step and ends when the iteration finishes, throws (recorded as an error), or
is closed early by break or return(), which also closes the wrapped
generator so its finally blocks run. The span is current only while the
generator's own code runs, so spans the caller opens between steps do not nest
under it. Its input is recorded; what it yields is not, as in the Python SDK.
const streamAnswer = observe(async function* streamAnswer(query: string) {
for await (const chunk of callModelStreaming(query)) yield chunk;
});
for await (const chunk of streamAnswer("hello")) process.stdout.write(chunk);Generators are recognised by function kind, so wrap the generator function
itself: a plain function that returns a generator is an ordinary function to
observe, and so is an async generator compiled to a target older than
ES2018.
A generator abandoned mid-iteration, dropped without finishing or being
closed, has its span ended when the garbage collector reclaims it. The span
is timed at the last value it yielded, so an async generator abandoned while
awaiting its next value is timed at the value before it, not at the wait.
That is best effort: the collector decides when, or whether, that happens,
so until then (and for good if the process exits first) the span stays open
and shows as pending, and the wrapped generator's own finally blocks never
run. Close a generator you stop iterating early, with
return() or a break out of the loop, for an exact end.
The wrapper's type follows the generator's: Generator/AsyncGenerator
when inferred, or the declared type when the generator function is annotated
with exactly Iterable<T>, IterableIterator<T>, AsyncIterable<T> or
AsyncIterableIterator<T>, so .then() on it does not compile. A function
returning an array, a string, a Set or a Map is typed as a promise, as it
runs. A type cannot see the function kind, so a few cases are typed
differently from what the wrapper returns:
- A plain function annotated as returning exactly one of those interfaces is typed as an iterator although its wrapper returns a promise; annotate it with the concrete type it returns instead.
- A plain function returning a built-in iterator, such as
arr.values(),map.entries(),set.values()orstr.matchAll(re), is typed as that iterator although its wrapper returns a promise, when yourlibsetting predates the ES2025 iterator helpers. With alibthat includes them (ESNext, orES2025where your TypeScript version has it), built-in iterators carrymap,filterand the rest, and such a function is correctly typed as a promise. - A generator function annotated with a union such as
Iterable<T> | undefinedis typed as a promise although its wrapper returns a generator; annotate it with the iteration interface alone.
An AGENT span (from observe, startSpan or startAsCurrentSpan) can also
carry agentId and agentVersion, which describe the agent it invoked, as
gen_ai.agent.id and gen_ai.agent.version. Both are taken verbatim (the
conventions' own version examples are 1.0.0 and 2025-05-01), and both are
ignored on every other kind.
An AGENT wrapper also scopes the calls it makes: TOOL spans opened while it
runs, local or MCP, carry that agent as gen_ai.agent.name. On an
execute-tool span the conventions define that key as the agent executing
the tool, where on an invoke-agent span it is the agent being invoked.
Outside any agent, a tool span falls back to the agent init() was given.
The scope follows async calls, so any nesting depth works; only
startAsCurrentSpan and observe open it, since startSpan does not make
its span current.
For finer control than observe, create spans directly:
import { startAsCurrentSpan } from "@glassflow-ai/rius";
await startAsCurrentSpan("fetch-documents", { input: query }, async (span) => {
const docs = await fetchDocuments(query);
span.setOutput(docs);
return docs;
});startSpan returns a handle you end yourself (or dispose with using);
startAsCurrentSpan runs a callback with the span active, ending it
automatically and recording any thrown exception. The options argument is
optional in both, so startAsCurrentSpan("step", async (span) => { ... })
works when you have nothing to configure. span.update({ input, output })
sets both in one call (on a generation, as messages); a field left out, or
null, is not touched.
The name is optional too. Omit it and the span is named the way the
OpenTelemetry GenAI conventions say to, {operation} {target}, composed
from the attributes the span already carries. The callback still comes last,
so startAsCurrentSpan(options, fn) and startAsCurrentSpan(fn) are both
valid:
| Kind | Default span name | Without the target |
|---|---|---|
| LLM | chat gpt-4o ({operation} {gen_ai.request.model}) |
chat |
| EMBEDDING | embeddings text-embedding-3-small |
embeddings |
| TOOL | execute_tool get_weather |
execute_tool |
| AGENT | invoke_agent planner |
invoke_agent |
| RETRIEVER | retrieval docs-index |
retrieval |
| RERANKER | rerank rerank-v3.5 ({operation} {gen_ai.request.model}) |
rerank |
| CHAIN | the function name for observe, else chain |
n/a |
// Named "execute_tool get_weather", with gen_ai.tool.name "get_weather".
await startAsCurrentSpan(
{ kind: SpanKind.TOOL, toolName: "get_weather", input: city },
async (span) => { ... },
);A name you pass always wins; this changes the default, not your ability to
choose. The LLM name uses the REQUEST model, never the response model: the
span is named when it starts, and a partial-span snapshot has to carry the
same name as the span that replaces it. CHAIN has no operation to compose
from, so an unnamed CHAIN span is called chain.
kind sets the span's taxonomy (openinference.span.kind, our SpanKind
enum: CHAIN by default, or TOOL, RETRIEVER, EMBEDDING, RERANKER, AGENT, LLM). A TOOL
span also carries gen_ai.tool.name, set to the span name unless you pass
toolName (and unset if you pass neither), which both the span helpers and observe accept for the case
where the span name is not the bare tool name. It also takes toolCallId
(gen_ai.tool.call.id, the id of the model tool-call this execution answers)
and toolType (gen_ai.tool.type: function, extension, datastore).
Both are yours to pass or omit, never derived, and neither changes the span
name. The MCP wrapper sets neither on purpose: a tool call id belongs to the
model's message, not to the protocol exchange, and the wrapper never sees it.
A RETRIEVER span carries
gen_ai.data_source.id when you pass dataSourceId, naming the index or
collection it searched, and gen_ai.retrieval.top_k when you pass topK.
Each kind also
decides the OpenTelemetry SpanKind field the conventions expect: LLM,
EMBEDDING and RERANKER spans are CLIENT, everything else INTERNAL, RETRIEVER
included, since a retrieval wraps calls that have CLIENT spans of their own. Pass
otelKind to override it, for example CLIENT for a call to a hosted agent.
Note the name collision: SpanKind exported by this package is the taxonomy
enum; the value for otelKind is SpanKind from @opentelemetry/api, so
import that one under an alias.
import { SpanKind as OtelSpanKind } from "@opentelemetry/api";
import { SpanKind, startAsCurrentSpan } from "@glassflow-ai/rius";
await startAsCurrentSpan(
"delegate-to-planner",
{ kind: SpanKind.AGENT, otelKind: OtelSpanKind.CLIENT, input: task },
async (span) => { ... },
);On the manual path, recordException() does what the scoped form does for
you: it records the error, sets ERROR status and sets error.type to the
error's name.
const span = startSpan("fetch-documents");
try {
span.setOutput(await fetchDocuments(query));
} catch (error) {
span.recordException(error);
throw error;
} finally {
span.end();
}A Generation is a span specialised for LLM calls, with setters for the
gen_ai message and usage attributes:
import { startAsCurrentGeneration } from "@glassflow-ai/rius";
await startAsCurrentGeneration(
"chat-completion",
{
model: "gpt-4o",
provider: "openai",
input: messages,
modelParameters: { temperature: 0.2, max_tokens: 512 },
},
async (generation) => {
const response = await client.chat.completions.create({ model: "gpt-4o", messages });
generation.setOutput(response.choices[0]?.message);
generation.setUsage({
inputTokens: response.usage?.prompt_tokens,
outputTokens: response.usage?.completion_tokens,
});
generation.setFinishReasons(response.choices[0]?.finish_reason ?? "stop");
return response;
},
);modelParameters are recorded when the span opens, so they also show up on
the live (pending) view of a call that is still running. A parameter the
GenAI conventions define is recorded under its canonical gen_ai.request.*
key, and the provider spellings for it are recognised too:
max_completion_tokens, maxOutputTokens and maxTokens all become
gen_ai.request.max_tokens, stop becomes gen_ai.request.stop_sequences,
and n becomes gen_ai.request.choice.count. Any other parameter is recorded
under rius.request.<key> with its key unchanged. Tool definitions passed as a
parameter (tools, functions) are treated as content and are dropped under
captureContent: false. setFinishReasons accepts one reason or a list.
Two more conventions keys sit on either side of the call. outputType
(gen_ai.output.type: text, json, image or speech) is an option,
because the output modality is something the request asks for and so is known
before the span starts. setResponseId (gen_ai.response.id) is a setter
alongside setModel, because the provider's id for the completion only exists
once the completion does.
The name is optional here as well: startAsCurrentGeneration({ model: "gpt-4o" }, fn) names the span chat gpt-4o, and an operation override
names it after that operation instead (embeddings text-embedding-3-small).
When an agent shortens its own history (summarising it, dropping old tool
results or thinking, truncating it) call markCompaction right where it
happens:
import { markCompaction } from "@glassflow-ai/rius";
const summary = await summarise(messages);
markCompaction({
kind: "summarize",
trigger: "auto",
tokensBefore: 182_000,
tokensAfter: 9_500,
messagesCompacted: 64,
messagesKept: 6,
summary,
});It records a point-in-time compaction span (a child of the current span, or a
root when there is none) with the fields as rius.compaction.* attributes and
rius.compaction.executor set to client. kind defaults to summarize and
may also be clear_tool_results, clear_thinking or truncate; trigger is
auto or manual. When both token counts are given and tokensBefore is not
smaller, rius.compaction.tokens.dropped is their difference. summary is
recorded as rius.compaction.summary.text with its UTF-8 size in
rius.compaction.summary.bytes; like every content attribute the text is
dropped under captureContent: false and the size stays. An unknown kind or
trigger, or a count that is not a non-negative integer, logs a warning and
records nothing, with or without an initialized client; it never throws.
The next LLM span started in the same async context is flagged
gen_ai.conversation.compacted, once, so a trace shows which call ran on the
compacted history. Mark the compaction in the flow that makes that call. The
mark belongs to the async context it ran in (it is set with
AsyncLocalStorage.enterWith), so:
- A mark made after an
awaitinside a helper is not seen by the caller. Only a mark in the synchronous prefix of anasyncfunction, before its firstawait, reaches the caller. - An
asyncfunction that is called eagerly and marks in its synchronous prefix also marks the context of flows the caller creates afterwards, so a sibling started after it can take the flag. Mark in the flow that makes the call, not in a helper that runs beside other concurrent flows.
Compactions the provider makes inside a request are recorded for you. When an
auto-instrumented Anthropic response reports context_management.applied_edits
or a compaction content block, or an OpenAI Responses response has a
compaction output item, the LLM span gets one rius.compaction event per
compaction (with rius.compaction.executor provider) and the same
gen_ai.conversation.compacted flag. Limits:
- A streamed Anthropic or chat completions response is recorded by the
instrumentation as its accumulated text, which carries none of this, so those
calls report no provider compaction; mark it with
markCompactionif you need it on the trace. A streamed OpenAI Responses call is reported, because its finalresponse.completedpayload is recorded as JSON. - OpenAI's standalone
/responses/compactendpoint is not instrumented by OpenInference, so a call to it produces no span and no event. - A span already at its event limit (
OTEL_SPAN_EVENT_COUNT_LIMIT, default 128) has no room for therius.compactionevents. It still gets thegen_ai.conversation.compactedflag, and the events that did not fit are counted in the span's dropped events. - The encrypted content of an OpenAI compaction item is never read or recorded.
The SDK bundles five integrations. Each one attaches to an optional peer
dependency: install the packages you need and init() enables whatever
it finds, so a plain npm install @glassflow-ai/rius patches nothing.
npm install @arizeai/openinference-instrumentation-openai @arizeai/openinference-instrumentation-anthropic @arizeai/openinference-instrumentation-langchain @modelcontextprotocol/sdkInstall only the ones you use:
openaiwraps the OpenAI SDK, via@arizeai/openinference-instrumentation-openai, turning provider calls into spans.anthropicwraps the Anthropic SDK, via@arizeai/openinference-instrumentation-anthropic, turning Messages calls into LLM spans with model, messages and token counts. Tested with@anthropic-ai/sdk0.133 and 1.1. From 0.134 the Anthropic SDK also starts a span of its own for each API call when a tracer provider is registered. From 1.0.1, the peer floor, the instrumentation stops that span for the calls it traces, so each call has one LLM span. Below the peer floor, while this integration is enabled, Rius keeps that span but takes itsgen_ai.*keys off it, exceptgen_ai.provider.nameandgen_ai.conversation.id, so each call counts and is priced once, as the instrumentation's LLM span. The Anthropic SDK's span is exported as a plain CLIENT span, with HTTP spans from your own instrumentation under it. Inside anobserved function or any other span, it sits in the same trace as the instrumentation's span. Amessages.stream()orbeta.messages.stream()call made outside any span is the exception: the Anthropic SDK starts its span before the instrumentation's, so each is the root of its own trace, and the trace with the demoted span (and its HTTP spans) has no LLM span. The call is still counted and priced once. The demoted span keepsgen_ai.conversation.id, which the backend reads as the session when a span has nosession.id, so if you pass a conversation id to the Anthropic SDK but set no Rius session, that span can be grouped in a different session from the rest of the call. The same holds for the Bedrock and Vertex clients (@anthropic-ai/bedrock-sdk,@anthropic-ai/vertex-sdk). The Anthropic SDK's tool runner spans are left as they are. Without this integration, the Anthropic SDK's span is the call's LLM span.langchaintraces LangChain.js chains, models, tools and retrievers, via@arizeai/openinference-instrumentation-langchain. It patches the callback manager in@langchain/core, which every LangChain.js application already has, and the SDK resolves that module for you so nothing has to be passed in atinit().vercel-aitraces the Vercel AI SDK. On AI SDK v7 it registers@ai-sdk/otel's OpenTelemetry integration with the SDK's tracer, so calls are traced with no telemetry code; install@ai-sdk/otelbesideai(both require Node 22 or newer). AI SDK v5 and v6 trace the calls you passexperimental_telemetry: { isEnabled: true }, and the SDK maps theirai.*spans (generate, stream, object, embed, rerank and tool calls) onto the GenAI conventions itself, on any Node version, with nothing else to install. v5 and v6 do not trace image, speech or transcription calls.mcppatches@modelcontextprotocol/sdk'sClient.callToolso every MCP tool call becomes a TOOL span namedexecute_tool <tool>, carrying the tool name, arguments, result, latency, and error status. The span follows the OpenTelemetry MCP conventions: OTelSpanKindCLIENT,mcp.method.nameset totools/call,mcp.protocol.versionset to the negotiated version when the transport exposes it (Streamable HTTP does; stdio and SSE do not), anderror.typeset totool_errorwhen the server returns anisErrorresult.
By default init() attempts every bundled integration, so which ones
actually attach is determined by which optional peers it can find, or, for
openai and anthropic, by the modules you pass in (see "pnpm and
serverless deployments" below). To choose, pass instruments with the names
above: only those are attempted, and [] enables none. A scoped client
(setGlobal: false) enables none unless you name them; see "Scoped clients".
init({ instruments: ["openai", "mcp"] }) // leave the others offclient.ready resolves with the
names that attached (for example ["openai", "mcp"]) and never rejects,
even if every peer is missing or one of them is broken. A package that
is not installed stays quiet, unless you named its integration in
instruments (then the warning says what to install) or it is an openai
or anthropic instrumentation package that your package.json lists: then
the SDK logs one warning, because the package is there but the SDK could not
load it. An unknown name in instruments logs a warning listing the known
ones. A package that is installed but fails to load logs a warning
naming the integration and the underlying error. In every case the SDK
continues without the integration.
TanStack AI needs no integration here: its own otelMiddleware writes the
spans, and takes the tracer from the provider init() registers.
import { init } from "@glassflow-ai/rius";
import { trace } from "@opentelemetry/api";
import { chat } from "@tanstack/ai";
import { otelMiddleware } from "@tanstack/ai/middlewares/otel";
init({ serviceName: "my-agent" });
const otel = otelMiddleware({ tracer: trace.getTracer("my-agent"), captureContent: true });
await chat({ adapter, messages, threadId, middleware: [otel], stream: false });The SDK maps what the middleware writes onto the conventions. The span of a
chat() call is an agent run (invoke_agent), and its token usage, which is
the sum of its model calls, moves to rius.aggregated_usage.* so each call is
counted once. A tool span is an execute_tool span with its arguments and
result. Messages are stored in the GenAI {role, parts} schema. The mapping
covers chat(): the spans of the media activities (image, speech,
transcription and the like) are exported as the middleware writes them. Tested
with @tanstack/ai 1.4.0. The middleware records prompts and answers only
with captureContent: true; captureContent: false and mask on init()
apply to what it records.
The SDK finds its optional peers by importing them at runtime, relative to
its own files. A file-tracing deployment of a pnpm app (a serverless
function on Vercel, for example) may not ship the links that import
follows, so the integration stays off: client.ready leaves out
anthropic or openai and no LLM spans are recorded. When your
package.json lists the integration's instrumentation package
(@arizeai/openinference-instrumentation-anthropic or
@arizeai/openinference-instrumentation-openai) but the SDK cannot load
it, init() logs one warning that names the integration and points at
instrumentModules. The check is best effort: it reads the
package.json in the working directory, and if that file is not
there, the integration is skipped without a warning. Your own import
statements are what the tracer does follow, so hand the modules to
init() and it patches those instead of looking for them:
import * as anthropicSdk from "@anthropic-ai/sdk";
import * as anthropicInstrumentation from "@arizeai/openinference-instrumentation-anthropic";
import { init } from "@glassflow-ai/rius";
init({
instrumentModules: {
anthropic: { instrumentation: anthropicInstrumentation, sdk: anthropicSdk },
},
});The openai integration takes the same shape:
import * as openaiSdk from "openai";
import * as openaiInstrumentation from "@arizeai/openinference-instrumentation-openai";
init({
instrumentModules: {
openai: { instrumentation: openaiInstrumentation, sdk: openaiSdk },
},
});The SDK module you pass must be the copy your own client calls go
through; patching a different copy records nothing. An integration passed
this way resolves no package. If a module has the wrong shape, init()
logs one warning naming the integration and leaves it out of
client.ready. Only openai and anthropic accept modules.
The openai and anthropic integrations work in both module systems:
CommonJS applications that require the provider SDK and pure-ESM
applications that import it are both patched, regardless of whether
the provider was loaded before or after init(). One combination is
not covered: the provider SDKs ship separate CommonJS and ESM builds,
and the instrumentation packages can patch only one of them per process
(Arize-ai/openinference#3557),
so exactly one build gets patched: the CommonJS build when anything in
the process required the provider before init(), the ESM build
otherwise. Two combinations therefore stay uncovered until the
upstream fix lands: a CommonJS application whose only require of
the provider happens lazily after init() (requiring it anywhere
before init() avoids this), and (the mirror image) an ESM
application where some CommonJS dependency required the provider
before init(), which wins the choice away from the ESM build the
application itself is calling. In those two combinations an Anthropic
call through the unpatched build has no LLM span: from 0.134 the
Anthropic SDK's own span for it is there, but demoted like every other
while the anthropic integration is enabled (see above). The
langchain, vercel-ai and mcp integrations attach differently and
have no such edge.
Content captured by these integrations, prompts, tool arguments and
results, and so on, is covered by the same mask and captureContent
controls as our own spans, since sanitisation happens centrally at
export rather than per integration.
disabled: true now means no third-party patching happens at all: no
optional package is even imported, and client.ready resolves to an
empty array.
Options passed to init() take priority, then RIUS_* environment
variables, then the defaults below.
| Option | Environment variable | Default |
|---|---|---|
endpoint |
RIUS_ENDPOINT |
https://ingest.eu.console.rius-glassflow.com |
apiKey |
RIUS_API_KEY |
none |
serviceName |
RIUS_SERVICE_NAME |
unknown_service |
serviceVersion |
RIUS_SERVICE_VERSION |
none (also read from service.version in OTEL_RESOURCE_ATTRIBUTES; left off the resource when unset, never defaulted) |
disabled |
RIUS_DISABLED |
false |
sampleRate |
RIUS_SAMPLE_RATE |
1.0 |
captureContent |
RIUS_CAPTURE_CONTENT, then OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT |
true |
mask |
(options only) | none ((value, { key }) => unknown; the return value is stored, JSON-encoded if not a primitive; return "" to blank, null or undefined to drop the attribute) |
heartbeat |
RIUS_HEARTBEAT |
true |
heartbeatInterval |
RIUS_HEARTBEAT_INTERVAL |
15 (seconds; clamped 5-300) |
agentName |
RIUS_AGENT_NAME |
serviceName |
mainAgentId |
RIUS_MAIN_AGENT_ID |
none (a STABLE id for the agent this process is; never a transient in-memory id) |
mainAgentDescription |
RIUS_MAIN_AGENT_DESCRIPTION |
none |
mainAgentVersion |
RIUS_MAIN_AGENT_VERSION |
none (the version of the AGENT DEFINITION, never derived from serviceVersion) |
partialSpans |
RIUS_PARTIAL_SPANS |
false |
partialSpansDelay |
RIUS_PARTIAL_SPANS_DELAY |
0 (seconds; clamped 0-60) |
sessionId |
RIUS_SESSION_ID |
none (process-wide session default; withSession overrides it) |
bridgeForeignProvider |
RIUS_BRIDGE_FOREIGN_PROVIDER |
false (also export the spans of another OpenTelemetry SDK that owns the global provider; see below) |
instruments |
(options only) | every bundled integration found (a list of names restricts to those, [] enables none; see "Auto-instrumentation") |
headers |
(options only) | none (extra headers for span exports and the heartbeat; see below) |
setGlobal |
(options only) | true (false builds a scoped client that registers no OpenTelemetry global; see "Scoped clients") |
Traces are posted to <endpoint>/v1/traces.
Use an https:// endpoint: an http:// endpoint sends traces and the API
key unencrypted, and logs a warning.
apiKey is sent as an Authorization: Bearer <apiKey> header. headers adds
your own headers to every request the SDK sends: span exports and the
heartbeat. An Authorization header in headers (in any case) replaces the
one apiKey would send, and counts as credentials for the heartbeat, which
does not start without any. Header names are case-insensitive: two that
differ only in case keep the last one, with a warning. A workspace destination
(see workspaces) sends the same headers with its own key as the
Authorization header. The OTLP exporter also reads
OTEL_EXPORTER_OTLP_HEADERS itself and merges it underneath: headers and the
Authorization from apiKey win on the same name, and the rest of the
variable is still sent. This differs from the Python SDK, whose exporter
ignores the variable entirely once any header is set. Credentials given only
in that variable do not start the heartbeat.
init({ headers: { Authorization: "Bearer <token>", "x-tenant": "acme" } });An empty endpoint or serviceName (option or environment variable) counts
as unset. A numeric environment variable that is not a number (0.5abc,
10s) is ignored with a warning, and the default applies. sampleRate,
heartbeatInterval and partialSpansDelay are range-checked the same way
whether they come from an option or the environment: out of range is clamped
with a warning, and NaN or an infinity warns and uses the default.
serviceVersion is stamped on the resource as service.version, so the
console can tell one build of an agent from another. It has no default on
purpose: an invented version would put every unversioned process under the
same wrong number, the way unknown_service does for unnamed ones, so the
key is simply absent until you supply one. This SDK builds its resource
explicitly, which in OpenTelemetry for JavaScript means the OTel environment
is not merged into it, so the SDK reads OTEL_RESOURCE_ATTRIBUTES by hand:
every key it carries (deployment.environment.name, cloud.region, ...) is
put on the resource, under the SDK's own keys, which win. service.version
there is the last tier after the option and RIUS_SERVICE_VERSION.
The agent this process is is described on the resource under the GenAI
conventions' gen_ai.main_agent.*. gen_ai.main_agent.id is the entity's
identity: it is mainAgentId when you set it (the option, then
RIUS_MAIN_AGENT_ID), then a gen_ai.main_agent.id you already put in
OTEL_RESOURCE_ATTRIBUTES, and otherwise it falls back to the agent name, so
renaming the agent changes the id unless mainAgentId is set. A one-time
message says so at debug level on OpenTelemetry's diag logger, which is silent
unless you install one (diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG)). gen_ai.main_agent.name is the resolved agentName,
and gen_ai.main_agent.description is mainAgentDescription when set; a name
or description you set in OTEL_RESOURCE_ATTRIBUTES is kept instead. When
there is neither an id nor a name (the unknown_service placeholder), none of
the gen_ai.main_agent.* keys is stamped, because the conventions do not
allow the entity without an identifier. The deprecated rius.main_agent.name,
.id and .description keep their old behaviour through their deprecation
window (rius.main_agent.id only ever carries a configured mainAgentId),
and rius.main_agent.version, which has no upstream twin, carries the
optional agent version. gen_ai.agent.name is still stamped alongside them
(and, like them, left off for the unknown_service placeholder): the keys are
additive so that no deployment loses its agent identity between an SDK upgrade
and a backend one. The main-agent keys exist
because gen_ai.agent.name has no resource-level meaning in the conventions
and on a span means the agent being invoked, so one key was answering two
questions.
mainAgentId must be a stable identifier, such as a registry id or a hosted
agent's ARN. A uuid minted at startup or another process-local id identifies
a run, not an agent, and would split one agent into a fresh bucket per
restart; service.instance.id already answers "which process".
Three versions travel separately and none is ever derived from another:
| Key | Answers |
|---|---|
service.version |
which build of the deployment is running |
rius.main_agent.version |
which version of the agent definition it runs: its prompt, tools and policy |
gen_ai.agent.version |
which version of the agent a given AGENT span invoked |
A service can sit at 2.3.1 while the agent definition it runs is at 7 and
the agent it calls out to is at 1.0.0; a prompt change moves the second
without touching the first.
captureContent controls whether input/output content (prompts,
completions, tool arguments) is attached to spans. It defaults to
true. When neither the option nor RIUS_CAPTURE_CONTENT is set, the
OpenTelemetry GenAI setting OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT is
read: NO_CONTENT turns capture off, and so does EVENT_ONLY, because Rius
records content on spans. SPAN_ONLY and SPAN_AND_EVENT keep it on. The
value is case-insensitive. An unrecognised one keeps capture on and logs a
warning naming the valid values (the OpenTelemetry conventions fall back to
NO_CONTENT instead). An empty value of either variable counts as unset (an
empty RIUS_CAPTURE_CONTENT also logs a warning). With neither variable set,
capture is on, unlike the OpenTelemetry default of NO_CONTENT. Set it to false, or supply a mask function, if your spans
must not carry raw content. Both apply to span attributes and to the
attributes of span events and links, including the metadata.* copies
@arizeai/openinference-vercel's span processor makes of attributes it does
not translate, if your app runs it on a provider Rius bridges onto: a
metadata.<key> is content exactly when <key> is. With captureContent: false the
message and stacktrace of a recorded exception are stripped as well,
since provider errors routinely echo the request back; the exception
event and its exception.type are kept, so failures stay visible.
The span's ERROR status message carries the same string, so it is
blanked too; the status code stays. A mask function scrubs content
attributes on spans, events and links, including the message and
stacktrace of a recorded exception (its key is exception.message or
exception.stacktrace), and runs over the status message as well (its
key is status.description). exception.type is never passed to it.
A mask that returns null or undefined, or throws, drops that
attribute; the exception event and its exception.type are kept.
disabled turns the SDK off completely: nothing is exported, and no
optional integration is loaded, so no third-party module is patched in your
process. client.ready resolves to an empty list. Spans can still be
created and are simply dropped.
init({ setGlobal: false }) builds a client that keeps out of the
process's OpenTelemetry setup, for a library or a test that must not change
it. It registers none of the globals (tracer provider, context manager,
propagator) and releases none on shutdown(). It neither takes nor checks
the one global-client slot, so a global init() before or after it is
unaffected. It never bridges or records another SDK's provider, and
bridgeForeignProvider does not apply to it. The SDK's own helpers
(observe, startSpan, the generation helpers) stay on the global client;
start a scoped client's spans from its own tracer.
const scoped = init({ setGlobal: false, apiKey: process.env.RIUS_API_KEY });
const span = scoped.getTracer().startSpan("work");
span.end();
await scoped.shutdown();An integration patches its library for the whole process, so a scoped client
enables only the integrations it names in instruments (an instruments
that is not a list enables none, with a warning), and never one that a live
global client holds: that one stays with the global client, with a warning.
The integrations a scoped client does hold, mcp included, send their spans
to it. A global init() takes an integration from a scoped client, and the
scoped client does not get it back when that global client later shuts down,
as in the Python SDK; initialize a new scoped client to enable it again.
Workspace routing on a scoped client is static: the routes passed in
init({ workspaces }) apply, but registerWorkspace() only reaches the global
client, and there is no client-level equivalent yet.
Nesting spans through the active context needs a context manager, which a scoped client leaves to your app or to another SDK; without one, pass the parent context explicitly.
OpenTelemetry has one global tracer provider per process, and the first
registration wins. If another SDK (Langfuse v3, for one) claims it before
init(), your own job and tool spans go to that SDK only, while the LLM spans
inside them still reach Rius, so Rius receives traces whose parents it never
gets. Rius detects this whatever you configure: those LLM spans carry
rius.parent.foreign=true, the resource records
rius.sdk.global_provider=foreign:<class>, and the first one logs a warning.
To send the other SDK's spans to Rius as well, opt in with
init({ bridgeForeignProvider: true }) or RIUS_BRIDGE_FOREIGN_PROVIDER=true.
Rius then attaches its own pipeline to that provider and exports its spans too,
subject to Rius's sampleRate, captureContent and mask, under the Rius
resource identity. It never modifies what the other SDK exports: that vendor
receives exactly what it would without Rius. client.shutdown() releases only
the OpenTelemetry globals Rius itself registered, so the other SDK's tracer
provider, context manager and propagator keep working after it.
init({ bridgeForeignProvider: true }) // export the other SDK's spans as wellTraces only leave the process when a span ends, so an idle-but-alive agent and a crashed one look identical from the outside. Two independent mechanisms close that gap: a heartbeat that reports the process is still running, and partial spans that leave a durable trace of in-flight work if the process disappears before finishing it.
With heartbeat: true (the default), the SDK posts to <endpoint>/v1/heartbeat
for the life of the process, provided it has credentials (apiKey, or an
Authorization header in headers); without them the heartbeat does not
start, since the endpoint would reject every ping. It sends an immediate
first ping when init() runs, then one every heartbeatInterval seconds
(default 15, clamped to 5-300), each with your headers and its own JSON
content type.
Each ping reports the count of currently open root spans, which is what
lets the backend tell a live-but-idle agent from one that has vanished.
The final ping, carrying stopped: true, is sent by client.shutdown().
The SDK also makes a best-effort attempt to send it when the process ends
naturally, on Node's beforeExit event. An application that never calls
shutdown() and exits abruptly, killed, crashed, or via process.exit(),
misses that last ping and reports as gone rather than stopped, the same way
a hard-killed agent looks in any language. Call client.shutdown() on a
graceful exit if you want that distinction to show up.
The heartbeat never keeps the process alive, its timer is unref'd, and never
throws into your code; delivery failures are logged once per client and
silent after that. agentName identifies the agent in heartbeat payloads and
on every span, where it is stamped on the resource as gen_ai.agent.name
(unless nothing was named, see above). It defaults to serviceName, so the
two agree unless you set it.
With partialSpans: true (default false), every sampled span additionally
exports a content-free snapshot the moment it starts, on top of the normal
export when it ends. The snapshot carries only identity and taxonomy
attributes, trace id, span id, name and timestamps, never content, whatever
instrumentation set on the span. The backend stores it as an unfinished row
and replaces it with the real span at end, so a snapshot that is never
replaced is the durable record of what a crashed agent was doing.
partialSpansDelay (default 0, clamped to 0-60 seconds) debounces the
snapshot: it is held for that long and only sent if the span is still open
once the delay elapses, so a span that finishes quickly costs zero network
calls.
Export is designed to never block or crash your application:
-
Async batched export. Spans are queued in-process and exported in batches from a background timer via OpenTelemetry's
BatchSpanProcessor. Span creation stays fast even when the backend is slow or unreachable. -
Retries. The OTLP/HTTP transport retries transient and retryable failures with exponential backoff and jitter, up to 5 attempts, bounded by the export timeout.
-
Graceful degradation. If the backend stays unreachable, spans are dropped and the failure is logged; an export failure is never raised into application code. Only the first export failure in a process is logged, naming
RIUS_API_KEY/RIUS_ENDPOINTas the likely cause; later failures stay silent so a persistent outage does not spam your logs.client.flush()returnsfalsewhen the most recent export failed, so you can check delivery explicitly instead of relying on logs alone. -
Bad input warns, never throws. An SDK call given input it cannot use (an invalid
markCompactionoption, an emptywithWorkspacealias, a message list whose getters throw) logs a warning and skips that one write; the rest of your code runs as if the SDK were not there. Each distinct warning is logged once per process, so the same bad input in a loop does not flood your logs. A span processor that throws is isolated from the others and fromspan.end(). -
Your errors stay yours. An error thrown by your own code inside
observe,startAsCurrentSpanorstartAsCurrentGenerationis recorded on the span and rethrown unchanged; the SDK never swallows or replaces it. -
Mask failures fail safe. If a
maskcallback throws, the affected attribute (or status description) is dropped and a warning logged, rather than leaking the unmasked value, dropping the batch or letting the exception escape. -
No automatic flush on exit. The only exit hook the SDK registers is the heartbeat's: on Node's
beforeExitit sends the finalstoppedping. Queued spans are not flushed there, andbeforeExitdoes not fire onprocess.exit()or a fatal signal. Callclient.flush()to force a pending export, orclient.shutdown()to drain the queue and tear the client down, before your process exits:await client.flush(); await client.shutdown();
Batching is tunable via the standard OpenTelemetry env vars:
OTEL_BSP_MAX_QUEUE_SIZE (default 2048; spans beyond this are dropped),
OTEL_BSP_SCHEDULE_DELAY (default 5000 ms), OTEL_BSP_MAX_EXPORT_BATCH_SIZE
(default 512), and OTEL_BSP_EXPORT_TIMEOUT (default 30000 ms).
OpenTelemetry caps a span at 128 attributes by default, and a span that
reaches the cap silently refuses every new key. OpenInference writes one
attribute per message field and per tool field, so an agent loop with ten
tools passes 128 after about nine turns, and the keys written last are
the ones that matter most: the token usage (so cost), the output messages,
output.value and the finish reason.
init() therefore raises the span attribute count limit to 4096. The
standard variables still win: if OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT or
OTEL_ATTRIBUTE_COUNT_LIMIT is set to a number, init() leaves the limit
to OpenTelemetry, which applies that value. The attribute value-length
limit is not changed.
If you run the OpenInference instrumentations without this SDK, on a
tracer provider of your own, set the limit yourself, for example
OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT=4096, or pass
spanLimits: { attributeCountLimit: 4096 } to your provider. Otherwise
long agent calls lose their usage and output.
npm ci
npm run lint
npm run typecheck
npm run build
npm testSee CONTRIBUTING.md for the full workflow, and SECURITY.md to report a vulnerability.
Releases are automated with release-please and published to npm.
- Merge changes to
mainwith Conventional Commit PR titles (feat:→ minor,fix:→ patch). Mark a breaking change with!in the PR title (feat!:→ major); PRs are squash-merged with a blank body, so aBREAKING CHANGE:footer is lost. - release-please keeps a Release PR open that bumps the package version and updates the changelog. Merge it when you want to cut a release.
- Merging the Release PR tags
vX.Y.Z, creates a GitHub Release, and publishes to npm automatically using npm trusted publishing, no token required.
Non-conventional commits are ignored for versioning.
MIT
