Skip to main content

JS Context

Trace context propagation in JavaScript/TypeScript.

The JavaScript SDK uses AsyncLocalStorage for automatic context propagation across async operations.

Getting Context

getCurrentContext()

Get the current context state:

import { getCurrentContext } from 'risicare';
 
const context = getCurrentContext();
if (context) {
  console.log('Session:', context.session);
  console.log('Agent:', context.agent);
  console.log('Span:', context.span);
  console.log('Phase:', context.phase);
}

getCurrentContext() returns a plain object snapshot of the current context. Its session and agent fields are either null (when not set) or objects with these keys:

{
  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';
 
const traceId = getCurrentTraceId();
const spanId = getCurrentSpanId();
const agentId = getCurrentAgentId();
const sessionId = getCurrentSessionId();

W3C Trace Context

Propagate context across service boundaries using W3C headers:

Inject Context

import { injectTraceContext } from 'risicare';
 
// Inject into HTTP headers
const headers: Record<string, string> = {};
injectTraceContext(headers);
 
// Inside an active span (for example in a function wrapped by agent()),
// headers now contains:
// {
//   'traceparent': '00-abc123...-def456...-01',
//   'tracestate': 'risicare=...'   // only when a session or an agent is current
// }
// Outside a span, headers stays empty.
 
await fetch('https://api.example.com', { headers });

Extract Context

extractTraceContext always returns a Record<string, string | undefined> (it is never undefined). traceId, parentSpanId and flags come from the traceparent header. sessionId and agentId come from a Risicare tracestate, when the caller sent one. Use those values to re-enter the corresponding context scope — for example, restoring the upstream session with withSession:

import { extractTraceContext, withSession } from 'risicare';
 
// In your HTTP handler
app.post('/api/endpoint', async (req, res) => {
  // The declared parameter type is Record<string, string>, so cast the Express headers.
  const context = extractTraceContext(req.headers as Record<string, string>);
 
  if (context.sessionId) {
    await withSession({ sessionId: context.sessionId }, async () => {
      // Spans created here are grouped under the propagated session
      await processRequest(req.body);
    });
  } else {
    await processRequest(req.body);
  }
 
  res.json({ success: true });
});

Manual Context Management

Use the exported scope wrappers to run code within an explicit session, agent, or phase context. Each takes the scope's options (or value) and a callback, runs the callback inside that scope, and returns its result. They nest naturally:

import { withSession, withAgent, withPhase } from 'risicare';
import { SemanticPhase } from 'risicare';
 
await withSession({ sessionId: 'sess-123', userId: 'user-456' }, async () => {
  await withAgent({ name: 'my-agent', role: 'worker' }, async () => {
    // Code here runs with the session + agent context applied
    await doWork();
  });
});
 
// A single phase scope:
await withPhase(SemanticPhase.THINK, async () => {
  await analyze();
});

Prefer the higher-level wrappers (session(), agent(), and the phase functions in JS Decorators) for instrumenting whole functions; the withX() forms are for ad-hoc scoping inside existing code.

Session outside, run inside

Open the session first. Then call the run (a function that agent() wraps) inside it:

import { agent, withSession } from 'risicare';
 
const answerTurn = agent({ name: 'support-agent' }, async (message: string) => {
  return await answer(message);
});
 
export async function handleMessage(sessionId: string, userId: string, message: string) {
  // 1. the session: outside. 2. the run: inside.
  return withSession({ sessionId, userId }, () => answerTurn(message));
}

The SDK writes the session on each span that starts inside the session. A run span that starts before the session does not get it. For Python, see Session outside, run inside.

The session.end marker. Each time a withSession() callback or a call of a function that session() wraps ends, the SDK sends one session.end marker span: one marker for each call. With the session outside the run, the marker is a one-span trace of its own. It is never a failed trace (since npm 0.19.1): its status is ok, not error, and the outcome is in risicare.lifecycle.status (ok, error or cancelled). Through npm 0.19.0, a failed turn made the marker an error span too. An AbortError that ends the callback is not an error: see An abort is not an error.

Span Registry

Access spans by ID for use in async generators and streaming:

import {
  getTracer,
  registerSpan,
  getSpanById,
  unregisterSpan,
} from 'risicare';
 
getTracer()!.startSpan({ name: 'stream-response' }, (span) => {
  // Register the span for later lookup by ID
  registerSpan(span, 30000); // optional TTL in ms
 
  // Get the span by its ID
  const same = getSpanById(span.spanId);
 
  // Clean up when done
  unregisterSpan(span.spanId);
});

When to Use the Span Registry

The span registry is designed for async generators and streaming scenarios where contextvars context may be lost after yield. Store the span ID before yielding, then retrieve it by ID in subsequent iterations.

Cross-Process Propagation

HTTP Client

import { injectTraceContext } from 'risicare';
 
async function fetchWithTracing(url: string, options: RequestInit = {}) {
  const headers = new Headers(options.headers);
 
  // Inject trace context
  const traceHeaders: Record<string, string> = {};
  injectTraceContext(traceHeaders);
 
  Object.entries(traceHeaders).forEach(([key, value]) => {
    headers.set(key, value);
  });
 
  return fetch(url, { ...options, headers });
}

Message Queues

import { injectTraceContext, extractTraceContext, withSession } from 'risicare';
 
// Producer
async function publishMessage(queue: Queue, payload: unknown) {
  const headers: Record<string, string> = {};
  injectTraceContext(headers);
 
  await queue.publish({
    payload,
    headers,
  });
}
 
// Consumer
async function handleMessage(message: Message) {
  const context = extractTraceContext(message.headers);
 
  if (context.sessionId) {
    await withSession({ sessionId: context.sessionId }, async () => {
      await processMessage(message.payload);
    });
  } else {
    await processMessage(message.payload);
  }
}

Next Steps