braintrust 0.4.9 → 0.4.10

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/index.js CHANGED
@@ -1504,7 +1504,7 @@ var init_util = __esm({
1504
1504
 
1505
1505
  // src/generated_types.ts
1506
1506
 
1507
- var AclObjectType, Permission, Acl, AISecret, ResponseFormatJsonSchema, ResponseFormatNullish, AnyModelParams, ApiKey, AsyncScoringState, AsyncScoringControl, BraintrustAttachmentReference, ExternalAttachmentReference, AttachmentReference, UploadStatus, AttachmentStatus, BraintrustModelParams, CallEvent, ChatCompletionContentPartTextWithTitle, ChatCompletionContentPartImageWithTitle, ChatCompletionContentPart, ChatCompletionContentPartText, ChatCompletionMessageToolCall, ChatCompletionMessageReasoning, ChatCompletionMessageParam, ChatCompletionOpenAIMessageParam, ChatCompletionTool, CodeBundle, Dataset, ObjectReferenceNullish, DatasetEvent, EnvVar, RepoInfo, Experiment, SpanType, SpanAttributes, ExperimentEvent, ExtendedSavedFunctionId, PromptBlockDataNullish, ModelParams, PromptOptionsNullish, PromptParserNullish, SavedFunctionId, PromptDataNullish, FunctionTypeEnumNullish, FunctionIdRef, PromptBlockData, GraphNode, GraphEdge, GraphData, FunctionData, Function, FunctionFormat, PromptData, FunctionTypeEnum, FunctionId, FunctionObjectType, FunctionOutputType, GitMetadataSettings, Group, IfExists, InvokeParent, StreamingMode, InvokeFunction, MessageRole, ObjectReference, OnlineScoreConfig, Organization, ProjectSettings, Project, RetentionObjectType, ProjectAutomation, ProjectLogsEvent, ProjectScoreType, ProjectScoreCategory, ProjectScoreCategories, ProjectScoreConfig, ProjectScore, ProjectTag, Prompt, PromptOptions, PromptSessionEvent, ResponseFormat, Role, RunEval, ServiceToken, SpanIFrame, SSEConsoleEventData, SSEProgressEventData, ToolFunctionDefinition, User, ViewDataSearch, ViewData, ViewOptions, View;
1507
+ var AclObjectType, Permission, Acl, AISecret, ResponseFormatJsonSchema, ResponseFormatNullish, AnyModelParams, ApiKey, AsyncScoringState, AsyncScoringControl, BraintrustAttachmentReference, ExternalAttachmentReference, AttachmentReference, UploadStatus, AttachmentStatus, BraintrustModelParams, CallEvent, ChatCompletionContentPartTextWithTitle, ChatCompletionContentPartImageWithTitle, ChatCompletionContentPartFileFile, ChatCompletionContentPartFileWithTitle, ChatCompletionContentPart, ChatCompletionContentPartText, ChatCompletionMessageToolCall, ChatCompletionMessageReasoning, ChatCompletionMessageParam, ChatCompletionOpenAIMessageParam, ChatCompletionTool, CodeBundle, Dataset, ObjectReferenceNullish, DatasetEvent, EnvVar, RepoInfo, Experiment, SpanType, SpanAttributes, ExperimentEvent, ExtendedSavedFunctionId, PromptBlockDataNullish, ModelParams, PromptOptionsNullish, PromptParserNullish, SavedFunctionId, PromptDataNullish, FunctionTypeEnumNullish, FunctionIdRef, PromptBlockData, GraphNode, GraphEdge, GraphData, FunctionData, Function, FunctionFormat, PromptData, FunctionTypeEnum, FunctionId, FunctionObjectType, FunctionOutputType, GitMetadataSettings, Group, IfExists, InvokeParent, StreamingMode, InvokeFunction, MessageRole, ObjectReference, OnlineScoreConfig, Organization, ProjectSettings, Project, RetentionObjectType, ProjectAutomation, ProjectLogsEvent, ProjectScoreType, ProjectScoreCategory, ProjectScoreCategories, ProjectScoreConfig, ProjectScore, ProjectTag, Prompt, PromptOptions, PromptSessionEvent, ResponseFormat, Role, RunEval, ServiceToken, SpanIFrame, SSEConsoleEventData, SSEProgressEventData, ToolFunctionDefinition, User, ViewDataSearch, ViewData, ViewOptions, View;
1508
1508
  var init_generated_types = __esm({
1509
1509
  "src/generated_types.ts"() {
1510
1510
  "use strict";
@@ -1595,10 +1595,12 @@ var init_generated_types = __esm({
1595
1595
  ]).optional(),
1596
1596
  n: _v3.z.number().optional(),
1597
1597
  stop: _v3.z.array(_v3.z.string()).optional(),
1598
- reasoning_effort: _v3.z.enum(["minimal", "low", "medium", "high"]).optional(),
1598
+ reasoning_effort: _v3.z.enum(["none", "minimal", "low", "medium", "high"]).optional(),
1599
1599
  verbosity: _v3.z.enum(["low", "medium", "high"]).optional(),
1600
1600
  top_k: _v3.z.number().optional(),
1601
1601
  stop_sequences: _v3.z.array(_v3.z.string()).optional(),
1602
+ reasoning_enabled: _v3.z.boolean().optional(),
1603
+ reasoning_budget: _v3.z.number().optional(),
1602
1604
  max_tokens_to_sample: _v3.z.number().optional(),
1603
1605
  maxOutputTokens: _v3.z.number().optional(),
1604
1606
  topP: _v3.z.number().optional(),
@@ -1654,7 +1656,11 @@ var init_generated_types = __esm({
1654
1656
  upload_status: UploadStatus,
1655
1657
  error_message: _v3.z.string().optional()
1656
1658
  });
1657
- BraintrustModelParams = _v3.z.object({ use_cache: _v3.z.boolean() }).partial();
1659
+ BraintrustModelParams = _v3.z.object({
1660
+ use_cache: _v3.z.boolean(),
1661
+ reasoning_enabled: _v3.z.boolean(),
1662
+ reasoning_budget: _v3.z.number()
1663
+ }).partial();
1658
1664
  CallEvent = _v3.z.union([
1659
1665
  _v3.z.object({
1660
1666
  id: _v3.z.string().optional(),
@@ -1709,9 +1715,15 @@ var init_generated_types = __esm({
1709
1715
  }),
1710
1716
  type: _v3.z.literal("image_url")
1711
1717
  });
1718
+ ChatCompletionContentPartFileFile = _v3.z.object({ file_data: _v3.z.string(), filename: _v3.z.string(), file_id: _v3.z.string() }).partial();
1719
+ ChatCompletionContentPartFileWithTitle = _v3.z.object({
1720
+ file: ChatCompletionContentPartFileFile,
1721
+ type: _v3.z.literal("file")
1722
+ });
1712
1723
  ChatCompletionContentPart = _v3.z.union([
1713
1724
  ChatCompletionContentPartTextWithTitle,
1714
- ChatCompletionContentPartImageWithTitle
1725
+ ChatCompletionContentPartImageWithTitle,
1726
+ ChatCompletionContentPartFileWithTitle
1715
1727
  ]);
1716
1728
  ChatCompletionContentPartText = _v3.z.object({
1717
1729
  text: _v3.z.string().default(""),
@@ -1808,7 +1820,7 @@ var init_generated_types = __esm({
1808
1820
  });
1809
1821
  CodeBundle = _v3.z.object({
1810
1822
  runtime_context: _v3.z.object({
1811
- runtime: _v3.z.enum(["node", "python"]),
1823
+ runtime: _v3.z.enum(["node", "python", "browser"]),
1812
1824
  version: _v3.z.string()
1813
1825
  }),
1814
1826
  location: _v3.z.union([
@@ -1869,7 +1881,9 @@ var init_generated_types = __esm({
1869
1881
  span_id: _v3.z.string(),
1870
1882
  root_span_id: _v3.z.string(),
1871
1883
  is_root: _v3.z.union([_v3.z.boolean(), _v3.z.null()]).optional(),
1872
- origin: ObjectReferenceNullish.optional()
1884
+ origin: ObjectReferenceNullish.optional(),
1885
+ comments: _v3.z.union([_v3.z.array(_v3.z.unknown()), _v3.z.null()]).optional(),
1886
+ audit_data: _v3.z.union([_v3.z.array(_v3.z.unknown()), _v3.z.null()]).optional()
1873
1887
  });
1874
1888
  EnvVar = _v3.z.object({
1875
1889
  id: _v3.z.string().uuid(),
@@ -1949,7 +1963,9 @@ var init_generated_types = __esm({
1949
1963
  root_span_id: _v3.z.string(),
1950
1964
  span_attributes: SpanAttributes.optional(),
1951
1965
  is_root: _v3.z.union([_v3.z.boolean(), _v3.z.null()]).optional(),
1952
- origin: ObjectReferenceNullish.optional()
1966
+ origin: ObjectReferenceNullish.optional(),
1967
+ comments: _v3.z.union([_v3.z.array(_v3.z.unknown()), _v3.z.null()]).optional(),
1968
+ audit_data: _v3.z.union([_v3.z.array(_v3.z.unknown()), _v3.z.null()]).optional()
1953
1969
  });
1954
1970
  ExtendedSavedFunctionId = _v3.z.union([
1955
1971
  _v3.z.object({ type: _v3.z.literal("function"), id: _v3.z.string() }),
@@ -1961,17 +1977,19 @@ var init_generated_types = __esm({
1961
1977
  })
1962
1978
  ]);
1963
1979
  PromptBlockDataNullish = _v3.z.union([
1964
- _v3.z.object({ type: _v3.z.literal("completion"), content: _v3.z.string() }),
1965
1980
  _v3.z.object({
1966
1981
  type: _v3.z.literal("chat"),
1967
1982
  messages: _v3.z.array(ChatCompletionMessageParam),
1968
1983
  tools: _v3.z.string().optional()
1969
1984
  }),
1985
+ _v3.z.object({ type: _v3.z.literal("completion"), content: _v3.z.string() }),
1970
1986
  _v3.z.null()
1971
1987
  ]);
1972
1988
  ModelParams = _v3.z.union([
1973
1989
  _v3.z.object({
1974
1990
  use_cache: _v3.z.boolean(),
1991
+ reasoning_enabled: _v3.z.boolean(),
1992
+ reasoning_budget: _v3.z.number(),
1975
1993
  temperature: _v3.z.number(),
1976
1994
  top_p: _v3.z.number(),
1977
1995
  max_tokens: _v3.z.number(),
@@ -1995,11 +2013,13 @@ var init_generated_types = __esm({
1995
2013
  ]),
1996
2014
  n: _v3.z.number(),
1997
2015
  stop: _v3.z.array(_v3.z.string()),
1998
- reasoning_effort: _v3.z.enum(["minimal", "low", "medium", "high"]),
2016
+ reasoning_effort: _v3.z.enum(["none", "minimal", "low", "medium", "high"]),
1999
2017
  verbosity: _v3.z.enum(["low", "medium", "high"])
2000
2018
  }).partial().passthrough(),
2001
2019
  _v3.z.object({
2002
2020
  use_cache: _v3.z.boolean().optional(),
2021
+ reasoning_enabled: _v3.z.boolean().optional(),
2022
+ reasoning_budget: _v3.z.number().optional(),
2003
2023
  max_tokens: _v3.z.number(),
2004
2024
  temperature: _v3.z.number(),
2005
2025
  top_p: _v3.z.number().optional(),
@@ -2009,6 +2029,8 @@ var init_generated_types = __esm({
2009
2029
  }).passthrough(),
2010
2030
  _v3.z.object({
2011
2031
  use_cache: _v3.z.boolean(),
2032
+ reasoning_enabled: _v3.z.boolean(),
2033
+ reasoning_budget: _v3.z.number(),
2012
2034
  temperature: _v3.z.number(),
2013
2035
  maxOutputTokens: _v3.z.number(),
2014
2036
  topP: _v3.z.number(),
@@ -2016,10 +2038,16 @@ var init_generated_types = __esm({
2016
2038
  }).partial().passthrough(),
2017
2039
  _v3.z.object({
2018
2040
  use_cache: _v3.z.boolean(),
2041
+ reasoning_enabled: _v3.z.boolean(),
2042
+ reasoning_budget: _v3.z.number(),
2019
2043
  temperature: _v3.z.number(),
2020
2044
  topK: _v3.z.number()
2021
2045
  }).partial().passthrough(),
2022
- _v3.z.object({ use_cache: _v3.z.boolean() }).partial().passthrough()
2046
+ _v3.z.object({
2047
+ use_cache: _v3.z.boolean(),
2048
+ reasoning_enabled: _v3.z.boolean(),
2049
+ reasoning_budget: _v3.z.number()
2050
+ }).partial().passthrough()
2023
2051
  ]);
2024
2052
  PromptOptionsNullish = _v3.z.union([
2025
2053
  _v3.z.object({ model: _v3.z.string(), params: ModelParams, position: _v3.z.string() }).partial(),
@@ -2055,17 +2083,17 @@ var init_generated_types = __esm({
2055
2083
  _v3.z.null()
2056
2084
  ]);
2057
2085
  FunctionTypeEnumNullish = _v3.z.union([
2058
- _v3.z.enum(["llm", "scorer", "task", "tool"]),
2086
+ _v3.z.enum(["llm", "scorer", "task", "tool", "custom_view"]),
2059
2087
  _v3.z.null()
2060
2088
  ]);
2061
2089
  FunctionIdRef = _v3.z.object({}).partial().passthrough();
2062
2090
  PromptBlockData = _v3.z.union([
2063
- _v3.z.object({ type: _v3.z.literal("completion"), content: _v3.z.string() }),
2064
2091
  _v3.z.object({
2065
2092
  type: _v3.z.literal("chat"),
2066
2093
  messages: _v3.z.array(ChatCompletionMessageParam),
2067
2094
  tools: _v3.z.string().optional()
2068
- })
2095
+ }),
2096
+ _v3.z.object({ type: _v3.z.literal("completion"), content: _v3.z.string() })
2069
2097
  ]);
2070
2098
  GraphNode = _v3.z.union([
2071
2099
  _v3.z.object({
@@ -2133,7 +2161,7 @@ var init_generated_types = __esm({
2133
2161
  _v3.z.object({
2134
2162
  type: _v3.z.literal("inline"),
2135
2163
  runtime_context: _v3.z.object({
2136
- runtime: _v3.z.enum(["node", "python"]),
2164
+ runtime: _v3.z.enum(["node", "python", "browser"]),
2137
2165
  version: _v3.z.string()
2138
2166
  }),
2139
2167
  code: _v3.z.string()
@@ -2192,7 +2220,13 @@ var init_generated_types = __esm({
2192
2220
  _v3.z.null()
2193
2221
  ])
2194
2222
  }).partial();
2195
- FunctionTypeEnum = _v3.z.enum(["llm", "scorer", "task", "tool"]);
2223
+ FunctionTypeEnum = _v3.z.enum([
2224
+ "llm",
2225
+ "scorer",
2226
+ "task",
2227
+ "tool",
2228
+ "custom_view"
2229
+ ]);
2196
2230
  FunctionId = _v3.z.union([
2197
2231
  _v3.z.object({ function_id: _v3.z.string(), version: _v3.z.string().optional() }),
2198
2232
  _v3.z.object({
@@ -2208,7 +2242,7 @@ var init_generated_types = __esm({
2208
2242
  }),
2209
2243
  _v3.z.object({
2210
2244
  inline_context: _v3.z.object({
2211
- runtime: _v3.z.enum(["node", "python"]),
2245
+ runtime: _v3.z.enum(["node", "python", "browser"]),
2212
2246
  version: _v3.z.string()
2213
2247
  }),
2214
2248
  code: _v3.z.string(),
@@ -2231,7 +2265,8 @@ var init_generated_types = __esm({
2231
2265
  "tool",
2232
2266
  "scorer",
2233
2267
  "task",
2234
- "agent"
2268
+ "agent",
2269
+ "custom_view"
2235
2270
  ]);
2236
2271
  FunctionOutputType = _v3.z.enum(["completion", "score", "any"]);
2237
2272
  GitMetadataSettings = _v3.z.object({
@@ -2359,7 +2394,8 @@ var init_generated_types = __esm({
2359
2394
  })
2360
2395
  ),
2361
2396
  _v3.z.null()
2362
- ])
2397
+ ]),
2398
+ disable_realtime_queries: _v3.z.union([_v3.z.boolean(), _v3.z.null()])
2363
2399
  }).partial(),
2364
2400
  _v3.z.null()
2365
2401
  ]);
@@ -2447,7 +2483,10 @@ var init_generated_types = __esm({
2447
2483
  root_span_id: _v3.z.string(),
2448
2484
  is_root: _v3.z.union([_v3.z.boolean(), _v3.z.null()]).optional(),
2449
2485
  span_attributes: SpanAttributes.optional(),
2450
- origin: ObjectReferenceNullish.optional()
2486
+ origin: ObjectReferenceNullish.optional(),
2487
+ comments: _v3.z.union([_v3.z.array(_v3.z.unknown()), _v3.z.null()]).optional(),
2488
+ audit_data: _v3.z.union([_v3.z.array(_v3.z.unknown()), _v3.z.null()]).optional(),
2489
+ _async_scoring_state: _v3.z.unknown().optional()
2451
2490
  });
2452
2491
  ProjectScoreType = _v3.z.enum([
2453
2492
  "slider",
@@ -2662,7 +2701,7 @@ var init_generated_types = __esm({
2662
2701
  _v3.z.null()
2663
2702
  ]);
2664
2703
  ViewData = _v3.z.union([
2665
- _v3.z.object({ search: ViewDataSearch }).partial(),
2704
+ _v3.z.object({ search: ViewDataSearch, custom_charts: _v3.z.unknown() }).partial(),
2666
2705
  _v3.z.null()
2667
2706
  ]);
2668
2707
  ViewOptions = _v3.z.union([
@@ -2728,7 +2767,8 @@ var init_generated_types = __esm({
2728
2767
  _v3.z.string(),
2729
2768
  _v3.z.object({ from: _v3.z.string(), to: _v3.z.string() }),
2730
2769
  _v3.z.null()
2731
- ])
2770
+ ]),
2771
+ queryShape: _v3.z.union([_v3.z.enum(["traces", "spans"]), _v3.z.null()])
2732
2772
  }).partial(),
2733
2773
  _v3.z.null()
2734
2774
  ]);
@@ -2749,7 +2789,8 @@ var init_generated_types = __esm({
2749
2789
  "scorers",
2750
2790
  "logs",
2751
2791
  "agents",
2752
- "monitor"
2792
+ "monitor",
2793
+ "for_review"
2753
2794
  ]),
2754
2795
  name: _v3.z.string(),
2755
2796
  created: _v3.z.union([_v3.z.string(), _v3.z.null()]).optional(),
@@ -6771,6 +6812,19 @@ function renderMessage(render, message) {
6771
6812
  url: render(c.image_url.url)
6772
6813
  }
6773
6814
  };
6815
+ case "file":
6816
+ return {
6817
+ ...c,
6818
+ file: {
6819
+ file_data: render(c.file.file_data || ""),
6820
+ ...c.file.file_id && {
6821
+ file_id: render(c.file.file_id)
6822
+ },
6823
+ ...c.file.filename && {
6824
+ filename: render(c.file.filename)
6825
+ }
6826
+ }
6827
+ };
6774
6828
  default:
6775
6829
  const _exhaustiveCheck = c;
6776
6830
  return _exhaustiveCheck;
@@ -8529,6 +8583,7 @@ Error: ${errorText}`;
8529
8583
  },
8530
8584
  use_columnstore: false,
8531
8585
  brainstore_realtime: true,
8586
+ query_source: `js_sdk_object_fetcher_${this.objectType}`,
8532
8587
  ...this.pinnedVersion !== void 0 ? {
8533
8588
  version: this.pinnedVersion
8534
8589
  } : {}
@@ -14852,250 +14907,6 @@ function BraintrustMiddleware(config = {}) {
14852
14907
  };
14853
14908
  }
14854
14909
 
14855
- // src/wrappers/mastra/mastra.ts
14856
- init_logger();
14857
- var aiSDKFormatWarning = false;
14858
- function wrapMastraAgent(agent, options) {
14859
- const prefix = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _226 => _226.name]), () => ( _optionalChain([options, 'optionalAccess', _227 => _227.span_name]))), () => ( agent.name)), () => ( "Agent"));
14860
- if (!hasAllMethods(agent)) {
14861
- return agent;
14862
- }
14863
- if (agent.tools) {
14864
- agent.__setTools(wrapTools2(agent.tools));
14865
- }
14866
- return new Proxy(agent, {
14867
- get(target, prop, receiver) {
14868
- const value = Reflect.get(target, prop, receiver);
14869
- if (prop === "generate" && typeof value === "function") {
14870
- return wrapGenerate(value, target, prefix);
14871
- }
14872
- if (prop === "stream" && typeof value === "function") {
14873
- return wrapStream(value, target, prefix);
14874
- }
14875
- if (typeof value === "function") {
14876
- return value.bind(target);
14877
- }
14878
- return value;
14879
- }
14880
- });
14881
- }
14882
- function hasAllMethods(a) {
14883
- return typeof a.generate === "function" && typeof a.stream === "function";
14884
- }
14885
- function wrapGenerate(original, target, prefix) {
14886
- return function(...args) {
14887
- const input = args[0];
14888
- return traced(
14889
- async (span) => {
14890
- const result = await original.apply(target, args);
14891
- const provider = detectProviderFromResult2(result);
14892
- const model = extractModelFromResult2(result);
14893
- const finishReason = normalizeFinishReason2(_optionalChain([result, 'optionalAccess', _228 => _228.finishReason]));
14894
- const metrics2 = _optionalChain([result, 'optionalAccess', _229 => _229.usage]) ? normalizeUsageMetrics2(
14895
- result.usage,
14896
- provider,
14897
- result.providerMetadata
14898
- ) : {};
14899
- span.log({
14900
- input,
14901
- output: result,
14902
- metadata: {
14903
- agent_name: _nullishCoalesce(target.name, () => ( prefix)),
14904
- ...provider ? { provider } : {},
14905
- ...model ? { model } : {},
14906
- ...finishReason ? { finish_reason: finishReason } : {}
14907
- },
14908
- metrics: metrics2
14909
- });
14910
- return result;
14911
- },
14912
- {
14913
- name: `${prefix}.generate`
14914
- }
14915
- );
14916
- };
14917
- }
14918
- function wrapStream(original, target, prefix) {
14919
- return function(...args) {
14920
- const input = args[0];
14921
- const span = startSpan({
14922
- name: `${prefix}.stream`,
14923
- event: {
14924
- input,
14925
- metadata: {
14926
- agent_name: _nullishCoalesce(target.name, () => ( prefix))
14927
- }
14928
- }
14929
- });
14930
- const baseOpts = typeof args[1] === "object" && args[1] !== null ? args[1] : {};
14931
- if (baseOpts.format && baseOpts.format !== "aisdk" && !aiSDKFormatWarning) {
14932
- aiSDKFormatWarning = true;
14933
- console.warn(
14934
- `Braintrust Mastra wrapper: For best compatibility, use { format: 'aisdk' } (AI SDK v5) instead of format: '${baseOpts.format}'. See https://mastra.ai/en/docs/frameworks/agentic-uis/ai-sdk for more details.`
14935
- );
14936
- }
14937
- const wrappedOpts = {
14938
- ...baseOpts,
14939
- format: baseOpts.format || "aisdk"
14940
- // Default to AI SDK v5 format if not specified
14941
- };
14942
- const userOnChunk = _optionalChain([baseOpts, 'optionalAccess', _230 => _230.onChunk]);
14943
- const userOnFinish = _optionalChain([baseOpts, 'optionalAccess', _231 => _231.onFinish]);
14944
- const userOnError = _optionalChain([baseOpts, 'optionalAccess', _232 => _232.onError]);
14945
- const startTime = Date.now();
14946
- let receivedFirst = false;
14947
- wrappedOpts.onChunk = (chunk) => {
14948
- try {
14949
- _optionalChain([userOnChunk, 'optionalCall', _233 => _233(chunk)]);
14950
- } finally {
14951
- if (!receivedFirst) {
14952
- receivedFirst = true;
14953
- span.log({
14954
- metrics: { time_to_first_token: (Date.now() - startTime) / 1e3 }
14955
- });
14956
- }
14957
- }
14958
- };
14959
- wrappedOpts.onFinish = async (event) => {
14960
- try {
14961
- await _optionalChain([userOnFinish, 'optionalCall', _234 => _234(event)]);
14962
- } finally {
14963
- const e = event;
14964
- const provider = detectProviderFromResult2(e);
14965
- const model = extractModelFromResult2(e);
14966
- const finishReason = normalizeFinishReason2(_optionalChain([e, 'optionalAccess', _235 => _235.finishReason]));
14967
- const metrics2 = _optionalChain([e, 'optionalAccess', _236 => _236.usage]) ? normalizeUsageMetrics2(e.usage, provider, e.providerMetadata) : {};
14968
- span.log({
14969
- output: _nullishCoalesce(_nullishCoalesce(e.text, () => ( e.content)), () => ( e)),
14970
- metadata: {
14971
- agent_name: _nullishCoalesce(target.name, () => ( prefix)),
14972
- ...provider ? { provider } : {},
14973
- ...model ? { model } : {},
14974
- ...finishReason ? { finish_reason: finishReason } : {}
14975
- },
14976
- metrics: metrics2
14977
- });
14978
- span.end();
14979
- }
14980
- };
14981
- wrappedOpts.onError = async (err) => {
14982
- try {
14983
- await _optionalChain([userOnError, 'optionalCall', _237 => _237(err)]);
14984
- } finally {
14985
- logError(span, err);
14986
- span.end();
14987
- }
14988
- };
14989
- return withCurrent(
14990
- span,
14991
- () => original.apply(target, [args[0], wrappedOpts, ...args.slice(2)])
14992
- );
14993
- };
14994
- }
14995
- function detectProviderFromResult2(result) {
14996
- if (!_optionalChain([result, 'optionalAccess', _238 => _238.providerMetadata])) {
14997
- return void 0;
14998
- }
14999
- const keys = Object.keys(result.providerMetadata);
15000
- return _optionalChain([keys, 'optionalAccess', _239 => _239.at, 'call', _240 => _240(0)]);
15001
- }
15002
- function extractModelFromResult2(result) {
15003
- if (_optionalChain([result, 'optionalAccess', _241 => _241.response, 'optionalAccess', _242 => _242.modelId])) {
15004
- return result.response.modelId;
15005
- }
15006
- if (_optionalChain([result, 'optionalAccess', _243 => _243.request, 'optionalAccess', _244 => _244.body, 'optionalAccess', _245 => _245.model])) {
15007
- return result.request.body.model;
15008
- }
15009
- return void 0;
15010
- }
15011
- function normalizeFinishReason2(reason) {
15012
- if (typeof reason !== "string") return void 0;
15013
- return reason.replace(/-/g, "_");
15014
- }
15015
- function normalizeUsageMetrics2(usage, provider, providerMetadata) {
15016
- const metrics2 = {};
15017
- const inputTokens = getNumberProperty2(usage, "inputTokens");
15018
- if (inputTokens !== void 0) {
15019
- metrics2.prompt_tokens = inputTokens;
15020
- }
15021
- const outputTokens = getNumberProperty2(usage, "outputTokens");
15022
- if (outputTokens !== void 0) {
15023
- metrics2.completion_tokens = outputTokens;
15024
- }
15025
- const totalTokens = getNumberProperty2(usage, "totalTokens");
15026
- if (totalTokens !== void 0) {
15027
- metrics2.tokens = totalTokens;
15028
- }
15029
- const reasoningTokens = getNumberProperty2(usage, "reasoningTokens");
15030
- if (reasoningTokens !== void 0) {
15031
- metrics2.completion_reasoning_tokens = reasoningTokens;
15032
- }
15033
- const cachedInputTokens = getNumberProperty2(usage, "cachedInputTokens");
15034
- if (cachedInputTokens !== void 0) {
15035
- metrics2.prompt_cached_tokens = cachedInputTokens;
15036
- }
15037
- if (provider === "anthropic") {
15038
- const anthropicMetadata = _optionalChain([providerMetadata, 'optionalAccess', _246 => _246.anthropic]);
15039
- if (anthropicMetadata) {
15040
- const cacheReadTokens = getNumberProperty2(anthropicMetadata.usage, "cache_read_input_tokens") || 0;
15041
- const cacheCreationTokens = getNumberProperty2(
15042
- anthropicMetadata.usage,
15043
- "cache_creation_input_tokens"
15044
- ) || 0;
15045
- const cacheTokens = extractAnthropicCacheTokens(
15046
- cacheReadTokens,
15047
- cacheCreationTokens
15048
- );
15049
- Object.assign(metrics2, cacheTokens);
15050
- Object.assign(metrics2, finalizeAnthropicTokens(metrics2));
15051
- }
15052
- }
15053
- return metrics2;
15054
- }
15055
- function wrapTools2(tools) {
15056
- if (!tools) return tools;
15057
- const inferName = (tool, fallback2) => tool && (tool.name || tool.toolName || tool.id) || fallback2;
15058
- if (Array.isArray(tools)) {
15059
- const arr = tools;
15060
- const out = arr.map((tool, idx) => {
15061
- if (tool != null && typeof tool === "object" && "execute" in tool && typeof tool.execute === "function") {
15062
- const name = inferName(tool, `tool[${idx}]`);
15063
- return {
15064
- ...tool,
15065
- execute: wrapTraced(tool.execute.bind(tool), {
15066
- name,
15067
- type: "tool"
15068
- })
15069
- };
15070
- }
15071
- return tool;
15072
- });
15073
- return out;
15074
- }
15075
- const wrappedTools = {};
15076
- for (const [key, tool] of Object.entries(tools)) {
15077
- if (tool != null && typeof tool === "object" && "execute" in tool && typeof tool.execute === "function") {
15078
- wrappedTools[key] = {
15079
- ...tool,
15080
- execute: wrapTraced(tool.execute.bind(tool), {
15081
- name: key,
15082
- type: "tool"
15083
- })
15084
- };
15085
- } else {
15086
- wrappedTools[key] = tool;
15087
- }
15088
- }
15089
- return wrappedTools;
15090
- }
15091
- function getNumberProperty2(obj, key) {
15092
- if (!obj || typeof obj !== "object" || !(key in obj)) {
15093
- return void 0;
15094
- }
15095
- const value = Reflect.get(obj, key);
15096
- return typeof value === "number" ? value : void 0;
15097
- }
15098
-
15099
14910
  // src/wrappers/anthropic.ts
15100
14911
  init_logger();
15101
14912
  init_util();
@@ -15171,10 +14982,14 @@ function createProxy(create) {
15171
14982
  const apiPromise = Reflect.apply(target, thisArg, argArray);
15172
14983
  const onThen = function(msgOrStream) {
15173
14984
  if (!args["stream"]) {
14985
+ const ttft = getCurrentUnixTimestamp() - sspan.startTime;
15174
14986
  const event = parseEventFromMessage(msgOrStream);
15175
14987
  span.log({
15176
14988
  ...event,
15177
- metrics: event.metrics ? finalizeAnthropicTokens(event.metrics) : void 0
14989
+ metrics: event.metrics ? finalizeAnthropicTokens({
14990
+ ...event.metrics,
14991
+ time_to_first_token: ttft
14992
+ }) : { time_to_first_token: ttft }
15178
14993
  });
15179
14994
  span.end();
15180
14995
  return msgOrStream;
@@ -15266,9 +15081,9 @@ function streamNextProxy(stream, sspan) {
15266
15081
  return result;
15267
15082
  }
15268
15083
  const item = result.value;
15269
- switch (_optionalChain([item, 'optionalAccess', _247 => _247.type])) {
15084
+ switch (_optionalChain([item, 'optionalAccess', _226 => _226.type])) {
15270
15085
  case "message_start":
15271
- const msg = _optionalChain([item, 'optionalAccess', _248 => _248.message]);
15086
+ const msg = _optionalChain([item, 'optionalAccess', _227 => _227.message]);
15272
15087
  if (msg) {
15273
15088
  const event = parseEventFromMessage(msg);
15274
15089
  totals = { ...totals, ...event.metrics };
@@ -15281,20 +15096,20 @@ function streamNextProxy(stream, sspan) {
15281
15096
  }
15282
15097
  break;
15283
15098
  case "content_block_delta":
15284
- if (_optionalChain([item, 'access', _249 => _249.delta, 'optionalAccess', _250 => _250.type]) === "text_delta") {
15285
- const text = _optionalChain([item, 'optionalAccess', _251 => _251.delta, 'optionalAccess', _252 => _252.text]);
15099
+ if (_optionalChain([item, 'access', _228 => _228.delta, 'optionalAccess', _229 => _229.type]) === "text_delta") {
15100
+ const text = _optionalChain([item, 'optionalAccess', _230 => _230.delta, 'optionalAccess', _231 => _231.text]);
15286
15101
  if (text) {
15287
15102
  deltas.push(text);
15288
15103
  }
15289
15104
  }
15290
15105
  break;
15291
15106
  case "message_delta":
15292
- const usage = _optionalChain([item, 'optionalAccess', _253 => _253.usage]);
15107
+ const usage = _optionalChain([item, 'optionalAccess', _232 => _232.usage]);
15293
15108
  if (usage) {
15294
15109
  const metrics2 = parseMetricsFromUsage2(usage);
15295
15110
  totals = { ...totals, ...metrics2 };
15296
15111
  }
15297
- const delta = _optionalChain([item, 'optionalAccess', _254 => _254.delta]);
15112
+ const delta = _optionalChain([item, 'optionalAccess', _233 => _233.delta]);
15298
15113
  if (delta) {
15299
15114
  metadata = { ...metadata, ...delta };
15300
15115
  }
@@ -15307,7 +15122,7 @@ function streamNextProxy(stream, sspan) {
15307
15122
  }
15308
15123
  function parseEventFromMessage(message) {
15309
15124
  const output = message ? { role: message.role, content: message.content } : null;
15310
- const metrics2 = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess', _255 => _255.usage]));
15125
+ const metrics2 = parseMetricsFromUsage2(_optionalChain([message, 'optionalAccess', _234 => _234.usage]));
15311
15126
  const metas = ["stop_reason", "stop_sequence"];
15312
15127
  const metadata = {};
15313
15128
  for (const m of metas) {
@@ -15390,6 +15205,11 @@ function coalesceInput(messages, system) {
15390
15205
  return input;
15391
15206
  }
15392
15207
 
15208
+ // src/wrappers/mastra.ts
15209
+ function wrapMastraAgent(agent, _options) {
15210
+ return agent;
15211
+ }
15212
+
15393
15213
  // src/wrappers/claude-agent-sdk/claude-agent-sdk.ts
15394
15214
  init_logger();
15395
15215
  init_util2();
@@ -15452,8 +15272,8 @@ function wrapClaudeAgentQuery(queryFn, defaultThis) {
15452
15272
  finalResults.push(finalMessageContent);
15453
15273
  }
15454
15274
  const lastMessage = currentMessages[currentMessages.length - 1];
15455
- if (_optionalChain([lastMessage, 'optionalAccess', _256 => _256.message, 'optionalAccess', _257 => _257.usage])) {
15456
- const outputTokens = getNumberProperty3(lastMessage.message.usage, "output_tokens") || 0;
15275
+ if (_optionalChain([lastMessage, 'optionalAccess', _235 => _235.message, 'optionalAccess', _236 => _236.usage])) {
15276
+ const outputTokens = getNumberProperty2(lastMessage.message.usage, "output_tokens") || 0;
15457
15277
  accumulatedOutputTokens += outputTokens;
15458
15278
  }
15459
15279
  currentMessages.length = 0;
@@ -15467,20 +15287,20 @@ function wrapClaudeAgentQuery(queryFn, defaultThis) {
15467
15287
  );
15468
15288
  for await (const message of generator) {
15469
15289
  const currentTime = getCurrentUnixTimestamp();
15470
- const messageId = _optionalChain([message, 'access', _258 => _258.message, 'optionalAccess', _259 => _259.id]);
15290
+ const messageId = _optionalChain([message, 'access', _237 => _237.message, 'optionalAccess', _238 => _238.id]);
15471
15291
  if (messageId && messageId !== currentMessageId) {
15472
15292
  await createLLMSpan();
15473
15293
  currentMessageId = messageId;
15474
15294
  currentMessageStartTime = currentTime;
15475
15295
  }
15476
- if (message.type === "assistant" && _optionalChain([message, 'access', _260 => _260.message, 'optionalAccess', _261 => _261.usage])) {
15296
+ if (message.type === "assistant" && _optionalChain([message, 'access', _239 => _239.message, 'optionalAccess', _240 => _240.usage])) {
15477
15297
  currentMessages.push(message);
15478
15298
  }
15479
15299
  if (message.type === "result" && message.usage) {
15480
15300
  finalUsageMetrics = _extractUsageFromMessage(message);
15481
15301
  if (currentMessages.length > 0 && finalUsageMetrics.completion_tokens !== void 0) {
15482
15302
  const lastMessage = currentMessages[currentMessages.length - 1];
15483
- if (_optionalChain([lastMessage, 'optionalAccess', _262 => _262.message, 'optionalAccess', _263 => _263.usage])) {
15303
+ if (_optionalChain([lastMessage, 'optionalAccess', _241 => _241.message, 'optionalAccess', _242 => _242.usage])) {
15484
15304
  const adjustedTokens = finalUsageMetrics.completion_tokens - accumulatedOutputTokens;
15485
15305
  if (adjustedTokens >= 0) {
15486
15306
  lastMessage.message.usage.output_tokens = adjustedTokens;
@@ -15561,23 +15381,23 @@ function _extractUsageFromMessage(message) {
15561
15381
  const metrics2 = {};
15562
15382
  let usage;
15563
15383
  if (message.type === "assistant") {
15564
- usage = _optionalChain([message, 'access', _264 => _264.message, 'optionalAccess', _265 => _265.usage]);
15384
+ usage = _optionalChain([message, 'access', _243 => _243.message, 'optionalAccess', _244 => _244.usage]);
15565
15385
  } else if (message.type === "result") {
15566
15386
  usage = message.usage;
15567
15387
  }
15568
15388
  if (!usage || typeof usage !== "object") {
15569
15389
  return metrics2;
15570
15390
  }
15571
- const inputTokens = getNumberProperty3(usage, "input_tokens");
15391
+ const inputTokens = getNumberProperty2(usage, "input_tokens");
15572
15392
  if (inputTokens !== void 0) {
15573
15393
  metrics2.prompt_tokens = inputTokens;
15574
15394
  }
15575
- const outputTokens = getNumberProperty3(usage, "output_tokens");
15395
+ const outputTokens = getNumberProperty2(usage, "output_tokens");
15576
15396
  if (outputTokens !== void 0) {
15577
15397
  metrics2.completion_tokens = outputTokens;
15578
15398
  }
15579
- const cacheReadTokens = getNumberProperty3(usage, "cache_read_input_tokens") || 0;
15580
- const cacheCreationTokens = getNumberProperty3(usage, "cache_creation_input_tokens") || 0;
15399
+ const cacheReadTokens = getNumberProperty2(usage, "cache_read_input_tokens") || 0;
15400
+ const cacheCreationTokens = getNumberProperty2(usage, "cache_creation_input_tokens") || 0;
15581
15401
  if (cacheReadTokens > 0 || cacheCreationTokens > 0) {
15582
15402
  const cacheTokens = extractAnthropicCacheTokens(
15583
15403
  cacheReadTokens,
@@ -15593,14 +15413,14 @@ function _extractUsageFromMessage(message) {
15593
15413
  async function _createLLMSpanForMessages(messages, prompt, conversationHistory, options, startTime, parentSpan) {
15594
15414
  if (messages.length === 0) return void 0;
15595
15415
  const lastMessage = messages[messages.length - 1];
15596
- if (lastMessage.type !== "assistant" || !_optionalChain([lastMessage, 'access', _266 => _266.message, 'optionalAccess', _267 => _267.usage])) {
15416
+ if (lastMessage.type !== "assistant" || !_optionalChain([lastMessage, 'access', _245 => _245.message, 'optionalAccess', _246 => _246.usage])) {
15597
15417
  return void 0;
15598
15418
  }
15599
15419
  const model = lastMessage.message.model || options.model;
15600
15420
  const usage = _extractUsageFromMessage(lastMessage);
15601
15421
  const input = _buildLLMInput(prompt, conversationHistory);
15602
15422
  const outputs = messages.map(
15603
- (m) => _optionalChain([m, 'access', _268 => _268.message, 'optionalAccess', _269 => _269.content]) && _optionalChain([m, 'access', _270 => _270.message, 'optionalAccess', _271 => _271.role]) ? { content: m.message.content, role: m.message.role } : void 0
15423
+ (m) => _optionalChain([m, 'access', _247 => _247.message, 'optionalAccess', _248 => _248.content]) && _optionalChain([m, 'access', _249 => _249.message, 'optionalAccess', _250 => _250.role]) ? { content: m.message.content, role: m.message.role } : void 0
15604
15424
  ).filter((c) => c !== void 0);
15605
15425
  await traced(
15606
15426
  (llmSpan) => {
@@ -15620,7 +15440,7 @@ async function _createLLMSpanForMessages(messages, prompt, conversationHistory,
15620
15440
  parent: parentSpan
15621
15441
  }
15622
15442
  );
15623
- return _optionalChain([lastMessage, 'access', _272 => _272.message, 'optionalAccess', _273 => _273.content]) && _optionalChain([lastMessage, 'access', _274 => _274.message, 'optionalAccess', _275 => _275.role]) ? { content: lastMessage.message.content, role: lastMessage.message.role } : void 0;
15443
+ return _optionalChain([lastMessage, 'access', _251 => _251.message, 'optionalAccess', _252 => _252.content]) && _optionalChain([lastMessage, 'access', _253 => _253.message, 'optionalAccess', _254 => _254.role]) ? { content: lastMessage.message.content, role: lastMessage.message.role } : void 0;
15624
15444
  }
15625
15445
  function wrapClaudeAgentSDK(sdk) {
15626
15446
  const cache = /* @__PURE__ */ new Map();
@@ -15668,7 +15488,7 @@ function wrapClaudeAgentSDK(sdk) {
15668
15488
  }
15669
15489
  });
15670
15490
  }
15671
- function getNumberProperty3(obj, key) {
15491
+ function getNumberProperty2(obj, key) {
15672
15492
  if (!obj || typeof obj !== "object" || !(key in obj)) {
15673
15493
  return void 0;
15674
15494
  }
@@ -15913,7 +15733,7 @@ function serializePart(part) {
15913
15733
  return part;
15914
15734
  }
15915
15735
  function serializeTools(params) {
15916
- if (!_optionalChain([params, 'access', _276 => _276.config, 'optionalAccess', _277 => _277.tools])) {
15736
+ if (!_optionalChain([params, 'access', _255 => _255.config, 'optionalAccess', _256 => _256.tools])) {
15917
15737
  return null;
15918
15738
  }
15919
15739
  try {
@@ -15996,7 +15816,7 @@ function aggregateGenerateContentChunks(chunks, start, firstTokenTime) {
15996
15816
  }
15997
15817
  if (chunk.candidates && Array.isArray(chunk.candidates)) {
15998
15818
  for (const candidate of chunk.candidates) {
15999
- if (_optionalChain([candidate, 'access', _278 => _278.content, 'optionalAccess', _279 => _279.parts])) {
15819
+ if (_optionalChain([candidate, 'access', _257 => _257.content, 'optionalAccess', _258 => _258.parts])) {
16000
15820
  for (const part of candidate.content.parts) {
16001
15821
  if (part.text !== void 0) {
16002
15822
  if (part.thought) {
@@ -16027,7 +15847,7 @@ function aggregateGenerateContentChunks(chunks, start, firstTokenTime) {
16027
15847
  parts.push({ text });
16028
15848
  }
16029
15849
  parts.push(...otherParts);
16030
- if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess', _280 => _280.candidates])) {
15850
+ if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess', _259 => _259.candidates])) {
16031
15851
  const candidates = [];
16032
15852
  for (const candidate of lastResponse.candidates) {
16033
15853
  const candidateDict = {
@@ -16256,8 +16076,8 @@ var BraintrustSpanProcessor = class _BraintrustSpanProcessor {
16256
16076
  span.instrumentationScope = span.instrumentationLibrary;
16257
16077
  }
16258
16078
  if (!span.parentSpanContext && span.parentSpanId) {
16259
- const spanContext = _optionalChain([span, 'access', _281 => _281.spanContext, 'optionalCall', _282 => _282()]);
16260
- if (_optionalChain([spanContext, 'optionalAccess', _283 => _283.traceId])) {
16079
+ const spanContext = _optionalChain([span, 'access', _260 => _260.spanContext, 'optionalCall', _261 => _261()]);
16080
+ if (_optionalChain([spanContext, 'optionalAccess', _262 => _262.traceId])) {
16261
16081
  span.parentSpanContext = {
16262
16082
  spanId: span.parentSpanId,
16263
16083
  traceId: spanContext.traceId
@@ -16300,7 +16120,7 @@ var BraintrustSpanProcessor = class _BraintrustSpanProcessor {
16300
16120
  let parentValue;
16301
16121
  if (otelApi && otelApi.context) {
16302
16122
  const currentContext = otelApi.context.active();
16303
- const contextValue = _optionalChain([currentContext, 'access', _284 => _284.getValue, 'optionalCall', _285 => _285("braintrust.parent")]);
16123
+ const contextValue = _optionalChain([currentContext, 'access', _263 => _263.getValue, 'optionalCall', _264 => _264("braintrust.parent")]);
16304
16124
  if (typeof contextValue === "string") {
16305
16125
  parentValue = contextValue;
16306
16126
  }
@@ -16364,7 +16184,7 @@ function otelContextFromSpanExport(exportStr) {
16364
16184
  traceId: traceIdHex,
16365
16185
  spanId: spanIdHex,
16366
16186
  isRemote: true,
16367
- traceFlags: _nullishCoalesce(_optionalChain([otelApi, 'access', _286 => _286.TraceFlags, 'optionalAccess', _287 => _287.SAMPLED]), () => ( 1))
16187
+ traceFlags: _nullishCoalesce(_optionalChain([otelApi, 'access', _265 => _265.TraceFlags, 'optionalAccess', _266 => _266.SAMPLED]), () => ( 1))
16368
16188
  // SAMPLED flag
16369
16189
  };
16370
16190
  const nonRecordingSpan = otelTrace2.wrapSpanContext(spanContext);
@@ -16469,7 +16289,7 @@ var BraintrustExporter = (_class21 = class _BraintrustExporter {
16469
16289
  function addParentToBaggage(parent, ctx) {
16470
16290
  if (!OTEL_AVAILABLE2 || !otelApi) {
16471
16291
  console.error("OpenTelemetry not available");
16472
- return ctx || _optionalChain([otelApi, 'optionalAccess', _288 => _288.context, 'access', _289 => _289.active, 'call', _290 => _290()]);
16292
+ return ctx || _optionalChain([otelApi, 'optionalAccess', _267 => _267.context, 'access', _268 => _268.active, 'call', _269 => _269()]);
16473
16293
  }
16474
16294
  try {
16475
16295
  const propagation2 = otelApi.propagation;
@@ -16530,7 +16350,7 @@ function parentFromHeaders(headers) {
16530
16350
  return void 0;
16531
16351
  }
16532
16352
  const baggage = propagation2.getBaggage(ctx);
16533
- const braintrustParent = _optionalChain([baggage, 'optionalAccess', _291 => _291.getEntry, 'call', _292 => _292("braintrust.parent"), 'optionalAccess', _293 => _293.value]);
16353
+ const braintrustParent = _optionalChain([baggage, 'optionalAccess', _270 => _270.getEntry, 'call', _271 => _271("braintrust.parent"), 'optionalAccess', _272 => _272.value]);
16534
16354
  if (!braintrustParent) {
16535
16355
  console.warn(
16536
16356
  "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."