TypeScript SDK API Reference

Both

Complete API reference for the Traccia TypeScript SDK.

This page documents all public functions, classes, and decorators in the @traccia/sdk package.

Initialization

Traccia.init()

Initializes the Traccia SDK with options and registers it globally. Must be awaited before creating traces.

typescript
static async init(config?: SDKConfig): Promise<ITracerProvider>

Parameters:

apiKey — API key for Traccia Platform (optional if set in env)
endpoint — OTLP endpoint (default: env or http://localhost:4318/v1/traces)
sampleRate — Ratio of traces to sample (default: 1.0)
maxQueueSize — Max number of buffered spans
enableConsoleExporter — Print spans to console for debugging
autoInstrument — Automatically instrument supported libraries like Axios/Express (default: false)
enableTokenCounting — Count tokens for LLM operations
enableCostTracking — Calculate LLM costs based on tokens
pricingOverride — Override pricing tables
redactPii — Mask sensitive patterns automatically before export

Returns:

Promise resolving to the ITracerProvider.

Example:

typescript
import { Traccia } from "@traccia/sdk";
// Minimal initialization
await Traccia.init();
// With configuration
await Traccia.init({
apiKey: "tr_live_xxxxxxxxxxxx",
sampleRate: 0.1,
autoInstrument: true,
enableTokenCounting: true
});

stopTracing()

Gracefully shutdown the TracerProvider, flush pending spans, and clean up resources.

typescript
import { stopTracing } from "@traccia/sdk";
// Flush and shutdown
await stopTracing();

Tracing API

@observe()

Decorator to automatically create spans around method execution. Note: Requires TypeScript experimentalDecorators or Babel.

typescript
function observe(options?: ObserveOptions): MethodDecorator

Parameters:

name — Override the span name (defaults to class.methodName)
attributes — Static attributes to add to the span
skipArgs — Array of argument names to omit from the span
skipResult — Boolean, if true the return value is not captured

See @observe() Documentation for detailed usage.

Traccia.getTracer()

Get a tracer instance to start spans manually.

typescript
static getTracer(name?: string, version?: string): ITracer
typescript
import { Traccia } from "@traccia/sdk";
const tracer = Traccia.getTracer("my-service");
await tracer.startActiveSpan("operation", async (span) => {
span.setAttribute("custom", "value");
await doWork();
span.end();
});

Traccia.getCurrentSpan()

Retrieve the currently active span in the async context.

typescript
import { Traccia } from "@traccia/sdk";
const span = Traccia.getCurrentSpan();
span?.setAttribute("step", "validation");

spanScope()

Start a span with explicit lifecycle control. Unlike startActiveSpan, the span is not ended automatically — call scope.end() when the operation completes. Use for long-lived operations such as streaming chat turns.

typescript
import { spanScope } from "@traccia/sdk";
async function handleStream() {
const turn = spanScope("chat.turn", { attributes: { "span.type": "llm" } });
try {
await turn.runAsync(async () => {
for await (const chunk of streamTokens()) {
// child spans created here attach to chat.turn
}
});
} catch (error) {
turn.end(error);
throw error;
}
turn.end();
}

runWithSpan() / runWithSpanAsync()

Run a function with a specific span set as the active parent. Used internally by spanScope().run() and spanScope().runAsync().

typescript
import { Traccia, runWithSpan, runWithSpanAsync } from "@traccia/sdk";
const tracer = Traccia.getTracer();
const span = tracer.startSpan("background_job");
// Sync
runWithSpan(span, () => processBatch());
// Async
await runWithSpanAsync(span, async () => processBatchAsync());
span.end();

Runtime Configuration

Functions to attach metadata (Session ID, User ID, Tenant ID) directly to the active root context.

typescript
import { Traccia } from "@traccia/sdk";
// Attach context to the active span context globally
Traccia.setSessionId("session-123");
Traccia.setUserId("user-456");
Traccia.setTenantId("tenant-789");

Instrumentation & HTTP Middlewares

expressMiddleware

Express middleware to auto-create spans for HTTP routes and extract incoming trace contexts.

typescript
import express from "express";
import { expressMiddleware } from "@traccia/sdk";
const app = express();
app.use(expressMiddleware());

patchAxios / createTracedAxios

Instrument Axios to inject trace context into outgoing HTTP headers.

typescript
import axios from "axios";
import { patchAxios } from "@traccia/sdk";
// Patch the global axios instance
patchAxios();

patchOpenAI / patchAnthropic

Manual instrumentation for LLM clients (automatically enabled if autoInstrument: true).

Prompts

Fetch versioned prompts from the Traccia library at runtime, compile {{variables}}, and stamp the active span with prompt identity. Narrative guide: Prompts in the SDK. Platform workflow: Platform Prompts.

Requires Traccia platform

Runtime fetch uses your workspace API key against the prompt-runtime API. Tracing-only setups can still compile an explicit fallback body.

loadPrompt()

typescript
async function loadPrompt(options: {
name: string;
label?: string; // default "production"
version?: number; // mutually exclusive with label
fallback?: Record<string, unknown>;
forceRefresh?: boolean;
}): Promise<LoadedPrompt>

LoadedPrompt

name, type, version, versionId, label
text / messages — uncompiled body by type
config — model hint from the version
isFallback, isStale
compile(vars) — substitutes {{var}}; missing required → CompileError
spanAttributes() / applySpanAttributes() — also applied on successful compile
typescript
import { init, loadPrompt, observe } from "@traccia/sdk";
await init({
apiKey: "tr_…",
endpoint: "https://api.traccia.ai/v2/traces",
promptCacheTtlS: 60,
});
const reply = observe({ type: "llm" })(async (question: string) => {
const prompt = await loadPrompt({
name: "support-reply",
label: "production",
fallback: {
type: "chat",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "{{question}}" },
],
},
});
const messages = prompt.compile({ question });
return callLlm(messages);
});

prefetchPrompts()

Warm the client cache at startup. Optional jitter spreads multi-replica stampedes.

typescript
async function prefetchPrompts(
names: string[],
opts?: { label?: string; jitterMs?: number },
): Promise<LoadedPrompt[]>
await prefetchPrompts(["support-reply", "billing-triage"], { jitterMs: 500 });

Cache, SWR, and init options

  • Default TTL ~60s; key is name + label or version
  • After expiry: return last good and refresh in the background (isStale)
  • Fetch failure with cache → last good. Without cache → fallback or throw PromptFetchError
promptCacheTtlS / TRACCIA_PROMPT_CACHE_TTL_S

Span attributes

traccia.prompt.name
traccia.prompt.version
traccia.prompt.version_id
traccia.prompt.label
traccia.prompt.is_fallback

Redaction allowlists these keys. Full catalog: Span Events & Attributes.

Governance

govern() requires Traccia platform

observe() works with any OTLP backend. govern() calls the Traccia agent-status API before each run. Tracing-only users should use observe().

govern()

Decorator or function wrapper combining observability with runtime policy enforcement. Policy URLs default from your tracing endpoint.

typescript
import { Traccia, govern, AgentBlockedError } from "@traccia/sdk";
await Traccia.init({ apiKey: "...", endpoint: "https://api.traccia.ai/v2/traces" });
const runAgent = govern({
agentId: "my-agent",
failOpen: false,
name: "run_agent",
})(async (prompt: string) => callLlm(prompt));

disclosure()

Record Art. 50 transparency evidence on the current span after your UI informed the user.

typescript
import { disclosure } from "@traccia/sdk";
disclosure({ channel: "ui", disclosedToUser: true });

governanceHooks

Register lifecycle hooks for pre/post execution and policy violations.

typescript
import { governanceHooks } from "@traccia/sdk";
governanceHooks.registerHooks({
onBeforeExecute: (span) => { /* ... */ },
onAfterExecute: (span) => { /* ... */ },
});

guardrailSpan()

Wrapper to track guardrail evaluations.

typescript
import { guardrailSpan } from "@traccia/sdk";
await guardrailSpan("PII_Check", async (span) => {
// Evaluation logic
}, { action: "block" });

RedactionSpanProcessor

Automatically strips configured sensitive patterns from attributes. Registered automatically via init({ redactPii: true }).

redactString / redactAttributes

Utility functions for manual redaction.

typescript
import { redactString, redactAttributes } from "@traccia/sdk";
const safeText = redactString("Email me at user@example.com");
// "Email me at [REDACTED_EMAIL]"
const safeObj = redactAttributes({ phone: "555-0199" });

Span Methods

When you have a span object (from tracer.startActiveSpan or getCurrentSpan), you can use these methods:

span.setAttribute(key: string, value: any)
span.addEvent(name: string, attributes?: Record<string, any>)
span.recordException(exception: Error)
span.setStatus(status: SpanStatus, description?: string)
span.end()

Next Steps

© 2026 Traccia.