braintrust 0.4.7 → 0.4.8

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.
package/dist/cli.js CHANGED
@@ -10233,7 +10233,7 @@ var require_package = __commonJS({
10233
10233
  "package.json"(exports2, module2) {
10234
10234
  module2.exports = {
10235
10235
  name: "braintrust",
10236
- version: "0.4.7",
10236
+ version: "0.4.8",
10237
10237
  description: "SDK for integrating Braintrust",
10238
10238
  repository: {
10239
10239
  type: "git",
@@ -10289,12 +10289,17 @@ var require_package = __commonJS({
10289
10289
  watch: "tsup --watch",
10290
10290
  clean: "rm -r dist/* && rm -r dev/dist/*",
10291
10291
  docs: "npx typedoc --options typedoc.json src/index.ts",
10292
- test: "vitest run --exclude src/wrappers/anthropic.test.ts --exclude src/wrappers/oai.test.ts --exclude src/otel.test.ts --exclude src/otel-no-deps.test.ts --exclude src/wrappers/google-genai.test.ts",
10292
+ test: 'vitest run --exclude "src/wrappers/**/*.test.ts" --exclude "src/otel/**/*.test.ts"',
10293
10293
  "test:anthropic": "vitest run src/wrappers/anthropic.test.ts",
10294
10294
  "test:openai": "vitest run src/wrappers/oai.test.ts",
10295
- "test:otel": "vitest run src/otel.test.ts",
10295
+ "test:otel": "vitest run --dir src/otel",
10296
+ "test:otel-no-deps": "vitest run src/otel-no-deps.test.ts --reporter=verbose",
10296
10297
  "test:google-genai": "vitest run src/wrappers/google-genai.test.ts",
10297
- "test:otel-no-deps": "vitest run src/otel-no-deps.test.ts --reporter=verbose"
10298
+ "test:ai-sdk-v1": "vitest run src/wrappers/ai-sdk-v1.test.ts",
10299
+ "test:ai-sdk-v2": "vitest run src/wrappers/ai-sdk-v2.test.ts src/wrappers/ai-sdk-v1.test.ts",
10300
+ "test:ai-sdk-v3": "vitest run src/wrappers/ai-sdk-v3.test.ts",
10301
+ "test:mastra": "vitest run src/wrappers/mastra.test.ts",
10302
+ "test:claude-agent-sdk": "vitest run src/wrappers/claude-agent-sdk.test.ts"
10298
10303
  },
10299
10304
  author: "",
10300
10305
  license: "MIT",
package/dist/index.d.mts CHANGED
@@ -21694,6 +21694,43 @@ declare class BraintrustSpanProcessor {
21694
21694
  shutdown(): Promise<void>;
21695
21695
  forceFlush(): Promise<void>;
21696
21696
  }
21697
+ /**
21698
+ * Create an OTEL context from a Braintrust span export string.
21699
+ *
21700
+ * Used for distributed tracing scenarios where a Braintrust span in one service
21701
+ * needs to be the parent of an OTEL span in another service.
21702
+ *
21703
+ * @param exportStr - The string returned from span.export()
21704
+ * @returns OTEL context that can be used when creating child spans
21705
+ *
21706
+ * @example
21707
+ * ```typescript
21708
+ * // Service A: Create BT span and export
21709
+ * const span = logger.startSpan({ name: "service-a" });
21710
+ * const exportStr = await span.export();
21711
+ * // Send exportStr to Service B (e.g., via HTTP header)
21712
+ *
21713
+ * // Service B: Import context and create OTEL child
21714
+ * import * as api from '@opentelemetry/api';
21715
+ * const ctx = otelContextFromSpanExport(exportStr);
21716
+ * await api.context.with(ctx, async () => {
21717
+ * await tracer.startActiveSpan("service-b", async (span) => {
21718
+ * // This span is now a child of the Service A span
21719
+ * span.end();
21720
+ * });
21721
+ * });
21722
+ * ```
21723
+ */
21724
+ declare function otelContextFromSpanExport(exportStr: string): unknown;
21725
+ /**
21726
+ * Construct a braintrust.parent identifier string from span components.
21727
+ *
21728
+ * @param objectType - Type of parent object (PROJECT_LOGS or EXPERIMENT)
21729
+ * @param objectId - Resolved object ID (project_id or experiment_id)
21730
+ * @param computeArgs - Optional dict with project_name/project_id for unresolved cases
21731
+ * @returns String like "project_id:abc", "project_name:my-proj", "experiment_id:exp-123", or undefined
21732
+ */
21733
+ declare function getBraintrustParent(objectType: number, objectId?: string | null, computeArgs?: Record<string, unknown> | null): string | undefined;
21697
21734
  /**
21698
21735
  * A trace exporter that sends OpenTelemetry spans to Braintrust.
21699
21736
  *
@@ -21760,6 +21797,111 @@ declare class BraintrustExporter {
21760
21797
  */
21761
21798
  forceFlush(): Promise<void>;
21762
21799
  }
21800
+ /**
21801
+ * Add braintrust.parent to OTEL baggage.
21802
+ *
21803
+ * This ensures that when using propagation inject() for distributed tracing,
21804
+ * the braintrust.parent will be propagated via baggage to downstream services.
21805
+ *
21806
+ * @param parent - Braintrust parent identifier (e.g., "project_name:my-project",
21807
+ * "project_id:abc123", "experiment_id:exp-456")
21808
+ * @param ctx - Optional OTEL context to use. If not provided, uses current context.
21809
+ * @returns Updated context with braintrust.parent in baggage
21810
+ *
21811
+ * @example
21812
+ * ```typescript
21813
+ * import { otel } from "braintrust";
21814
+ * import { propagation } from "@opentelemetry/api";
21815
+ *
21816
+ * // Set braintrust.parent in baggage
21817
+ * otel.addParentToBaggage("project_name:my-project");
21818
+ *
21819
+ * // Export headers (will include braintrust.parent in baggage)
21820
+ * const headers = {};
21821
+ * propagation.inject(context.active(), headers);
21822
+ * ```
21823
+ */
21824
+ declare function addParentToBaggage(parent: string, ctx?: Context): Context;
21825
+ /**
21826
+ * Copy braintrust.parent from span attribute to OTEL baggage.
21827
+ *
21828
+ * BraintrustSpanProcessor automatically sets braintrust.parent as a span attribute
21829
+ * when OTEL spans are created within Braintrust contexts. This function copies that
21830
+ * attribute to OTEL baggage so it propagates when using inject() for distributed tracing.
21831
+ *
21832
+ * @param span - OTEL span that has braintrust.parent attribute set
21833
+ * @param ctx - Optional OTEL context to use. If not provided, uses current context.
21834
+ * @returns Updated context with braintrust.parent in baggage, or undefined if attribute not found
21835
+ *
21836
+ * @example
21837
+ * ```typescript
21838
+ * import { otel } from "braintrust";
21839
+ * import { propagation } from "@opentelemetry/api";
21840
+ *
21841
+ * tracer.startActiveSpan("service_b", (span) => {
21842
+ * // Copy braintrust.parent from span attribute to baggage
21843
+ * otel.addSpanParentToBaggage(span);
21844
+ *
21845
+ * // Export headers (will include braintrust.parent in baggage)
21846
+ * const headers = {};
21847
+ * propagation.inject(context.active(), headers);
21848
+ * span.end();
21849
+ * });
21850
+ * ```
21851
+ */
21852
+ declare function addSpanParentToBaggage(span: Span, ctx?: Context): Context | undefined;
21853
+ /**
21854
+ * Extract a Braintrust-compatible parent string from W3C Trace Context headers.
21855
+ *
21856
+ * This converts OTEL trace context headers (traceparent/baggage) into a format
21857
+ * that can be passed as the 'parent' parameter to Braintrust's traced() method.
21858
+ *
21859
+ * @param headers - Dictionary with 'traceparent' and optionally 'baggage' keys
21860
+ * @returns Braintrust V4 export string that can be used as parent parameter,
21861
+ * or undefined if no valid span context is found or braintrust.parent is missing.
21862
+ *
21863
+ * @example
21864
+ * ```typescript
21865
+ * import { otel, initLogger } from "braintrust";
21866
+ *
21867
+ * // Service C receives headers from Service B
21868
+ * const headers = { traceparent: '00-trace_id-span_id-01', baggage: '...' };
21869
+ * const parent = otel.parentFromHeaders(headers);
21870
+ *
21871
+ * const logger = initLogger({ projectName: "my-project" });
21872
+ * await logger.traced(async (span) => {
21873
+ * span.log({ input: "BT span as child of OTEL parent" });
21874
+ * }, { name: "service_c", parent });
21875
+ * ```
21876
+ */
21877
+ declare function parentFromHeaders(headers: Record<string, string>): string | undefined;
21878
+ /**
21879
+ * OTEL namespace containing distributed tracing helper functions.
21880
+ *
21881
+ * @example
21882
+ * ```typescript
21883
+ * import { otel } from "braintrust";
21884
+ *
21885
+ * // Export Braintrust span context for OTEL
21886
+ * const ctx = otel.contextFromSpanExport(exportStr);
21887
+ *
21888
+ * // Add parent to baggage before propagating
21889
+ * otel.addParentToBaggage("project_name:my-project");
21890
+ *
21891
+ * // Copy span attribute to baggage
21892
+ * otel.addSpanParentToBaggage(span);
21893
+ *
21894
+ * // Create Braintrust parent from OTEL headers
21895
+ * const parent = otel.parentFromHeaders(headers);
21896
+ * ```
21897
+ */
21898
+ declare const otel: {
21899
+ contextFromSpanExport: typeof otelContextFromSpanExport;
21900
+ getBraintrustParent: typeof getBraintrustParent;
21901
+ addParentToBaggage: typeof addParentToBaggage;
21902
+ addSpanParentToBaggage: typeof addSpanParentToBaggage;
21903
+ parentFromHeaders: typeof parentFromHeaders;
21904
+ };
21763
21905
 
21764
21906
  type braintrust_AISpanProcessor = AISpanProcessor;
21765
21907
  declare const braintrust_AISpanProcessor: typeof AISpanProcessor;
@@ -21918,6 +22060,7 @@ declare const braintrust_logError: typeof logError;
21918
22060
  declare const braintrust_login: typeof login;
21919
22061
  declare const braintrust_loginToState: typeof loginToState;
21920
22062
  declare const braintrust_newId: typeof newId;
22063
+ declare const braintrust_otel: typeof otel;
21921
22064
  declare const braintrust_parseCachedHeader: typeof parseCachedHeader;
21922
22065
  declare const braintrust_permalink: typeof permalink;
21923
22066
  declare const braintrust_projects: typeof projects;
@@ -21952,7 +22095,7 @@ declare const braintrust_wrapOpenAI: typeof wrapOpenAI;
21952
22095
  declare const braintrust_wrapOpenAIv4: typeof wrapOpenAIv4;
21953
22096
  declare const braintrust_wrapTraced: typeof wrapTraced;
21954
22097
  declare namespace braintrust {
21955
- export { braintrust_AISpanProcessor as AISpanProcessor, type braintrust_AnyDataset as AnyDataset, braintrust_Attachment as Attachment, type braintrust_AttachmentParams as AttachmentParams, type braintrust_BackgroundLoggerOpts as BackgroundLoggerOpts, braintrust_BaseAttachment as BaseAttachment, braintrust_BaseExperiment as BaseExperiment, type braintrust_BaseMetadata as BaseMetadata, braintrust_BraintrustExporter as BraintrustExporter, braintrust_BraintrustMiddleware as BraintrustMiddleware, braintrust_BraintrustSpanProcessor as BraintrustSpanProcessor, braintrust_BraintrustState as BraintrustState, braintrust_BraintrustStream as BraintrustStream, type braintrust_BraintrustStreamChunk as BraintrustStreamChunk, type braintrust_ChatPrompt as ChatPrompt, braintrust_CodeFunction as CodeFunction, type braintrust_CodeOpts as CodeOpts, braintrust_CodePrompt as CodePrompt, type braintrust_CompiledPrompt as CompiledPrompt, type braintrust_CompiledPromptParams as CompiledPromptParams, type braintrust_CompletionPrompt as CompletionPrompt, braintrust_ContextManager as ContextManager, type braintrust_ContextParentSpanIds as ContextParentSpanIds, type braintrust_CreateProjectOpts as CreateProjectOpts, type braintrust_DataSummary as DataSummary, braintrust_Dataset as Dataset, type braintrust_DatasetSummary as DatasetSummary, type braintrust_DefaultMetadataType as DefaultMetadataType, type braintrust_DefaultPromptArgs as DefaultPromptArgs, braintrust_ERR_PERMALINK as ERR_PERMALINK, type braintrust_EndSpanArgs as EndSpanArgs, braintrust_Eval as Eval, type braintrust_EvalCase as EvalCase, type braintrust_EvalHooks as EvalHooks, type braintrust_EvalResult as EvalResult, braintrust_EvalResultWithSummary as EvalResultWithSummary, type braintrust_EvalScorer as EvalScorer, type braintrust_EvalScorerArgs as EvalScorerArgs, type braintrust_EvalTask as EvalTask, type braintrust_Evaluator as Evaluator, type braintrust_EvaluatorDef as EvaluatorDef, type braintrust_EvaluatorFile as EvaluatorFile, braintrust_Experiment as Experiment, type braintrust_ExperimentSummary as ExperimentSummary, type braintrust_Exportable as Exportable, braintrust_ExternalAttachment as ExternalAttachment, type braintrust_ExternalAttachmentParams as ExternalAttachmentParams, braintrust_FailedHTTPResponse as FailedHTTPResponse, type braintrust_FullInitOptions as FullInitOptions, type braintrust_FullLoginOptions as FullLoginOptions, type braintrust_FunctionEvent as FunctionEvent, braintrust_IDGenerator as IDGenerator, braintrust_INTERNAL_BTQL_LIMIT as INTERNAL_BTQL_LIMIT, type braintrust_InitOptions as InitOptions, type braintrust_InvokeFunctionArgs as InvokeFunctionArgs, type braintrust_InvokeReturn as InvokeReturn, braintrust_JSONAttachment as JSONAttachment, braintrust_LEGACY_CACHED_HEADER as LEGACY_CACHED_HEADER, braintrust_LazyValue as LazyValue, type braintrust_LogOptions as LogOptions, braintrust_Logger as Logger, type braintrust_LoginOptions as LoginOptions, type braintrust_MetricSummary as MetricSummary, braintrust_NOOP_SPAN as NOOP_SPAN, braintrust_NOOP_SPAN_PERMALINK as NOOP_SPAN_PERMALINK, braintrust_NoopSpan as NoopSpan, braintrust_OTELIDGenerator as OTELIDGenerator, type braintrust_ObjectMetadata as ObjectMetadata, braintrust_Project as Project, braintrust_ProjectNameIdMap as ProjectNameIdMap, type braintrust_PromiseUnless as PromiseUnless, braintrust_Prompt as Prompt, braintrust_PromptBuilder as PromptBuilder, type braintrust_PromptContents as PromptContents, type braintrust_PromptDefinition as PromptDefinition, type braintrust_PromptDefinitionWithTools as PromptDefinitionWithTools, type braintrust_PromptOpts as PromptOpts, type braintrust_PromptRowWithId as PromptRowWithId, braintrust_ReadonlyAttachment as ReadonlyAttachment, braintrust_ReadonlyExperiment as ReadonlyExperiment, braintrust_Reporter as Reporter, type braintrust_ReporterBody as ReporterBody, type braintrust_ScoreSummary as ScoreSummary, braintrust_ScorerBuilder as ScorerBuilder, type braintrust_ScorerOpts as ScorerOpts, type braintrust_SerializedBraintrustState as SerializedBraintrustState, type braintrust_SetCurrentArg as SetCurrentArg, type Span$1 as Span, type braintrust_SpanContext as SpanContext, braintrust_SpanImpl as SpanImpl, type braintrust_StartSpanArgs as StartSpanArgs, braintrust_TestBackgroundLogger as TestBackgroundLogger, braintrust_ToolBuilder as ToolBuilder, braintrust_UUIDGenerator as UUIDGenerator, type braintrust_WithTransactionId as WithTransactionId, braintrust_X_CACHED_HEADER as X_CACHED_HEADER, braintrust__exportsForTestingOnly as _exportsForTestingOnly, braintrust__internalGetGlobalState as _internalGetGlobalState, braintrust__internalSetInitialState as _internalSetInitialState, braintrust_braintrustStreamChunkSchema as braintrustStreamChunkSchema, braintrust_buildLocalSummary as buildLocalSummary, braintrust_createFinalValuePassThroughStream as createFinalValuePassThroughStream, braintrust_currentExperiment as currentExperiment, braintrust_currentLogger as currentLogger, braintrust_currentSpan as currentSpan, braintrust_deepCopyEvent as deepCopyEvent, braintrust_defaultErrorScoreHandler as defaultErrorScoreHandler, braintrust_deserializePlainStringAsJSON as deserializePlainStringAsJSON, braintrust_devNullWritableStream as devNullWritableStream, braintrust_flush as flush, braintrust_getContextManager as getContextManager, braintrust_getIdGenerator as getIdGenerator, braintrust_getPromptVersions as getPromptVersions, braintrust_getSpanParentObject as getSpanParentObject, graphFramework as graph, braintrust_init as init, braintrust_initDataset as initDataset, braintrust_initExperiment as initExperiment, braintrust_initFunction as initFunction, braintrust_initLogger as initLogger, braintrust_invoke as invoke, braintrust_loadPrompt as loadPrompt, braintrust_log as log, braintrust_logError as logError, braintrust_login as login, braintrust_loginToState as loginToState, braintrust_newId as newId, braintrust_parseCachedHeader as parseCachedHeader, braintrust_permalink as permalink, braintrust_projects as projects, braintrust_promptContentsSchema as promptContentsSchema, braintrust_promptDefinitionSchema as promptDefinitionSchema, braintrust_promptDefinitionToPromptData as promptDefinitionToPromptData, braintrust_promptDefinitionWithToolsSchema as promptDefinitionWithToolsSchema, braintrust_renderMessage as renderMessage, braintrust_renderPromptParams as renderPromptParams, braintrust_reportFailures as reportFailures, braintrust_runEvaluator as runEvaluator, braintrust_setFetch as setFetch, braintrust_setMaskingFunction as setMaskingFunction, braintrust_spanComponentsToObjectId as spanComponentsToObjectId, braintrust_startSpan as startSpan, braintrust_summarize as summarize, ToolFunctionDefinition as toolFunctionDefinitionSchema, braintrust_traceable as traceable, braintrust_traced as traced, braintrust_updateSpan as updateSpan, braintrust_withCurrent as withCurrent, braintrust_withDataset as withDataset, braintrust_withExperiment as withExperiment, braintrust_withLogger as withLogger, braintrust_withParent as withParent, braintrust_wrapAISDK as wrapAISDK, braintrust_wrapAISDKModel as wrapAISDKModel, braintrust_wrapAnthropic as wrapAnthropic, braintrust_wrapClaudeAgentSDK as wrapClaudeAgentSDK, braintrust_wrapGoogleGenAI as wrapGoogleGenAI, braintrust_wrapMastraAgent as wrapMastraAgent, braintrust_wrapOpenAI as wrapOpenAI, braintrust_wrapOpenAIv4 as wrapOpenAIv4, braintrust_wrapTraced as wrapTraced };
22098
+ export { braintrust_AISpanProcessor as AISpanProcessor, type braintrust_AnyDataset as AnyDataset, braintrust_Attachment as Attachment, type braintrust_AttachmentParams as AttachmentParams, type braintrust_BackgroundLoggerOpts as BackgroundLoggerOpts, braintrust_BaseAttachment as BaseAttachment, braintrust_BaseExperiment as BaseExperiment, type braintrust_BaseMetadata as BaseMetadata, braintrust_BraintrustExporter as BraintrustExporter, braintrust_BraintrustMiddleware as BraintrustMiddleware, braintrust_BraintrustSpanProcessor as BraintrustSpanProcessor, braintrust_BraintrustState as BraintrustState, braintrust_BraintrustStream as BraintrustStream, type braintrust_BraintrustStreamChunk as BraintrustStreamChunk, type braintrust_ChatPrompt as ChatPrompt, braintrust_CodeFunction as CodeFunction, type braintrust_CodeOpts as CodeOpts, braintrust_CodePrompt as CodePrompt, type braintrust_CompiledPrompt as CompiledPrompt, type braintrust_CompiledPromptParams as CompiledPromptParams, type braintrust_CompletionPrompt as CompletionPrompt, braintrust_ContextManager as ContextManager, type braintrust_ContextParentSpanIds as ContextParentSpanIds, type braintrust_CreateProjectOpts as CreateProjectOpts, type braintrust_DataSummary as DataSummary, braintrust_Dataset as Dataset, type braintrust_DatasetSummary as DatasetSummary, type braintrust_DefaultMetadataType as DefaultMetadataType, type braintrust_DefaultPromptArgs as DefaultPromptArgs, braintrust_ERR_PERMALINK as ERR_PERMALINK, type braintrust_EndSpanArgs as EndSpanArgs, braintrust_Eval as Eval, type braintrust_EvalCase as EvalCase, type braintrust_EvalHooks as EvalHooks, type braintrust_EvalResult as EvalResult, braintrust_EvalResultWithSummary as EvalResultWithSummary, type braintrust_EvalScorer as EvalScorer, type braintrust_EvalScorerArgs as EvalScorerArgs, type braintrust_EvalTask as EvalTask, type braintrust_Evaluator as Evaluator, type braintrust_EvaluatorDef as EvaluatorDef, type braintrust_EvaluatorFile as EvaluatorFile, braintrust_Experiment as Experiment, type braintrust_ExperimentSummary as ExperimentSummary, type braintrust_Exportable as Exportable, braintrust_ExternalAttachment as ExternalAttachment, type braintrust_ExternalAttachmentParams as ExternalAttachmentParams, braintrust_FailedHTTPResponse as FailedHTTPResponse, type braintrust_FullInitOptions as FullInitOptions, type braintrust_FullLoginOptions as FullLoginOptions, type braintrust_FunctionEvent as FunctionEvent, braintrust_IDGenerator as IDGenerator, braintrust_INTERNAL_BTQL_LIMIT as INTERNAL_BTQL_LIMIT, type braintrust_InitOptions as InitOptions, type braintrust_InvokeFunctionArgs as InvokeFunctionArgs, type braintrust_InvokeReturn as InvokeReturn, braintrust_JSONAttachment as JSONAttachment, braintrust_LEGACY_CACHED_HEADER as LEGACY_CACHED_HEADER, braintrust_LazyValue as LazyValue, type braintrust_LogOptions as LogOptions, braintrust_Logger as Logger, type braintrust_LoginOptions as LoginOptions, type braintrust_MetricSummary as MetricSummary, braintrust_NOOP_SPAN as NOOP_SPAN, braintrust_NOOP_SPAN_PERMALINK as NOOP_SPAN_PERMALINK, braintrust_NoopSpan as NoopSpan, braintrust_OTELIDGenerator as OTELIDGenerator, type braintrust_ObjectMetadata as ObjectMetadata, braintrust_Project as Project, braintrust_ProjectNameIdMap as ProjectNameIdMap, type braintrust_PromiseUnless as PromiseUnless, braintrust_Prompt as Prompt, braintrust_PromptBuilder as PromptBuilder, type braintrust_PromptContents as PromptContents, type braintrust_PromptDefinition as PromptDefinition, type braintrust_PromptDefinitionWithTools as PromptDefinitionWithTools, type braintrust_PromptOpts as PromptOpts, type braintrust_PromptRowWithId as PromptRowWithId, braintrust_ReadonlyAttachment as ReadonlyAttachment, braintrust_ReadonlyExperiment as ReadonlyExperiment, braintrust_Reporter as Reporter, type braintrust_ReporterBody as ReporterBody, type braintrust_ScoreSummary as ScoreSummary, braintrust_ScorerBuilder as ScorerBuilder, type braintrust_ScorerOpts as ScorerOpts, type braintrust_SerializedBraintrustState as SerializedBraintrustState, type braintrust_SetCurrentArg as SetCurrentArg, type Span$1 as Span, type braintrust_SpanContext as SpanContext, braintrust_SpanImpl as SpanImpl, type braintrust_StartSpanArgs as StartSpanArgs, braintrust_TestBackgroundLogger as TestBackgroundLogger, braintrust_ToolBuilder as ToolBuilder, braintrust_UUIDGenerator as UUIDGenerator, type braintrust_WithTransactionId as WithTransactionId, braintrust_X_CACHED_HEADER as X_CACHED_HEADER, braintrust__exportsForTestingOnly as _exportsForTestingOnly, braintrust__internalGetGlobalState as _internalGetGlobalState, braintrust__internalSetInitialState as _internalSetInitialState, braintrust_braintrustStreamChunkSchema as braintrustStreamChunkSchema, braintrust_buildLocalSummary as buildLocalSummary, braintrust_createFinalValuePassThroughStream as createFinalValuePassThroughStream, braintrust_currentExperiment as currentExperiment, braintrust_currentLogger as currentLogger, braintrust_currentSpan as currentSpan, braintrust_deepCopyEvent as deepCopyEvent, braintrust_defaultErrorScoreHandler as defaultErrorScoreHandler, braintrust_deserializePlainStringAsJSON as deserializePlainStringAsJSON, braintrust_devNullWritableStream as devNullWritableStream, braintrust_flush as flush, braintrust_getContextManager as getContextManager, braintrust_getIdGenerator as getIdGenerator, braintrust_getPromptVersions as getPromptVersions, braintrust_getSpanParentObject as getSpanParentObject, graphFramework as graph, braintrust_init as init, braintrust_initDataset as initDataset, braintrust_initExperiment as initExperiment, braintrust_initFunction as initFunction, braintrust_initLogger as initLogger, braintrust_invoke as invoke, braintrust_loadPrompt as loadPrompt, braintrust_log as log, braintrust_logError as logError, braintrust_login as login, braintrust_loginToState as loginToState, braintrust_newId as newId, braintrust_otel as otel, braintrust_parseCachedHeader as parseCachedHeader, braintrust_permalink as permalink, braintrust_projects as projects, braintrust_promptContentsSchema as promptContentsSchema, braintrust_promptDefinitionSchema as promptDefinitionSchema, braintrust_promptDefinitionToPromptData as promptDefinitionToPromptData, braintrust_promptDefinitionWithToolsSchema as promptDefinitionWithToolsSchema, braintrust_renderMessage as renderMessage, braintrust_renderPromptParams as renderPromptParams, braintrust_reportFailures as reportFailures, braintrust_runEvaluator as runEvaluator, braintrust_setFetch as setFetch, braintrust_setMaskingFunction as setMaskingFunction, braintrust_spanComponentsToObjectId as spanComponentsToObjectId, braintrust_startSpan as startSpan, braintrust_summarize as summarize, ToolFunctionDefinition as toolFunctionDefinitionSchema, braintrust_traceable as traceable, braintrust_traced as traced, braintrust_updateSpan as updateSpan, braintrust_withCurrent as withCurrent, braintrust_withDataset as withDataset, braintrust_withExperiment as withExperiment, braintrust_withLogger as withLogger, braintrust_withParent as withParent, braintrust_wrapAISDK as wrapAISDK, braintrust_wrapAISDKModel as wrapAISDKModel, braintrust_wrapAnthropic as wrapAnthropic, braintrust_wrapClaudeAgentSDK as wrapClaudeAgentSDK, braintrust_wrapGoogleGenAI as wrapGoogleGenAI, braintrust_wrapMastraAgent as wrapMastraAgent, braintrust_wrapOpenAI as wrapOpenAI, braintrust_wrapOpenAIv4 as wrapOpenAIv4, braintrust_wrapTraced as wrapTraced };
21956
22099
  }
21957
22100
 
21958
22101
  type EvaluatorManifest = Record<string, EvaluatorDef<unknown, unknown, unknown, BaseMetadata>>;
@@ -29009,4 +29152,4 @@ type EvaluatorDefinitions = z.infer<typeof evaluatorDefinitionsSchema>;
29009
29152
  * @module braintrust
29010
29153
  */
29011
29154
 
29012
- export { AISpanProcessor, type AnyDataset, Attachment, type AttachmentParams, AttachmentReference, type BackgroundLoggerOpts, BaseAttachment, BaseExperiment, type BaseMetadata, BraintrustExporter, BraintrustMiddleware, BraintrustSpanProcessor, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, CodeFunction, type CodeOpts, CodePrompt, type CommentEvent, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, ContextManager, type ContextParentSpanIds, type CreateProjectOpts, type DataSummary, Dataset, type DatasetRecord, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, ERR_PERMALINK, type EndSpanArgs, Eval, type EvalCase, type EvalHooks, type EvalParameterSerializedSchema, type EvalParameters, type EvalResult, EvalResultWithSummary, type EvalScorer, type EvalScorerArgs, type EvalTask, type Evaluator, type EvaluatorDef, type EvaluatorDefinition, type EvaluatorDefinitions, type EvaluatorFile, type EvaluatorManifest, Experiment, type ExperimentLogFullArgs, type ExperimentLogPartialArgs, type ExperimentSummary, type Exportable, ExternalAttachment, type ExternalAttachmentParams, FailedHTTPResponse, type FullInitOptions, type FullLoginOptions, type FunctionEvent, IDGenerator, INTERNAL_BTQL_LIMIT, type IdField, type InitOptions, type InputField, type InvokeFunctionArgs, type InvokeReturn, JSONAttachment, LEGACY_CACHED_HEADER, LazyValue, type LogCommentFullArgs, type LogFeedbackFullArgs, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NOOP_SPAN_PERMALINK, NoopSpan, OTELIDGenerator, type ObjectMetadata, type OtherExperimentLogFields, type ParentExperimentIds, type ParentProjectLogIds, Project, ProjectNameIdMap, type PromiseUnless, Prompt, PromptBuilder, type PromptContents, type PromptDefinition, type PromptDefinitionWithTools, type PromptOpts, type PromptRowWithId, ReadonlyAttachment, ReadonlyExperiment, Reporter, type ReporterBody, type ScoreSummary, ScorerBuilder, type ScorerOpts, type SerializedBraintrustState, type SetCurrentArg, type Span$1 as Span, type SpanContext, SpanImpl, type StartSpanArgs, TestBackgroundLogger, ToolBuilder, UUIDGenerator, type WithTransactionId, X_CACHED_HEADER, _exportsForTestingOnly, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, buildLocalSummary, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, deepCopyEvent, braintrust as default, defaultErrorScoreHandler, deserializePlainStringAsJSON, devNullWritableStream, evaluatorDefinitionSchema, evaluatorDefinitionsSchema, flush, getContextManager, getIdGenerator, getPromptVersions, getSpanParentObject, graphFramework as graph, init, initDataset, initExperiment, initFunction, initLogger, invoke, loadPrompt, log, logError, login, loginToState, newId, parseCachedHeader, permalink, projects, promptContentsSchema, promptDefinitionSchema, promptDefinitionToPromptData, promptDefinitionWithToolsSchema, renderMessage, renderPromptParams, reportFailures, runEvaluator, setFetch, setMaskingFunction, spanComponentsToObjectId, startSpan, summarize, ToolFunctionDefinition as toolFunctionDefinitionSchema, traceable, traced, updateSpan, withCurrent, withDataset, withExperiment, withLogger, withParent, wrapAISDK, wrapAISDKModel, wrapAnthropic, wrapClaudeAgentSDK, wrapGoogleGenAI, wrapMastraAgent, wrapOpenAI, wrapOpenAIv4, wrapTraced };
29155
+ export { AISpanProcessor, type AnyDataset, Attachment, type AttachmentParams, AttachmentReference, type BackgroundLoggerOpts, BaseAttachment, BaseExperiment, type BaseMetadata, BraintrustExporter, BraintrustMiddleware, BraintrustSpanProcessor, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, CodeFunction, type CodeOpts, CodePrompt, type CommentEvent, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, ContextManager, type ContextParentSpanIds, type CreateProjectOpts, type DataSummary, Dataset, type DatasetRecord, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, ERR_PERMALINK, type EndSpanArgs, Eval, type EvalCase, type EvalHooks, type EvalParameterSerializedSchema, type EvalParameters, type EvalResult, EvalResultWithSummary, type EvalScorer, type EvalScorerArgs, type EvalTask, type Evaluator, type EvaluatorDef, type EvaluatorDefinition, type EvaluatorDefinitions, type EvaluatorFile, type EvaluatorManifest, Experiment, type ExperimentLogFullArgs, type ExperimentLogPartialArgs, type ExperimentSummary, type Exportable, ExternalAttachment, type ExternalAttachmentParams, FailedHTTPResponse, type FullInitOptions, type FullLoginOptions, type FunctionEvent, IDGenerator, INTERNAL_BTQL_LIMIT, type IdField, type InitOptions, type InputField, type InvokeFunctionArgs, type InvokeReturn, JSONAttachment, LEGACY_CACHED_HEADER, LazyValue, type LogCommentFullArgs, type LogFeedbackFullArgs, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NOOP_SPAN_PERMALINK, NoopSpan, OTELIDGenerator, type ObjectMetadata, type OtherExperimentLogFields, type ParentExperimentIds, type ParentProjectLogIds, Project, ProjectNameIdMap, type PromiseUnless, Prompt, PromptBuilder, type PromptContents, type PromptDefinition, type PromptDefinitionWithTools, type PromptOpts, type PromptRowWithId, ReadonlyAttachment, ReadonlyExperiment, Reporter, type ReporterBody, type ScoreSummary, ScorerBuilder, type ScorerOpts, type SerializedBraintrustState, type SetCurrentArg, type Span$1 as Span, type SpanContext, SpanImpl, type StartSpanArgs, TestBackgroundLogger, ToolBuilder, UUIDGenerator, type WithTransactionId, X_CACHED_HEADER, _exportsForTestingOnly, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, buildLocalSummary, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, deepCopyEvent, braintrust as default, defaultErrorScoreHandler, deserializePlainStringAsJSON, devNullWritableStream, evaluatorDefinitionSchema, evaluatorDefinitionsSchema, flush, getContextManager, getIdGenerator, getPromptVersions, getSpanParentObject, graphFramework as graph, init, initDataset, initExperiment, initFunction, initLogger, invoke, loadPrompt, log, logError, login, loginToState, newId, otel, parseCachedHeader, permalink, projects, promptContentsSchema, promptDefinitionSchema, promptDefinitionToPromptData, promptDefinitionWithToolsSchema, renderMessage, renderPromptParams, reportFailures, runEvaluator, setFetch, setMaskingFunction, spanComponentsToObjectId, startSpan, summarize, ToolFunctionDefinition as toolFunctionDefinitionSchema, traceable, traced, updateSpan, withCurrent, withDataset, withExperiment, withLogger, withParent, wrapAISDK, wrapAISDKModel, wrapAnthropic, wrapClaudeAgentSDK, wrapGoogleGenAI, wrapMastraAgent, wrapOpenAI, wrapOpenAIv4, wrapTraced };
package/dist/index.d.ts CHANGED
@@ -21694,6 +21694,43 @@ declare class BraintrustSpanProcessor {
21694
21694
  shutdown(): Promise<void>;
21695
21695
  forceFlush(): Promise<void>;
21696
21696
  }
21697
+ /**
21698
+ * Create an OTEL context from a Braintrust span export string.
21699
+ *
21700
+ * Used for distributed tracing scenarios where a Braintrust span in one service
21701
+ * needs to be the parent of an OTEL span in another service.
21702
+ *
21703
+ * @param exportStr - The string returned from span.export()
21704
+ * @returns OTEL context that can be used when creating child spans
21705
+ *
21706
+ * @example
21707
+ * ```typescript
21708
+ * // Service A: Create BT span and export
21709
+ * const span = logger.startSpan({ name: "service-a" });
21710
+ * const exportStr = await span.export();
21711
+ * // Send exportStr to Service B (e.g., via HTTP header)
21712
+ *
21713
+ * // Service B: Import context and create OTEL child
21714
+ * import * as api from '@opentelemetry/api';
21715
+ * const ctx = otelContextFromSpanExport(exportStr);
21716
+ * await api.context.with(ctx, async () => {
21717
+ * await tracer.startActiveSpan("service-b", async (span) => {
21718
+ * // This span is now a child of the Service A span
21719
+ * span.end();
21720
+ * });
21721
+ * });
21722
+ * ```
21723
+ */
21724
+ declare function otelContextFromSpanExport(exportStr: string): unknown;
21725
+ /**
21726
+ * Construct a braintrust.parent identifier string from span components.
21727
+ *
21728
+ * @param objectType - Type of parent object (PROJECT_LOGS or EXPERIMENT)
21729
+ * @param objectId - Resolved object ID (project_id or experiment_id)
21730
+ * @param computeArgs - Optional dict with project_name/project_id for unresolved cases
21731
+ * @returns String like "project_id:abc", "project_name:my-proj", "experiment_id:exp-123", or undefined
21732
+ */
21733
+ declare function getBraintrustParent(objectType: number, objectId?: string | null, computeArgs?: Record<string, unknown> | null): string | undefined;
21697
21734
  /**
21698
21735
  * A trace exporter that sends OpenTelemetry spans to Braintrust.
21699
21736
  *
@@ -21760,6 +21797,111 @@ declare class BraintrustExporter {
21760
21797
  */
21761
21798
  forceFlush(): Promise<void>;
21762
21799
  }
21800
+ /**
21801
+ * Add braintrust.parent to OTEL baggage.
21802
+ *
21803
+ * This ensures that when using propagation inject() for distributed tracing,
21804
+ * the braintrust.parent will be propagated via baggage to downstream services.
21805
+ *
21806
+ * @param parent - Braintrust parent identifier (e.g., "project_name:my-project",
21807
+ * "project_id:abc123", "experiment_id:exp-456")
21808
+ * @param ctx - Optional OTEL context to use. If not provided, uses current context.
21809
+ * @returns Updated context with braintrust.parent in baggage
21810
+ *
21811
+ * @example
21812
+ * ```typescript
21813
+ * import { otel } from "braintrust";
21814
+ * import { propagation } from "@opentelemetry/api";
21815
+ *
21816
+ * // Set braintrust.parent in baggage
21817
+ * otel.addParentToBaggage("project_name:my-project");
21818
+ *
21819
+ * // Export headers (will include braintrust.parent in baggage)
21820
+ * const headers = {};
21821
+ * propagation.inject(context.active(), headers);
21822
+ * ```
21823
+ */
21824
+ declare function addParentToBaggage(parent: string, ctx?: Context): Context;
21825
+ /**
21826
+ * Copy braintrust.parent from span attribute to OTEL baggage.
21827
+ *
21828
+ * BraintrustSpanProcessor automatically sets braintrust.parent as a span attribute
21829
+ * when OTEL spans are created within Braintrust contexts. This function copies that
21830
+ * attribute to OTEL baggage so it propagates when using inject() for distributed tracing.
21831
+ *
21832
+ * @param span - OTEL span that has braintrust.parent attribute set
21833
+ * @param ctx - Optional OTEL context to use. If not provided, uses current context.
21834
+ * @returns Updated context with braintrust.parent in baggage, or undefined if attribute not found
21835
+ *
21836
+ * @example
21837
+ * ```typescript
21838
+ * import { otel } from "braintrust";
21839
+ * import { propagation } from "@opentelemetry/api";
21840
+ *
21841
+ * tracer.startActiveSpan("service_b", (span) => {
21842
+ * // Copy braintrust.parent from span attribute to baggage
21843
+ * otel.addSpanParentToBaggage(span);
21844
+ *
21845
+ * // Export headers (will include braintrust.parent in baggage)
21846
+ * const headers = {};
21847
+ * propagation.inject(context.active(), headers);
21848
+ * span.end();
21849
+ * });
21850
+ * ```
21851
+ */
21852
+ declare function addSpanParentToBaggage(span: Span, ctx?: Context): Context | undefined;
21853
+ /**
21854
+ * Extract a Braintrust-compatible parent string from W3C Trace Context headers.
21855
+ *
21856
+ * This converts OTEL trace context headers (traceparent/baggage) into a format
21857
+ * that can be passed as the 'parent' parameter to Braintrust's traced() method.
21858
+ *
21859
+ * @param headers - Dictionary with 'traceparent' and optionally 'baggage' keys
21860
+ * @returns Braintrust V4 export string that can be used as parent parameter,
21861
+ * or undefined if no valid span context is found or braintrust.parent is missing.
21862
+ *
21863
+ * @example
21864
+ * ```typescript
21865
+ * import { otel, initLogger } from "braintrust";
21866
+ *
21867
+ * // Service C receives headers from Service B
21868
+ * const headers = { traceparent: '00-trace_id-span_id-01', baggage: '...' };
21869
+ * const parent = otel.parentFromHeaders(headers);
21870
+ *
21871
+ * const logger = initLogger({ projectName: "my-project" });
21872
+ * await logger.traced(async (span) => {
21873
+ * span.log({ input: "BT span as child of OTEL parent" });
21874
+ * }, { name: "service_c", parent });
21875
+ * ```
21876
+ */
21877
+ declare function parentFromHeaders(headers: Record<string, string>): string | undefined;
21878
+ /**
21879
+ * OTEL namespace containing distributed tracing helper functions.
21880
+ *
21881
+ * @example
21882
+ * ```typescript
21883
+ * import { otel } from "braintrust";
21884
+ *
21885
+ * // Export Braintrust span context for OTEL
21886
+ * const ctx = otel.contextFromSpanExport(exportStr);
21887
+ *
21888
+ * // Add parent to baggage before propagating
21889
+ * otel.addParentToBaggage("project_name:my-project");
21890
+ *
21891
+ * // Copy span attribute to baggage
21892
+ * otel.addSpanParentToBaggage(span);
21893
+ *
21894
+ * // Create Braintrust parent from OTEL headers
21895
+ * const parent = otel.parentFromHeaders(headers);
21896
+ * ```
21897
+ */
21898
+ declare const otel: {
21899
+ contextFromSpanExport: typeof otelContextFromSpanExport;
21900
+ getBraintrustParent: typeof getBraintrustParent;
21901
+ addParentToBaggage: typeof addParentToBaggage;
21902
+ addSpanParentToBaggage: typeof addSpanParentToBaggage;
21903
+ parentFromHeaders: typeof parentFromHeaders;
21904
+ };
21763
21905
 
21764
21906
  type braintrust_AISpanProcessor = AISpanProcessor;
21765
21907
  declare const braintrust_AISpanProcessor: typeof AISpanProcessor;
@@ -21918,6 +22060,7 @@ declare const braintrust_logError: typeof logError;
21918
22060
  declare const braintrust_login: typeof login;
21919
22061
  declare const braintrust_loginToState: typeof loginToState;
21920
22062
  declare const braintrust_newId: typeof newId;
22063
+ declare const braintrust_otel: typeof otel;
21921
22064
  declare const braintrust_parseCachedHeader: typeof parseCachedHeader;
21922
22065
  declare const braintrust_permalink: typeof permalink;
21923
22066
  declare const braintrust_projects: typeof projects;
@@ -21952,7 +22095,7 @@ declare const braintrust_wrapOpenAI: typeof wrapOpenAI;
21952
22095
  declare const braintrust_wrapOpenAIv4: typeof wrapOpenAIv4;
21953
22096
  declare const braintrust_wrapTraced: typeof wrapTraced;
21954
22097
  declare namespace braintrust {
21955
- export { braintrust_AISpanProcessor as AISpanProcessor, type braintrust_AnyDataset as AnyDataset, braintrust_Attachment as Attachment, type braintrust_AttachmentParams as AttachmentParams, type braintrust_BackgroundLoggerOpts as BackgroundLoggerOpts, braintrust_BaseAttachment as BaseAttachment, braintrust_BaseExperiment as BaseExperiment, type braintrust_BaseMetadata as BaseMetadata, braintrust_BraintrustExporter as BraintrustExporter, braintrust_BraintrustMiddleware as BraintrustMiddleware, braintrust_BraintrustSpanProcessor as BraintrustSpanProcessor, braintrust_BraintrustState as BraintrustState, braintrust_BraintrustStream as BraintrustStream, type braintrust_BraintrustStreamChunk as BraintrustStreamChunk, type braintrust_ChatPrompt as ChatPrompt, braintrust_CodeFunction as CodeFunction, type braintrust_CodeOpts as CodeOpts, braintrust_CodePrompt as CodePrompt, type braintrust_CompiledPrompt as CompiledPrompt, type braintrust_CompiledPromptParams as CompiledPromptParams, type braintrust_CompletionPrompt as CompletionPrompt, braintrust_ContextManager as ContextManager, type braintrust_ContextParentSpanIds as ContextParentSpanIds, type braintrust_CreateProjectOpts as CreateProjectOpts, type braintrust_DataSummary as DataSummary, braintrust_Dataset as Dataset, type braintrust_DatasetSummary as DatasetSummary, type braintrust_DefaultMetadataType as DefaultMetadataType, type braintrust_DefaultPromptArgs as DefaultPromptArgs, braintrust_ERR_PERMALINK as ERR_PERMALINK, type braintrust_EndSpanArgs as EndSpanArgs, braintrust_Eval as Eval, type braintrust_EvalCase as EvalCase, type braintrust_EvalHooks as EvalHooks, type braintrust_EvalResult as EvalResult, braintrust_EvalResultWithSummary as EvalResultWithSummary, type braintrust_EvalScorer as EvalScorer, type braintrust_EvalScorerArgs as EvalScorerArgs, type braintrust_EvalTask as EvalTask, type braintrust_Evaluator as Evaluator, type braintrust_EvaluatorDef as EvaluatorDef, type braintrust_EvaluatorFile as EvaluatorFile, braintrust_Experiment as Experiment, type braintrust_ExperimentSummary as ExperimentSummary, type braintrust_Exportable as Exportable, braintrust_ExternalAttachment as ExternalAttachment, type braintrust_ExternalAttachmentParams as ExternalAttachmentParams, braintrust_FailedHTTPResponse as FailedHTTPResponse, type braintrust_FullInitOptions as FullInitOptions, type braintrust_FullLoginOptions as FullLoginOptions, type braintrust_FunctionEvent as FunctionEvent, braintrust_IDGenerator as IDGenerator, braintrust_INTERNAL_BTQL_LIMIT as INTERNAL_BTQL_LIMIT, type braintrust_InitOptions as InitOptions, type braintrust_InvokeFunctionArgs as InvokeFunctionArgs, type braintrust_InvokeReturn as InvokeReturn, braintrust_JSONAttachment as JSONAttachment, braintrust_LEGACY_CACHED_HEADER as LEGACY_CACHED_HEADER, braintrust_LazyValue as LazyValue, type braintrust_LogOptions as LogOptions, braintrust_Logger as Logger, type braintrust_LoginOptions as LoginOptions, type braintrust_MetricSummary as MetricSummary, braintrust_NOOP_SPAN as NOOP_SPAN, braintrust_NOOP_SPAN_PERMALINK as NOOP_SPAN_PERMALINK, braintrust_NoopSpan as NoopSpan, braintrust_OTELIDGenerator as OTELIDGenerator, type braintrust_ObjectMetadata as ObjectMetadata, braintrust_Project as Project, braintrust_ProjectNameIdMap as ProjectNameIdMap, type braintrust_PromiseUnless as PromiseUnless, braintrust_Prompt as Prompt, braintrust_PromptBuilder as PromptBuilder, type braintrust_PromptContents as PromptContents, type braintrust_PromptDefinition as PromptDefinition, type braintrust_PromptDefinitionWithTools as PromptDefinitionWithTools, type braintrust_PromptOpts as PromptOpts, type braintrust_PromptRowWithId as PromptRowWithId, braintrust_ReadonlyAttachment as ReadonlyAttachment, braintrust_ReadonlyExperiment as ReadonlyExperiment, braintrust_Reporter as Reporter, type braintrust_ReporterBody as ReporterBody, type braintrust_ScoreSummary as ScoreSummary, braintrust_ScorerBuilder as ScorerBuilder, type braintrust_ScorerOpts as ScorerOpts, type braintrust_SerializedBraintrustState as SerializedBraintrustState, type braintrust_SetCurrentArg as SetCurrentArg, type Span$1 as Span, type braintrust_SpanContext as SpanContext, braintrust_SpanImpl as SpanImpl, type braintrust_StartSpanArgs as StartSpanArgs, braintrust_TestBackgroundLogger as TestBackgroundLogger, braintrust_ToolBuilder as ToolBuilder, braintrust_UUIDGenerator as UUIDGenerator, type braintrust_WithTransactionId as WithTransactionId, braintrust_X_CACHED_HEADER as X_CACHED_HEADER, braintrust__exportsForTestingOnly as _exportsForTestingOnly, braintrust__internalGetGlobalState as _internalGetGlobalState, braintrust__internalSetInitialState as _internalSetInitialState, braintrust_braintrustStreamChunkSchema as braintrustStreamChunkSchema, braintrust_buildLocalSummary as buildLocalSummary, braintrust_createFinalValuePassThroughStream as createFinalValuePassThroughStream, braintrust_currentExperiment as currentExperiment, braintrust_currentLogger as currentLogger, braintrust_currentSpan as currentSpan, braintrust_deepCopyEvent as deepCopyEvent, braintrust_defaultErrorScoreHandler as defaultErrorScoreHandler, braintrust_deserializePlainStringAsJSON as deserializePlainStringAsJSON, braintrust_devNullWritableStream as devNullWritableStream, braintrust_flush as flush, braintrust_getContextManager as getContextManager, braintrust_getIdGenerator as getIdGenerator, braintrust_getPromptVersions as getPromptVersions, braintrust_getSpanParentObject as getSpanParentObject, graphFramework as graph, braintrust_init as init, braintrust_initDataset as initDataset, braintrust_initExperiment as initExperiment, braintrust_initFunction as initFunction, braintrust_initLogger as initLogger, braintrust_invoke as invoke, braintrust_loadPrompt as loadPrompt, braintrust_log as log, braintrust_logError as logError, braintrust_login as login, braintrust_loginToState as loginToState, braintrust_newId as newId, braintrust_parseCachedHeader as parseCachedHeader, braintrust_permalink as permalink, braintrust_projects as projects, braintrust_promptContentsSchema as promptContentsSchema, braintrust_promptDefinitionSchema as promptDefinitionSchema, braintrust_promptDefinitionToPromptData as promptDefinitionToPromptData, braintrust_promptDefinitionWithToolsSchema as promptDefinitionWithToolsSchema, braintrust_renderMessage as renderMessage, braintrust_renderPromptParams as renderPromptParams, braintrust_reportFailures as reportFailures, braintrust_runEvaluator as runEvaluator, braintrust_setFetch as setFetch, braintrust_setMaskingFunction as setMaskingFunction, braintrust_spanComponentsToObjectId as spanComponentsToObjectId, braintrust_startSpan as startSpan, braintrust_summarize as summarize, ToolFunctionDefinition as toolFunctionDefinitionSchema, braintrust_traceable as traceable, braintrust_traced as traced, braintrust_updateSpan as updateSpan, braintrust_withCurrent as withCurrent, braintrust_withDataset as withDataset, braintrust_withExperiment as withExperiment, braintrust_withLogger as withLogger, braintrust_withParent as withParent, braintrust_wrapAISDK as wrapAISDK, braintrust_wrapAISDKModel as wrapAISDKModel, braintrust_wrapAnthropic as wrapAnthropic, braintrust_wrapClaudeAgentSDK as wrapClaudeAgentSDK, braintrust_wrapGoogleGenAI as wrapGoogleGenAI, braintrust_wrapMastraAgent as wrapMastraAgent, braintrust_wrapOpenAI as wrapOpenAI, braintrust_wrapOpenAIv4 as wrapOpenAIv4, braintrust_wrapTraced as wrapTraced };
22098
+ export { braintrust_AISpanProcessor as AISpanProcessor, type braintrust_AnyDataset as AnyDataset, braintrust_Attachment as Attachment, type braintrust_AttachmentParams as AttachmentParams, type braintrust_BackgroundLoggerOpts as BackgroundLoggerOpts, braintrust_BaseAttachment as BaseAttachment, braintrust_BaseExperiment as BaseExperiment, type braintrust_BaseMetadata as BaseMetadata, braintrust_BraintrustExporter as BraintrustExporter, braintrust_BraintrustMiddleware as BraintrustMiddleware, braintrust_BraintrustSpanProcessor as BraintrustSpanProcessor, braintrust_BraintrustState as BraintrustState, braintrust_BraintrustStream as BraintrustStream, type braintrust_BraintrustStreamChunk as BraintrustStreamChunk, type braintrust_ChatPrompt as ChatPrompt, braintrust_CodeFunction as CodeFunction, type braintrust_CodeOpts as CodeOpts, braintrust_CodePrompt as CodePrompt, type braintrust_CompiledPrompt as CompiledPrompt, type braintrust_CompiledPromptParams as CompiledPromptParams, type braintrust_CompletionPrompt as CompletionPrompt, braintrust_ContextManager as ContextManager, type braintrust_ContextParentSpanIds as ContextParentSpanIds, type braintrust_CreateProjectOpts as CreateProjectOpts, type braintrust_DataSummary as DataSummary, braintrust_Dataset as Dataset, type braintrust_DatasetSummary as DatasetSummary, type braintrust_DefaultMetadataType as DefaultMetadataType, type braintrust_DefaultPromptArgs as DefaultPromptArgs, braintrust_ERR_PERMALINK as ERR_PERMALINK, type braintrust_EndSpanArgs as EndSpanArgs, braintrust_Eval as Eval, type braintrust_EvalCase as EvalCase, type braintrust_EvalHooks as EvalHooks, type braintrust_EvalResult as EvalResult, braintrust_EvalResultWithSummary as EvalResultWithSummary, type braintrust_EvalScorer as EvalScorer, type braintrust_EvalScorerArgs as EvalScorerArgs, type braintrust_EvalTask as EvalTask, type braintrust_Evaluator as Evaluator, type braintrust_EvaluatorDef as EvaluatorDef, type braintrust_EvaluatorFile as EvaluatorFile, braintrust_Experiment as Experiment, type braintrust_ExperimentSummary as ExperimentSummary, type braintrust_Exportable as Exportable, braintrust_ExternalAttachment as ExternalAttachment, type braintrust_ExternalAttachmentParams as ExternalAttachmentParams, braintrust_FailedHTTPResponse as FailedHTTPResponse, type braintrust_FullInitOptions as FullInitOptions, type braintrust_FullLoginOptions as FullLoginOptions, type braintrust_FunctionEvent as FunctionEvent, braintrust_IDGenerator as IDGenerator, braintrust_INTERNAL_BTQL_LIMIT as INTERNAL_BTQL_LIMIT, type braintrust_InitOptions as InitOptions, type braintrust_InvokeFunctionArgs as InvokeFunctionArgs, type braintrust_InvokeReturn as InvokeReturn, braintrust_JSONAttachment as JSONAttachment, braintrust_LEGACY_CACHED_HEADER as LEGACY_CACHED_HEADER, braintrust_LazyValue as LazyValue, type braintrust_LogOptions as LogOptions, braintrust_Logger as Logger, type braintrust_LoginOptions as LoginOptions, type braintrust_MetricSummary as MetricSummary, braintrust_NOOP_SPAN as NOOP_SPAN, braintrust_NOOP_SPAN_PERMALINK as NOOP_SPAN_PERMALINK, braintrust_NoopSpan as NoopSpan, braintrust_OTELIDGenerator as OTELIDGenerator, type braintrust_ObjectMetadata as ObjectMetadata, braintrust_Project as Project, braintrust_ProjectNameIdMap as ProjectNameIdMap, type braintrust_PromiseUnless as PromiseUnless, braintrust_Prompt as Prompt, braintrust_PromptBuilder as PromptBuilder, type braintrust_PromptContents as PromptContents, type braintrust_PromptDefinition as PromptDefinition, type braintrust_PromptDefinitionWithTools as PromptDefinitionWithTools, type braintrust_PromptOpts as PromptOpts, type braintrust_PromptRowWithId as PromptRowWithId, braintrust_ReadonlyAttachment as ReadonlyAttachment, braintrust_ReadonlyExperiment as ReadonlyExperiment, braintrust_Reporter as Reporter, type braintrust_ReporterBody as ReporterBody, type braintrust_ScoreSummary as ScoreSummary, braintrust_ScorerBuilder as ScorerBuilder, type braintrust_ScorerOpts as ScorerOpts, type braintrust_SerializedBraintrustState as SerializedBraintrustState, type braintrust_SetCurrentArg as SetCurrentArg, type Span$1 as Span, type braintrust_SpanContext as SpanContext, braintrust_SpanImpl as SpanImpl, type braintrust_StartSpanArgs as StartSpanArgs, braintrust_TestBackgroundLogger as TestBackgroundLogger, braintrust_ToolBuilder as ToolBuilder, braintrust_UUIDGenerator as UUIDGenerator, type braintrust_WithTransactionId as WithTransactionId, braintrust_X_CACHED_HEADER as X_CACHED_HEADER, braintrust__exportsForTestingOnly as _exportsForTestingOnly, braintrust__internalGetGlobalState as _internalGetGlobalState, braintrust__internalSetInitialState as _internalSetInitialState, braintrust_braintrustStreamChunkSchema as braintrustStreamChunkSchema, braintrust_buildLocalSummary as buildLocalSummary, braintrust_createFinalValuePassThroughStream as createFinalValuePassThroughStream, braintrust_currentExperiment as currentExperiment, braintrust_currentLogger as currentLogger, braintrust_currentSpan as currentSpan, braintrust_deepCopyEvent as deepCopyEvent, braintrust_defaultErrorScoreHandler as defaultErrorScoreHandler, braintrust_deserializePlainStringAsJSON as deserializePlainStringAsJSON, braintrust_devNullWritableStream as devNullWritableStream, braintrust_flush as flush, braintrust_getContextManager as getContextManager, braintrust_getIdGenerator as getIdGenerator, braintrust_getPromptVersions as getPromptVersions, braintrust_getSpanParentObject as getSpanParentObject, graphFramework as graph, braintrust_init as init, braintrust_initDataset as initDataset, braintrust_initExperiment as initExperiment, braintrust_initFunction as initFunction, braintrust_initLogger as initLogger, braintrust_invoke as invoke, braintrust_loadPrompt as loadPrompt, braintrust_log as log, braintrust_logError as logError, braintrust_login as login, braintrust_loginToState as loginToState, braintrust_newId as newId, braintrust_otel as otel, braintrust_parseCachedHeader as parseCachedHeader, braintrust_permalink as permalink, braintrust_projects as projects, braintrust_promptContentsSchema as promptContentsSchema, braintrust_promptDefinitionSchema as promptDefinitionSchema, braintrust_promptDefinitionToPromptData as promptDefinitionToPromptData, braintrust_promptDefinitionWithToolsSchema as promptDefinitionWithToolsSchema, braintrust_renderMessage as renderMessage, braintrust_renderPromptParams as renderPromptParams, braintrust_reportFailures as reportFailures, braintrust_runEvaluator as runEvaluator, braintrust_setFetch as setFetch, braintrust_setMaskingFunction as setMaskingFunction, braintrust_spanComponentsToObjectId as spanComponentsToObjectId, braintrust_startSpan as startSpan, braintrust_summarize as summarize, ToolFunctionDefinition as toolFunctionDefinitionSchema, braintrust_traceable as traceable, braintrust_traced as traced, braintrust_updateSpan as updateSpan, braintrust_withCurrent as withCurrent, braintrust_withDataset as withDataset, braintrust_withExperiment as withExperiment, braintrust_withLogger as withLogger, braintrust_withParent as withParent, braintrust_wrapAISDK as wrapAISDK, braintrust_wrapAISDKModel as wrapAISDKModel, braintrust_wrapAnthropic as wrapAnthropic, braintrust_wrapClaudeAgentSDK as wrapClaudeAgentSDK, braintrust_wrapGoogleGenAI as wrapGoogleGenAI, braintrust_wrapMastraAgent as wrapMastraAgent, braintrust_wrapOpenAI as wrapOpenAI, braintrust_wrapOpenAIv4 as wrapOpenAIv4, braintrust_wrapTraced as wrapTraced };
21956
22099
  }
21957
22100
 
21958
22101
  type EvaluatorManifest = Record<string, EvaluatorDef<unknown, unknown, unknown, BaseMetadata>>;
@@ -29009,4 +29152,4 @@ type EvaluatorDefinitions = z.infer<typeof evaluatorDefinitionsSchema>;
29009
29152
  * @module braintrust
29010
29153
  */
29011
29154
 
29012
- export { AISpanProcessor, type AnyDataset, Attachment, type AttachmentParams, AttachmentReference, type BackgroundLoggerOpts, BaseAttachment, BaseExperiment, type BaseMetadata, BraintrustExporter, BraintrustMiddleware, BraintrustSpanProcessor, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, CodeFunction, type CodeOpts, CodePrompt, type CommentEvent, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, ContextManager, type ContextParentSpanIds, type CreateProjectOpts, type DataSummary, Dataset, type DatasetRecord, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, ERR_PERMALINK, type EndSpanArgs, Eval, type EvalCase, type EvalHooks, type EvalParameterSerializedSchema, type EvalParameters, type EvalResult, EvalResultWithSummary, type EvalScorer, type EvalScorerArgs, type EvalTask, type Evaluator, type EvaluatorDef, type EvaluatorDefinition, type EvaluatorDefinitions, type EvaluatorFile, type EvaluatorManifest, Experiment, type ExperimentLogFullArgs, type ExperimentLogPartialArgs, type ExperimentSummary, type Exportable, ExternalAttachment, type ExternalAttachmentParams, FailedHTTPResponse, type FullInitOptions, type FullLoginOptions, type FunctionEvent, IDGenerator, INTERNAL_BTQL_LIMIT, type IdField, type InitOptions, type InputField, type InvokeFunctionArgs, type InvokeReturn, JSONAttachment, LEGACY_CACHED_HEADER, LazyValue, type LogCommentFullArgs, type LogFeedbackFullArgs, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NOOP_SPAN_PERMALINK, NoopSpan, OTELIDGenerator, type ObjectMetadata, type OtherExperimentLogFields, type ParentExperimentIds, type ParentProjectLogIds, Project, ProjectNameIdMap, type PromiseUnless, Prompt, PromptBuilder, type PromptContents, type PromptDefinition, type PromptDefinitionWithTools, type PromptOpts, type PromptRowWithId, ReadonlyAttachment, ReadonlyExperiment, Reporter, type ReporterBody, type ScoreSummary, ScorerBuilder, type ScorerOpts, type SerializedBraintrustState, type SetCurrentArg, type Span$1 as Span, type SpanContext, SpanImpl, type StartSpanArgs, TestBackgroundLogger, ToolBuilder, UUIDGenerator, type WithTransactionId, X_CACHED_HEADER, _exportsForTestingOnly, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, buildLocalSummary, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, deepCopyEvent, braintrust as default, defaultErrorScoreHandler, deserializePlainStringAsJSON, devNullWritableStream, evaluatorDefinitionSchema, evaluatorDefinitionsSchema, flush, getContextManager, getIdGenerator, getPromptVersions, getSpanParentObject, graphFramework as graph, init, initDataset, initExperiment, initFunction, initLogger, invoke, loadPrompt, log, logError, login, loginToState, newId, parseCachedHeader, permalink, projects, promptContentsSchema, promptDefinitionSchema, promptDefinitionToPromptData, promptDefinitionWithToolsSchema, renderMessage, renderPromptParams, reportFailures, runEvaluator, setFetch, setMaskingFunction, spanComponentsToObjectId, startSpan, summarize, ToolFunctionDefinition as toolFunctionDefinitionSchema, traceable, traced, updateSpan, withCurrent, withDataset, withExperiment, withLogger, withParent, wrapAISDK, wrapAISDKModel, wrapAnthropic, wrapClaudeAgentSDK, wrapGoogleGenAI, wrapMastraAgent, wrapOpenAI, wrapOpenAIv4, wrapTraced };
29155
+ export { AISpanProcessor, type AnyDataset, Attachment, type AttachmentParams, AttachmentReference, type BackgroundLoggerOpts, BaseAttachment, BaseExperiment, type BaseMetadata, BraintrustExporter, BraintrustMiddleware, BraintrustSpanProcessor, BraintrustState, BraintrustStream, type BraintrustStreamChunk, type ChatPrompt, CodeFunction, type CodeOpts, CodePrompt, type CommentEvent, type CompiledPrompt, type CompiledPromptParams, type CompletionPrompt, ContextManager, type ContextParentSpanIds, type CreateProjectOpts, type DataSummary, Dataset, type DatasetRecord, type DatasetSummary, type DefaultMetadataType, type DefaultPromptArgs, ERR_PERMALINK, type EndSpanArgs, Eval, type EvalCase, type EvalHooks, type EvalParameterSerializedSchema, type EvalParameters, type EvalResult, EvalResultWithSummary, type EvalScorer, type EvalScorerArgs, type EvalTask, type Evaluator, type EvaluatorDef, type EvaluatorDefinition, type EvaluatorDefinitions, type EvaluatorFile, type EvaluatorManifest, Experiment, type ExperimentLogFullArgs, type ExperimentLogPartialArgs, type ExperimentSummary, type Exportable, ExternalAttachment, type ExternalAttachmentParams, FailedHTTPResponse, type FullInitOptions, type FullLoginOptions, type FunctionEvent, IDGenerator, INTERNAL_BTQL_LIMIT, type IdField, type InitOptions, type InputField, type InvokeFunctionArgs, type InvokeReturn, JSONAttachment, LEGACY_CACHED_HEADER, LazyValue, type LogCommentFullArgs, type LogFeedbackFullArgs, type LogOptions, Logger, type LoginOptions, type MetricSummary, NOOP_SPAN, NOOP_SPAN_PERMALINK, NoopSpan, OTELIDGenerator, type ObjectMetadata, type OtherExperimentLogFields, type ParentExperimentIds, type ParentProjectLogIds, Project, ProjectNameIdMap, type PromiseUnless, Prompt, PromptBuilder, type PromptContents, type PromptDefinition, type PromptDefinitionWithTools, type PromptOpts, type PromptRowWithId, ReadonlyAttachment, ReadonlyExperiment, Reporter, type ReporterBody, type ScoreSummary, ScorerBuilder, type ScorerOpts, type SerializedBraintrustState, type SetCurrentArg, type Span$1 as Span, type SpanContext, SpanImpl, type StartSpanArgs, TestBackgroundLogger, ToolBuilder, UUIDGenerator, type WithTransactionId, X_CACHED_HEADER, _exportsForTestingOnly, _internalGetGlobalState, _internalSetInitialState, braintrustStreamChunkSchema, buildLocalSummary, createFinalValuePassThroughStream, currentExperiment, currentLogger, currentSpan, deepCopyEvent, braintrust as default, defaultErrorScoreHandler, deserializePlainStringAsJSON, devNullWritableStream, evaluatorDefinitionSchema, evaluatorDefinitionsSchema, flush, getContextManager, getIdGenerator, getPromptVersions, getSpanParentObject, graphFramework as graph, init, initDataset, initExperiment, initFunction, initLogger, invoke, loadPrompt, log, logError, login, loginToState, newId, otel, parseCachedHeader, permalink, projects, promptContentsSchema, promptDefinitionSchema, promptDefinitionToPromptData, promptDefinitionWithToolsSchema, renderMessage, renderPromptParams, reportFailures, runEvaluator, setFetch, setMaskingFunction, spanComponentsToObjectId, startSpan, summarize, ToolFunctionDefinition as toolFunctionDefinitionSchema, traceable, traced, updateSpan, withCurrent, withDataset, withExperiment, withLogger, withParent, wrapAISDK, wrapAISDKModel, wrapAnthropic, wrapClaudeAgentSDK, wrapGoogleGenAI, wrapMastraAgent, wrapOpenAI, wrapOpenAIv4, wrapTraced };
package/dist/index.js CHANGED
@@ -10026,6 +10026,7 @@ __export(exports_node_exports, {
10026
10026
  login: () => login,
10027
10027
  loginToState: () => loginToState,
10028
10028
  newId: () => newId,
10029
+ otel: () => otel,
10029
10030
  parseCachedHeader: () => parseCachedHeader,
10030
10031
  permalink: () => permalink,
10031
10032
  projects: () => projects,
@@ -15523,6 +15524,8 @@ function tryToDict(obj) {
15523
15524
  }
15524
15525
 
15525
15526
  // src/otel.ts
15527
+ init_span_identifier_v4();
15528
+ init_span_identifier_v3();
15526
15529
  var otelApi = null;
15527
15530
  var otelSdk = null;
15528
15531
  var OTEL_AVAILABLE2 = false;
@@ -15776,6 +15779,80 @@ var BraintrustSpanProcessor = class _BraintrustSpanProcessor {
15776
15779
  return this.aiSpanProcessor.forceFlush();
15777
15780
  }
15778
15781
  };
15782
+ function otelContextFromSpanExport(exportStr) {
15783
+ if (!OTEL_AVAILABLE2 || !otelApi) {
15784
+ return void 0;
15785
+ }
15786
+ const components = SpanComponentsV4.fromStr(exportStr);
15787
+ const traceIdHex = components.data.root_span_id;
15788
+ const spanIdHex = components.data.span_id;
15789
+ if (!traceIdHex || !spanIdHex) {
15790
+ throw new Error(
15791
+ "Export string must contain root_span_id and span_id for distributed tracing"
15792
+ );
15793
+ }
15794
+ const otelTrace2 = otelApi.trace;
15795
+ const spanContext = {
15796
+ traceId: traceIdHex,
15797
+ spanId: spanIdHex,
15798
+ isRemote: true,
15799
+ traceFlags: _nullishCoalesce(_optionalChain([otelApi, 'access', _269 => _269.TraceFlags, 'optionalAccess', _270 => _270.SAMPLED]), () => ( 1))
15800
+ // SAMPLED flag
15801
+ };
15802
+ const nonRecordingSpan = otelTrace2.wrapSpanContext(spanContext);
15803
+ let ctx = otelTrace2.setSpan(otelApi.context.active(), nonRecordingSpan);
15804
+ const braintrustParent = getBraintrustParent(
15805
+ components.data.object_type,
15806
+ components.data.object_id,
15807
+ components.data.compute_object_metadata_args
15808
+ );
15809
+ if (braintrustParent) {
15810
+ try {
15811
+ const propagation2 = otelApi.propagation;
15812
+ if (propagation2) {
15813
+ const baggage = propagation2.getBaggage(ctx) || propagation2.createBaggage();
15814
+ ctx = propagation2.setBaggage(
15815
+ ctx,
15816
+ baggage.setEntry("braintrust.parent", { value: braintrustParent })
15817
+ );
15818
+ }
15819
+ } catch (error2) {
15820
+ console.error(
15821
+ "Failed to set braintrust.parent in baggage during context import:",
15822
+ error2
15823
+ );
15824
+ }
15825
+ }
15826
+ return ctx;
15827
+ }
15828
+ function getBraintrustParent(objectType, objectId, computeArgs) {
15829
+ if (!objectType) {
15830
+ return void 0;
15831
+ }
15832
+ if (objectType === 2 /* PROJECT_LOGS */) {
15833
+ if (objectId) {
15834
+ return `project_id:${objectId}`;
15835
+ } else if (computeArgs) {
15836
+ const projectId = computeArgs["project_id"];
15837
+ const projectName = computeArgs["project_name"];
15838
+ if (typeof projectId === "string") {
15839
+ return `project_id:${projectId}`;
15840
+ } else if (typeof projectName === "string") {
15841
+ return `project_name:${projectName}`;
15842
+ }
15843
+ }
15844
+ } else if (objectType === 1 /* EXPERIMENT */) {
15845
+ if (objectId) {
15846
+ return `experiment_id:${objectId}`;
15847
+ } else if (computeArgs) {
15848
+ const experimentId = computeArgs["experiment_id"];
15849
+ if (typeof experimentId === "string") {
15850
+ return `experiment_id:${experimentId}`;
15851
+ }
15852
+ }
15853
+ }
15854
+ return void 0;
15855
+ }
15779
15856
  var BraintrustExporter = (_class21 = class _BraintrustExporter {
15780
15857
  static checkOtelAvailable() {
15781
15858
  if (!OTEL_AVAILABLE2) {
@@ -15821,6 +15898,140 @@ var BraintrustExporter = (_class21 = class _BraintrustExporter {
15821
15898
  return this.processor.forceFlush();
15822
15899
  }
15823
15900
  }, _class21);
15901
+ function addParentToBaggage(parent, ctx) {
15902
+ if (!OTEL_AVAILABLE2 || !otelApi) {
15903
+ console.error("OpenTelemetry not available");
15904
+ return ctx || _optionalChain([otelApi, 'optionalAccess', _271 => _271.context, 'access', _272 => _272.active, 'call', _273 => _273()]);
15905
+ }
15906
+ try {
15907
+ const propagation2 = otelApi.propagation;
15908
+ if (!propagation2) {
15909
+ console.error("OTEL propagation API not available");
15910
+ return ctx || otelApi.context.active();
15911
+ }
15912
+ const currentCtx = ctx || otelApi.context.active();
15913
+ const baggage = propagation2.getBaggage(currentCtx) || propagation2.createBaggage();
15914
+ return propagation2.setBaggage(
15915
+ currentCtx,
15916
+ baggage.setEntry("braintrust.parent", { value: parent })
15917
+ );
15918
+ } catch (error2) {
15919
+ console.error("Failed to add braintrust.parent to baggage:", error2);
15920
+ return ctx || otelApi.context.active();
15921
+ }
15922
+ }
15923
+ function addSpanParentToBaggage(span, ctx) {
15924
+ if (!span || !span.attributes) {
15925
+ console.warn("addSpanParentToBaggage: span has no attributes");
15926
+ return void 0;
15927
+ }
15928
+ const parentValue = span.attributes["braintrust.parent"];
15929
+ if (!parentValue || typeof parentValue !== "string") {
15930
+ console.warn(
15931
+ "addSpanParentToBaggage: braintrust.parent attribute not found. Ensure BraintrustSpanProcessor is configured or span is created within Braintrust context."
15932
+ );
15933
+ return void 0;
15934
+ }
15935
+ return addParentToBaggage(parentValue, ctx);
15936
+ }
15937
+ function parentFromHeaders(headers) {
15938
+ if (!OTEL_AVAILABLE2 || !otelApi) {
15939
+ console.error("OpenTelemetry not available");
15940
+ return void 0;
15941
+ }
15942
+ try {
15943
+ const propagation2 = otelApi.propagation;
15944
+ if (!propagation2) {
15945
+ console.error("OTEL propagation API not available");
15946
+ return void 0;
15947
+ }
15948
+ const ctx = propagation2.extract(otelApi.context.active(), headers);
15949
+ const spanContext = otelApi.trace.getSpanContext(ctx);
15950
+ if (!spanContext) {
15951
+ console.error("parentFromHeaders: No valid span context in headers");
15952
+ return void 0;
15953
+ }
15954
+ const traceIdHex = spanContext.traceId;
15955
+ const spanIdHex = spanContext.spanId;
15956
+ if (!traceIdHex || typeof traceIdHex !== "string" || traceIdHex === "00000000000000000000000000000000") {
15957
+ console.error("parentFromHeaders: Invalid trace_id (all zeros)");
15958
+ return void 0;
15959
+ }
15960
+ if (!spanIdHex || typeof spanIdHex !== "string" || spanIdHex === "0000000000000000") {
15961
+ console.error("parentFromHeaders: Invalid span_id (all zeros)");
15962
+ return void 0;
15963
+ }
15964
+ const baggage = propagation2.getBaggage(ctx);
15965
+ const braintrustParent = _optionalChain([baggage, 'optionalAccess', _274 => _274.getEntry, 'call', _275 => _275("braintrust.parent"), 'optionalAccess', _276 => _276.value]);
15966
+ if (!braintrustParent) {
15967
+ console.warn(
15968
+ "parentFromHeaders: braintrust.parent not found in OTEL baggage. Cannot create Braintrust parent without project information. Ensure the OTEL span sets braintrust.parent in baggage before exporting headers."
15969
+ );
15970
+ return void 0;
15971
+ }
15972
+ let objectType;
15973
+ let objectId;
15974
+ let computeArgs;
15975
+ if (braintrustParent.startsWith("project_id:")) {
15976
+ objectType = 2 /* PROJECT_LOGS */;
15977
+ objectId = braintrustParent.substring("project_id:".length);
15978
+ if (!objectId) {
15979
+ console.error(
15980
+ `parentFromHeaders: Invalid braintrust.parent format (empty project_id): ${braintrustParent}`
15981
+ );
15982
+ return void 0;
15983
+ }
15984
+ } else if (braintrustParent.startsWith("project_name:")) {
15985
+ objectType = 2 /* PROJECT_LOGS */;
15986
+ const projectName = braintrustParent.substring("project_name:".length);
15987
+ if (!projectName) {
15988
+ console.error(
15989
+ `parentFromHeaders: Invalid braintrust.parent format (empty project_name): ${braintrustParent}`
15990
+ );
15991
+ return void 0;
15992
+ }
15993
+ computeArgs = { project_name: projectName };
15994
+ } else if (braintrustParent.startsWith("experiment_id:")) {
15995
+ objectType = 1 /* EXPERIMENT */;
15996
+ objectId = braintrustParent.substring("experiment_id:".length);
15997
+ if (!objectId) {
15998
+ console.error(
15999
+ `parentFromHeaders: Invalid braintrust.parent format (empty experiment_id): ${braintrustParent}`
16000
+ );
16001
+ return void 0;
16002
+ }
16003
+ } else {
16004
+ console.error(
16005
+ `parentFromHeaders: Invalid braintrust.parent format: ${braintrustParent}. Expected format: 'project_id:ID', 'project_name:NAME', or 'experiment_id:ID'`
16006
+ );
16007
+ return void 0;
16008
+ }
16009
+ const componentsData = {
16010
+ object_type: objectType,
16011
+ row_id: "otel",
16012
+ // Dummy row_id to enable span_id/root_span_id fields
16013
+ span_id: spanIdHex,
16014
+ root_span_id: traceIdHex
16015
+ };
16016
+ if (computeArgs) {
16017
+ componentsData.compute_object_metadata_args = computeArgs;
16018
+ } else {
16019
+ componentsData.object_id = objectId;
16020
+ }
16021
+ const components = new SpanComponentsV4(componentsData);
16022
+ return components.toStr();
16023
+ } catch (error2) {
16024
+ console.error("parentFromHeaders: Error parsing headers:", error2);
16025
+ return void 0;
16026
+ }
16027
+ }
16028
+ var otel = {
16029
+ contextFromSpanExport: otelContextFromSpanExport,
16030
+ getBraintrustParent,
16031
+ addParentToBaggage,
16032
+ addSpanParentToBaggage,
16033
+ parentFromHeaders
16034
+ };
15824
16035
 
15825
16036
  // dev/types.ts
15826
16037
  init_generated_types();
@@ -15979,4 +16190,5 @@ var index_default = exports_node_exports;
15979
16190
 
15980
16191
 
15981
16192
 
15982
- exports.AISpanProcessor = AISpanProcessor; exports.Attachment = Attachment; exports.BaseAttachment = BaseAttachment; exports.BaseExperiment = BaseExperiment; exports.BraintrustExporter = BraintrustExporter; exports.BraintrustMiddleware = BraintrustMiddleware; exports.BraintrustSpanProcessor = BraintrustSpanProcessor; exports.BraintrustState = BraintrustState; exports.BraintrustStream = BraintrustStream; exports.CodeFunction = CodeFunction; exports.CodePrompt = CodePrompt; exports.ContextManager = ContextManager; exports.Dataset = Dataset2; exports.ERR_PERMALINK = ERR_PERMALINK; exports.Eval = Eval; exports.EvalResultWithSummary = EvalResultWithSummary; exports.Experiment = Experiment2; exports.ExternalAttachment = ExternalAttachment; exports.FailedHTTPResponse = FailedHTTPResponse; exports.IDGenerator = IDGenerator; exports.INTERNAL_BTQL_LIMIT = INTERNAL_BTQL_LIMIT; exports.JSONAttachment = JSONAttachment; exports.LEGACY_CACHED_HEADER = LEGACY_CACHED_HEADER; exports.LazyValue = LazyValue; exports.Logger = Logger; exports.NOOP_SPAN = NOOP_SPAN; exports.NOOP_SPAN_PERMALINK = NOOP_SPAN_PERMALINK; exports.NoopSpan = NoopSpan; exports.OTELIDGenerator = OTELIDGenerator; exports.Project = Project2; exports.ProjectNameIdMap = ProjectNameIdMap; exports.Prompt = Prompt2; exports.PromptBuilder = PromptBuilder; exports.ReadonlyAttachment = ReadonlyAttachment; exports.ReadonlyExperiment = ReadonlyExperiment; exports.Reporter = Reporter; exports.ScorerBuilder = ScorerBuilder; exports.SpanImpl = SpanImpl; exports.TestBackgroundLogger = TestBackgroundLogger; exports.ToolBuilder = ToolBuilder; exports.UUIDGenerator = UUIDGenerator; exports.X_CACHED_HEADER = X_CACHED_HEADER; exports._exportsForTestingOnly = _exportsForTestingOnly; exports._internalGetGlobalState = _internalGetGlobalState; exports._internalSetInitialState = _internalSetInitialState; exports.braintrustStreamChunkSchema = braintrustStreamChunkSchema; exports.buildLocalSummary = buildLocalSummary; exports.createFinalValuePassThroughStream = createFinalValuePassThroughStream; exports.currentExperiment = currentExperiment; exports.currentLogger = currentLogger; exports.currentSpan = currentSpan; exports.deepCopyEvent = deepCopyEvent; exports.default = index_default; exports.defaultErrorScoreHandler = defaultErrorScoreHandler; exports.deserializePlainStringAsJSON = deserializePlainStringAsJSON; exports.devNullWritableStream = devNullWritableStream; exports.evaluatorDefinitionSchema = evaluatorDefinitionSchema; exports.evaluatorDefinitionsSchema = evaluatorDefinitionsSchema; exports.flush = flush; exports.getContextManager = getContextManager; exports.getIdGenerator = getIdGenerator; exports.getPromptVersions = getPromptVersions; exports.getSpanParentObject = getSpanParentObject; exports.graph = graph_framework_exports; exports.init = init; exports.initDataset = initDataset; exports.initExperiment = initExperiment; exports.initFunction = initFunction; exports.initLogger = initLogger; exports.invoke = invoke; exports.loadPrompt = loadPrompt; exports.log = log; exports.logError = logError; exports.login = login; exports.loginToState = loginToState; exports.newId = newId; exports.parseCachedHeader = parseCachedHeader; exports.permalink = permalink; exports.projects = projects; exports.promptContentsSchema = promptContentsSchema; exports.promptDefinitionSchema = promptDefinitionSchema; exports.promptDefinitionToPromptData = promptDefinitionToPromptData; exports.promptDefinitionWithToolsSchema = promptDefinitionWithToolsSchema; exports.renderMessage = renderMessage; exports.renderPromptParams = renderPromptParams; exports.reportFailures = reportFailures; exports.runEvaluator = runEvaluator; exports.setFetch = setFetch; exports.setMaskingFunction = setMaskingFunction; exports.spanComponentsToObjectId = spanComponentsToObjectId; exports.startSpan = startSpan; exports.summarize = summarize; exports.toolFunctionDefinitionSchema = ToolFunctionDefinition; exports.traceable = traceable; exports.traced = traced; exports.updateSpan = updateSpan; exports.withCurrent = withCurrent; exports.withDataset = withDataset; exports.withExperiment = withExperiment; exports.withLogger = withLogger; exports.withParent = withParent; exports.wrapAISDK = wrapAISDK; exports.wrapAISDKModel = wrapAISDKModel; exports.wrapAnthropic = wrapAnthropic; exports.wrapClaudeAgentSDK = wrapClaudeAgentSDK; exports.wrapGoogleGenAI = wrapGoogleGenAI; exports.wrapMastraAgent = wrapMastraAgent; exports.wrapOpenAI = wrapOpenAI; exports.wrapOpenAIv4 = wrapOpenAIv4; exports.wrapTraced = wrapTraced;
16193
+
16194
+ exports.AISpanProcessor = AISpanProcessor; exports.Attachment = Attachment; exports.BaseAttachment = BaseAttachment; exports.BaseExperiment = BaseExperiment; exports.BraintrustExporter = BraintrustExporter; exports.BraintrustMiddleware = BraintrustMiddleware; exports.BraintrustSpanProcessor = BraintrustSpanProcessor; exports.BraintrustState = BraintrustState; exports.BraintrustStream = BraintrustStream; exports.CodeFunction = CodeFunction; exports.CodePrompt = CodePrompt; exports.ContextManager = ContextManager; exports.Dataset = Dataset2; exports.ERR_PERMALINK = ERR_PERMALINK; exports.Eval = Eval; exports.EvalResultWithSummary = EvalResultWithSummary; exports.Experiment = Experiment2; exports.ExternalAttachment = ExternalAttachment; exports.FailedHTTPResponse = FailedHTTPResponse; exports.IDGenerator = IDGenerator; exports.INTERNAL_BTQL_LIMIT = INTERNAL_BTQL_LIMIT; exports.JSONAttachment = JSONAttachment; exports.LEGACY_CACHED_HEADER = LEGACY_CACHED_HEADER; exports.LazyValue = LazyValue; exports.Logger = Logger; exports.NOOP_SPAN = NOOP_SPAN; exports.NOOP_SPAN_PERMALINK = NOOP_SPAN_PERMALINK; exports.NoopSpan = NoopSpan; exports.OTELIDGenerator = OTELIDGenerator; exports.Project = Project2; exports.ProjectNameIdMap = ProjectNameIdMap; exports.Prompt = Prompt2; exports.PromptBuilder = PromptBuilder; exports.ReadonlyAttachment = ReadonlyAttachment; exports.ReadonlyExperiment = ReadonlyExperiment; exports.Reporter = Reporter; exports.ScorerBuilder = ScorerBuilder; exports.SpanImpl = SpanImpl; exports.TestBackgroundLogger = TestBackgroundLogger; exports.ToolBuilder = ToolBuilder; exports.UUIDGenerator = UUIDGenerator; exports.X_CACHED_HEADER = X_CACHED_HEADER; exports._exportsForTestingOnly = _exportsForTestingOnly; exports._internalGetGlobalState = _internalGetGlobalState; exports._internalSetInitialState = _internalSetInitialState; exports.braintrustStreamChunkSchema = braintrustStreamChunkSchema; exports.buildLocalSummary = buildLocalSummary; exports.createFinalValuePassThroughStream = createFinalValuePassThroughStream; exports.currentExperiment = currentExperiment; exports.currentLogger = currentLogger; exports.currentSpan = currentSpan; exports.deepCopyEvent = deepCopyEvent; exports.default = index_default; exports.defaultErrorScoreHandler = defaultErrorScoreHandler; exports.deserializePlainStringAsJSON = deserializePlainStringAsJSON; exports.devNullWritableStream = devNullWritableStream; exports.evaluatorDefinitionSchema = evaluatorDefinitionSchema; exports.evaluatorDefinitionsSchema = evaluatorDefinitionsSchema; exports.flush = flush; exports.getContextManager = getContextManager; exports.getIdGenerator = getIdGenerator; exports.getPromptVersions = getPromptVersions; exports.getSpanParentObject = getSpanParentObject; exports.graph = graph_framework_exports; exports.init = init; exports.initDataset = initDataset; exports.initExperiment = initExperiment; exports.initFunction = initFunction; exports.initLogger = initLogger; exports.invoke = invoke; exports.loadPrompt = loadPrompt; exports.log = log; exports.logError = logError; exports.login = login; exports.loginToState = loginToState; exports.newId = newId; exports.otel = otel; exports.parseCachedHeader = parseCachedHeader; exports.permalink = permalink; exports.projects = projects; exports.promptContentsSchema = promptContentsSchema; exports.promptDefinitionSchema = promptDefinitionSchema; exports.promptDefinitionToPromptData = promptDefinitionToPromptData; exports.promptDefinitionWithToolsSchema = promptDefinitionWithToolsSchema; exports.renderMessage = renderMessage; exports.renderPromptParams = renderPromptParams; exports.reportFailures = reportFailures; exports.runEvaluator = runEvaluator; exports.setFetch = setFetch; exports.setMaskingFunction = setMaskingFunction; exports.spanComponentsToObjectId = spanComponentsToObjectId; exports.startSpan = startSpan; exports.summarize = summarize; exports.toolFunctionDefinitionSchema = ToolFunctionDefinition; exports.traceable = traceable; exports.traced = traced; exports.updateSpan = updateSpan; exports.withCurrent = withCurrent; exports.withDataset = withDataset; exports.withExperiment = withExperiment; exports.withLogger = withLogger; exports.withParent = withParent; exports.wrapAISDK = wrapAISDK; exports.wrapAISDKModel = wrapAISDKModel; exports.wrapAnthropic = wrapAnthropic; exports.wrapClaudeAgentSDK = wrapClaudeAgentSDK; exports.wrapGoogleGenAI = wrapGoogleGenAI; exports.wrapMastraAgent = wrapMastraAgent; exports.wrapOpenAI = wrapOpenAI; exports.wrapOpenAIv4 = wrapOpenAIv4; exports.wrapTraced = wrapTraced;
package/dist/index.mjs CHANGED
@@ -10026,6 +10026,7 @@ __export(exports_node_exports, {
10026
10026
  login: () => login,
10027
10027
  loginToState: () => loginToState,
10028
10028
  newId: () => newId,
10029
+ otel: () => otel,
10029
10030
  parseCachedHeader: () => parseCachedHeader,
10030
10031
  permalink: () => permalink,
10031
10032
  projects: () => projects,
@@ -15523,6 +15524,8 @@ function tryToDict(obj) {
15523
15524
  }
15524
15525
 
15525
15526
  // src/otel.ts
15527
+ init_span_identifier_v4();
15528
+ init_span_identifier_v3();
15526
15529
  var otelApi = null;
15527
15530
  var otelSdk = null;
15528
15531
  var OTEL_AVAILABLE2 = false;
@@ -15776,6 +15779,80 @@ var BraintrustSpanProcessor = class _BraintrustSpanProcessor {
15776
15779
  return this.aiSpanProcessor.forceFlush();
15777
15780
  }
15778
15781
  };
15782
+ function otelContextFromSpanExport(exportStr) {
15783
+ if (!OTEL_AVAILABLE2 || !otelApi) {
15784
+ return void 0;
15785
+ }
15786
+ const components = SpanComponentsV4.fromStr(exportStr);
15787
+ const traceIdHex = components.data.root_span_id;
15788
+ const spanIdHex = components.data.span_id;
15789
+ if (!traceIdHex || !spanIdHex) {
15790
+ throw new Error(
15791
+ "Export string must contain root_span_id and span_id for distributed tracing"
15792
+ );
15793
+ }
15794
+ const otelTrace2 = otelApi.trace;
15795
+ const spanContext = {
15796
+ traceId: traceIdHex,
15797
+ spanId: spanIdHex,
15798
+ isRemote: true,
15799
+ traceFlags: otelApi.TraceFlags?.SAMPLED ?? 1
15800
+ // SAMPLED flag
15801
+ };
15802
+ const nonRecordingSpan = otelTrace2.wrapSpanContext(spanContext);
15803
+ let ctx = otelTrace2.setSpan(otelApi.context.active(), nonRecordingSpan);
15804
+ const braintrustParent = getBraintrustParent(
15805
+ components.data.object_type,
15806
+ components.data.object_id,
15807
+ components.data.compute_object_metadata_args
15808
+ );
15809
+ if (braintrustParent) {
15810
+ try {
15811
+ const propagation2 = otelApi.propagation;
15812
+ if (propagation2) {
15813
+ const baggage = propagation2.getBaggage(ctx) || propagation2.createBaggage();
15814
+ ctx = propagation2.setBaggage(
15815
+ ctx,
15816
+ baggage.setEntry("braintrust.parent", { value: braintrustParent })
15817
+ );
15818
+ }
15819
+ } catch (error2) {
15820
+ console.error(
15821
+ "Failed to set braintrust.parent in baggage during context import:",
15822
+ error2
15823
+ );
15824
+ }
15825
+ }
15826
+ return ctx;
15827
+ }
15828
+ function getBraintrustParent(objectType, objectId, computeArgs) {
15829
+ if (!objectType) {
15830
+ return void 0;
15831
+ }
15832
+ if (objectType === 2 /* PROJECT_LOGS */) {
15833
+ if (objectId) {
15834
+ return `project_id:${objectId}`;
15835
+ } else if (computeArgs) {
15836
+ const projectId = computeArgs["project_id"];
15837
+ const projectName = computeArgs["project_name"];
15838
+ if (typeof projectId === "string") {
15839
+ return `project_id:${projectId}`;
15840
+ } else if (typeof projectName === "string") {
15841
+ return `project_name:${projectName}`;
15842
+ }
15843
+ }
15844
+ } else if (objectType === 1 /* EXPERIMENT */) {
15845
+ if (objectId) {
15846
+ return `experiment_id:${objectId}`;
15847
+ } else if (computeArgs) {
15848
+ const experimentId = computeArgs["experiment_id"];
15849
+ if (typeof experimentId === "string") {
15850
+ return `experiment_id:${experimentId}`;
15851
+ }
15852
+ }
15853
+ }
15854
+ return void 0;
15855
+ }
15779
15856
  var BraintrustExporter = class _BraintrustExporter {
15780
15857
  static checkOtelAvailable() {
15781
15858
  if (!OTEL_AVAILABLE2) {
@@ -15821,6 +15898,140 @@ var BraintrustExporter = class _BraintrustExporter {
15821
15898
  return this.processor.forceFlush();
15822
15899
  }
15823
15900
  };
15901
+ function addParentToBaggage(parent, ctx) {
15902
+ if (!OTEL_AVAILABLE2 || !otelApi) {
15903
+ console.error("OpenTelemetry not available");
15904
+ return ctx || otelApi?.context.active();
15905
+ }
15906
+ try {
15907
+ const propagation2 = otelApi.propagation;
15908
+ if (!propagation2) {
15909
+ console.error("OTEL propagation API not available");
15910
+ return ctx || otelApi.context.active();
15911
+ }
15912
+ const currentCtx = ctx || otelApi.context.active();
15913
+ const baggage = propagation2.getBaggage(currentCtx) || propagation2.createBaggage();
15914
+ return propagation2.setBaggage(
15915
+ currentCtx,
15916
+ baggage.setEntry("braintrust.parent", { value: parent })
15917
+ );
15918
+ } catch (error2) {
15919
+ console.error("Failed to add braintrust.parent to baggage:", error2);
15920
+ return ctx || otelApi.context.active();
15921
+ }
15922
+ }
15923
+ function addSpanParentToBaggage(span, ctx) {
15924
+ if (!span || !span.attributes) {
15925
+ console.warn("addSpanParentToBaggage: span has no attributes");
15926
+ return void 0;
15927
+ }
15928
+ const parentValue = span.attributes["braintrust.parent"];
15929
+ if (!parentValue || typeof parentValue !== "string") {
15930
+ console.warn(
15931
+ "addSpanParentToBaggage: braintrust.parent attribute not found. Ensure BraintrustSpanProcessor is configured or span is created within Braintrust context."
15932
+ );
15933
+ return void 0;
15934
+ }
15935
+ return addParentToBaggage(parentValue, ctx);
15936
+ }
15937
+ function parentFromHeaders(headers) {
15938
+ if (!OTEL_AVAILABLE2 || !otelApi) {
15939
+ console.error("OpenTelemetry not available");
15940
+ return void 0;
15941
+ }
15942
+ try {
15943
+ const propagation2 = otelApi.propagation;
15944
+ if (!propagation2) {
15945
+ console.error("OTEL propagation API not available");
15946
+ return void 0;
15947
+ }
15948
+ const ctx = propagation2.extract(otelApi.context.active(), headers);
15949
+ const spanContext = otelApi.trace.getSpanContext(ctx);
15950
+ if (!spanContext) {
15951
+ console.error("parentFromHeaders: No valid span context in headers");
15952
+ return void 0;
15953
+ }
15954
+ const traceIdHex = spanContext.traceId;
15955
+ const spanIdHex = spanContext.spanId;
15956
+ if (!traceIdHex || typeof traceIdHex !== "string" || traceIdHex === "00000000000000000000000000000000") {
15957
+ console.error("parentFromHeaders: Invalid trace_id (all zeros)");
15958
+ return void 0;
15959
+ }
15960
+ if (!spanIdHex || typeof spanIdHex !== "string" || spanIdHex === "0000000000000000") {
15961
+ console.error("parentFromHeaders: Invalid span_id (all zeros)");
15962
+ return void 0;
15963
+ }
15964
+ const baggage = propagation2.getBaggage(ctx);
15965
+ const braintrustParent = baggage?.getEntry("braintrust.parent")?.value;
15966
+ if (!braintrustParent) {
15967
+ console.warn(
15968
+ "parentFromHeaders: braintrust.parent not found in OTEL baggage. Cannot create Braintrust parent without project information. Ensure the OTEL span sets braintrust.parent in baggage before exporting headers."
15969
+ );
15970
+ return void 0;
15971
+ }
15972
+ let objectType;
15973
+ let objectId;
15974
+ let computeArgs;
15975
+ if (braintrustParent.startsWith("project_id:")) {
15976
+ objectType = 2 /* PROJECT_LOGS */;
15977
+ objectId = braintrustParent.substring("project_id:".length);
15978
+ if (!objectId) {
15979
+ console.error(
15980
+ `parentFromHeaders: Invalid braintrust.parent format (empty project_id): ${braintrustParent}`
15981
+ );
15982
+ return void 0;
15983
+ }
15984
+ } else if (braintrustParent.startsWith("project_name:")) {
15985
+ objectType = 2 /* PROJECT_LOGS */;
15986
+ const projectName = braintrustParent.substring("project_name:".length);
15987
+ if (!projectName) {
15988
+ console.error(
15989
+ `parentFromHeaders: Invalid braintrust.parent format (empty project_name): ${braintrustParent}`
15990
+ );
15991
+ return void 0;
15992
+ }
15993
+ computeArgs = { project_name: projectName };
15994
+ } else if (braintrustParent.startsWith("experiment_id:")) {
15995
+ objectType = 1 /* EXPERIMENT */;
15996
+ objectId = braintrustParent.substring("experiment_id:".length);
15997
+ if (!objectId) {
15998
+ console.error(
15999
+ `parentFromHeaders: Invalid braintrust.parent format (empty experiment_id): ${braintrustParent}`
16000
+ );
16001
+ return void 0;
16002
+ }
16003
+ } else {
16004
+ console.error(
16005
+ `parentFromHeaders: Invalid braintrust.parent format: ${braintrustParent}. Expected format: 'project_id:ID', 'project_name:NAME', or 'experiment_id:ID'`
16006
+ );
16007
+ return void 0;
16008
+ }
16009
+ const componentsData = {
16010
+ object_type: objectType,
16011
+ row_id: "otel",
16012
+ // Dummy row_id to enable span_id/root_span_id fields
16013
+ span_id: spanIdHex,
16014
+ root_span_id: traceIdHex
16015
+ };
16016
+ if (computeArgs) {
16017
+ componentsData.compute_object_metadata_args = computeArgs;
16018
+ } else {
16019
+ componentsData.object_id = objectId;
16020
+ }
16021
+ const components = new SpanComponentsV4(componentsData);
16022
+ return components.toStr();
16023
+ } catch (error2) {
16024
+ console.error("parentFromHeaders: Error parsing headers:", error2);
16025
+ return void 0;
16026
+ }
16027
+ }
16028
+ var otel = {
16029
+ contextFromSpanExport: otelContextFromSpanExport,
16030
+ getBraintrustParent,
16031
+ addParentToBaggage,
16032
+ addSpanParentToBaggage,
16033
+ parentFromHeaders
16034
+ };
15824
16035
 
15825
16036
  // dev/types.ts
15826
16037
  init_generated_types();
@@ -15945,6 +16156,7 @@ export {
15945
16156
  login,
15946
16157
  loginToState,
15947
16158
  newId,
16159
+ otel,
15948
16160
  parseCachedHeader,
15949
16161
  permalink,
15950
16162
  projects,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "braintrust",
3
- "version": "0.4.7",
3
+ "version": "0.4.8",
4
4
  "description": "SDK for integrating Braintrust",
5
5
  "repository": {
6
6
  "type": "git",
@@ -56,12 +56,17 @@
56
56
  "watch": "tsup --watch",
57
57
  "clean": "rm -r dist/* && rm -r dev/dist/*",
58
58
  "docs": "npx typedoc --options typedoc.json src/index.ts",
59
- "test": "vitest run --exclude src/wrappers/anthropic.test.ts --exclude src/wrappers/oai.test.ts --exclude src/otel.test.ts --exclude src/otel-no-deps.test.ts --exclude src/wrappers/google-genai.test.ts",
59
+ "test": "vitest run --exclude \"src/wrappers/**/*.test.ts\" --exclude \"src/otel/**/*.test.ts\"",
60
60
  "test:anthropic": "vitest run src/wrappers/anthropic.test.ts",
61
61
  "test:openai": "vitest run src/wrappers/oai.test.ts",
62
- "test:otel": "vitest run src/otel.test.ts",
62
+ "test:otel": "vitest run --dir src/otel",
63
+ "test:otel-no-deps": "vitest run src/otel-no-deps.test.ts --reporter=verbose",
63
64
  "test:google-genai": "vitest run src/wrappers/google-genai.test.ts",
64
- "test:otel-no-deps": "vitest run src/otel-no-deps.test.ts --reporter=verbose"
65
+ "test:ai-sdk-v1": "vitest run src/wrappers/ai-sdk-v1.test.ts",
66
+ "test:ai-sdk-v2": "vitest run src/wrappers/ai-sdk-v2.test.ts src/wrappers/ai-sdk-v1.test.ts",
67
+ "test:ai-sdk-v3": "vitest run src/wrappers/ai-sdk-v3.test.ts",
68
+ "test:mastra": "vitest run src/wrappers/mastra.test.ts",
69
+ "test:claude-agent-sdk": "vitest run src/wrappers/claude-agent-sdk.test.ts"
65
70
  },
66
71
  "author": "",
67
72
  "license": "MIT",