@temporalio/langsmith 1.23.0 → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,7 @@
10
10
  * @internal
11
11
  */
12
12
 
13
- import type { RunTree } from 'langsmith/run_trees';
13
+ import { RunTree } from 'langsmith/run_trees';
14
14
  import { AsyncLocalStorageProviderSingleton } from 'langsmith/singletons/traceable';
15
15
  import type {
16
16
  ContinueAsNewInput,
@@ -21,6 +21,8 @@ import type {
21
21
  WorkflowOutboundCallsInterceptor,
22
22
  } from '@temporalio/workflow';
23
23
  import {
24
+ ContinueAsNew,
25
+ isCancellation,
24
26
  workflowInfo,
25
27
  type ActivityInput,
26
28
  type Headers,
@@ -38,16 +40,17 @@ import {
38
40
  encodeContextString,
39
41
  isInternalQuery,
40
42
  readContextHeader,
41
- scrubSensitive,
42
43
  withContextHeader,
44
+ type LangSmithTraceContext,
43
45
  } from './propagation';
44
46
  import {
45
- ReplaySafeRunTree,
46
- _RootReplaySafeRunTreeFactory,
47
47
  RUN_TYPE,
48
- asOutputs,
49
- describeError,
50
- emitMarkerRun,
48
+ type Destination,
49
+ type RunEnd,
50
+ isUntraced,
51
+ statusOutputs,
52
+ suppressRun,
53
+ thrownEnd,
51
54
  handleQueryRunName,
52
55
  handleSignalRunName,
53
56
  handleUpdateRunName,
@@ -60,7 +63,10 @@ import {
60
63
  startChildWorkflowRunName,
61
64
  startNexusOperationRunName,
62
65
  validateUpdateRunName,
66
+ wrapWithRun,
63
67
  } from './run-tree';
68
+ import { destination, type ReplicaRouting } from './routing';
69
+ import { installRunTreeOverrides, workflowRunTreeContext } from './workflow-run-tree';
64
70
 
65
71
  /**
66
72
  * Configuration the worker injects into the workflow bundle via the bundler's
@@ -71,7 +77,14 @@ import {
71
77
  */
72
78
  export interface WorkflowLangSmithConfig {
73
79
  addTemporalRuns: boolean;
74
- projectName?: string;
80
+ replicas?: ReplicaRouting[];
81
+ /**
82
+ * The plugin's project or address, else LangSmith's env defaults, resolved outside the isolate when the bundle is
83
+ * built. New roots use this destination; propagated parents retain their own. Absent when neither names one.
84
+ */
85
+ destination?: Destination;
86
+ /** LangSmith's env tracing state outside the isolate. When false, only runs under a propagated parent are traced. */
87
+ tracingEnabled?: boolean;
75
88
  tags?: string[];
76
89
  metadata?: Record<string, unknown>;
77
90
  }
@@ -113,309 +126,209 @@ AsyncLocalStorageProviderSingleton.initializeGlobalInstance(
113
126
  );
114
127
  const sharedStore = AsyncLocalStorageProviderSingleton.getInstance() as RunTreeStore;
115
128
 
116
- /** Reconstruct the propagated parent run from a Payload-keyed header map. */
117
- function reconstructParent(headers: Record<string, unknown> | undefined): RunTree | undefined {
118
- return runTreeFromContext(readContextHeader(headers as Record<string, never> | undefined));
119
- }
120
-
121
129
  /**
122
- * Re-wrap a reconstructed (plain) parent so its `createChild` produces
123
- * replay-safe children. Carries the same id/trace/dotted so descendants parent
124
- * under the real propagated run; never emitted itself.
130
+ * Reconstruct the propagated parent run from a Payload-keyed header map. A header naming no destination takes
131
+ * `config.destination`, as LangSmith would take its env defaults outside the isolate. This plugin never propagates a
132
+ * run with no destination (see {@link runHeaders}), so such a header comes from an older release; if the Worker has
133
+ * no destination either, LangSmith fills in `"default"` for it here.
125
134
  */
126
- function asReplaySafeParent(
127
- parent: RunTree | undefined,
128
- generateNewUuid4?: () => string
129
- ): ReplaySafeRunTree | undefined {
130
- if (!parent) {
131
- return undefined;
132
- }
133
- return new ReplaySafeRunTree(
134
- {
135
- name: parent.name,
136
- run_type: parent.run_type,
137
- id: parent.id,
138
- trace_id: parent.trace_id,
139
- dotted_order: parent.dotted_order,
140
- parent_run_id: parent.parent_run_id,
141
- project_name: parent.project_name,
142
- },
143
- generateNewUuid4
144
- );
135
+ function reconstructParent(
136
+ headers: Headers | undefined,
137
+ config: WorkflowLangSmithConfig,
138
+ readOnly: boolean
139
+ ): RunTree | undefined {
140
+ const context = readContextHeader(headers);
141
+ return workflowRunTreeContext(config, () => runTreeFromContext(context, config.destination), readOnly);
145
142
  }
146
143
 
147
- /**
148
- * A placeholder parent for the no-propagated-parent case. Installed as the ambient
149
- * so a workflow-body `traceable` always nests via `createChild`; never emitted,
150
- * and its children are independent roots (see {@link _RootReplaySafeRunTreeFactory}).
151
- */
152
- function placeholderRoot(generateNewUuid4?: () => string): _RootReplaySafeRunTreeFactory {
153
- return new _RootReplaySafeRunTreeFactory(
154
- { name: workflowInfo().workflowType, run_type: RUN_TYPE.CHAIN },
155
- generateNewUuid4
156
- );
144
+ /** The `RunTree.end` arguments for a Workflow run whose handler threw `err`; continue-as-new isn't an error. */
145
+ function workflowThrownEnd(err: unknown): RunEnd {
146
+ if (isCancellation(err)) return [statusOutputs('cancelled'), undefined];
147
+ return err instanceof ContinueAsNew ? [statusOutputs('continued_as_new'), undefined] : thrownEnd(err);
157
148
  }
158
149
 
159
- /** Emit a short-lived marker run as a child of `parent`. */
160
- async function emitMarker(
161
- parent: ReplaySafeRunTree,
162
- name: string,
163
- inputs: Record<string, unknown>
164
- ): Promise<ReplaySafeRunTree> {
165
- const marker = parent.createChild({ name, run_type: RUN_TYPE.CHAIN, inputs });
166
- await emitMarkerRun(marker);
167
- return marker;
150
+ /** Keep the incoming parent ambient when a Temporal run has no destination. */
151
+ function bodyAmbient(run: RunTree, parent: RunTree | undefined): RunTree {
152
+ return isUntraced(run) ? parent ?? run : run;
168
153
  }
169
154
 
170
- function buildReplaySafeRunTree(
171
- config: WorkflowLangSmithConfig,
172
- params: {
173
- name: string;
174
- runType: string;
175
- parent: ReplaySafeRunTree | undefined;
176
- inputs: Record<string, unknown>;
177
- generateNewUuid4?: () => string;
178
- }
179
- ): ReplaySafeRunTree {
180
- return new ReplaySafeRunTree(
181
- {
182
- name: params.name,
183
- run_type: params.runType,
184
- parent_run: params.parent,
185
- project_name: config.projectName,
186
- tags: config.tags,
187
- extra: { metadata: scrubSensitive(config.metadata) ?? {} },
188
- inputs: params.inputs,
189
- },
190
- params.generateNewUuid4
191
- );
155
+ /**
156
+ * Emit a short-lived marker run as a child of `parent`. With no destination in `config` the marker has none either,
157
+ * but it's built and awaited all the same: the isolate's awaits, and so the order of its commands, must not depend
158
+ * on the Worker's env, or a history recorded under one env fails to replay under another.
159
+ */
160
+ async function emitMarker(config: WorkflowLangSmithConfig, parent: RunTree, name: string): Promise<void> {
161
+ const marker = parent.createChild({
162
+ name,
163
+ run_type: RUN_TYPE.CHAIN,
164
+ tags: config.tags,
165
+ extra: { metadata: { ...config.metadata } },
166
+ });
167
+ if (config.destination === undefined) suppressRun(marker);
168
+ if (!marker.tracingEnabled) return;
169
+ await marker.postRun();
170
+ await marker.end(statusOutputs('ok'));
171
+ await marker.patchRun();
172
+ }
173
+
174
+ function buildWorkflowRunTree(config: WorkflowLangSmithConfig, name: string, parent: RunTree | undefined): RunTree {
175
+ const { workflowId, runId } = workflowInfo();
176
+ const run = new RunTree({
177
+ name,
178
+ run_type: RUN_TYPE.CHAIN,
179
+ parent_run: parent,
180
+ parent_run_id: parent?.id,
181
+ ...destination(parent, config.destination),
182
+ replicas: parent?.replicas ?? config.replicas,
183
+ tags: config.tags,
184
+ extra: { metadata: { ...config.metadata, temporalWorkflowID: workflowId, temporalRunID: runId } },
185
+ });
186
+ if (config.destination === undefined) suppressRun(run);
187
+ return run;
192
188
  }
193
189
 
194
190
  class LangSmithWorkflowInbound implements WorkflowInboundCallsInterceptor {
195
- constructor(private readonly config: WorkflowLangSmithConfig) {}
191
+ constructor(private readonly config: WorkflowLangSmithConfig) { }
196
192
 
197
193
  async execute(input: WorkflowExecuteInput, next: Next<WorkflowInboundCallsInterceptor, 'execute'>): Promise<unknown> {
198
- const parent = reconstructParent(input.headers);
199
- return this.runInbound(
200
- runWorkflowRunName(workflowInfo().workflowType),
201
- RUN_TYPE.CHAIN,
202
- parent,
203
- { args: input.args },
204
- () => next(input)
205
- );
194
+ return this.runInbound(runWorkflowRunName(workflowInfo().workflowType), input.headers, () => next(input));
206
195
  }
207
196
 
208
197
  async handleSignal(input: SignalInput, next: Next<WorkflowInboundCallsInterceptor, 'handleSignal'>): Promise<void> {
209
- const parent = reconstructParent(input.headers);
210
- await this.runInbound(handleSignalRunName(input.signalName), RUN_TYPE.CHAIN, parent, { args: input.args }, () =>
211
- next(input)
212
- );
198
+ await this.runInbound(handleSignalRunName(input.signalName), input.headers, () => next(input));
213
199
  }
214
200
 
215
201
  async handleQuery(input: QueryInput, next: Next<WorkflowInboundCallsInterceptor, 'handleQuery'>): Promise<unknown> {
216
202
  if (isInternalQuery(input.queryName)) {
217
203
  return next(input);
218
204
  }
219
- const parent = reconstructParent(input.headers);
220
- return this.runInbound(
221
- handleQueryRunName(input.queryName),
222
- RUN_TYPE.CHAIN,
223
- parent,
224
- { args: input.args },
225
- () => next(input),
226
- // Read-only: mint run ids from the nondeterministic unsafe random source so the
227
- // handler never draws from the Workflow main PRNG (which a clean replay would not advance).
228
- workflowInfo().unsafe.random.uuid4
229
- );
205
+ return this.runInbound(handleQueryRunName(input.queryName), input.headers, () => next(input), true);
230
206
  }
231
207
 
232
208
  async handleUpdate(
233
209
  input: UpdateInput,
234
210
  next: Next<WorkflowInboundCallsInterceptor, 'handleUpdate'>
235
211
  ): Promise<unknown> {
236
- const parent = reconstructParent(input.headers);
237
- return this.runInbound(handleUpdateRunName(input.name), RUN_TYPE.CHAIN, parent, { args: input.args }, () =>
238
- next(input)
239
- );
212
+ return this.runInbound(handleUpdateRunName(input.name), input.headers, () => next(input));
240
213
  }
241
214
 
242
215
  validateUpdate(input: UpdateInput, next: Next<WorkflowInboundCallsInterceptor, 'validateUpdate'>): void {
243
- // Read-only: mint run ids from the nondeterministic unsafe random source so the validator
244
- // never draws from the Workflow main PRNG (which a clean replay would not advance).
245
- const generateNewUuid4 = workflowInfo().unsafe.random.uuid4;
246
- if (!this.config.addTemporalRuns) {
247
- // Propagation only: install the reconstructed parent (or a placeholder parent
248
- // when none was propagated, to keep a validator-body `traceable` off the
249
- // no-parent `crypto` path) so the validator body nests under the update's
250
- // trace.
251
- const ambient =
252
- asReplaySafeParent(reconstructParent(input.headers), generateNewUuid4) ?? placeholderRoot(generateNewUuid4);
253
- sharedStore.run(ambient, () => next(input));
254
- return;
255
- }
256
- const run = buildReplaySafeRunTree(this.config, {
257
- name: validateUpdateRunName(input.name),
258
- runType: RUN_TYPE.CHAIN,
259
- parent: asReplaySafeParent(reconstructParent(input.headers), generateNewUuid4),
260
- inputs: { args: input.args },
261
- generateNewUuid4,
262
- });
263
- // Validators are synchronous and must not be made async; emit start/end
264
- // around the synchronous call, with the run installed as the active store so
265
- // a `traceable` in the validator body nests under it.
266
- void run.postRun();
267
- try {
268
- sharedStore.run(run, () => next(input));
269
- void run.end({});
270
- } catch (err) {
271
- void run.end(undefined, describeError(err));
272
- void run.patchRun();
273
- throw err;
274
- }
275
- void run.patchRun();
216
+ const parent = reconstructParent(input.headers, this.config, true);
217
+ workflowRunTreeContext(this.config, () => {
218
+ if (!this.config.addTemporalRuns) {
219
+ sharedStore.run(parent, () => next(input));
220
+ return;
221
+ }
222
+ const run = buildWorkflowRunTree(this.config, validateUpdateRunName(input.name), parent);
223
+ void run.postRun();
224
+ let end: RunEnd = [statusOutputs('ok'), undefined];
225
+ try {
226
+ sharedStore.run(bodyAmbient(run, parent), () => next(input));
227
+ } catch (err) {
228
+ end = workflowThrownEnd(err);
229
+ throw err;
230
+ } finally {
231
+ void run.end(...end);
232
+ void run.patchRun();
233
+ }
234
+ }, true);
276
235
  }
277
236
 
278
237
  /**
279
- * Open the inbound run, install it as the active run for the whole `next`
238
+ * Open the inbound run, install it (see {@link bodyAmbient}) as the active run for the whole `next`
280
239
  * async scope, and close it. The real ALS scopes the run to this branch, so a
281
240
  * handler running concurrently with the workflow body never leaks its run into
282
241
  * the body's context.
283
242
  */
284
243
  private async runInbound(
285
244
  name: string,
286
- runType: string,
287
- parent: RunTree | undefined,
288
- inputs: Record<string, unknown>,
245
+ headers: Headers,
289
246
  next: () => Promise<unknown>,
290
- generateNewUuid4?: () => string
247
+ readOnly = false
291
248
  ): Promise<unknown> {
292
- if (!this.config.addTemporalRuns) {
293
- // Propagation only: install the reconstructed parent as the active run so
294
- // user `traceable` runs nest under it; never emit a Temporal-operation run.
295
- // With no propagated parent, install a placeholder parent instead of
296
- // `undefined` so a workflow-body `traceable` takes LangSmith's
297
- // `createChild` branch (deterministic id) rather than the no-parent branch
298
- // that mints a uuid via `crypto`, which the isolate lacks.
299
- const ambient = asReplaySafeParent(parent, generateNewUuid4) ?? placeholderRoot(generateNewUuid4);
300
- return sharedStore.run(ambient, next);
301
- }
302
- const run = buildReplaySafeRunTree(this.config, {
303
- name,
304
- runType,
305
- parent: asReplaySafeParent(parent, generateNewUuid4),
306
- inputs,
307
- generateNewUuid4,
308
- });
309
- void run.postRun();
310
- const body = async (): Promise<unknown> => {
311
- try {
312
- const result = await next();
313
- await run.end(asOutputs(result));
314
- await run.patchRun();
315
- return result;
316
- } catch (err) {
317
- await run.end(undefined, describeError(err));
318
- await run.patchRun();
319
- throw err;
249
+ const parent = reconstructParent(headers, this.config, readOnly);
250
+ return workflowRunTreeContext(this.config, () => {
251
+ if (!this.config.addTemporalRuns) {
252
+ return sharedStore.run(parent, next);
320
253
  }
321
- };
322
- return sharedStore.run(run, body);
254
+ const run = buildWorkflowRunTree(this.config, name, parent);
255
+ void run.postRun();
256
+ return sharedStore.run(bodyAmbient(run, parent), () => wrapWithRun(run, next, workflowThrownEnd));
257
+ }, readOnly);
323
258
  }
324
259
  }
325
260
 
326
261
  class LangSmithWorkflowOutbound implements WorkflowOutboundCallsInterceptor {
327
- constructor(private readonly config: WorkflowLangSmithConfig) {}
262
+ constructor(private readonly config: WorkflowLangSmithConfig) { }
328
263
 
329
264
  async scheduleActivity(
330
265
  input: ActivityInput,
331
266
  next: Next<WorkflowOutboundCallsInterceptor, 'scheduleActivity'>
332
267
  ): Promise<unknown> {
333
- return this.peerMarker(startActivityRunName(input.activityType), input, (headers: Headers) =>
334
- next({ ...input, headers })
335
- );
268
+ return this.withHeaders(startActivityRunName(input.activityType), input, next);
336
269
  }
337
270
 
338
271
  async scheduleLocalActivity(
339
272
  input: LocalActivityInput,
340
273
  next: Next<WorkflowOutboundCallsInterceptor, 'scheduleLocalActivity'>
341
274
  ): Promise<unknown> {
342
- return this.peerMarker(startActivityRunName(input.activityType), input, (headers: Headers) =>
343
- next({ ...input, headers })
344
- );
275
+ return this.withHeaders(startActivityRunName(input.activityType), input, next);
345
276
  }
346
277
 
347
278
  async startChildWorkflowExecution(
348
279
  input: StartChildWorkflowExecutionInput,
349
280
  next: Next<WorkflowOutboundCallsInterceptor, 'startChildWorkflowExecution'>
350
281
  ): Promise<[Promise<string>, Promise<unknown>]> {
351
- return this.peerMarker(startChildWorkflowRunName(input.workflowType), input, (headers: Headers) =>
352
- next({ ...input, headers })
353
- );
282
+ return this.withHeaders(startChildWorkflowRunName(input.workflowType), input, next);
354
283
  }
355
284
 
356
285
  continueAsNew(
357
286
  input: ContinueAsNewInput,
358
287
  next: Next<WorkflowOutboundCallsInterceptor, 'continueAsNew'>
359
288
  ): Promise<never> {
360
- // Don't propagate a placeholder root: it is never emitted, so the successor's
361
- // runs would dangle under a nonexistent parent. Let it install its own.
362
- const ambient = sharedStore.getStore();
363
- const context = ambient instanceof _RootReplaySafeRunTreeFactory ? undefined : runHeaders(ambient);
364
- const headers = withContextHeader(input.headers, context);
365
- return next({ ...input, headers });
289
+ return next({ ...input, headers: withContextHeader(input.headers, runHeaders(sharedStore.getStore())) });
366
290
  }
367
291
 
368
292
  async signalWorkflow(
369
293
  input: SignalWorkflowInput,
370
294
  next: Next<WorkflowOutboundCallsInterceptor, 'signalWorkflow'>
371
295
  ): Promise<void> {
372
- const isChild = input.target.type === 'child';
373
- const name = isChild
296
+ const name = input.target.type === 'child'
374
297
  ? signalChildWorkflowRunName(input.signalName)
375
298
  : signalExternalWorkflowRunName(input.signalName);
376
- return this.parentMarker(name, input, (headers: Headers) => next({ ...input, headers }));
299
+ return this.withHeaders(name, input, next);
377
300
  }
378
301
 
379
302
  async startNexusOperation(
380
303
  input: StartNexusOperationInput,
381
304
  next: Next<WorkflowOutboundCallsInterceptor, 'startNexusOperation'>
382
305
  ): Promise<StartNexusOperationOutput> {
383
- const ambient = sharedStore.getStore();
384
- if (this.config.addTemporalRuns && ambient instanceof ReplaySafeRunTree) {
385
- await emitMarker(ambient, startNexusOperationRunName(input.service, input.operation), {});
386
- }
387
- const ctx = runHeaders(ambient);
388
- const headers = ctx ? { ...input.headers, [HEADER_KEY]: encodeContextString(ctx) } : input.headers;
389
- return next({ ...input, headers });
306
+ return this.traceOutbound(startNexusOperationRunName(input.service, input.operation), (context) => {
307
+ const headers = context ? { ...input.headers, [HEADER_KEY]: encodeContextString(context) } : input.headers;
308
+ return next({ ...input, headers });
309
+ });
390
310
  }
391
311
 
392
- /** Sibling-marker operations: marker is a peer of the remote run; propagate ambient. */
393
- private async peerMarker<R>(
312
+ /** Emit the marker, then pass `call` the caller's context, so the remote run is the marker's sibling. */
313
+ private async traceOutbound<R>(
394
314
  name: string,
395
- input: { headers: Headers; args?: unknown[] },
396
- next: (headers: Headers) => Promise<R>
315
+ call: (context: LangSmithTraceContext | undefined) => Promise<R>
397
316
  ): Promise<R> {
398
317
  const ambient = sharedStore.getStore();
399
- if (this.config.addTemporalRuns && ambient instanceof ReplaySafeRunTree) {
400
- await emitMarker(ambient, name, { args: input.args ?? [] });
318
+ if (this.config.addTemporalRuns && ambient !== undefined) {
319
+ await emitMarker(this.config, ambient, name);
401
320
  }
402
- const headers = withContextHeader(input.headers, runHeaders(ambient));
403
- return next(headers);
321
+ return call(runHeaders(ambient));
404
322
  }
405
323
 
406
- /** Parent-marker operations: remote handler nests under the marker; propagate marker. */
407
- private async parentMarker<R>(
324
+ private withHeaders<I extends { headers: Headers }, R>(
408
325
  name: string,
409
- input: { headers: Headers; args?: unknown[] },
410
- next: (headers: Headers) => Promise<R>
326
+ input: I,
327
+ next: (input: I) => Promise<R>
411
328
  ): Promise<R> {
412
- const ambient = sharedStore.getStore();
413
- let propagate: RunTree | undefined = ambient;
414
- if (this.config.addTemporalRuns && ambient instanceof ReplaySafeRunTree) {
415
- propagate = await emitMarker(ambient, name, { args: input.args ?? [] });
416
- }
417
- const headers = withContextHeader(input.headers, runHeaders(propagate));
418
- return next(headers);
329
+ return this.traceOutbound(name, (context) =>
330
+ next({ ...input, headers: withContextHeader(input.headers, context) })
331
+ );
419
332
  }
420
333
  }
421
334
 
@@ -427,6 +340,7 @@ class LangSmithWorkflowOutbound implements WorkflowOutboundCallsInterceptor {
427
340
  */
428
341
  export function interceptors(): WorkflowInterceptors {
429
342
  const config = readConfig();
343
+ installRunTreeOverrides();
430
344
  return {
431
345
  inbound: [new LangSmithWorkflowInbound(config)],
432
346
  outbound: [new LangSmithWorkflowOutbound(config)],
@@ -0,0 +1,127 @@
1
+ /** Native LangSmith lifecycle overrides, scoped to this plugin's workflow handlers. */
2
+
3
+ import { AsyncLocalStorage } from 'node:async_hooks';
4
+ import type { Client } from 'langsmith';
5
+ import type { KVMap } from 'langsmith/schemas';
6
+ import type { RunTree, RunTreeConfig } from 'langsmith/run_trees';
7
+ import { v7 as uuidv7 } from 'uuid';
8
+ import { getRandomStream, proxySinks, workflowInfo } from '@temporalio/workflow';
9
+ import { isUntraced, patchRunTree, serializeRun, suppressRun, type RunTreeOverrides } from './run-tree';
10
+ import { LANGSMITH_SINK_NAME, type LangSmithSinks } from './sinks';
11
+ import type { WorkflowLangSmithConfig } from './workflow-interceptors';
12
+
13
+ const LANGSMITH_RUN_TREE_STREAM = 'package-langsmith-tracing';
14
+
15
+ interface WorkflowRunTreeContext {
16
+ config: WorkflowLangSmithConfig;
17
+ readOnly: boolean;
18
+ }
19
+
20
+ // The bundle rewrites `node:async_hooks` to the AsyncLocalStorage the SDK injects into the sandbox.
21
+ const context = new AsyncLocalStorage<WorkflowRunTreeContext>();
22
+
23
+ export function workflowRunTreeContext<T>(
24
+ config: WorkflowLangSmithConfig,
25
+ fn: () => T,
26
+ readOnly = false
27
+ ): T {
28
+ return context.run({ config, readOnly }, fn);
29
+ }
30
+
31
+ function runId(readOnly: boolean): string {
32
+ const bytes = new Uint8Array(16);
33
+
34
+ if (readOnly) {
35
+ const { unsafe } = workflowInfo();
36
+ return uuidv7({ msecs: unsafe.now(), random: unsafe.random.fillRandom(bytes) });
37
+ }
38
+
39
+ return uuidv7({ msecs: Date.now(), random: getRandomStream(LANGSMITH_RUN_TREE_STREAM).fill(bytes) });
40
+ }
41
+
42
+ function workerOrServerTime(): number {
43
+ const { unsafe } = workflowInfo();
44
+ return unsafe.isReplayingHistoryEvents ? Date.now() : unsafe.now();
45
+ }
46
+
47
+ // Every write inside a workflow is routed through a sink instead of this client.
48
+ const NOOP_CLIENT = {
49
+ createRun: async (): Promise<void> => { },
50
+ updateRun: async (): Promise<void> => { },
51
+ } as unknown as Client;
52
+
53
+ // LangSmith calls getDefaultConfig and _resolveAddressing from its constructor. Patching them also covers
54
+ // RunTree aliases imported before installation, including its own createChild.
55
+ /** Preserve native root/child selection, ordering, and replica inheritance. */
56
+ export const WORKFLOW_RUN_TREE_OVERRIDES: RunTreeOverrides = {
57
+ statics: {
58
+ getDefaultConfig: (original) =>
59
+ function (this: typeof RunTree, ...args: unknown[]): RunTreeConfig {
60
+ const defaults = original.apply(this, args);
61
+ const active = context.getStore();
62
+ if (!active) return defaults;
63
+ return {
64
+ ...defaults,
65
+ id: runId(active.readOnly),
66
+ start_time: workerOrServerTime(),
67
+ replicas: active.config.replicas,
68
+ // Keep traceable's awaits independent of the worker's destination env.
69
+ tracingEnabled: true,
70
+ };
71
+ },
72
+ getSharedClient: (original) =>
73
+ function (this: typeof RunTree, ...args: unknown[]): Client {
74
+ return context.getStore() ? NOOP_CLIENT : original.apply(this, args);
75
+ },
76
+ },
77
+ methods: {
78
+ _resolveAddressing: (original) =>
79
+ function (this: RunTree, config: RunTreeConfig, ...args: unknown[]): void {
80
+ const active = context.getStore();
81
+ if (!active) return original.call(this, config, ...args);
82
+ const selected = config.project_name || config.address ? config : { ...config, ...active.config.destination };
83
+ original.call(this, selected, ...args);
84
+ if (!selected.project_name && !selected.address) suppressRun(this);
85
+ // A run with no parent and no propagated trace starts a new trace, which LangSmith's env gates.
86
+ if (!config.parent_run && !config.trace_id && active.config.tracingEnabled === false) suppressRun(this);
87
+ // A child of an untraced run stays untraced, whether built by createChild or `new RunTree({ parent_run })`.
88
+ if (config.parent_run && isUntraced(config.parent_run)) suppressRun(this);
89
+ },
90
+ end: (original) =>
91
+ async function (this: RunTree, outputs?: KVMap, error?: string, endTime?: number, ...args: unknown[]): Promise<void> {
92
+ if (context.getStore() && endTime === undefined) endTime = workerOrServerTime();
93
+ return original.call(this, outputs, error, endTime, ...args);
94
+ },
95
+ postRun: (original) =>
96
+ async function (this: RunTree, excludeChildRuns = true, ...args: unknown[]): Promise<void> {
97
+ if (!context.getStore()) return original.call(this, excludeChildRuns, ...args);
98
+ // Native traceable can defer asynchronous input processing until postRun.
99
+ if ((this as RunTree & { _awaitInputsOnPost?: boolean })._awaitInputsOnPost) {
100
+ this.inputs = await this.inputs;
101
+ }
102
+ if (!workflowInfo().unsafe.isReplayingHistoryEvents && !isUntraced(this)) {
103
+ proxySinks<LangSmithSinks>()[LANGSMITH_SINK_NAME].createRun(serializeRun(this));
104
+ }
105
+ if (!excludeChildRuns) {
106
+ for (const child of this.child_runs) await child.postRun(false);
107
+ }
108
+ this.child_runs = [];
109
+ },
110
+ patchRun: (original) =>
111
+ async function (this: RunTree, options?: Parameters<RunTree['patchRun']>[0], ...args: unknown[]): Promise<void> {
112
+ if (!context.getStore()) return original.call(this, options, ...args);
113
+ if (!workflowInfo().unsafe.isReplayingHistoryEvents && !isUntraced(this)) {
114
+ proxySinks<LangSmithSinks>()[LANGSMITH_SINK_NAME].updateRun(serializeRun(this), options);
115
+ }
116
+ this.child_runs = [];
117
+ },
118
+ },
119
+ };
120
+
121
+ let installed = false;
122
+
123
+ export function installRunTreeOverrides(): void {
124
+ if (installed) return;
125
+ patchRunTree(WORKFLOW_RUN_TREE_OVERRIDES);
126
+ installed = true;
127
+ }