Skip to main content

JavaScript SDK

Complete JavaScript/TypeScript SDK reference.

Reference for the Risicare JavaScript/TypeScript SDK. The current published version is 0.19.1 — see the Changelog. Only the newest release is supported.

Installation

npm install risicare

To read the installed version, use require('risicare/package.json').version. Since npm 0.19.1, ./package.json is in the exports map of the package. Through npm 0.19.0, require('risicare/package.json') threw ERR_PACKAGE_PATH_NOT_EXPORTED.

The package has named exports only. It has no default export. Use import { init } from 'risicare' or import * as risicare from 'risicare'.

Core Functions

init

Initialize the SDK.

import { init } from 'risicare';
 
init(config?: RisicareConfig): void

enable / disable / isEnabled

Runtime control.

import { enable, disable, isEnabled } from 'risicare';
 
enable(): void
disable(): void
isEnabled(): boolean

isEnabled() is false before init(), with tracing off, with no API key, and after the SDK's own SIGTERM or SIGINT drain. enable() cannot turn tracing on when the SDK has no API key. In 0.8.0 and earlier, RISICARE_TRACING=true with no key left it true.

flush / shutdown

Export control.

import { flush, shutdown } from 'risicare';
 
flush(timeoutMs?: number): Promise<boolean>     // default 5000
shutdown(timeoutMs?: number): Promise<void>     // default: shutdownTimeoutS of init(), 10 s

shutdown() waits up to timeoutMs. When you give none, the budget is the shutdownTimeoutS of init() (default 10 s; it was 5 s through 0.10.0). Spans that the SDK cannot send in that time are counted as shutdown_residue.

flush() resolves true only when the gateway acknowledged every span and every score that the SDK accepted since the previous flush() returned (or since init()), and nothing is in the queue or in flight. This holds also in a SIGTERM or SIGINT listener and after shutdown().

A loss makes the next flush() resolve false one time, and the one after it true again. A loss is a span dropped for any reason (shutdown_residue, after_shutdown and open_at_shutdown included), a span rejected or left out of an acknowledgement, and a failed score (also a score that score() refuses at the call). Each one raises a counter that names the reason: droppedSpansByReason, rejectedSpans, failedScores. A flush() that resolves false at its deadline (timeoutMs, default 5000 ms) while none of them went up since the previous flush() means that the spans are still in flight, not lost. failedExports is not a loss counter: a later round can still deliver those spans.

flush() also resolves false when the SDK has no evidence of delivery: before init(), with tracing off, and with no API key. A flush() that you call while a shutdown() runs (your own call, or the SDK's own drain at SIGTERM or SIGINT when your application has no listener) waits for it inside its own deadline. flush() only waits; to end a process in a fixed time, call await shutdown(timeoutMs). A new init() starts a new count.

In 0.8.0 and earlier, flush() resolved true before init() and with tracing off, and it could resolve true in a signal listener or after shutdown() with nothing delivered.

A span that starts after shutdown() (and before a new init()) is not made. The SDK counts it as after_shutdown, the next flush() resolves false, and one WARNING says what to call instead. It counts it also after the SDK's own drain at SIGTERM, SIGINT or beforeExit. A span that was open when shutdown() ran and ends after it is counted as open_at_shutdown. In a serverless function, call await flush() at the end of each invocation, and await shutdown() only where the process ends. After shutdown(), getTracer() returns a retired tracer: it never throws and makes no span. See Serverless functions.

At SIGTERM and SIGINT, what the SDK does depends on whether your application has a listener for the signal (since npm 0.19.0):

  • Your application has a listener (registered before init(), or present when the signal comes; for example a server that closes in a graceful way). Your listener decides the exit, and the SDK does not shut down at the signal. It flushes at once and every 250 ms while your application stops, and it drains at beforeExit. When the process still runs shutdownTimeoutS after the signal, the SDK shuts down. It does not end the process. isEnabled() is true in your listener, so the spans that your listener makes are delivered, in both orders of registration.
  • Your application has no listener. The SDK drains what it holds. Then it raises the signal again, so that the default action ends the process.

The flushes that the SDK makes at the signal do not use up the loss report of your next flush(). A listener that calls process.exit() at once ends the process before an asynchronous flush, and what is queued is not sent. Since npm 0.19.1, any exit before the drain of the SDK (process.exit(), after a signal or not, in both orders of registration) writes one WARNING that names the spans that are queued or in an export. The WARNING does not send them: end the process after the work has stopped, or await flush() before process.exit(). See SIGTERM and SIGINT and the known limits. Before npm 0.19.0, the SDK started shutdown() at the signal and retired its tracer at once, so the spans of the requests in flight were lost.

An uncaught exception or an unhandled rejection loses the queue by default: Node.js ends the process at once. With flushOnCrash: true (or RISICARE_FLUSH_ON_CRASH=true), the SDK sends the queued spans first. The main thread waits at most 2,000 ms. The SDK never takes the crash from your code or from a library such as Sentry or PM2. See Uncaught exceptions in Node.js.

getMetrics

Returns processor metrics for monitoring export health.

import { getMetrics } from 'risicare';
 
getMetrics(): {
  sdkState: 'running' | 'shutdown' | 'uninitialised';
  exportedSpans: number;
  droppedSpans: number;
  droppedSpansByReason: {
    queue_full: number;
    transport_refused: number;
    shutdown_residue: number;
    after_shutdown: number;
    open_at_shutdown: number;
    unacknowledged: number;
    quota_exceeded: number;
    retry_exhausted: number;
    too_large: number;
  };
  droppedQuota: number;       // the quota_exceeded count again
  rejectedSpans: number;
  failedScores: number;
  failedExports: number;
  attempts: number;           // HTTP export requests; each retry and each 413 half counts
  oldestPendingAgeS: number;  // age of the oldest queued or in-flight span, in seconds
  maskErrors?: number;        // absent when sdkState is 'uninitialised'
  queueSize: number;
  queueCapacity: number;
  queueUtilization: number;
}

exportedSpans counts the spans that the gateway accepted, rejectedSpans the spans that it rejected, and failedScores the score requests that failed. queue_full counts the oldest queued span that the SDK dropped when the queue was full (npm 0.11.0 and later; through 0.10.0 it counted the new span). retry_exhausted counts the spans of a batch that the gateway did not take within retryHorizonS, and too_large the spans of a batch that got 413 again after one split. sdkState: 'shutdown' marks the final counts, kept after shutdown().

getTraceContent

Returns whether content tracing is enabled. After init() it is true unless you set traceContent: false or set RISICARE_TRACE_CONTENT to an off-word (false, 0, no, off), to an empty value or to an unknown value (the default is true since 0.10.0). Before init() it returns false. Content includes the prompts, the completions and the arguments of tool calls. With content tracing off, the text of an error is withheld too (see errorText in JS Configuration).

import { getTraceContent } from 'risicare';
 
getTraceContent(): boolean

reportError

Report a caught exception so Risicare records it on an error span and classifies it against the error taxonomy. Root-cause diagnosis and fix generation are held for the beta, so reporting an error does not trigger them. Never throws.

import { reportError } from 'risicare';
 
try {
    const result = await llm.invoke(query);
} catch (error) {
    reportError(error);          // Records and classifies the error
    return fallbackResponse;
}
ParameterTypeDefaultDescription
errorError | string(required)The caught exception
options.namestringerror class nameCustom span name
options.attributesRecord{}Additional span attributes

score

Record a score on a trace, a span or a session. Non-blocking — sends in background via fetch(). Never throws.

import { score } from 'risicare';
 
score({
    name: 'factual_accuracy',
    value: 0.92,
    traceId: '4bf92f3577b34da6a3ce929d0e0e4736',
    comment: 'Verified against source documents',
});
 
// A boolean outcome on a session
score({ name: 'resolved', value: true, sessionId: 'conv-7', kind: 'outcome' });
OptionTypeDefaultDescription
namestring(required)Score name, 1 to 128 characters
valuenumber | string | boolean(required, except with judgeFailed: true)A finite number (any range), a string of 1 to 256 characters, or a boolean. A number that is not finite is refused at the call
traceIdstringundefinedThe trace to score: 32 lowercase hex characters. Give traceId, sessionId or both. The SDK does not check the form; the API refuses any other form
spanIdstringundefinedSpecific span within the trace. It needs traceId
sessionIdstringundefinedThe session to score, 1 to 255 characters. A score can be on a session with no trace
commentstringundefinedHuman-readable explanation, at most 4,096 characters
kindstring'annotation'annotation, eval, feedback or outcome
failureClassstringundefinedA key of the failure-class vocabulary of your project: 2 to 63 lowercase letters, digits and underscores. Any kind. The API checks the key and answers 422 (unknown_failure_class) for an unknown one
judgeModelstringundefinedThe model id that the judge used, at most 128 characters. Needs kind: 'eval'
judgeVersionstringundefinedYour own version of the judge, at most 64 characters. Needs kind: 'eval'
judgePromptHashstringundefinedSHA-256 of the judge prompt, 64 lowercase hex characters. Needs kind: 'eval'
judgeFailedbooleanfalsetrue posts a result with no value: the judge or the check ran and gave no result. Needs kind: 'eval'. Leave out value. Risicare stores the row and counts it as failed. It is never read as 0 or 1, and it is not billed
trialnumberundefinedThe trial number in one experiment, 1 to 1,000. Needs experimentId
experimentIdstringundefinedYour id of the experiment or CI run, at most 128 characters

The type of the argument is ScoreOptions, a union of ScoreValueOptions (has value) and ScoreFailedOptions (judgeFailed: true, no value). The package exports both, and ScoreKind. A TypeScript interface that extends ScoreOptions does not compile (npm 0.14.0): extend ScoreValueOptions or use a type alias. The SDK sends a field only when you set it. It does not change kind when you set a judge field: pass kind: 'eval'. The positional form of 0.10.0 and earlier, score(traceId, name, value, { spanId, comment }), still sends the score. The first such call writes one WARNING. Use the object form.

npm 0.11.0 added the typed value, the kind and the session scores. Before, value was a number from 0.0 to 1.0, and the SDK refused any other value at the call. npm 0.14.0 added the judge fields, failureClass, trial and experimentId. See the Changelog.

A score that the SDK refuses at the call (for example a name over 128 characters, a value of the wrong type, no trace and no session, or a judge field with a kind other than eval) is not sent, writes a WARNING that names the rule, and adds 1 to failedScores. A failed request (an error, a timeout after 2000 ms, or a status of 300 or more) adds 1 to failedScores; the first failure logs a WARNING, and failures in the next 10 seconds are counted in the next one. The SDK does not follow a redirect.

A 429 from the api (since npm 0.19.1). When the api limits the request rate, it answers 429 with error.code RATE_LIMIT_EXCEEDED and a Retry-After header. score() then waits for that time (never less, at least 1 s, with a small random part on top) and sends again: one wait of at most 10 s, at most 2 retries, at most 20 s in all. At exit, the process waits for a score retry, as it waits for a score in flight. When the api asks for a longer wait, or a bound is used up, the request fails at once and the error says why. A 429 with no Retry-After fails as before.

setUser / setSession / setRelease / addTags

Set the user, the session, the release and the tags of the current trace.

import { setUser, setSession, setRelease, addTags } from 'risicare';
 
setUser(userId: string | number): boolean
setSession(sessionId: string | number): boolean
setRelease(version: string | number): boolean
addTags(tags: readonly string[]): boolean

The SDK writes user.id, session.id, risicare.release and tag.tags (a list) on the current span, and on each other span of the same trace that ends after the call (also the open root span), unless that span has the attribute already. Outside a span, a helper sets nothing, returns false and writes one WARNING. With tracing off (no init(), enabled: false, RISICARE_TRACING off or not recognised, after shutdown()), the helpers are silent: they set nothing, return false and write no WARNING (since npm 0.19.1; through 0.19.0 they wrote "called outside a span", a wrong cause). For a release on every span with no code, use init({ serviceVersion }) or RISICARE_SERVICE_VERSION. See the Changelog.

getPrompt

Pull a prompt by label or by version.

import { getPrompt, PromptContent } from 'risicare';
 
const prompt = await getPrompt(name: string, {
    label?: string,
    version?: number,
    fallback?: PromptContent,
    cacheTtlMs?: number,
    timeoutMs?: number,
}): Promise<Prompt>

Give label or version, not both. With neither, the label is production. A bad argument rejects with a TypeError. The call sends GET /v1/prompts/resolve to the api host with the key of init(), and the key needs the scope prompts:read. An ingest key and a secret key have it. The SDK pulls nothing at import time or at init(). The cache is in memory, with at most 500 entries. cacheTtlMs is 5,000 to 3,600,000 (default 60,000) and timeoutMs is 100 to 10,000 (default 1,000). When the first pull fails and nothing is cached, the call returns fallback. With no fallback it rejects with PromptUnavailable. A 429 from the api does not make getPrompt() wait: the cached value or the fallback serves the call, and the SDK does not ask again before the Retry-After time (at most one hour). A prompt that the api limits has the reason rate_limited (since npm 0.19.1). The Prompt has name, version, hash, label, source and the content (messages, model, parameters, tools, outputSchema, variables), and the methods compile(), openaiBody(), anthropicBody() and run(). MissingVariable is thrown by compile() for a placeholder with no value. The package exports getPrompt, Prompt, PromptContent, PromptUnavailable and MissingVariable. See the Changelog.

withPrompt

Name the prompt and its version for the LLM calls inside a function.

import { withPrompt } from 'risicare';
 
withPrompt(name, version, fn, { hash, label })

Each LLM span that starts inside fn gets risicare.prompt.name, risicare.prompt.version and llm.prompt_template.version, and risicare.prompt.hash and risicare.prompt.label when you give them. The SDK does not send the prompt text. See the Changelog.

risicare/evals

A new entry point for eval runs.

import { runDataset, defineCheck } from 'risicare/evals';
 
await runDataset({ dataset, fn, checks, trials });

runDataset runs each case and trial under its own trace and posts one score for each check and trial. The entry point also exports RisicareEvalError and the types Case, Check, CheckResult, Judge, Run, RunSummary and TrialRecord. The package has a risicare command (the bin of the package): risicare eval gate. See the Changelog.

Provider Patches

12 native provider patches, each imported from a sub-path export. All client-based patches return a transparent ES Proxy wrapper — the original client is unchanged. patchVercelAI() is the exception — it takes no client and wraps top-level functions, returning { tracedGenerateText, tracedStreamText, tracedGenerateObject }.

ProviderImportPatch Function
OpenAIrisicare/openaipatchOpenAI(client)
Anthropicrisicare/anthropicpatchAnthropic(client)
Vercel AIrisicare/vercel-aipatchVercelAI()
Google Geminirisicare/googlepatchGoogleAI(client)
Mistralrisicare/mistralpatchMistral(client)
Groqrisicare/groqpatchGroq(client)
Cohererisicare/coherepatchCohere(client)
Together AIrisicare/togetherpatchTogether(client)
Ollamarisicare/ollamapatchOllama(client)
HuggingFacerisicare/huggingfacepatchHuggingFace(client)
Cerebrasrisicare/cerebraspatchCerebras(client)
AWS Bedrockrisicare/bedrockpatchBedrock(client)
import { patchOpenAI } from 'risicare/openai';
import { patchAnthropic } from 'risicare/anthropic';
import { patchGroq } from 'risicare/groq';
import OpenAI from 'openai';
 
const openai = patchOpenAI(new OpenAI());
// chat.completions.create, embeddings.create and the Responses API (responses.create,
// also with stream: true, and responses.parse) are now traced. So are the stream helpers
// responses.stream() and chat.completions.stream() (see traceStreamHelpers)

Host Detection (OpenAI-Compatible)

When using patchOpenAI() with a client pointing to an OpenAI-compatible API, the SDK automatically detects the real provider from the base URL and sets gen_ai.system correctly:

ProviderBase URL
DeepSeekapi.deepseek.com
Together AIapi.together.xyz
Groqapi.groq.com
xAI (Grok)api.x.ai
Fireworksapi.fireworks.ai
Baseteninference.baseten.co
Novitaapi.novita.ai
BytePlusapi.byteplus.com, ark.cn-beijing.byteplus.com
import { patchOpenAI } from 'risicare/openai';
import OpenAI from 'openai';
 
// DeepSeek via OpenAI-compatible API — auto-detected as "deepseek"
const deepseek = patchOpenAI(new OpenAI({
    baseURL: 'https://api.deepseek.com/v1',
    apiKey: process.env.DEEPSEEK_API_KEY,
}));

patchVercelAI

Returns higher-order wrapper functions for Vercel AI SDK:

import { generateText, streamText, generateObject } from 'ai';
import { patchVercelAI } from 'risicare/vercel-ai';
 
const { tracedGenerateText, tracedStreamText, tracedGenerateObject } = patchVercelAI();
const generate = tracedGenerateText(generateText);
const stream = tracedStreamText(streamText);
const genObject = tracedGenerateObject(generateObject);

Framework Integrations

4 framework integrations, each imported from a sub-path export:

LangChain.js

import { RisicareCallbackHandler } from 'risicare/langchain';
 
const handler = new RisicareCallbackHandler();
const result = await chain.invoke(input, { callbacks: [handler] });

LangGraph.js

import { instrumentLangGraph } from 'risicare/langgraph';
 
const tracedGraph = instrumentLangGraph(compiledGraph);
const result = await tracedGraph.invoke(input);

instrumentLangGraph() never changes your config (since npm 0.19.0). See LangGraph.

Instructor

import { patchInstructor } from 'risicare/instructor';
 
const patchedClient = patchInstructor(instructorClient);
const result = await patchedClient.chat.completions.create({
  model: 'gpt-4o',
  response_model: { schema: MySchema, name: 'MySchema' },
  messages: [{ role: 'user', content: 'Extract the data' }],
});

LlamaIndex.TS

import { Settings } from 'llamaindex';
import { RisicareLlamaIndexHandler } from 'risicare/llamaindex';
 
const handler = new RisicareLlamaIndexHandler();
for (const name of RisicareLlamaIndexHandler.EVENT_NAMES) {
  Settings.callbackManager.on(name as any, (e: any) => handler.onEvent(e));
}
 
// Provider spans are suppressed only inside withSuppression():
const result = await handler.withSuppression(() => queryEngine.query({ query: '...' }));

Streaming

Trace async iterables with automatic span lifecycle management:

import { tracedStream } from 'risicare';
 
const stream = tracedStream(asyncIterable, { name: 'llm-stream' });
for await (const chunk of stream) {
    handleChunk(chunk);
}
// Span automatically records stream.chunk_count and stream.completed

Dedup

Framework integrations can suppress provider-level tracing to prevent double-tracing:

import { suppressProviderInstrumentation, isProviderInstrumentationSuppressed } from 'risicare';
 
await suppressProviderInstrumentation(async () => {
    // Provider patches are suppressed inside this scope
    await client.chat.completions.create(/* ... */);
});

Higher-Order Functions

agent

import { agent } from 'risicare';
 
agent<T extends (...args: any[]) => any>(
  options: {
    name?: string;
    role?: string;  // any string; canonical values are the AgentRole enum
    agentType?: string;
    version?: number;
    metadata?: Record<string, unknown>;
  },
  fn: T
): T

session

import { session } from 'risicare';
 
session<T extends (...args: any[]) => any>(
  optionsOrResolver: SessionOptions | ((...args: any[]) => SessionOptions),
  fn: T
): T
 
interface SessionOptions {
  sessionId: string;
  userId?: string;
}

Put the session outside the run: call the function that agent() wraps inside the session. Each call sends one session.end marker span, which is never a failed span (since npm 0.19.1). An AbortError that ends agent(), a phase function, session() or withSession() is not an error (since npm 0.19.1). See Session outside, run inside and An abort is not an error.

Phase Functions

Phase decorators accept either a bare function or a name + function (added in 0.2.1):

These return a wrapped function — you must call it

traceThink / traceDecide / traceAct / traceObserve do not run your function. They return a wrapper, and a span is emitted only when you invoke that wrapper. Writing traceAct('execute-tool', fn); on its own emits zero spans — with no error and no warning, which reads as "tracing is broken" rather than "the wrapper was never called".

import { traceThink, traceDecide, traceAct, traceObserve } from 'risicare';
 
// Bare form with an anonymous function — the span is named `phase:think`.
// With a named function, the span is `<phase>:<function>`, for example `think:analyzeQuery`.
const analyzeBare = traceThink(async () => { /* ... */ });
 
// Named form — explicit span name
const analyze = traceThink('analyze-query', async () => { /* ... */ });
 
// All four phases support both forms
const choose = traceDecide('choose-action', async () => { /* ... */ });
const execute = traceAct('execute-tool', async () => { /* ... */ });
const check = traceObserve('check-result', async () => { /* ... */ });
 
// Nothing is traced until the wrappers are invoked:
await analyze();
await choose();
await execute();
await check();

Multi-Agent Functions

import { traceMessage, traceDelegate, traceCoordinate } from 'risicare';
 
traceMessage<T extends (...args: any[]) => any>(
  options: { to: string },
  fn: T
): T
 
traceDelegate<T extends (...args: any[]) => any>(
  options: { to: string },
  fn: T
): T
 
traceCoordinate<T extends (...args: any[]) => any>(
  options: { participants: string[] },
  fn: T
): T

Context Functions

getCurrentContext

import { getCurrentContext } from 'risicare';
 
// Returns a plain object snapshot. session/agent/span are either an
// object or null; phase is a SemanticPhase or null.
getCurrentContext(): {
  session: { sessionId: string; userId?: string } | null;
  agent: {
    agentId: string;
    agentName?: string;
    agentRole?: string;
    agentType?: string;
  } | null;
  span: { spanId: string; traceId: string } | null;
  phase: SemanticPhase | null;
}

Individual Getters

import {
  getCurrentTraceId,
  getCurrentSpanId,
  getCurrentAgentId,
  getCurrentSessionId,
} from 'risicare';
 
getCurrentTraceId(): string | undefined
getCurrentSpanId(): string | undefined
getCurrentAgentId(): string | undefined
getCurrentSessionId(): string | undefined

W3C Trace Context

import { injectTraceContext, extractTraceContext } from 'risicare';
 
injectTraceContext(headers: Record<string, string>): Record<string, string>
 
// Always returns a record (never undefined). When the incoming headers
// carry a Risicare tracestate it includes traceId, parentSpanId, flags,
// and any propagated sessionId / agentId.
extractTraceContext(headers: Record<string, string>): Record<string, string | undefined>

getTraceContext

Returns the current trace context as a serializable object. When called outside any active span it pre-allocates a root trace ID so the next span created in the same context inherits it.

import { getTraceContext } from 'risicare';
 
getTraceContext(): TraceContext   // { traceId, spanId, sessionId?, agentId? }

Context Scope Wrappers

Run a callback inside an explicit session, agent, or phase scope. Each returns the callback's result.

import { withSession, withAgent, withPhase } from 'risicare';
import { SemanticPhase } from 'risicare';
 
withSession(options: { sessionId: string; userId?: string }, fn: () => T): T
withAgent(options: { name?: string; role?: string; agentType?: string }, fn: () => T): T
withPhase(phase: SemanticPhase, fn: () => T): T

Webhook Verification

Verify the signature of an incoming Risicare webhook delivery before processing it. verifyWebhookSignature is a root export (import { verifyWebhookSignature } from 'risicare') — there is no risicare/webhooks subpath. It is dependency-light (Node crypto only) and ships in risicare@0.4.0.

import {
  verifyWebhookSignature,
  WebhookVerificationError,
  DEFAULT_TIMESTAMP_TOLERANCE_S,   // 300 (seconds)
} from 'risicare';
 
verifyWebhookSignature(
  payload: Uint8Array | ArrayBuffer | string,   // raw request body bytes
  headers: Headers | Map<string, string> | Record<string, string | string[] | undefined>,
  secret: string,
  opts?: { toleranceS?: number },               // default 300s skew window
): void   // returns undefined on success; throws on any failure

The verifier enforces three checks (all must pass): both X-Risicare-Signature and X-Risicare-Timestamp headers present and well-formed; timestamp within toleranceS of now (replay protection); and a constant-time HMAC-SHA256 match over the canonical <timestamp>.<payload_bytes> string. Any failure throws WebhookVerificationError — catch it specifically to return a 401.

Pass the raw body, not parsed JSON

The signature is computed over the EXACT bytes received. Parsing JSON and re-serializing changes key ordering and whitespace, so the signature will not match. Use your framework's raw-body option (e.g. express.raw()).

import express from 'express';
import { verifyWebhookSignature, WebhookVerificationError } from 'risicare';
 
const app = express();
app.post('/risicare-webhook', express.raw({ type: '*/*' }), (req, res) => {
  try {
    verifyWebhookSignature(req.body, req.headers, process.env.WEBHOOK_SECRET!);
  } catch (e) {
    if (e instanceof WebhookVerificationError) {
      return res.status(401).send(e.message);
    }
    throw e;
  }
  // ... process the verified event ...
  res.status(200).end();
});

Node runtime only

This verifier is synchronous and uses Node's crypto module. It does not run as-is on Cloudflare Workers / Vercel Edge / Deno Deploy. An async Web Crypto variant can be added on request.

Span Registry

import {
  registerSpan,
  getSpanById,
  unregisterSpan,
} from 'risicare';
 
registerSpan(span: Span, ttlMs?: number): void
getSpanById(spanId: string): Span | undefined
unregisterSpan(spanId: string): void

Types

RisicareConfig

interface RisicareConfig {
  apiKey?: string;
  projectId?: string;  // DEPRECATED — emits console.warn. Will be removed in v1.0.
  endpoint?: string;     // default 'https://ingest.risicare.ai' (spans)
  apiEndpoint?: string;  // default 'https://api.risicare.ai' (scores, prompts, evals, fix reads)
  environment?: string;
  serviceName?: string;
  serviceVersion?: string;  // the SDK puts it on every span as service.version
  enabled?: boolean;
  traceContent?: boolean;  // default true since 0.10.0
  errorText?: boolean | 'auto';  // default 'auto': follows traceContent
  flushOnCrash?: boolean;  // default false (Node.js only)
  streamUsage?: boolean | 'auto';  // default 'auto'
  traceStreamHelpers?: boolean;  // default true
  compress?: boolean;
  sampleRate?: number;
  batchSize?: number;
  batchTimeoutMs?: number;
  maxQueueSize?: number;
  retryHorizonS?: number;  // default 300
  shutdownTimeoutS?: number;  // default 10
  maxInputMessagesBytes?: number;  // default 49152
  debug?: boolean;
  fixRuntime?: boolean;  // default false since 0.7.0
  metadata?: Record<string, unknown>;
  mask?: (key: string, value: unknown) => unknown;
}

TraceContext

interface TraceContext {
  traceId: string;
  spanId: string;
  sessionId?: string;
  agentId?: string;
}

Span

Span and Tracer are types only. Import them with import type { Span, Tracer } from 'risicare'. A value import (import { Span } from 'risicare') is a compile error in TypeScript (TS2693), and a SyntaxError at run time in plain JavaScript under ESM (under CommonJS, require('risicare').Span is undefined).

class Span {
  traceId: string;
  spanId: string;
  name: string;
  kind: SpanKind;
  startTime: string;        // ISO 8601 timestamp
  endTime?: string;         // ISO 8601 timestamp, set on end()
  attributes: Record<string, unknown>;
  events: SpanEvent[];
  status: SpanStatus;
 
  setAttribute(key: string, value: unknown): this;
  addEvent(name: string, attributes?: Record<string, unknown>): this;
  setStatus(status: SpanStatus, message?: string): this;
  end(): void;
}

SpanKind

enum SpanKind {
  INTERNAL = 'internal',
  SERVER = 'server',
  CLIENT = 'client',
  PRODUCER = 'producer',
  CONSUMER = 'consumer',
  AGENT = 'agent',
  LLM_CALL = 'llm_call',
  TOOL_CALL = 'tool_call',
  RETRIEVAL = 'retrieval',
  DECISION = 'decision',
  DELEGATION = 'delegation',
  COORDINATION = 'coordination',
  MESSAGE = 'message',
  THINK = 'think',
  DECIDE = 'decide',
  OBSERVE = 'observe',
  REFLECT = 'reflect',
}

SpanStatus

enum SpanStatus {
  UNSET = 'unset',
  OK = 'ok',
  ERROR = 'error',
}

Next Steps