/** * Replay-safe LangSmith run construction for workflow code, plus the pure * run-name builders shared by every interceptor. * * Inside the workflow isolate LangSmith's default `RunTree` is unsafe on two * counts that the workflow lifecycle overrides fix: * * 1. **Non-deterministic ids.** Its default random-tailed uuid7 would mint a * fresh id on every replay, flooding the backend with duplicates. * 2. **Network I/O on replay.** `postRun` / `patchRun` would re-POST runs on * every history replay. * * Internal: every export here is consumed only by sibling modules in this * package; none is reachable through a package entry point. * * @module * @internal */ import { __version__ } from 'langsmith'; import { RunTree, type RunTreeConfig } from 'langsmith/run_trees'; import { ApplicationFailure, ApplicationFailureCategory, CancelledFailure } from '@temporalio/common'; import type { LangSmithTraceContext } from './propagation'; import type { EmitterConfig, SerializedRun } from './sinks'; import { destination, normalizeReplicaHeaders, replicaHeaders, replicaRouting } from './routing'; /** LangSmith run-type constants used for Temporal-operation runs. */ export const RUN_TYPE = { /** Workflow / child-workflow / scheduling / handler spans. */ CHAIN: 'chain', /** Activity-body execution spans. */ TOOL: 'tool', } as const; /** `StartWorkflow:` — client/parent-side workflow-start marker. */ export const startWorkflowRunName = (workflowType: string): string => `StartWorkflow:${workflowType}`; /** `RunWorkflow:` — the workflow-execution span (inbound). */ export const runWorkflowRunName = (workflowType: string): string => `RunWorkflow:${workflowType}`; /** `StartActivity:` — workflow-side activity-schedule marker. */ export const startActivityRunName = (activityType: string): string => `StartActivity:${activityType}`; /** `RunActivity:` — the activity-execution span (activity inbound). */ export const runActivityRunName = (activityType: string): string => `RunActivity:${activityType}`; /** `StartChildWorkflow:` — workflow-side child-start marker. */ export const startChildWorkflowRunName = (workflowType: string): string => `StartChildWorkflow:${workflowType}`; /** `StartNexusOperation:/` — workflow-side Nexus-start marker. */ export const startNexusOperationRunName = (service: string, operation: string): string => `StartNexusOperation:${service}/${operation}`; /** `RunStartNexusOperationHandler:/` — Nexus start-handler span. */ export const runStartNexusHandlerRunName = (service: string, operation: string): string => `RunStartNexusOperationHandler:${service}/${operation}`; /** `RunCancelNexusOperationHandler:/` — Nexus cancel-handler span. */ export const runCancelNexusHandlerRunName = (service: string, operation: string): string => `RunCancelNexusOperationHandler:${service}/${operation}`; /** `HandleSignal:` — inbound signal handler span. */ export const handleSignalRunName = (signalName: string): string => `HandleSignal:${signalName}`; /** `HandleQuery:` — inbound query handler span. */ export const handleQueryRunName = (queryName: string): string => `HandleQuery:${queryName}`; /** `HandleUpdate:` — inbound update handler span. */ export const handleUpdateRunName = (updateName: string): string => `HandleUpdate:${updateName}`; /** `ValidateUpdate:` — inbound update validator span. */ export const validateUpdateRunName = (updateName: string): string => `ValidateUpdate:${updateName}`; /** `SignalWorkflow:` — client/outbound signal marker. */ export const signalWorkflowRunName = (signalName: string): string => `SignalWorkflow:${signalName}`; /** `SignalChildWorkflow:` — workflow-side signal-child marker. */ export const signalChildWorkflowRunName = (signalName: string): string => `SignalChildWorkflow:${signalName}`; /** `SignalExternalWorkflow:` — workflow-side signal-external marker. */ export const signalExternalWorkflowRunName = (signalName: string): string => `SignalExternalWorkflow:${signalName}`; /** `SignalWithStartWorkflow:` — client signal-with-start marker. */ export const signalWithStartRunName = (workflowType: string): string => `SignalWithStartWorkflow:${workflowType}`; /** `QueryWorkflow:` — client query marker. */ export const queryWorkflowRunName = (queryName: string): string => `QueryWorkflow:${queryName}`; /** `StartWorkflowUpdate:` — client update-start marker. */ export const startWorkflowUpdateRunName = (updateName: string): string => `StartWorkflowUpdate:${updateName}`; /** `StartUpdateWithStartWorkflow:` — client update-with-start marker. */ export const startUpdateWithStartRunName = (workflowType: string): string => `StartUpdateWithStartWorkflow:${workflowType}`; type RunTreeMember = (this: any, ...args: any[]) => any; /** RunTree members to replace, each mapped to a function that builds the replacement from LangSmith's original. */ export interface RunTreeOverrides { statics: Record RunTreeMember>; methods: Record RunTreeMember>; } const runTreeOwners = (overrides: RunTreeOverrides) => [ ['RunTree.', RunTree as unknown as Record, overrides.statics], ['RunTree.prototype.', RunTree.prototype as unknown as Record, overrides.methods], ] as const; /** * Throw, naming each one, unless every member the overrides replace is a function. The Workflow bundle may carry a * different LangSmith copy than the Worker, so both check. */ export function requireRunTreeMembers(...overrides: RunTreeOverrides[]): void { const missing = new Set( overrides.flatMap((override) => runTreeOwners(override).flatMap(([label, owner, members]) => Object.keys(members) .filter((name) => typeof owner[name] !== 'function') .map((name) => `${label}${name}`) ) ) ); if (missing.size > 0) { throw new Error(`@temporalio/langsmith does not support LangSmith ${__version__}: missing ${[...missing].join(', ')}`); } } /** Replace the overridden RunTree members, or none if any is missing. */ export function patchRunTree(overrides: RunTreeOverrides): void { requireRunTreeMembers(overrides); for (const [, owner, members] of runTreeOwners(overrides)) { for (const [name, override] of Object.entries(members)) { owner[name] = override(owner[name]!); } } } /** Flatten a {@link RunTree} into the plain wire shape consumed by the Sink. */ export function serializeRun(run: RunTree): SerializedRun { return { id: run.id, trace_id: run.trace_id, dotted_order: run.dotted_order, parent_run_id: run.parent_run?.id ?? run.parent_run_id, name: run.name, run_type: run.run_type, start_time: run.start_time, end_time: run.end_time, inputs: run.inputs as Record | undefined, outputs: run.outputs as Record | undefined, error: run.error, extra: run.extra ? { ...run.extra } : undefined, tags: run.tags, project_name: run.project_name, address: run.address, replicas: replicaRouting(run.replicas), distributedParentId: run.distributedParentId, events: run.events as Record[] | undefined, }; } /** * Render an error into the LangSmith `error` string, honoring Temporal's * benign-failure category. * * A `BENIGN`-category `ApplicationFailure` is an expected, non-alarming outcome * (e.g. a control-flow signal), so it leaves the run's `error` unset. All other * failures produce `": "`. */ export function describeError(err: unknown): string | undefined { if (err instanceof ApplicationFailure && err.category === ApplicationFailureCategory.BENIGN) { return undefined; } if (err instanceof Error) { return `${err.name}: ${err.message}`; } return String(err); } /** Outputs of a plugin run that ends without an error. Plugin runs never record Temporal arguments or results. */ export function statusOutputs(status: 'ok' | 'cancelled' | 'continued_as_new'): Record { return { status }; } /** The `RunTree.end` arguments that close a plugin run. */ export type RunEnd = [outputs: Record | undefined, error: string | undefined]; /** The `RunTree.end` arguments for a plugin run whose operation threw `err`; cancellation isn't an error. */ export function thrownEnd(err: unknown): RunEnd { if (err instanceof CancelledFailure) { return [statusOutputs('cancelled'), undefined]; } return [undefined, describeError(err)]; } /** Run `fn`, then end and patch the already-posted `run` with an ok status, or with `endThrown` of what `fn` threw. */ export async function wrapWithRun( run: RunTree, fn: () => Promise, endThrown: (err: unknown) => RunEnd = thrownEnd ): Promise { let end: RunEnd = [statusOutputs('ok'), undefined]; try { return await fn(); } catch (err) { end = endThrown(err); throw err; } finally { await run.end(...end); await run.patchRun(); } } /** Runs suppressed because the worker has no usable destination, or its env turns off a trace starting here. */ const untracedRuns = new WeakSet(); export function isUntraced(run: RunTree): boolean { return untracedRuns.has(run); } export function suppressRun(run: RunTree): void { untracedRuns.add(run); } /** * The trace context to propagate for `run`, or `undefined` when no LangSmith run exists to parent under: no run, a * run with no destination, or a run LangSmith won't trace (`tracingEnabled: false`). LangSmith turns tracing off for * a run built in an env it can't use, such as a client marker. */ export function runHeaders(run: RunTree | undefined): LangSmithTraceContext | undefined { if (!run || run.tracingEnabled === false || isUntraced(run)) { return undefined; } const headers = run.toHeaders() as LangSmithTraceContext; const baggage = headers.baggage.split(',').filter( (item) => !item.startsWith('langsmith-replicas=') && !item.startsWith('langsmith-metadata=') ); const metadata = run.extra?.metadata as Record | undefined; if (metadata && Object.keys(metadata).length > 0) { baggage.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(metadata))}`); } const replicas = replicaRouting(run.replicas); if (replicas !== undefined) baggage.push(`langsmith-replicas=${encodeURIComponent(JSON.stringify(replicaHeaders(replicas)))}`); headers.baggage = baggage.filter(Boolean).join(','); return headers; } /** * A run's destination: a LangSmith project, or an agent address (LangSmith's `RunTreeConfig.address`, in the * installed version's own form). */ export type Destination = Pick; /** * Reconstruct a propagated parent {@link RunTree} from a trace context; never throws. LangSmith's `RunTree.fromHeaders` * lets the context's destination outrank `fallback`, so `fallback` applies only when the context names none. */ export function runTreeFromContext( ctx: LangSmithTraceContext | undefined, fallback?: Destination ): RunTree | undefined { if (!ctx) { return undefined; } try { const run = RunTree.fromHeaders({ ...ctx, baggage: normalizeReplicaHeaders(ctx.baggage ?? '') }, fallback); if (!run) return undefined; run.replicas = replicaRouting(run.replicas); return run; } catch { return undefined; } } interface RunTreeParams { name: string; runType: string; parent: RunTree | undefined; /** Merged over the plugin's metadata. */ metadata?: Record; } /** * Build an emitter-side {@link RunTree} (client / activity / Nexus); force-enables * tracing so nested body `traceable` runs emit — tracing gate is `isTracingEnabled()`. */ export function buildRunTree(config: EmitterConfig, params: RunTreeParams): RunTree { return new RunTree({ name: params.name, run_type: params.runType, inputs: {}, parent_run: params.parent, client: config.client, ...destination(params.parent, { project_name: config.projectName, address: config.address }), replicas: params.parent?.replicas ?? config.replicas, tags: config.tags, extra: { metadata: { ...config.metadata, ...params.metadata } }, tracingEnabled: true, }); }