Skip to content

JavaScript and TypeScript SDK (softprobe-js) ​

API reference for the @softprobe/* npm packages (version 0.1.18, Node.js 20 or newer).

PackagePurposeSource
@softprobe/tracingCore OpenTelemetry tracer, observations, generations, OpenAI wrapper, and scoressoftprobe-js/packages/tracing
@softprobe/web-recordBrowser rrweb DOM recording, same-origin HTTP tracing, and JSON body capturesoftprobe-js/packages/web-record
@softprobe/vercel-ai-sdkVercel AI SDK telemetry integration and HTTP context propagationsoftprobe-js/packages/vercel-ai-sdk
@softprobe/langchainLangChain and LangGraph auto-instrumentation and CallbackHandlersoftprobe-js/packages/langchain
@softprobe/opencode-pluginOpenCode coding-agent pluginsoftprobe-js/packages/opencode-plugin

@softprobe/tracing ​

Install the core package:

bash
npm install @softprobe/tracing

SoftprobeClient ​

SoftprobeClient configures an OpenTelemetry NodeTracerProvider, exports OTLP HTTP/protobuf spans with automatic retries, and sends scores to the Softprobe API.

SoftprobeClient.fromEnv(overrides?) ​

Builds a client from standard OpenTelemetry and Softprobe environment variables, merged with optional overrides (Partial<SoftprobeClientOptions>). Throws MissingSoftprobeCredentialsError if no Ingestion Key is found in overrides.ingestionKey, INGESTION_KEY, OTEL_EXPORTER_OTLP_TRACES_HEADERS, or OTEL_EXPORTER_OTLP_HEADERS.

ts
import { SoftprobeClient } from "@softprobe/tracing";

const client = SoftprobeClient.fromEnv({ serviceName: "my-agent" });

new SoftprobeClient(options) ​

Creates a client from an explicit SoftprobeClientOptions object.

OptionTypeDefaultDescription
ingestionKeystringRequiredAgent Ingestion Key (spk_...)
baseUrlstringhttps://explorer.softprobe.ai/api/thelakeScore API base URL. Does not change the OTLP trace endpoint.
otlpOtlpExportOptions{}{ endpoint?, tracesEndpoint?, protocol?, headers? }
otlpEndpointstringProduction traces URLLegacy alias for otlp.tracesEndpoint
resourceAttributesRecord<string, ResourceAttributeValue>{}Additional OpenTelemetry resource attributes
serviceNamestring"softprobe-app"Sets OpenTelemetry service.name
serviceVersionstringundefinedSets OpenTelemetry service.version
environmentstringundefinedSets deployment.environment.name
releasestringundefinedDefault release tag on observations
sessionIdstringundefinedDefault gen_ai.conversation.id and session.id
userIdstringundefinedDefault user.id
tagsstring[]undefinedDefault tags on observations
redactKeysstring[]defaultRedactKeys()Keys replaced with [REDACTED] in captured payloads
timeoutMsnumber10000HTTP timeout in milliseconds
headersRecord<string, string>{}Additional headers merged into OTLP and score requests
useSimpleProcessorbooleanfalseUse SimpleSpanProcessor instead of BatchSpanProcessor
retryExportbooleantrueWrap the OTLP exporter in RetryingSpanExporter

OtlpExportOptions:

FieldTypeDescription
tracesEndpointstringFull OTLP HTTP traces URL, used as written
endpointstringGeneric OTLP base URL. The SDK appends /v1/traces.
protocol"http/protobuf"Softprobe exporters support http/protobuf
headersRecord<string, string>Additional OTLP request headers (not sent to the score API)

Observation and generation methods ​

  • startObservation(options: StartObservationOptions): Observation
  • startGeneration(options: StartGenerationOptions): Generation
  • startAgent(options) (sets asType: "agent")
  • startTool(options: StartToolOptions) (sets asType: "tool" and tool attributes such as toolName, toolCallId, kind, status, index, mcpServer, mcpTool)
  • startChain(options), startRetriever(options), startEvaluator(options), startEmbedding(options), startGuardrail(options), startEvent(options)
  • withObservation(options, fn) and withGeneration(options, fn) run fn inside the active span context, record any thrown error, and end the span automatically.

StartObservationOptions supports name, asType ("span" | "event" | "generation" | "agent" | "tool" | "chain" | "retriever" | "evaluator" | "embedding" | "guardrail"), attributes, input, output, sessionId, userId, release, tags, metadata, version, traceName, parent, parentSpanContext ({ traceId, spanId }), root (detach from ambient OpenTelemetry context), and startTime.

StartGenerationOptions adds model, modelParameters ({ temperature?, maxTokens? }), provider, operationName, usage ({ inputTokens?, outputTokens?, totalTokens? }), cost ({ input?, output?, total? }), completionStartTime, prompt, promptEvent, completionEvent, and inferenceDetails.

Context, scores, and lifecycle ​

  • withAttributes(attributes, fn) propagates sessionId, userId, tags, metadata, version, release, and traceName across async calls via AsyncLocalStorage.
  • createScore(options: CreateScoreOptions): Promise<void> sends a score (scoreId, name, dataType, source, traceId?, spanId?, sessionId?, numericValue?, stringValue?, booleanValue?, comment?, configId?, authorId?, metadata?) to baseUrl.
  • forceFlush(): Promise<void> (alias flush()) flushes pending spans.
  • shutdown(): Promise<void> flushes and closes the NodeTracerProvider.

Observation and Generation ​

  • Properties: spanId, traceId, otelSpan.
  • update(options) updates attributes, input, output, statusMessage, or endTime. Generation.update also accepts model, responseModel, modelParameters, provider, usage, cost, completionStartTime, responseId, finishReasons, prompt, promptEvent, completionEvent, and inferenceDetails.
  • setAttributes(attributes), addEvent(name, attributes?), addContentEvent(name, content), recordException(error), and end(options?).

observeOpenAI(client, config) ​

Wraps an OpenAI JS client instance (client.chat.completions.create) to emit generation spans automatically.

ts
import OpenAI from "openai";
import { SoftprobeClient, observeOpenAI } from "@softprobe/tracing";

const sp = SoftprobeClient.fromEnv({ serviceName: "openai-app" });
const openai = observeOpenAI(new OpenAI(), {
  softprobeClient: sp,
  sessionId: "sess-1",
});

ObserveOpenAIConfig: softprobeClient (required), generationName, sessionId, userId, tags, release. Individual create() calls can also pass name, sessionId, userId, metadata, tags, and release.

Utility exports ​

  • withAttributes(attributes, fn) and getPropagatedAttributes()
  • defaultRedactKeys() and redactValue(value, redactKeys, placeholder?)
  • normalizeToolDefinitions(tools), normalizeToolCalls(toolCalls), recordToolDefinitions(obs, tools), recordToolCalls(obs, toolCalls), toolResultEventPayload(...), accumulateToolCallDeltas(...), finalizeToolCallDeltas(...)
  • resolveSoftprobeConfigFromEnv(env?), resolveSoftprobeConfigFromObject(obj), deriveOtlpEndpoint(base)

@softprobe/web-record ​

Browser SDK that records rrweb DOM events, traces fetch and XMLHttpRequest calls with W3C traceparent propagation, and captures redacted JSON bodies.

bash
npm install @softprobe/web-record

RecordSdk.init(options) ​

Initializes browser capture once and returns a WebRecordController.

ts
import { RecordSdk } from "@softprobe/web-record";

const recorder = RecordSdk.init({
  ingestionKey: "spk_REPLACE_WITH_INGESTION_KEY",
  serviceName: "my-web",
  otlp: {
    tracesEndpoint: "https://explorer.softprobe.ai/api/thelake/v1/traces",
    protocol: "http/protobuf",
  },
  resourceAttributes: {
    "deployment.environment.name": "production",
  },
});

You can also load the UMD bundle in HTML <head> with either data-softprobe-options (full JSON options) or data-ingestion-key:

html
<script
  src="https://unpkg.com/@softprobe/web-record/dist/browser.js"
  data-softprobe-options='{"ingestionKey":"spk_REPLACE_WITH_INGESTION_KEY","serviceName":"my-web"}'
  defer
></script>

WebRecordInitOptions ​

OptionTypeDefaultDescription
ingestionKeystringRequiredIngest-only key (spk_...). Never place user passwords, cookies, or account tokens in browser code.
serviceNamestring"softprobe-web"OpenTelemetry service.name for browser spans
otlpOtlpExportOptionsProduction traces URLSet otlp.tracesEndpoint (full URL) or otlp.endpoint (base URL) and protocol: "http/protobuf"
resourceAttributesResourceAttributes{}Extra resource attributes such as deployment.environment.name
environmentstringundefinedShorthand for deployment.environment.name
sessionIdstringAuto-detectedExplicit session ID. When omitted, adopts IDs from sessionStorage, /sessions/:id URLs, or /sessions JSON responses.
userIdstringundefinedEnd-user identifier on spans
apiOriginsstring[]window.location.originExact HTTP(S) origins to trace and inject traceparent headers into
httpBodyCaptureboolean | HttpBodyCaptureOptionstrueCaptures same-origin JSON request and response bodies on a softprobe.http.body.capture child span. Pass false to disable.
intervalnumber5000rrweb flush interval in milliseconds (minimum 5000)
manualbooleanfalseWhen true, do not start rrweb until recorder.record() is called
maskAllInputsbooleantrueMask all HTML <input> values in DOM recordings
maskTextSelectorstringundefinedCSS selector for visible text masked by rrweb
blockSelectorstringundefinedCSS selector for DOM regions excluded from rrweb
tagsTags{}Browser metadata tags (userId, clientId, email, phoneNo, or custom string keys)
softDisablebooleantrueDisable quietly when credentials are incomplete instead of throwing
onUploadStatus(status) => voidundefinedCallback receiving `"idle"

HttpBodyCaptureOptions and HttpBodyCaptureRoute ​

FieldTypeDefaultDescription
maxBodyBytesnumber65536Bodies larger than this byte limit are omitted
routesHttpBodyCaptureRoute[]undefinedOptional route allowlist. Omit to capture JSON bodies on all traced apiOrigins.

Each HttpBodyCaptureRoute accepts:

  • method (string): HTTP method such as "POST".
  • path (string): Relative path ("/agent/api/sessions/*/messages", wildcard * segments supported) or full HTTP(S) URL without query string or fragment.
  • origin (string, optional): Exact origin for cross-origin relative paths.
  • redactJsonPaths (string[], optional): JSONPath expressions such as ["$.paymentDetails.cardNumber"]. Built-in redaction already replaces cardNumber, cvv, cvc, password, and secret anywhere in JSON with [REDACTED].

WebRecordController ​

RecordSdk.init() returns a WebRecordController with:

  • enabled (boolean) and sessionId (string) and uploadStatus (RecordingUploadStatus)
  • record(opts?: { tags?: Tags }): RecordingHandle | null
  • stop(): void
  • setTags(tags: Tags, override?: boolean): void
  • setSessionId(sessionId: string): void | Promise<void>
  • flush(): Promise<boolean>

@softprobe/vercel-ai-sdk ​

Integrates Vercel AI SDK generateText, streamText, and tool calls with Softprobe and propagates W3C traceparent and session IDs across Node.js HTTP requests.

bash
npm install @softprobe/vercel-ai-sdk @softprobe/tracing

initVercelAiTelemetry(options?) ​

Creates a SoftprobeVercelAiSdkIntegration, installs incoming/outgoing HTTP context propagation, and registers the integration with the ai package (registerTelemetry).

ts
import { initVercelAiTelemetry } from "@softprobe/vercel-ai-sdk";

const telemetry = initVercelAiTelemetry({
  ingestionKey: "spk_REPLACE_WITH_INGESTION_KEY",
  serviceName: "travel-agent",
});

SoftprobeVercelAiSdkIntegrationOptions ​

OptionTypeDefaultDescription
ingestionKeystringINGESTION_KEY or OTLP headerAgent Ingestion Key (spk_...)
serviceNamestringOTEL_SERVICE_NAME or "softprobe-app"OpenTelemetry service.name for the AI server
otlpOtlpExportOptionsEnv OTLP vars or production URLTrace exporter endpoint, protocol, and headers
resourceAttributesResourceAttributesEnv OTEL_RESOURCE_ATTRIBUTESAdditional OpenTelemetry resource attributes
environmentstringSOFTPROBE_ENVIRONMENTSets deployment.environment.name
baseUrlstringSOFTPROBE_BASE_URLOptional score API base URL
tracerTracerCreated from SoftprobeClientBring-your-own OpenTelemetry Tracer
useSimpleProcessorbooleanfalseFlush spans synchronously when each span ends

Other exports ​

  • SoftprobeVercelAiSdkIntegration: Class with forceFlush(), shutdown(), executeTool(), executeLanguageModelCall(), and AI SDK lifecycle hooks (onStart, onStepStart, onLanguageModelCallStart, onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, onEnd, onAbort, onError).
  • SoftprobeVercelAiSpanProcessor: OpenTelemetry SpanProcessor that normalizes Vercel AI spans (ai.*) into Softprobe agent, generation, tool, embedding, and retriever observations.
  • installIncomingHttpContextPropagation(options?): Patches Node http, https, and fetch to extract incoming traceparent, baggage, and session headers (x-softprobe-session-id, x-session-id, x-conversation-id, x-thread-id, x-chat-id) and forward traceparent on outgoing downstream calls (skipping OTLP collector URLs).
  • createSoftprobeObservationAttributes(params): Builds Softprobe observation attributes for custom AI SDK telemetry delegates.

@softprobe/langchain ​

LangChain and LangGraph tracing for TypeScript and Node.js. See the LangChain install guide for setup steps.

bash
npm install @softprobe/langchain @softprobe/tracing @langchain/core

Importing @softprobe/langchain calls autoInstrumentFromEnv() automatically when OTLP credentials are present, unless SOFTPROBE_LANGCHAIN is 0, false, off, or no.

Exports ​

  • instrument(params?: CallbackHandlerParams): CallbackHandler: Registers a LangChain configure hook so all runs in the async context are traced.
  • uninstrument(): void: Clears the active LangChain hook handler.
  • isInstrumented(): boolean and getHandler(): CallbackHandler | null.
  • autoInstrumentFromEnv(params?, env?): CallbackHandler | null.
  • CallbackHandler: Extends @langchain/core/callbacks/base BaseCallbackHandler.
    • Constructor CallbackHandlerParams: softprobeClient?, sessionId?, userId?, tags?, metadata?, version?, parentSpanContext?.
    • handler.flush(): Promise<void> flushes pending spans.
    • handler.lastTraceId exposes the most recent trace ID.

@softprobe/opencode-plugin ​

OpenCode plugin that sends coding-agent turns, model generations, tool calls, and sub-agent tasks to Softprobe. See the OpenCode install guide for opencode.json and opencode-softprobe.json configuration.


Environment variables ​

All Node.js packages (@softprobe/tracing, @softprobe/vercel-ai-sdk, @softprobe/langchain, @softprobe/opencode-plugin) share these environment variables:

VariableDescriptionDefault
INGESTION_KEYBearer token for OTLP trace export and score APIParsed from Authorization header if omitted
OTEL_EXPORTER_OTLP_TRACES_ENDPOINTFull OTLP HTTP traces URL, used as writtenhttps://explorer.softprobe.ai/api/thelake/v1/traces
OTEL_EXPORTER_OTLP_ENDPOINTBase OTLP URL; /v1/traces is appendedNone
OTEL_EXPORTER_OTLP_TRACES_HEADERSComma-separated key=value headers (for example Authorization=Bearer spk_...)Overrides OTEL_EXPORTER_OTLP_HEADERS
OTEL_EXPORTER_OTLP_TRACES_PROTOCOLOTLP protocol (http/protobuf)http/protobuf
OTEL_SERVICE_NAMEOpenTelemetry service.name (SOFTPROBE_SERVICE_NAME also accepted)"softprobe-app"
OTEL_RESOURCE_ATTRIBUTESComma-separated resource attributes (for example deployment.environment.name=staging)None
SOFTPROBE_BASE_URLREST API base for createScore only. Does not change trace routing.https://explorer.softprobe.ai/api/thelake
SOFTPROBE_ENVIRONMENTSets deployment.environment.nameNone
SOFTPROBE_SESSION_IDFallback session ID when no run or request session ID is presentNone
SOFTPROBE_USER_IDFallback user IDNone
SOFTPROBE_LANGCHAINSet to 0, false, off, or no to disable @softprobe/langchain auto-instrumentationEnabled when credentials exist

Arex · Blackbox · Lisa