braintrust 3.30.0 → 3.32.0

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.
Files changed (55) hide show
  1. package/dev/dist/index.d.mts +740 -1
  2. package/dev/dist/index.d.ts +740 -1
  3. package/dev/dist/index.js +1307 -434
  4. package/dev/dist/index.mjs +886 -13
  5. package/dist/apply-auto-instrumentation.js +281 -216
  6. package/dist/apply-auto-instrumentation.mjs +66 -1
  7. package/dist/auto-instrumentations/bundler/esbuild.cjs +104 -2
  8. package/dist/auto-instrumentations/bundler/esbuild.mjs +2 -2
  9. package/dist/auto-instrumentations/bundler/next.cjs +113 -5
  10. package/dist/auto-instrumentations/bundler/next.mjs +12 -6
  11. package/dist/auto-instrumentations/bundler/rollup.cjs +104 -2
  12. package/dist/auto-instrumentations/bundler/rollup.mjs +2 -2
  13. package/dist/auto-instrumentations/bundler/vite.cjs +104 -2
  14. package/dist/auto-instrumentations/bundler/vite.mjs +2 -2
  15. package/dist/auto-instrumentations/bundler/webpack-loader.cjs +104 -2
  16. package/dist/auto-instrumentations/bundler/webpack.cjs +104 -2
  17. package/dist/auto-instrumentations/bundler/webpack.mjs +3 -3
  18. package/dist/auto-instrumentations/{chunk-U64OYU4Q.mjs → chunk-AFND2U7E.mjs} +38 -1
  19. package/dist/auto-instrumentations/{chunk-OXINGIEZ.mjs → chunk-QEEPRBIS.mjs} +1 -1
  20. package/dist/auto-instrumentations/{chunk-LW4HDHXT.mjs → chunk-RI4Y55ZF.mjs} +69 -2
  21. package/dist/auto-instrumentations/hook.mjs +126 -3
  22. package/dist/auto-instrumentations/index.cjs +39 -1
  23. package/dist/auto-instrumentations/index.d.mts +3 -1
  24. package/dist/auto-instrumentations/index.d.ts +3 -1
  25. package/dist/auto-instrumentations/index.mjs +3 -1
  26. package/dist/browser.d.mts +3052 -927
  27. package/dist/browser.d.ts +3052 -927
  28. package/dist/browser.js +1023 -18
  29. package/dist/browser.mjs +1023 -18
  30. package/dist/{chunk-BU6SM54N.mjs → chunk-4QSAHP7D.mjs} +834 -10
  31. package/dist/{chunk-2XDW3UCG.js → chunk-AW4QECG5.js} +47 -4
  32. package/dist/{chunk-TWCDSYJN.js → chunk-BTRLPQG5.js} +1679 -855
  33. package/dist/{chunk-N3JKQ3D3.mjs → chunk-WV6QZI2W.mjs} +46 -3
  34. package/dist/cli.js +950 -14
  35. package/dist/edge-light.d.mts +1 -1
  36. package/dist/edge-light.d.ts +1 -1
  37. package/dist/edge-light.js +1023 -18
  38. package/dist/edge-light.mjs +1023 -18
  39. package/dist/index.d.mts +3052 -927
  40. package/dist/index.d.ts +3052 -927
  41. package/dist/index.js +594 -450
  42. package/dist/index.mjs +149 -5
  43. package/dist/instrumentation/index.d.mts +434 -0
  44. package/dist/instrumentation/index.d.ts +434 -0
  45. package/dist/instrumentation/index.js +875 -12
  46. package/dist/instrumentation/index.mjs +875 -12
  47. package/dist/vitest-evals-reporter.js +16 -16
  48. package/dist/vitest-evals-reporter.mjs +2 -2
  49. package/dist/workerd.d.mts +1 -1
  50. package/dist/workerd.d.ts +1 -1
  51. package/dist/workerd.js +1023 -18
  52. package/dist/workerd.mjs +1023 -18
  53. package/package.json +1 -1
  54. package/util/dist/index.d.mts +326 -0
  55. package/util/dist/index.d.ts +326 -0
package/dev/dist/index.js CHANGED
@@ -3115,6 +3115,14 @@ var ChatCompletionContentPartImageWithTitle = _v3.z.object({
3115
3115
  ttl: _v3.z.enum(["5m", "1h"]).optional()
3116
3116
  }).optional()
3117
3117
  });
3118
+ var ChatCompletionContentPartInputAudioWithTitle = _v3.z.object({
3119
+ input_audio: _v3.z.object({ data: _v3.z.string(), format: _v3.z.enum(["wav", "mp3"]) }),
3120
+ type: _v3.z.literal("input_audio"),
3121
+ cache_control: _v3.z.object({
3122
+ type: _v3.z.literal("ephemeral"),
3123
+ ttl: _v3.z.enum(["5m", "1h"]).optional()
3124
+ }).optional()
3125
+ });
3118
3126
  var ChatCompletionContentPartFileFile = _v3.z.object({ file_data: _v3.z.string(), filename: _v3.z.string(), file_id: _v3.z.string() }).partial();
3119
3127
  var ChatCompletionContentPartFileWithTitle = _v3.z.object({
3120
3128
  file: ChatCompletionContentPartFileFile,
@@ -3127,6 +3135,7 @@ var ChatCompletionContentPartFileWithTitle = _v3.z.object({
3127
3135
  var ChatCompletionContentPart = _v3.z.union([
3128
3136
  ChatCompletionContentPartTextWithTitle,
3129
3137
  ChatCompletionContentPartImageWithTitle,
3138
+ ChatCompletionContentPartInputAudioWithTitle,
3130
3139
  ChatCompletionContentPartFileWithTitle
3131
3140
  ]);
3132
3141
  var ChatCompletionContentPartText = _v3.z.object({
@@ -4118,6 +4127,7 @@ var ProjectSettings = _v3.z.union([
4118
4127
  ]),
4119
4128
  disable_realtime_queries: _v3.z.union([_v3.z.boolean(), _v3.z.null()]),
4120
4129
  monitor_charts_use_metrics_start: _v3.z.union([_v3.z.boolean(), _v3.z.null()]),
4130
+ blind_reviews: _v3.z.union([_v3.z.boolean(), _v3.z.null()]),
4121
4131
  default_preprocessor: NullableSavedFunctionId
4122
4132
  }).partial(),
4123
4133
  _v3.z.null()
@@ -4179,6 +4189,7 @@ var WindowedAutomationConfig = _v3.z.object({
4179
4189
  auto_approve_tools: _v3.z.array(_v3.z.string().min(1)).optional().default([]),
4180
4190
  harness: _v3.z.enum(["native", "codex", "claude-code"]).optional(),
4181
4191
  model: _v3.z.string().min(1).optional(),
4192
+ endpoint_name: _v3.z.string().min(1).optional(),
4182
4193
  reasoning_effort: _v3.z.enum(["none", "minimal", "low", "medium", "high", "xhigh", "max"]).optional()
4183
4194
  }).optional(),
4184
4195
  actions: _v3.z.array(
@@ -5952,6 +5963,7 @@ var INSTRUMENTATION_NAMES = {
5952
5963
  GENKIT: "genkit",
5953
5964
  GITHUB_COPILOT: "github-copilot",
5954
5965
  GOOGLE_ADK: "google-adk",
5966
+ GOOGLE_GENERATIVE_AI: "google-generative-ai",
5955
5967
  GOOGLE_GENAI: "google-genai",
5956
5968
  GROQ: "groq",
5957
5969
  HUGGINGFACE: "huggingface",
@@ -5967,12 +5979,13 @@ var INSTRUMENTATION_NAMES = {
5967
5979
  OPENROUTER_AGENT: "openrouter-agent",
5968
5980
  PI_CODING_AGENT: "pi-coding-agent",
5969
5981
  STRANDS_AGENT_SDK: "strands-agent-sdk",
5970
- VOYAGEAI: "voyageai"
5982
+ VOYAGEAI: "voyageai",
5983
+ ELEVENLABS: "elevenlabs"
5971
5984
  };
5972
5985
  var INTERNAL_SPAN_INSTRUMENTATION_NAME = /* @__PURE__ */ Symbol.for(
5973
5986
  "braintrust.spanInstrumentationName"
5974
5987
  );
5975
- var SDK_VERSION = true ? "3.30.0" : "0.0.0";
5988
+ var SDK_VERSION = true ? "3.32.0" : "0.0.0";
5976
5989
  function withSpanInstrumentationName(args, instrumentationName) {
5977
5990
  return {
5978
5991
  ...args,
@@ -11146,6 +11159,16 @@ function renderMessageImpl(render, message, variables) {
11146
11159
  }
11147
11160
  }
11148
11161
  ];
11162
+ case "input_audio":
11163
+ return [
11164
+ {
11165
+ ...c,
11166
+ input_audio: {
11167
+ ...c.input_audio,
11168
+ data: render(c.input_audio.data)
11169
+ }
11170
+ }
11171
+ ];
11149
11172
  case "file":
11150
11173
  return [
11151
11174
  {
@@ -19197,6 +19220,12 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
19197
19220
  if (!activeEntry) {
19198
19221
  return result;
19199
19222
  }
19223
+ const executionOptions = args[1];
19224
+ const toolCallId = isObject(executionOptions) ? executionOptions.toolCallId : void 0;
19225
+ const toolInput = {
19226
+ input: serializeToolExecutionInput(args),
19227
+ ...typeof toolCallId === "string" ? { metadata: { toolCallId } } : {}
19228
+ };
19200
19229
  if (isAsyncGenerator(result)) {
19201
19230
  return (async function* () {
19202
19231
  const span = activeEntry.parentSpan.startSpan(
@@ -19210,7 +19239,7 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
19210
19239
  INSTRUMENTATION_NAMES.AI_SDK
19211
19240
  )
19212
19241
  );
19213
- span.log({ input: serializeToolExecutionInput(args) });
19242
+ span.log(toolInput);
19214
19243
  try {
19215
19244
  let lastValue;
19216
19245
  for await (const value of result) {
@@ -19228,7 +19257,7 @@ function prepareAISDKChildTracing(params, self, parentSpan, denyOutputPaths, aiS
19228
19257
  }
19229
19258
  return activeEntry.parentSpan.traced(
19230
19259
  async (span) => {
19231
- span.log({ input: serializeToolExecutionInput(args) });
19260
+ span.log(toolInput);
19232
19261
  const awaitedResult = await result;
19233
19262
  span.log({ output: awaitedResult });
19234
19263
  return awaitedResult;
@@ -23632,6 +23661,342 @@ var OpenAIAgentsPlugin = (_class23 = class extends BasePlugin {constructor(...ar
23632
23661
  }
23633
23662
  }, _class23);
23634
23663
 
23664
+ // src/instrumentation/plugins/google-generative-ai-channels.ts
23665
+ var googleGenerativeAIChannels = defineChannels(
23666
+ "@google/generative-ai",
23667
+ {
23668
+ generateContent: channel({ channelName: "GenerativeModel.generateContent", kind: "async" }),
23669
+ generateContentStream: channel({ channelName: "GenerativeModel.generateContentStream", kind: "async" }),
23670
+ embedContent: channel({ channelName: "GenerativeModel.embedContent", kind: "async" }),
23671
+ batchEmbedContents: channel({ channelName: "GenerativeModel.batchEmbedContents", kind: "async" }),
23672
+ sendMessage: channel({ channelName: "ChatSession.sendMessage", kind: "async" }),
23673
+ sendMessageStream: channel({ channelName: "ChatSession.sendMessageStream", kind: "async" })
23674
+ },
23675
+ { instrumentationName: INSTRUMENTATION_NAMES.GOOGLE_GENERATIVE_AI }
23676
+ );
23677
+
23678
+ // src/instrumentation/plugins/google-generative-ai-plugin.ts
23679
+ var GENERATION_CONFIG_KEYS = [
23680
+ "temperature",
23681
+ "topP",
23682
+ "topK",
23683
+ "candidateCount",
23684
+ "maxOutputTokens",
23685
+ "stopSequences",
23686
+ "responseMimeType",
23687
+ "responseSchema",
23688
+ "presencePenalty",
23689
+ "frequencyPenalty",
23690
+ "responseLogprobs",
23691
+ "logprobs",
23692
+ "thinkingConfig"
23693
+ ];
23694
+ var GoogleGenerativeAIPlugin = class extends BasePlugin {
23695
+ onEnable() {
23696
+ this.unsubscribers.push(
23697
+ interceptCall(
23698
+ googleGenerativeAIChannels.generateContent,
23699
+ "generateContent"
23700
+ ),
23701
+ interceptCall(
23702
+ googleGenerativeAIChannels.generateContentStream,
23703
+ "generateContentStream"
23704
+ ),
23705
+ interceptCall(googleGenerativeAIChannels.sendMessage, "sendMessage"),
23706
+ interceptCall(
23707
+ googleGenerativeAIChannels.sendMessageStream,
23708
+ "sendMessageStream"
23709
+ ),
23710
+ interceptCall(googleGenerativeAIChannels.embedContent, "embedContent"),
23711
+ interceptCall(
23712
+ googleGenerativeAIChannels.batchEmbedContents,
23713
+ "batchEmbedContents"
23714
+ )
23715
+ );
23716
+ }
23717
+ onDisable() {
23718
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
23719
+ }
23720
+ };
23721
+ function interceptCall(channel2, operation) {
23722
+ return channel2.intercept((target, thisArg, args) => {
23723
+ const invokeTarget = () => Reflect.apply(target, thisArg, args);
23724
+ if (isAutoInstrumentationSuppressed()) return invokeTarget();
23725
+ const self = thisArg;
23726
+ const chat = operation.startsWith("sendMessage");
23727
+ const embedding = operation === "embedContent" || operation === "batchEmbedContents";
23728
+ const start = getCurrentUnixTimestamp();
23729
+ let span;
23730
+ try {
23731
+ span = startSpan(
23732
+ withSpanInstrumentationName(
23733
+ {
23734
+ name: embedding ? operation === "embedContent" ? "embed_content" : "batch_embed_contents" : "generate_content",
23735
+ spanAttributes: { type: "llm" /* LLM */ },
23736
+ event: extractInput(self, args[0], operation)
23737
+ },
23738
+ INSTRUMENTATION_NAMES.GOOGLE_GENERATIVE_AI
23739
+ )
23740
+ );
23741
+ } catch (error) {
23742
+ debugLogger.error("Error starting Google Generative AI span:", error);
23743
+ return invokeTarget();
23744
+ }
23745
+ let ended = false;
23746
+ const finish = (log2) => {
23747
+ if (ended) return;
23748
+ ended = true;
23749
+ try {
23750
+ log2();
23751
+ } catch (error) {
23752
+ debugLogger.error("Error logging Google Generative AI span:", error);
23753
+ }
23754
+ try {
23755
+ span.end();
23756
+ } catch (error) {
23757
+ debugLogger.error("Error ending Google Generative AI span:", error);
23758
+ }
23759
+ };
23760
+ if (chat) {
23761
+ try {
23762
+ void self._sendPromise.then(
23763
+ () => {
23764
+ try {
23765
+ span.log(extractInput(self, args[0], operation));
23766
+ } catch (error) {
23767
+ debugLogger.error("Error capturing Google chat history:", error);
23768
+ }
23769
+ },
23770
+ () => {
23771
+ }
23772
+ );
23773
+ } catch (error) {
23774
+ debugLogger.error("Error observing Google chat history:", error);
23775
+ }
23776
+ }
23777
+ let result;
23778
+ try {
23779
+ result = withCurrent(
23780
+ span,
23781
+ () => runWithAutoInstrumentationSuppressed(invokeTarget)
23782
+ );
23783
+ } catch (error) {
23784
+ finish(() => span.log({ error }));
23785
+ throw error;
23786
+ }
23787
+ void Promise.resolve(result).then(
23788
+ (value) => {
23789
+ try {
23790
+ if ("stream" in value) {
23791
+ let firstToken = false;
23792
+ const partial = { candidates: [] };
23793
+ const candidates = /* @__PURE__ */ new Map();
23794
+ patchStreamIfNeeded(value.stream, {
23795
+ aroundNext: (callback) => withCurrent(span, callback),
23796
+ onChunk: (chunk) => {
23797
+ for (const candidate of _nullishCoalesce(chunk.candidates, () => ( []))) {
23798
+ const index = _nullishCoalesce(candidate.index, () => ( 0));
23799
+ const previous = candidates.get(index);
23800
+ const parts = [..._nullishCoalesce(_optionalChain([previous, 'optionalAccess', _521 => _521.content, 'optionalAccess', _522 => _522.parts]), () => ( []))];
23801
+ for (const part of _nullishCoalesce(_optionalChain([candidate, 'access', _523 => _523.content, 'optionalAccess', _524 => _524.parts]), () => ( []))) {
23802
+ const last = parts[parts.length - 1];
23803
+ if (part.text !== void 0 && _optionalChain([last, 'optionalAccess', _525 => _525.text]) !== void 0) {
23804
+ parts[parts.length - 1] = {
23805
+ ...last,
23806
+ text: last.text + part.text
23807
+ };
23808
+ } else parts.push(part);
23809
+ }
23810
+ candidates.set(index, {
23811
+ ...previous,
23812
+ ...candidate,
23813
+ content: {
23814
+ role: _nullishCoalesce(_nullishCoalesce(_optionalChain([candidate, 'access', _526 => _526.content, 'optionalAccess', _527 => _527.role]), () => ( _optionalChain([previous, 'optionalAccess', _528 => _528.content, 'optionalAccess', _529 => _529.role]))), () => ( "model")),
23815
+ parts
23816
+ }
23817
+ });
23818
+ }
23819
+ partial.candidates = Array.from(candidates.values());
23820
+ if (chunk.usageMetadata)
23821
+ partial.usageMetadata = chunk.usageMetadata;
23822
+ if (!firstToken && _optionalChain([chunk, 'access', _530 => _530.candidates, 'optionalAccess', _531 => _531.some, 'call', _532 => _532(
23823
+ (candidate) => _optionalChain([candidate, 'access', _533 => _533.content, 'optionalAccess', _534 => _534.parts, 'access', _535 => _535.some, 'call', _536 => _536(
23824
+ (part) => part.text !== void 0 ? part.text.length > 0 : Object.keys(part).length > 0
23825
+ )])
23826
+ )])) {
23827
+ firstToken = true;
23828
+ span.log({
23829
+ metrics: {
23830
+ time_to_first_token: getCurrentUnixTimestamp() - start
23831
+ }
23832
+ });
23833
+ }
23834
+ },
23835
+ onComplete: () => {
23836
+ },
23837
+ onError: (error) => finish(() => {
23838
+ logResponse(span, partial);
23839
+ span.log({ error });
23840
+ }),
23841
+ onCancel: () => finish(() => logResponse(span, partial))
23842
+ });
23843
+ void value.response.then(
23844
+ (response) => finish(() => logResponse(span, response)),
23845
+ (error) => finish(() => {
23846
+ logResponse(span, partial);
23847
+ span.log({ error });
23848
+ })
23849
+ );
23850
+ } else if ("response" in value) {
23851
+ finish(() => logResponse(span, value.response));
23852
+ } else {
23853
+ const metrics = {};
23854
+ const promptTokens = _optionalChain([value, 'access', _537 => _537.usageMetadata, 'optionalAccess', _538 => _538.promptTokenCount]);
23855
+ if (typeof promptTokens === "number" && Number.isFinite(promptTokens) && promptTokens >= 0) {
23856
+ metrics.prompt_tokens = promptTokens;
23857
+ metrics.tokens = promptTokens;
23858
+ }
23859
+ for (const detail of _nullishCoalesce(_optionalChain([value, 'access', _539 => _539.usageMetadata, 'optionalAccess', _540 => _540.promptTokenDetails]), () => ( []))) {
23860
+ if (detail.modality === "AUDIO" && typeof detail.tokenCount === "number" && Number.isFinite(detail.tokenCount) && detail.tokenCount >= 0) {
23861
+ metrics.prompt_audio_tokens = (_nullishCoalesce(metrics.prompt_audio_tokens, () => ( 0))) + detail.tokenCount;
23862
+ }
23863
+ }
23864
+ finish(
23865
+ () => span.log({
23866
+ metrics,
23867
+ output: {
23868
+ count: _nullishCoalesce(_optionalChain([value, 'access', _541 => _541.embeddings, 'optionalAccess', _542 => _542.length]), () => ( (value.embedding ? 1 : 0)))
23869
+ }
23870
+ })
23871
+ );
23872
+ }
23873
+ } catch (error) {
23874
+ debugLogger.error(
23875
+ "Error observing Google Generative AI result:",
23876
+ error
23877
+ );
23878
+ finish(() => {
23879
+ });
23880
+ }
23881
+ },
23882
+ (error) => finish(() => span.log({ error }))
23883
+ );
23884
+ return result;
23885
+ });
23886
+ }
23887
+ function normalizeContent(message) {
23888
+ const parts = (typeof message === "string" ? [message] : message).map(
23889
+ (part) => typeof part === "string" ? { text: part } : part
23890
+ );
23891
+ return {
23892
+ role: parts.some((part) => part.functionResponse) ? "function" : "user",
23893
+ parts
23894
+ };
23895
+ }
23896
+ function extractInput(self, request, operation) {
23897
+ const model = self.model.replace(/^models\//, "");
23898
+ if (operation === "embedContent" || operation === "batchEmbedContents") {
23899
+ const requests = operation === "batchEmbedContents" ? request.requests : [
23900
+ typeof request === "string" || Array.isArray(request) ? { content: normalizeContent(request) } : request
23901
+ ];
23902
+ const dimensions = _optionalChain([requests, 'access', _543 => _543[0], 'optionalAccess', _544 => _544.outputDimensionality]);
23903
+ return {
23904
+ input: {
23905
+ inputs: convertAttachments(requests).map((item) => ({
23906
+ content: item.content.parts.length === 1 && item.content.parts[0].text !== void 0 ? item.content.parts[0].text : item.content.parts.map((part) => {
23907
+ if (part.text !== void 0)
23908
+ return { type: "text", text: part.text };
23909
+ const mimeType = _nullishCoalesce(_optionalChain([part, 'access', _545 => _545.inlineData, 'optionalAccess', _546 => _546.mimeType]), () => ( _optionalChain([part, 'access', _547 => _547.fileData, 'optionalAccess', _548 => _548.mimeType])));
23910
+ const data = part.inlineData ? typeof part.inlineData.data === "string" ? `data:${mimeType};base64,${part.inlineData.data}` : part.inlineData.data : _optionalChain([part, 'access', _549 => _549.fileData, 'optionalAccess', _550 => _550.fileUri]);
23911
+ return _optionalChain([mimeType, 'optionalAccess', _551 => _551.startsWith, 'call', _552 => _552("image/")]) ? { type: "image_url", image_url: { url: data } } : { type: "file", file: { file_data: data } };
23912
+ })
23913
+ })),
23914
+ ...dimensions !== void 0 && requests.every((item) => item.outputDimensionality === dimensions) ? { output_dimensions: dimensions } : {}
23915
+ },
23916
+ metadata: { model, provider: "google" }
23917
+ };
23918
+ }
23919
+ const chat = operation.startsWith("sendMessage");
23920
+ const config = chat ? _nullishCoalesce(self.params, () => ( {})) : self;
23921
+ const params = typeof request === "string" || Array.isArray(request) ? { contents: [normalizeContent(request)] } : request;
23922
+ const system = _nullishCoalesce(params.systemInstruction, () => ( config.systemInstruction));
23923
+ const systemContent = typeof system === "string" ? { role: "system", parts: [{ text: system }] } : system && "parts" in system ? { ...system, role: "system" } : system ? { role: "system", parts: [system] } : void 0;
23924
+ const contents = [
23925
+ ...systemContent ? [systemContent] : [],
23926
+ ...chat ? self._history : [],
23927
+ ...params.contents
23928
+ ];
23929
+ const metadata = { model, provider: "google" };
23930
+ const generation = _nullishCoalesce(params.generationConfig, () => ( config.generationConfig));
23931
+ for (const key of GENERATION_CONFIG_KEYS) {
23932
+ if (generation && Object.hasOwn(generation, key))
23933
+ metadata[key] = generation[key];
23934
+ }
23935
+ for (const key of ["tools", "toolConfig", "safetySettings"]) {
23936
+ const value = _nullishCoalesce(params[key], () => ( config[key]));
23937
+ if (value !== void 0) metadata[key] = value;
23938
+ }
23939
+ const cached = _nullishCoalesce(params.cachedContent, () => ( config.cachedContent));
23940
+ if (cached)
23941
+ metadata.cachedContent = typeof cached === "string" ? cached : cached.name;
23942
+ return { input: convertAttachments({ model, contents }), metadata };
23943
+ }
23944
+ function convertAttachments(value) {
23945
+ const convert = (node) => {
23946
+ if (Array.isArray(node)) return node.map(convert);
23947
+ if (!isObject(node)) return node;
23948
+ if (isObject(node.inlineData)) {
23949
+ const { data, mimeType } = node.inlineData;
23950
+ const processed = processInputAttachments({
23951
+ type: "file",
23952
+ file: { file_data: `data:${mimeType};base64,${data}` }
23953
+ });
23954
+ if (typeof processed.file.file_data === "string")
23955
+ throw new Error("Unable to convert Google inline data");
23956
+ return {
23957
+ ...node,
23958
+ inlineData: { ...node.inlineData, data: processed.file.file_data }
23959
+ };
23960
+ }
23961
+ return Object.fromEntries(
23962
+ Object.entries(node).map(([key, item]) => [key, convert(item)])
23963
+ );
23964
+ };
23965
+ try {
23966
+ return convert(value);
23967
+ } catch (error) {
23968
+ debugLogger.error(
23969
+ "Error converting Google Generative AI attachments:",
23970
+ error
23971
+ );
23972
+ return value;
23973
+ }
23974
+ }
23975
+ function logResponse(span, response) {
23976
+ const usage = response.usageMetadata;
23977
+ const metrics = {};
23978
+ if (usage) {
23979
+ if (usage.promptTokenCount !== void 0)
23980
+ metrics.prompt_tokens = usage.promptTokenCount;
23981
+ if (usage.candidatesTokenCount !== void 0 || usage.thoughtsTokenCount !== void 0)
23982
+ metrics.completion_tokens = (_nullishCoalesce(usage.candidatesTokenCount, () => ( 0))) + (_nullishCoalesce(usage.thoughtsTokenCount, () => ( 0)));
23983
+ if (usage.totalTokenCount !== void 0)
23984
+ metrics.tokens = usage.totalTokenCount;
23985
+ if (usage.cachedContentTokenCount !== void 0)
23986
+ metrics.prompt_cached_tokens = usage.cachedContentTokenCount;
23987
+ if (usage.thoughtsTokenCount !== void 0)
23988
+ metrics.completion_reasoning_tokens = usage.thoughtsTokenCount;
23989
+ }
23990
+ span.log({
23991
+ output: convertAttachments({
23992
+ candidates: response.candidates,
23993
+ promptFeedback: response.promptFeedback
23994
+ }),
23995
+ metrics,
23996
+ ...response.modelVersion ? { metadata: { model: response.modelVersion } } : {}
23997
+ });
23998
+ }
23999
+
23635
24000
  // src/instrumentation/plugins/google-genai-channels.ts
23636
24001
  var googleGenAIChannels = defineChannels(
23637
24002
  "@google/genai",
@@ -23762,7 +24127,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
23762
24127
  };
23763
24128
  tracingChannel.subscribe(handlers);
23764
24129
  this.unsubscribers.push(() => {
23765
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _521 => _521()]);
24130
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _553 => _553()]);
23766
24131
  tracingChannel.unsubscribe(handlers);
23767
24132
  });
23768
24133
  }
@@ -23869,7 +24234,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
23869
24234
  };
23870
24235
  tracingChannel.subscribe(handlers);
23871
24236
  this.unsubscribers.push(() => {
23872
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _522 => _522()]);
24237
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _554 => _554()]);
23873
24238
  tracingChannel.unsubscribe(handlers);
23874
24239
  });
23875
24240
  }
@@ -23895,7 +24260,7 @@ var GoogleGenAIPlugin = class extends BasePlugin {
23895
24260
  }
23896
24261
  };
23897
24262
  function isBackgroundInteractionCreate(params) {
23898
- return _optionalChain([tryToDict, 'call', _523 => _523(params), 'optionalAccess', _524 => _524.background]) === true;
24263
+ return _optionalChain([tryToDict, 'call', _555 => _555(params), 'optionalAccess', _556 => _556.background]) === true;
23899
24264
  }
23900
24265
  function ensureSpanState(states, event, create) {
23901
24266
  const existing = states.get(event);
@@ -23908,10 +24273,10 @@ function ensureSpanState(states, event, create) {
23908
24273
  }
23909
24274
  function bindCurrentSpanStoreToStart2(tracingChannel, states, create) {
23910
24275
  const state = _internalGetGlobalState();
23911
- const contextManager = _optionalChain([state, 'optionalAccess', _525 => _525.contextManager]);
24276
+ const contextManager = _optionalChain([state, 'optionalAccess', _557 => _557.contextManager]);
23912
24277
  const startChannel = tracingChannel.start;
23913
24278
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
23914
- if (!_optionalChain([startChannel, 'optionalAccess', _526 => _526.bindStore]) || !currentSpanStore) {
24279
+ if (!_optionalChain([startChannel, 'optionalAccess', _558 => _558.bindStore]) || !currentSpanStore) {
23915
24280
  return void 0;
23916
24281
  }
23917
24282
  startChannel.bindStore(currentSpanStore, (event) => {
@@ -23923,7 +24288,7 @@ function bindCurrentSpanStoreToStart2(tracingChannel, states, create) {
23923
24288
  return contextManager.wrapSpanForStore(span);
23924
24289
  });
23925
24290
  return () => {
23926
- _optionalChain([startChannel, 'access', _527 => _527.unbindStore, 'optionalCall', _528 => _528(currentSpanStore)]);
24291
+ _optionalChain([startChannel, 'access', _559 => _559.unbindStore, 'optionalCall', _560 => _560(currentSpanStore)]);
23927
24292
  };
23928
24293
  }
23929
24294
  function logErrorAndEndSpan(states, event) {
@@ -24257,7 +24622,7 @@ function createAttachmentFromInlineData(data, mimeType) {
24257
24622
  }
24258
24623
  function serializeGenerateContentTools(params) {
24259
24624
  const config = params.config ? tryToDict(params.config) : null;
24260
- const tools = _optionalChain([config, 'optionalAccess', _529 => _529.tools]);
24625
+ const tools = _optionalChain([config, 'optionalAccess', _561 => _561.tools]);
24261
24626
  if (!Array.isArray(tools)) {
24262
24627
  return null;
24263
24628
  }
@@ -24316,7 +24681,7 @@ function extractGenerateContentMetrics(response, startTime) {
24316
24681
  metrics.end = end;
24317
24682
  metrics.duration = end - startTime;
24318
24683
  }
24319
- if (_optionalChain([response, 'optionalAccess', _530 => _530.usageMetadata])) {
24684
+ if (_optionalChain([response, 'optionalAccess', _562 => _562.usageMetadata])) {
24320
24685
  populateUsageMetrics(metrics, response.usageMetadata);
24321
24686
  }
24322
24687
  return metrics;
@@ -24329,7 +24694,7 @@ function extractEmbedContentMetrics(response, startTime) {
24329
24694
  metrics.end = end;
24330
24695
  metrics.duration = end - startTime;
24331
24696
  }
24332
- if (_optionalChain([response, 'optionalAccess', _531 => _531.usageMetadata])) {
24697
+ if (_optionalChain([response, 'optionalAccess', _563 => _563.usageMetadata])) {
24333
24698
  populateUsageMetrics(metrics, response.usageMetadata);
24334
24699
  }
24335
24700
  const embeddingTokenCount = extractEmbedPromptTokenCount(response);
@@ -24347,7 +24712,7 @@ function extractInteractionMetrics(response, startTime) {
24347
24712
  metrics.end = end;
24348
24713
  metrics.duration = end - startTime;
24349
24714
  }
24350
- if (_optionalChain([response, 'optionalAccess', _532 => _532.usage])) {
24715
+ if (_optionalChain([response, 'optionalAccess', _564 => _564.usage])) {
24351
24716
  populateInteractionUsageMetrics(metrics, response.usage);
24352
24717
  }
24353
24718
  return metrics;
@@ -24370,11 +24735,11 @@ function extractEmbedPromptTokenCount(response) {
24370
24735
  if (!response) {
24371
24736
  return void 0;
24372
24737
  }
24373
- const usagePromptTokens = _optionalChain([response, 'access', _533 => _533.usageMetadata, 'optionalAccess', _534 => _534.promptTokenCount]);
24738
+ const usagePromptTokens = _optionalChain([response, 'access', _565 => _565.usageMetadata, 'optionalAccess', _566 => _566.promptTokenCount]);
24374
24739
  if (typeof usagePromptTokens === "number" && Number.isFinite(usagePromptTokens)) {
24375
24740
  return usagePromptTokens;
24376
24741
  }
24377
- const usageTotalTokens = _optionalChain([response, 'access', _535 => _535.usageMetadata, 'optionalAccess', _536 => _536.totalTokenCount]);
24742
+ const usageTotalTokens = _optionalChain([response, 'access', _567 => _567.usageMetadata, 'optionalAccess', _568 => _568.totalTokenCount]);
24378
24743
  if (typeof usageTotalTokens === "number" && Number.isFinite(usageTotalTokens)) {
24379
24744
  return usageTotalTokens;
24380
24745
  }
@@ -24385,8 +24750,8 @@ function extractEmbedPromptTokenCount(response) {
24385
24750
  let total = 0;
24386
24751
  let sawAny = false;
24387
24752
  for (const embedding of embeddings) {
24388
- const embeddingStats = tryToDict(_optionalChain([tryToDict, 'call', _537 => _537(embedding), 'optionalAccess', _538 => _538.statistics]));
24389
- const tokenCount2 = _optionalChain([embeddingStats, 'optionalAccess', _539 => _539.tokenCount]);
24753
+ const embeddingStats = tryToDict(_optionalChain([tryToDict, 'call', _569 => _569(embedding), 'optionalAccess', _570 => _570.statistics]));
24754
+ const tokenCount2 = _optionalChain([embeddingStats, 'optionalAccess', _571 => _571.tokenCount]);
24390
24755
  if (typeof tokenCount2 === "number" && Number.isFinite(tokenCount2)) {
24391
24756
  total += tokenCount2;
24392
24757
  sawAny = true;
@@ -24402,7 +24767,7 @@ function summarizeEmbedContentOutput(response) {
24402
24767
  if (embeddings.length === 0) {
24403
24768
  return void 0;
24404
24769
  }
24405
- const firstValues = _optionalChain([embeddings, 'access', _540 => _540[0], 'optionalAccess', _541 => _541.values]);
24770
+ const firstValues = _optionalChain([embeddings, 'access', _572 => _572[0], 'optionalAccess', _573 => _573.values]);
24406
24771
  if (!Array.isArray(firstValues)) {
24407
24772
  return void 0;
24408
24773
  }
@@ -24458,12 +24823,12 @@ function populateInteractionUsageMetrics(metrics, usage) {
24458
24823
  metrics.completion_reasoning_tokens = usage.total_thought_tokens;
24459
24824
  }
24460
24825
  for (const detail of Array.isArray(usage.input_tokens_by_modality) ? usage.input_tokens_by_modality : []) {
24461
- if (typeof _optionalChain([detail, 'optionalAccess', _542 => _542.modality]) === "string" && detail.modality.toLowerCase() === "audio" && typeof detail.tokens === "number") {
24826
+ if (typeof _optionalChain([detail, 'optionalAccess', _574 => _574.modality]) === "string" && detail.modality.toLowerCase() === "audio" && typeof detail.tokens === "number") {
24462
24827
  metrics.prompt_audio_tokens = (_nullishCoalesce(metrics.prompt_audio_tokens, () => ( 0))) + detail.tokens;
24463
24828
  }
24464
24829
  }
24465
24830
  for (const detail of Array.isArray(usage.output_tokens_by_modality) ? usage.output_tokens_by_modality : []) {
24466
- if (typeof _optionalChain([detail, 'optionalAccess', _543 => _543.modality]) !== "string" || typeof detail.tokens !== "number") {
24831
+ if (typeof _optionalChain([detail, 'optionalAccess', _575 => _575.modality]) !== "string" || typeof detail.tokens !== "number") {
24467
24832
  continue;
24468
24833
  }
24469
24834
  switch (detail.modality.toLowerCase()) {
@@ -24505,7 +24870,7 @@ function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
24505
24870
  }
24506
24871
  if (chunk.candidates && Array.isArray(chunk.candidates)) {
24507
24872
  for (const candidate of chunk.candidates) {
24508
- if (_optionalChain([candidate, 'access', _544 => _544.content, 'optionalAccess', _545 => _545.parts])) {
24873
+ if (_optionalChain([candidate, 'access', _576 => _576.content, 'optionalAccess', _577 => _577.parts])) {
24509
24874
  for (const part of candidate.content.parts) {
24510
24875
  if (part.text !== void 0) {
24511
24876
  if (part.thought) {
@@ -24536,7 +24901,7 @@ function aggregateGenerateContentChunks(chunks, startTime, firstTokenTime) {
24536
24901
  parts.push({ text });
24537
24902
  }
24538
24903
  parts.push(...otherParts);
24539
- if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess', _546 => _546.candidates])) {
24904
+ if (parts.length > 0 && _optionalChain([lastResponse, 'optionalAccess', _578 => _578.candidates])) {
24540
24905
  const candidates = [];
24541
24906
  for (const candidate of lastResponse.candidates) {
24542
24907
  const candidateDict = {
@@ -24658,16 +25023,16 @@ function aggregateInteractionEvents(chunks, startTime) {
24658
25023
  }
24659
25024
  function extractInteractionUsageFromEvent(event) {
24660
25025
  const metadata = tryToDict(event.metadata);
24661
- const metadataUsage = tryToDict(_optionalChain([metadata, 'optionalAccess', _547 => _547.usage]));
25026
+ const metadataUsage = tryToDict(_optionalChain([metadata, 'optionalAccess', _579 => _579.usage]));
24662
25027
  if (metadataUsage) {
24663
25028
  return metadataUsage;
24664
25029
  }
24665
- const metadataTotalUsage = tryToDict(_optionalChain([metadata, 'optionalAccess', _548 => _548.total_usage]));
25030
+ const metadataTotalUsage = tryToDict(_optionalChain([metadata, 'optionalAccess', _580 => _580.total_usage]));
24666
25031
  if (metadataTotalUsage) {
24667
25032
  return metadataTotalUsage;
24668
25033
  }
24669
25034
  const interaction = tryToDict(event.interaction);
24670
- const interactionUsage = tryToDict(_optionalChain([interaction, 'optionalAccess', _549 => _549.usage]));
25035
+ const interactionUsage = tryToDict(_optionalChain([interaction, 'optionalAccess', _581 => _581.usage]));
24671
25036
  return interactionUsage ? interactionUsage : void 0;
24672
25037
  }
24673
25038
  function compactInteractionStep(step) {
@@ -24733,7 +25098,7 @@ function extractResponseMetadata(response) {
24733
25098
  if (Array.isArray(responseDict.candidates)) {
24734
25099
  for (const candidate of responseDict.candidates) {
24735
25100
  const candidateDict = tryToDict(candidate);
24736
- if (_optionalChain([candidateDict, 'optionalAccess', _550 => _550.groundingMetadata]) !== void 0) {
25101
+ if (_optionalChain([candidateDict, 'optionalAccess', _582 => _582.groundingMetadata]) !== void 0) {
24737
25102
  candidateGroundingMetadata.push(candidateDict.groundingMetadata);
24738
25103
  }
24739
25104
  }
@@ -24818,9 +25183,9 @@ var HuggingFacePlugin = class extends BasePlugin {
24818
25183
  name: "huggingface.chat_completion",
24819
25184
  type: "llm" /* LLM */,
24820
25185
  extractInput: extractChatInputWithMetadata,
24821
- extractOutput: (result) => _optionalChain([result, 'optionalAccess', _551 => _551.choices]),
25186
+ extractOutput: (result) => _optionalChain([result, 'optionalAccess', _583 => _583.choices]),
24822
25187
  extractMetadata: (result) => extractResponseMetadata2(result),
24823
- extractMetrics: (result) => parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _552 => _552.usage]))
25188
+ extractMetrics: (result) => parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _584 => _584.usage]))
24824
25189
  }),
24825
25190
  traceSyncStreamChannel(huggingFaceChannels.chatCompletionStream, {
24826
25191
  name: "huggingface.chat_completion_stream",
@@ -24838,7 +25203,7 @@ var HuggingFacePlugin = class extends BasePlugin {
24838
25203
  extractInput: extractTextGenerationInputWithMetadata,
24839
25204
  extractOutput: (result) => isObject(result) ? { generated_text: result.generated_text } : result,
24840
25205
  extractMetadata: extractTextGenerationMetadata,
24841
- extractMetrics: (result) => extractTextGenerationMetrics(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _553 => _553.details]), () => ( null)))
25206
+ extractMetrics: (result) => extractTextGenerationMetrics(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _585 => _585.details]), () => ( null)))
24842
25207
  }),
24843
25208
  traceSyncStreamChannel(huggingFaceChannels.textGenerationStream, {
24844
25209
  name: "huggingface.text_generation_stream",
@@ -24957,7 +25322,7 @@ function extractTextGenerationMetrics(details) {
24957
25322
  return metrics;
24958
25323
  }
24959
25324
  function extractTextGenerationMetadata(result) {
24960
- if (!isObject(_optionalChain([result, 'optionalAccess', _554 => _554.details]))) {
25325
+ if (!isObject(_optionalChain([result, 'optionalAccess', _586 => _586.details]))) {
24961
25326
  return void 0;
24962
25327
  }
24963
25328
  return typeof result.details.finish_reason === "string" ? {
@@ -25003,7 +25368,7 @@ function patchChatCompletionStream(args) {
25003
25368
  const lastChunk = chunks.at(-1);
25004
25369
  const responseMetadata = extractResponseMetadata2(lastChunk);
25005
25370
  const metrics = {
25006
- ...parseMetricsFromUsage(_optionalChain([lastChunk, 'optionalAccess', _555 => _555.usage])),
25371
+ ...parseMetricsFromUsage(_optionalChain([lastChunk, 'optionalAccess', _587 => _587.usage])),
25007
25372
  ...firstChunkTime !== void 0 ? { time_to_first_token: firstChunkTime - startTime } : {}
25008
25373
  };
25009
25374
  span.log({
@@ -25041,8 +25406,8 @@ function patchTextGenerationStream(args) {
25041
25406
  output: aggregateTextGenerationStreamChunks(chunks),
25042
25407
  ...streamMetadata ? { metadata: streamMetadata } : {},
25043
25408
  metrics: {
25044
- ...extractTextGenerationMetrics(_nullishCoalesce(_optionalChain([lastChunk, 'optionalAccess', _556 => _556.details]), () => ( null))),
25045
- ...parseMetricsFromUsage(_optionalChain([lastChunk, 'optionalAccess', _557 => _557.usage])),
25409
+ ...extractTextGenerationMetrics(_nullishCoalesce(_optionalChain([lastChunk, 'optionalAccess', _588 => _588.details]), () => ( null))),
25410
+ ...parseMetricsFromUsage(_optionalChain([lastChunk, 'optionalAccess', _589 => _589.usage])),
25046
25411
  ...firstChunkTime !== void 0 ? { time_to_first_token: firstChunkTime - startTime } : {}
25047
25412
  }
25048
25413
  });
@@ -25071,14 +25436,14 @@ function aggregateChatCompletionChunks2(chunks) {
25071
25436
  }));
25072
25437
  const delta = isObject(choice.delta) ? choice.delta : void 0;
25073
25438
  const message = isObject(choice.message) ? choice.message : void 0;
25074
- if (typeof _optionalChain([delta, 'optionalAccess', _558 => _558.content]) === "string") {
25439
+ if (typeof _optionalChain([delta, 'optionalAccess', _590 => _590.content]) === "string") {
25075
25440
  existing.content += delta.content;
25076
- } else if (typeof _optionalChain([message, 'optionalAccess', _559 => _559.content]) === "string") {
25441
+ } else if (typeof _optionalChain([message, 'optionalAccess', _591 => _591.content]) === "string") {
25077
25442
  existing.content = message.content;
25078
25443
  }
25079
- if (typeof _optionalChain([delta, 'optionalAccess', _560 => _560.role]) === "string") {
25444
+ if (typeof _optionalChain([delta, 'optionalAccess', _592 => _592.role]) === "string") {
25080
25445
  existing.role = delta.role;
25081
- } else if (typeof _optionalChain([message, 'optionalAccess', _561 => _561.role]) === "string") {
25446
+ } else if (typeof _optionalChain([message, 'optionalAccess', _593 => _593.role]) === "string") {
25082
25447
  existing.role = message.role;
25083
25448
  }
25084
25449
  if (choice.finish_reason !== void 0) {
@@ -25106,7 +25471,7 @@ function aggregateChatCompletionChunks2(chunks) {
25106
25471
  };
25107
25472
  }
25108
25473
  function getChatToolCallDeltas(value) {
25109
- if (!Array.isArray(_optionalChain([value, 'optionalAccess', _562 => _562.tool_calls]))) {
25474
+ if (!Array.isArray(_optionalChain([value, 'optionalAccess', _594 => _594.tool_calls]))) {
25110
25475
  return void 0;
25111
25476
  }
25112
25477
  const toolCalls = value.tool_calls.filter((toolCall) => isObject(toolCall));
@@ -25171,7 +25536,7 @@ function aggregateTextGenerationStreamChunks(chunks) {
25171
25536
  for (const chunk of chunks) {
25172
25537
  if (typeof chunk.generated_text === "string") {
25173
25538
  generatedText = chunk.generated_text;
25174
- } else if (typeof _optionalChain([chunk, 'access', _563 => _563.token, 'optionalAccess', _564 => _564.text]) === "string" && !chunk.token.special) {
25539
+ } else if (typeof _optionalChain([chunk, 'access', _595 => _595.token, 'optionalAccess', _596 => _596.text]) === "string" && !chunk.token.special) {
25175
25540
  generatedText += chunk.token.text;
25176
25541
  } else if (Array.isArray(chunk.choices)) {
25177
25542
  for (const choice of chunk.choices) {
@@ -25195,17 +25560,17 @@ function aggregateTextGenerationStreamChunks(chunks) {
25195
25560
  function extractTextGenerationStreamMetadata(chunks) {
25196
25561
  for (let index = chunks.length - 1; index >= 0; index--) {
25197
25562
  const chunk = chunks[index];
25198
- if (isObject(_optionalChain([chunk, 'optionalAccess', _565 => _565.details])) && typeof chunk.details.finish_reason === "string") {
25563
+ if (isObject(_optionalChain([chunk, 'optionalAccess', _597 => _597.details])) && typeof chunk.details.finish_reason === "string") {
25199
25564
  return {
25200
25565
  finish_reason: chunk.details.finish_reason
25201
25566
  };
25202
25567
  }
25203
- if (!Array.isArray(_optionalChain([chunk, 'optionalAccess', _566 => _566.choices]))) {
25568
+ if (!Array.isArray(_optionalChain([chunk, 'optionalAccess', _598 => _598.choices]))) {
25204
25569
  continue;
25205
25570
  }
25206
25571
  for (let choiceIndex = chunk.choices.length - 1; choiceIndex >= 0; choiceIndex--) {
25207
25572
  const choice = chunk.choices[choiceIndex];
25208
- if (_optionalChain([choice, 'optionalAccess', _567 => _567.finish_reason]) !== void 0) {
25573
+ if (_optionalChain([choice, 'optionalAccess', _599 => _599.finish_reason]) !== void 0) {
25209
25574
  return { finish_reason: choice.finish_reason };
25210
25575
  }
25211
25576
  }
@@ -25267,7 +25632,7 @@ var HuggingFaceTransformersPlugin = class extends BasePlugin {
25267
25632
  traceAsyncChannel(huggingFaceTransformersChannels.pipelineCall, {
25268
25633
  name: (_args, event) => {
25269
25634
  const task = getTask(event);
25270
- const operation = _nullishCoalesce(_optionalChain([task, 'optionalAccess', _568 => _568.replaceAll, 'call', _569 => _569("-", "_")]), () => ( "unknown"));
25635
+ const operation = _nullishCoalesce(_optionalChain([task, 'optionalAccess', _600 => _600.replaceAll, 'call', _601 => _601("-", "_")]), () => ( "unknown"));
25271
25636
  return `huggingface.transformers.${operation}`;
25272
25637
  },
25273
25638
  type: "llm" /* LLM */,
@@ -25275,7 +25640,7 @@ var HuggingFaceTransformersPlugin = class extends BasePlugin {
25275
25640
  getTask(event)
25276
25641
  ),
25277
25642
  extractInput: (args, event) => ({
25278
- input: extractInput(
25643
+ input: extractInput2(
25279
25644
  getTask(event),
25280
25645
  args
25281
25646
  ),
@@ -25304,8 +25669,8 @@ var HuggingFaceTransformersPlugin = class extends BasePlugin {
25304
25669
  }
25305
25670
  registerHuggingFaceTransformersPipeline(
25306
25671
  event.result,
25307
- _optionalChain([event, 'access', _570 => _570.arguments, 'optionalAccess', _571 => _571[0]]),
25308
- _optionalChain([event, 'access', _572 => _572.arguments, 'optionalAccess', _573 => _573[1]])
25672
+ _optionalChain([event, 'access', _602 => _602.arguments, 'optionalAccess', _603 => _603[0]]),
25673
+ _optionalChain([event, 'access', _604 => _604.arguments, 'optionalAccess', _605 => _605[1]])
25309
25674
  );
25310
25675
  }
25311
25676
  };
@@ -25315,11 +25680,11 @@ var HuggingFaceTransformersPlugin = class extends BasePlugin {
25315
25680
  };
25316
25681
  function getTask(event) {
25317
25682
  const self = event.self;
25318
- const registeredTask = _optionalChain([getHuggingFaceTransformersPipelineInfo, 'call', _574 => _574(self), 'optionalAccess', _575 => _575.task]);
25683
+ const registeredTask = _optionalChain([getHuggingFaceTransformersPipelineInfo, 'call', _606 => _606(self), 'optionalAccess', _607 => _607.task]);
25319
25684
  if (registeredTask !== void 0) {
25320
25685
  return registeredTask;
25321
25686
  }
25322
- if (typeof _optionalChain([self, 'optionalAccess', _576 => _576.task]) === "string") {
25687
+ if (typeof _optionalChain([self, 'optionalAccess', _608 => _608.task]) === "string") {
25323
25688
  return self.task;
25324
25689
  }
25325
25690
  return void 0;
@@ -25328,9 +25693,9 @@ function extractMetadata(event, args) {
25328
25693
  const metadata = {
25329
25694
  provider: "huggingface"
25330
25695
  };
25331
- const registeredModel = _optionalChain([getHuggingFaceTransformersPipelineInfo, 'call', _577 => _577(
25696
+ const registeredModel = _optionalChain([getHuggingFaceTransformersPipelineInfo, 'call', _609 => _609(
25332
25697
  event.self
25333
- ), 'optionalAccess', _578 => _578.model]);
25698
+ ), 'optionalAccess', _610 => _610.model]);
25334
25699
  const model = _nullishCoalesce(registeredModel, () => ( modelIdentifier(event.self)));
25335
25700
  if (model) {
25336
25701
  metadata.model = model;
@@ -25347,16 +25712,16 @@ function extractMetadata(event, args) {
25347
25712
  return metadata;
25348
25713
  }
25349
25714
  function modelIdentifier(pipeline) {
25350
- const model = _optionalChain([pipeline, 'optionalAccess', _579 => _579.model]);
25715
+ const model = _optionalChain([pipeline, 'optionalAccess', _611 => _611.model]);
25351
25716
  if (!isObject(model)) {
25352
25717
  return void 0;
25353
25718
  }
25354
25719
  const config = isObject(model.config) ? model.config : void 0;
25355
25720
  for (const value of [
25356
- _optionalChain([config, 'optionalAccess', _580 => _580._name_or_path]),
25357
- _optionalChain([config, 'optionalAccess', _581 => _581.name_or_path]),
25358
- _optionalChain([config, 'optionalAccess', _582 => _582.model_id]),
25359
- _optionalChain([config, 'optionalAccess', _583 => _583.modelId]),
25721
+ _optionalChain([config, 'optionalAccess', _612 => _612._name_or_path]),
25722
+ _optionalChain([config, 'optionalAccess', _613 => _613.name_or_path]),
25723
+ _optionalChain([config, 'optionalAccess', _614 => _614.model_id]),
25724
+ _optionalChain([config, 'optionalAccess', _615 => _615.modelId]),
25360
25725
  model.name
25361
25726
  ]) {
25362
25727
  if (typeof value === "string" && value.length > 0) {
@@ -25365,7 +25730,7 @@ function modelIdentifier(pipeline) {
25365
25730
  }
25366
25731
  return void 0;
25367
25732
  }
25368
- function extractInput(task, args) {
25733
+ function extractInput2(task, args) {
25369
25734
  switch (task) {
25370
25735
  case "feature-extraction":
25371
25736
  return args[0];
@@ -25487,7 +25852,7 @@ function choicesFromGenerations(result) {
25487
25852
  if (typeof generated === "string") {
25488
25853
  content = generated;
25489
25854
  } else if (isChat(generated)) {
25490
- content = _optionalChain([generated, 'access', _584 => _584.at, 'call', _585 => _585(-1), 'optionalAccess', _586 => _586.content]);
25855
+ content = _optionalChain([generated, 'access', _616 => _616.at, 'call', _617 => _617(-1), 'optionalAccess', _618 => _618.content]);
25491
25856
  }
25492
25857
  if (typeof content !== "string") {
25493
25858
  return [];
@@ -25578,14 +25943,14 @@ var OpenRouterAgentPlugin = class extends BasePlugin {
25578
25943
  extractMetadata: (result, event) => {
25579
25944
  if (!isObject(result)) {
25580
25945
  return {
25581
- step: _optionalChain([event, 'optionalAccess', _587 => _587.step]),
25582
- step_type: _optionalChain([event, 'optionalAccess', _588 => _588.stepType])
25946
+ step: _optionalChain([event, 'optionalAccess', _619 => _619.step]),
25947
+ step_type: _optionalChain([event, 'optionalAccess', _620 => _620.stepType])
25583
25948
  };
25584
25949
  }
25585
25950
  return {
25586
25951
  ...extractOpenRouterResponseMetadata(result) || {},
25587
- ..._optionalChain([event, 'optionalAccess', _589 => _589.step]) !== void 0 ? { step: event.step } : {},
25588
- ..._optionalChain([event, 'optionalAccess', _590 => _590.stepType]) ? { step_type: event.stepType } : {}
25952
+ ..._optionalChain([event, 'optionalAccess', _621 => _621.step]) !== void 0 ? { step: event.step } : {},
25953
+ ..._optionalChain([event, 'optionalAccess', _622 => _622.stepType]) ? { step_type: event.stepType } : {}
25589
25954
  };
25590
25955
  },
25591
25956
  extractMetrics: (result) => isObject(result) ? parseOpenRouterMetricsFromUsage(result.usage) : {}
@@ -25946,7 +26311,7 @@ function publishToolResult(tracingChannel, event, result) {
25946
26311
  }
25947
26312
  function getToolCallId(context) {
25948
26313
  const toolContext = context;
25949
- return typeof _optionalChain([toolContext, 'optionalAccess', _591 => _591.toolCall, 'optionalAccess', _592 => _592.id]) === "string" ? toolContext.toolCall.id : void 0;
26314
+ return typeof _optionalChain([toolContext, 'optionalAccess', _623 => _623.toolCall, 'optionalAccess', _624 => _624.id]) === "string" ? toolContext.toolCall.id : void 0;
25950
26315
  }
25951
26316
  var OPENROUTER_WRAPPED_CALL_MODEL_RESULT = /* @__PURE__ */ Symbol(
25952
26317
  "braintrust.openrouter.wrappedCallModelResult"
@@ -26344,9 +26709,9 @@ var OpenRouterPlugin = class extends BasePlugin {
26344
26709
  type: "llm" /* LLM */,
26345
26710
  extractInput: (args) => {
26346
26711
  const request = getOpenRouterRequestArg(args);
26347
- const chatGenerationParams = isObject(_optionalChain([request, 'optionalAccess', _593 => _593.chatGenerationParams])) ? request.chatGenerationParams : {};
26348
- const httpReferer = _optionalChain([request, 'optionalAccess', _594 => _594.httpReferer]);
26349
- const xTitle = _optionalChain([request, 'optionalAccess', _595 => _595.xTitle]);
26712
+ const chatGenerationParams = isObject(_optionalChain([request, 'optionalAccess', _625 => _625.chatGenerationParams])) ? request.chatGenerationParams : {};
26713
+ const httpReferer = _optionalChain([request, 'optionalAccess', _626 => _626.httpReferer]);
26714
+ const xTitle = _optionalChain([request, 'optionalAccess', _627 => _627.xTitle]);
26350
26715
  const { messages, ...metadata } = chatGenerationParams;
26351
26716
  return {
26352
26717
  input: messages,
@@ -26357,7 +26722,7 @@ var OpenRouterPlugin = class extends BasePlugin {
26357
26722
  return isObject(result) ? result.choices : void 0;
26358
26723
  },
26359
26724
  extractMetrics: (result, startTime) => {
26360
- const metrics = parseOpenRouterMetricsFromUsage2(_optionalChain([result, 'optionalAccess', _596 => _596.usage]));
26725
+ const metrics = parseOpenRouterMetricsFromUsage2(_optionalChain([result, 'optionalAccess', _628 => _628.usage]));
26361
26726
  if (startTime) {
26362
26727
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
26363
26728
  }
@@ -26372,9 +26737,9 @@ var OpenRouterPlugin = class extends BasePlugin {
26372
26737
  type: "llm" /* LLM */,
26373
26738
  extractInput: (args) => {
26374
26739
  const request = getOpenRouterRequestArg(args);
26375
- const requestBody = isObject(_optionalChain([request, 'optionalAccess', _597 => _597.requestBody])) ? request.requestBody : {};
26376
- const httpReferer = _optionalChain([request, 'optionalAccess', _598 => _598.httpReferer]);
26377
- const xTitle = _optionalChain([request, 'optionalAccess', _599 => _599.xTitle]);
26740
+ const requestBody = isObject(_optionalChain([request, 'optionalAccess', _629 => _629.requestBody])) ? request.requestBody : {};
26741
+ const httpReferer = _optionalChain([request, 'optionalAccess', _630 => _630.httpReferer]);
26742
+ const xTitle = _optionalChain([request, 'optionalAccess', _631 => _631.xTitle]);
26378
26743
  const { input, ...metadata } = requestBody;
26379
26744
  return {
26380
26745
  input,
@@ -26389,7 +26754,7 @@ var OpenRouterPlugin = class extends BasePlugin {
26389
26754
  if (!isObject(result)) {
26390
26755
  return void 0;
26391
26756
  }
26392
- const embedding = _optionalChain([result, 'access', _600 => _600.data, 'optionalAccess', _601 => _601[0], 'optionalAccess', _602 => _602.embedding]);
26757
+ const embedding = _optionalChain([result, 'access', _632 => _632.data, 'optionalAccess', _633 => _633[0], 'optionalAccess', _634 => _634.embedding]);
26393
26758
  return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
26394
26759
  },
26395
26760
  extractMetadata: (result) => {
@@ -26409,9 +26774,9 @@ var OpenRouterPlugin = class extends BasePlugin {
26409
26774
  type: "llm" /* LLM */,
26410
26775
  extractInput: (args) => {
26411
26776
  const request = getOpenRouterRequestArg(args);
26412
- const requestBody = isObject(_optionalChain([request, 'optionalAccess', _603 => _603.requestBody])) ? request.requestBody : {};
26413
- const httpReferer = _optionalChain([request, 'optionalAccess', _604 => _604.httpReferer]);
26414
- const xTitle = _nullishCoalesce(_optionalChain([request, 'optionalAccess', _605 => _605.xTitle]), () => ( _optionalChain([request, 'optionalAccess', _606 => _606.appTitle])));
26777
+ const requestBody = isObject(_optionalChain([request, 'optionalAccess', _635 => _635.requestBody])) ? request.requestBody : {};
26778
+ const httpReferer = _optionalChain([request, 'optionalAccess', _636 => _636.httpReferer]);
26779
+ const xTitle = _nullishCoalesce(_optionalChain([request, 'optionalAccess', _637 => _637.xTitle]), () => ( _optionalChain([request, 'optionalAccess', _638 => _638.appTitle])));
26415
26780
  const { documents, query, ...metadata } = requestBody;
26416
26781
  return {
26417
26782
  input: {
@@ -26437,9 +26802,9 @@ var OpenRouterPlugin = class extends BasePlugin {
26437
26802
  type: "llm" /* LLM */,
26438
26803
  extractInput: (args) => {
26439
26804
  const request = getOpenRouterRequestArg(args);
26440
- const openResponsesRequest = isObject(_optionalChain([request, 'optionalAccess', _607 => _607.openResponsesRequest])) ? request.openResponsesRequest : {};
26441
- const httpReferer = _optionalChain([request, 'optionalAccess', _608 => _608.httpReferer]);
26442
- const xTitle = _optionalChain([request, 'optionalAccess', _609 => _609.xTitle]);
26805
+ const openResponsesRequest = isObject(_optionalChain([request, 'optionalAccess', _639 => _639.openResponsesRequest])) ? request.openResponsesRequest : {};
26806
+ const httpReferer = _optionalChain([request, 'optionalAccess', _640 => _640.httpReferer]);
26807
+ const xTitle = _optionalChain([request, 'optionalAccess', _641 => _641.xTitle]);
26443
26808
  const { input, ...metadata } = openResponsesRequest;
26444
26809
  return {
26445
26810
  input,
@@ -26449,7 +26814,7 @@ var OpenRouterPlugin = class extends BasePlugin {
26449
26814
  extractOutput: (result) => extractOpenRouterResponseOutput2(result),
26450
26815
  extractMetadata: (result) => extractOpenRouterResponseMetadata2(result),
26451
26816
  extractMetrics: (result, startTime) => {
26452
- const metrics = parseOpenRouterMetricsFromUsage2(_optionalChain([result, 'optionalAccess', _610 => _610.usage]));
26817
+ const metrics = parseOpenRouterMetricsFromUsage2(_optionalChain([result, 'optionalAccess', _642 => _642.usage]));
26453
26818
  if (startTime) {
26454
26819
  metrics.time_to_first_token = getCurrentUnixTimestamp() - startTime;
26455
26820
  }
@@ -26501,14 +26866,14 @@ var OpenRouterPlugin = class extends BasePlugin {
26501
26866
  extractMetadata: (result, event) => {
26502
26867
  if (!isObject(result)) {
26503
26868
  return {
26504
- step: _optionalChain([event, 'optionalAccess', _611 => _611.step]),
26505
- step_type: _optionalChain([event, 'optionalAccess', _612 => _612.stepType])
26869
+ step: _optionalChain([event, 'optionalAccess', _643 => _643.step]),
26870
+ step_type: _optionalChain([event, 'optionalAccess', _644 => _644.stepType])
26506
26871
  };
26507
26872
  }
26508
26873
  return {
26509
26874
  ...extractOpenRouterResponseMetadata2(result) || {},
26510
- ..._optionalChain([event, 'optionalAccess', _613 => _613.step]) !== void 0 ? { step: event.step } : {},
26511
- ..._optionalChain([event, 'optionalAccess', _614 => _614.stepType]) ? { step_type: event.stepType } : {}
26875
+ ..._optionalChain([event, 'optionalAccess', _645 => _645.step]) !== void 0 ? { step: event.step } : {},
26876
+ ..._optionalChain([event, 'optionalAccess', _646 => _646.stepType]) ? { step_type: event.stepType } : {}
26512
26877
  };
26513
26878
  },
26514
26879
  extractMetrics: (result) => isObject(result) ? parseOpenRouterMetricsFromUsage2(result.usage) : {}
@@ -26888,7 +27253,7 @@ function publishToolResult2(tracingChannel, event, result) {
26888
27253
  }
26889
27254
  function getToolCallId2(context) {
26890
27255
  const toolContext = context;
26891
- return typeof _optionalChain([toolContext, 'optionalAccess', _615 => _615.toolCall, 'optionalAccess', _616 => _616.id]) === "string" ? toolContext.toolCall.id : void 0;
27256
+ return typeof _optionalChain([toolContext, 'optionalAccess', _647 => _647.toolCall, 'optionalAccess', _648 => _648.id]) === "string" ? toolContext.toolCall.id : void 0;
26892
27257
  }
26893
27258
  function aggregateOpenRouterChatChunks(chunks) {
26894
27259
  let role;
@@ -26904,12 +27269,12 @@ function aggregateOpenRouterChatChunks(chunks) {
26904
27269
  for (const chunk of chunks) {
26905
27270
  metrics = {
26906
27271
  ...metrics,
26907
- ...parseOpenRouterMetricsFromUsage2(_optionalChain([chunk, 'optionalAccess', _617 => _617.usage]))
27272
+ ...parseOpenRouterMetricsFromUsage2(_optionalChain([chunk, 'optionalAccess', _649 => _649.usage]))
26908
27273
  };
26909
- const choice = _optionalChain([chunk, 'optionalAccess', _618 => _618.choices, 'optionalAccess', _619 => _619[0]]);
26910
- const delta = _optionalChain([choice, 'optionalAccess', _620 => _620.delta]);
27274
+ const choice = _optionalChain([chunk, 'optionalAccess', _650 => _650.choices, 'optionalAccess', _651 => _651[0]]);
27275
+ const delta = _optionalChain([choice, 'optionalAccess', _652 => _652.delta]);
26911
27276
  if (!delta) {
26912
- if (_optionalChain([choice, 'optionalAccess', _621 => _621.finish_reason]) !== void 0) {
27277
+ if (_optionalChain([choice, 'optionalAccess', _653 => _653.finish_reason]) !== void 0) {
26913
27278
  finishReason = choice.finish_reason;
26914
27279
  }
26915
27280
  continue;
@@ -26935,7 +27300,7 @@ function aggregateOpenRouterChatChunks(chunks) {
26935
27300
  ...delta.reasoning_details
26936
27301
  ];
26937
27302
  }
26938
- const choiceFinishReason = _nullishCoalesce(_nullishCoalesce(_optionalChain([choice, 'optionalAccess', _622 => _622.finishReason]), () => ( _optionalChain([choice, 'optionalAccess', _623 => _623.finish_reason]))), () => ( void 0));
27303
+ const choiceFinishReason = _nullishCoalesce(_nullishCoalesce(_optionalChain([choice, 'optionalAccess', _654 => _654.finishReason]), () => ( _optionalChain([choice, 'optionalAccess', _655 => _655.finish_reason]))), () => ( void 0));
26939
27304
  const deltaFinishReason = _nullishCoalesce(_nullishCoalesce(delta.finishReason, () => ( delta.finish_reason)), () => ( void 0));
26940
27305
  if (choiceFinishReason !== void 0) {
26941
27306
  finishReason = choiceFinishReason;
@@ -26947,11 +27312,11 @@ function aggregateOpenRouterChatChunks(chunks) {
26947
27312
  continue;
26948
27313
  }
26949
27314
  for (const toolDelta of toolCallDeltas) {
26950
- if (!_optionalChain([toolDelta, 'optionalAccess', _624 => _624.function])) {
27315
+ if (!_optionalChain([toolDelta, 'optionalAccess', _656 => _656.function])) {
26951
27316
  continue;
26952
27317
  }
26953
27318
  const toolIndex = _nullishCoalesce(toolDelta.index, () => ( 0));
26954
- const existingToolCall = _optionalChain([toolCalls, 'optionalAccess', _625 => _625[toolIndex]]);
27319
+ const existingToolCall = _optionalChain([toolCalls, 'optionalAccess', _657 => _657[toolIndex]]);
26955
27320
  if (!existingToolCall || toolDelta.id && existingToolCall.id !== void 0 && existingToolCall.id !== toolDelta.id) {
26956
27321
  const nextToolCalls = [...toolCalls || []];
26957
27322
  nextToolCalls[toolIndex] = {
@@ -27001,7 +27366,7 @@ function aggregateOpenRouterChatChunks(chunks) {
27001
27366
  function aggregateOpenRouterResponseStreamEvents(chunks) {
27002
27367
  let finalResponse;
27003
27368
  for (const chunk of chunks) {
27004
- const response = _optionalChain([chunk, 'optionalAccess', _626 => _626.response]);
27369
+ const response = _optionalChain([chunk, 'optionalAccess', _658 => _658.response]);
27005
27370
  if (!response) {
27006
27371
  continue;
27007
27372
  }
@@ -27433,10 +27798,10 @@ var MistralPlugin = class extends BasePlugin {
27433
27798
  type: "llm" /* LLM */,
27434
27799
  extractInput: extractMessagesInputWithMetadata,
27435
27800
  extractOutput: (result) => {
27436
- return _optionalChain([result, 'optionalAccess', _627 => _627.choices]);
27801
+ return _optionalChain([result, 'optionalAccess', _659 => _659.choices]);
27437
27802
  },
27438
27803
  extractMetadata: (result) => extractMistralResponseMetadata(result),
27439
- extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _628 => _628.usage]), startTime)
27804
+ extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _660 => _660.usage]), startTime)
27440
27805
  })
27441
27806
  );
27442
27807
  this.unsubscribers.push(
@@ -27456,11 +27821,11 @@ var MistralPlugin = class extends BasePlugin {
27456
27821
  type: "llm" /* LLM */,
27457
27822
  extractInput: extractEmbeddingInputWithMetadata,
27458
27823
  extractOutput: (result) => {
27459
- const embedding = _optionalChain([result, 'optionalAccess', _629 => _629.data, 'optionalAccess', _630 => _630[0], 'optionalAccess', _631 => _631.embedding]);
27824
+ const embedding = _optionalChain([result, 'optionalAccess', _661 => _661.data, 'optionalAccess', _662 => _662[0], 'optionalAccess', _663 => _663.embedding]);
27460
27825
  return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
27461
27826
  },
27462
27827
  extractMetadata: (result) => extractMistralResponseMetadata(result),
27463
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _632 => _632.usage]))
27828
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _664 => _664.usage]))
27464
27829
  })
27465
27830
  );
27466
27831
  this.unsubscribers.push(
@@ -27470,7 +27835,7 @@ var MistralPlugin = class extends BasePlugin {
27470
27835
  extractInput: extractClassifierInputWithMetadata,
27471
27836
  extractOutput: extractClassifierOutput,
27472
27837
  extractMetadata: (result) => extractMistralResponseMetadata(result),
27473
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _633 => _633.usage]))
27838
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _665 => _665.usage]))
27474
27839
  })
27475
27840
  );
27476
27841
  this.unsubscribers.push(
@@ -27480,7 +27845,7 @@ var MistralPlugin = class extends BasePlugin {
27480
27845
  extractInput: extractClassifierInputWithMetadata,
27481
27846
  extractOutput: extractClassifierOutput,
27482
27847
  extractMetadata: (result) => extractMistralResponseMetadata(result),
27483
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _634 => _634.usage]))
27848
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _666 => _666.usage]))
27484
27849
  })
27485
27850
  );
27486
27851
  this.unsubscribers.push(
@@ -27490,7 +27855,7 @@ var MistralPlugin = class extends BasePlugin {
27490
27855
  extractInput: extractClassifierInputWithMetadata,
27491
27856
  extractOutput: extractClassifierOutput,
27492
27857
  extractMetadata: (result) => extractMistralResponseMetadata(result),
27493
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _635 => _635.usage]))
27858
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _667 => _667.usage]))
27494
27859
  })
27495
27860
  );
27496
27861
  this.unsubscribers.push(
@@ -27500,7 +27865,7 @@ var MistralPlugin = class extends BasePlugin {
27500
27865
  extractInput: extractClassifierInputWithMetadata,
27501
27866
  extractOutput: extractClassifierOutput,
27502
27867
  extractMetadata: (result) => extractMistralResponseMetadata(result),
27503
- extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _636 => _636.usage]))
27868
+ extractMetrics: (result) => parseMistralMetricsFromUsage(_optionalChain([result, 'optionalAccess', _668 => _668.usage]))
27504
27869
  })
27505
27870
  );
27506
27871
  this.unsubscribers.push(
@@ -27509,10 +27874,10 @@ var MistralPlugin = class extends BasePlugin {
27509
27874
  type: "llm" /* LLM */,
27510
27875
  extractInput: extractPromptInputWithMetadata,
27511
27876
  extractOutput: (result) => {
27512
- return _optionalChain([result, 'optionalAccess', _637 => _637.choices]);
27877
+ return _optionalChain([result, 'optionalAccess', _669 => _669.choices]);
27513
27878
  },
27514
27879
  extractMetadata: (result) => extractMistralResponseMetadata(result),
27515
- extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _638 => _638.usage]), startTime)
27880
+ extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _670 => _670.usage]), startTime)
27516
27881
  })
27517
27882
  );
27518
27883
  this.unsubscribers.push(
@@ -27532,10 +27897,10 @@ var MistralPlugin = class extends BasePlugin {
27532
27897
  type: "llm" /* LLM */,
27533
27898
  extractInput: extractMessagesInputWithMetadata,
27534
27899
  extractOutput: (result) => {
27535
- return _optionalChain([result, 'optionalAccess', _639 => _639.choices]);
27900
+ return _optionalChain([result, 'optionalAccess', _671 => _671.choices]);
27536
27901
  },
27537
27902
  extractMetadata: (result) => extractMistralResponseMetadata(result),
27538
- extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _640 => _640.usage]), startTime)
27903
+ extractMetrics: (result, startTime) => extractMistralMetrics(_optionalChain([result, 'optionalAccess', _672 => _672.usage]), startTime)
27539
27904
  })
27540
27905
  );
27541
27906
  this.unsubscribers.push(
@@ -27790,11 +28155,11 @@ function mergeMistralContentParts(left, right) {
27790
28155
  const merged = [...(left || []).map((part) => structuredClone(part))];
27791
28156
  for (const part of right) {
27792
28157
  const lastPart = merged[merged.length - 1];
27793
- if (part.type === "text" && _optionalChain([lastPart, 'optionalAccess', _641 => _641.type]) === "text" && typeof lastPart.text === "string" && typeof part.text === "string") {
28158
+ if (part.type === "text" && _optionalChain([lastPart, 'optionalAccess', _673 => _673.type]) === "text" && typeof lastPart.text === "string" && typeof part.text === "string") {
27794
28159
  lastPart.text += part.text;
27795
28160
  continue;
27796
28161
  }
27797
- if (part.type === "thinking" && _optionalChain([lastPart, 'optionalAccess', _642 => _642.type]) === "thinking" && Array.isArray(lastPart.thinking) && Array.isArray(part.thinking)) {
28162
+ if (part.type === "thinking" && _optionalChain([lastPart, 'optionalAccess', _674 => _674.type]) === "thinking" && Array.isArray(lastPart.thinking) && Array.isArray(part.thinking)) {
27798
28163
  lastPart.thinking = mergeMistralTextSegments(
27799
28164
  lastPart.thinking,
27800
28165
  part.thinking
@@ -27849,13 +28214,13 @@ function createMergedToolCallDelta(delta) {
27849
28214
  ...delta,
27850
28215
  function: {
27851
28216
  ...delta.function,
27852
- arguments: typeof _optionalChain([delta, 'access', _643 => _643.function, 'optionalAccess', _644 => _644.arguments]) === "string" ? delta.function.arguments : ""
28217
+ arguments: typeof _optionalChain([delta, 'access', _675 => _675.function, 'optionalAccess', _676 => _676.arguments]) === "string" ? delta.function.arguments : ""
27853
28218
  }
27854
28219
  };
27855
28220
  }
27856
28221
  function mergeToolCallDeltaPair(current, delta) {
27857
- const currentArguments = typeof _optionalChain([current, 'access', _645 => _645.function, 'optionalAccess', _646 => _646.arguments]) === "string" ? current.function.arguments : "";
27858
- const deltaArguments = typeof _optionalChain([delta, 'access', _647 => _647.function, 'optionalAccess', _648 => _648.arguments]) === "string" ? delta.function.arguments : "";
28222
+ const currentArguments = typeof _optionalChain([current, 'access', _677 => _677.function, 'optionalAccess', _678 => _678.arguments]) === "string" ? current.function.arguments : "";
28223
+ const deltaArguments = typeof _optionalChain([delta, 'access', _679 => _679.function, 'optionalAccess', _680 => _680.arguments]) === "string" ? delta.function.arguments : "";
27859
28224
  return {
27860
28225
  ...current,
27861
28226
  ...delta,
@@ -27958,7 +28323,7 @@ function aggregateMistralStreamChunks(chunks) {
27958
28323
  let metrics = {};
27959
28324
  let metadata;
27960
28325
  for (const event of chunks) {
27961
- const chunk = isMistralChatCompletionChunk(_optionalChain([event, 'optionalAccess', _649 => _649.data])) ? event.data : void 0;
28326
+ const chunk = isMistralChatCompletionChunk(_optionalChain([event, 'optionalAccess', _681 => _681.data])) ? event.data : void 0;
27962
28327
  if (!chunk) {
27963
28328
  continue;
27964
28329
  }
@@ -28065,7 +28430,7 @@ var OllamaPlugin = class extends BasePlugin {
28065
28430
  extractInput: extractOllamaChatInput,
28066
28431
  extractOutput: (result, event) => extractOllamaChatOutput(
28067
28432
  result,
28068
- countOllamaToolCalls(_optionalChain([event, 'optionalAccess', _650 => _650.arguments, 'optionalAccess', _651 => _651[0], 'optionalAccess', _652 => _652.messages]))
28433
+ countOllamaToolCalls(_optionalChain([event, 'optionalAccess', _682 => _682.arguments, 'optionalAccess', _683 => _683[0], 'optionalAccess', _684 => _684.messages]))
28069
28434
  ),
28070
28435
  extractMetadata: extractOllamaResponseMetadata,
28071
28436
  extractMetrics: extractOllamaMetrics,
@@ -28101,7 +28466,7 @@ function normalizeFinishReason(response, hasToolCalls = false) {
28101
28466
  if (hasToolCalls) {
28102
28467
  return "tool_calls";
28103
28468
  }
28104
- return _optionalChain([response, 'optionalAccess', _653 => _653.done_reason]) || "stop";
28469
+ return _optionalChain([response, 'optionalAccess', _685 => _685.done_reason]) || "stop";
28105
28470
  }
28106
28471
  function stringifyArguments(value) {
28107
28472
  if (typeof value === "string") {
@@ -28118,7 +28483,7 @@ function syntheticToolCallId(name, index) {
28118
28483
  return `ollama_call_${normalizedName}_${index}`;
28119
28484
  }
28120
28485
  function normalizeToolCall(toolCall, index) {
28121
- const name = _optionalChain([toolCall, 'access', _654 => _654.function, 'optionalAccess', _655 => _655.name]);
28486
+ const name = _optionalChain([toolCall, 'access', _686 => _686.function, 'optionalAccess', _687 => _687.name]);
28122
28487
  if (typeof name !== "string" || name.length === 0) {
28123
28488
  return void 0;
28124
28489
  }
@@ -28127,7 +28492,7 @@ function normalizeToolCall(toolCall, index) {
28127
28492
  type: "function",
28128
28493
  function: {
28129
28494
  name,
28130
- arguments: stringifyArguments(_optionalChain([toolCall, 'access', _656 => _656.function, 'optionalAccess', _657 => _657.arguments]))
28495
+ arguments: stringifyArguments(_optionalChain([toolCall, 'access', _688 => _688.function, 'optionalAccess', _689 => _689.arguments]))
28131
28496
  }
28132
28497
  };
28133
28498
  }
@@ -28168,7 +28533,7 @@ function imageBytes(value) {
28168
28533
  }
28169
28534
  function inferImageMediaType(value) {
28170
28535
  if (typeof value === "string") {
28171
- const dataUrlType = _optionalChain([value, 'access', _658 => _658.match, 'call', _659 => _659(/^data:(image\/[^;]+);base64,/i), 'optionalAccess', _660 => _660[1]]);
28536
+ const dataUrlType = _optionalChain([value, 'access', _690 => _690.match, 'call', _691 => _691(/^data:(image\/[^;]+);base64,/i), 'optionalAccess', _692 => _692[1]]);
28172
28537
  if (dataUrlType) {
28173
28538
  return dataUrlType;
28174
28539
  }
@@ -28202,7 +28567,7 @@ function normalizeTextAndImages(content, images) {
28202
28567
  let localImagePath;
28203
28568
  let localPathMediaType;
28204
28569
  if (typeof image === "string" && !/^data:/i.test(image) && !/^https?:\/\//i.test(image)) {
28205
- const extension = _optionalChain([image, 'access', _661 => _661.match, 'call', _662 => _662(/\.([a-z0-9]+)$/i), 'optionalAccess', _663 => _663[1], 'optionalAccess', _664 => _664.toLowerCase, 'call', _665 => _665()]);
28570
+ const extension = _optionalChain([image, 'access', _693 => _693.match, 'call', _694 => _694(/\.([a-z0-9]+)$/i), 'optionalAccess', _695 => _695[1], 'optionalAccess', _696 => _696.toLowerCase, 'call', _697 => _697()]);
28206
28571
  const extensionMediaType = {
28207
28572
  png: "image/png",
28208
28573
  jpg: "image/jpeg",
@@ -28287,7 +28652,7 @@ function normalizeMessages(messages) {
28287
28652
  if (ollamaMessage.role === "tool") {
28288
28653
  const toolName = ollamaMessage.tool_name;
28289
28654
  if (typeof toolName === "string") {
28290
- toolCallId = _optionalChain([pendingToolCallIds, 'access', _666 => _666.get, 'call', _667 => _667(toolName), 'optionalAccess', _668 => _668.shift, 'call', _669 => _669()]);
28655
+ toolCallId = _optionalChain([pendingToolCallIds, 'access', _698 => _698.get, 'call', _699 => _699(toolName), 'optionalAccess', _700 => _700.shift, 'call', _701 => _701()]);
28291
28656
  }
28292
28657
  }
28293
28658
  const normalized = normalizeMessage(
@@ -28366,9 +28731,9 @@ function extractOptionsMetadata(options) {
28366
28731
  function extractRequestMetadata(request) {
28367
28732
  return {
28368
28733
  provider: "ollama",
28369
- ...typeof _optionalChain([request, 'optionalAccess', _670 => _670.model]) === "string" ? { model: request.model } : {},
28370
- ...extractOptionsMetadata(_optionalChain([request, 'optionalAccess', _671 => _671.options])),
28371
- ..._optionalChain([request, 'optionalAccess', _672 => _672.format]) !== void 0 ? { response_format: request.format } : {}
28734
+ ...typeof _optionalChain([request, 'optionalAccess', _702 => _702.model]) === "string" ? { model: request.model } : {},
28735
+ ...extractOptionsMetadata(_optionalChain([request, 'optionalAccess', _703 => _703.options])),
28736
+ ..._optionalChain([request, 'optionalAccess', _704 => _704.format]) !== void 0 ? { response_format: request.format } : {}
28372
28737
  };
28373
28738
  }
28374
28739
  function extractOllamaChatInput([request]) {
@@ -28443,16 +28808,16 @@ function extractOllamaGenerateOutput(result) {
28443
28808
  ];
28444
28809
  }
28445
28810
  function extractOllamaEmbedOutput(result) {
28446
- const embedding = Array.isArray(_optionalChain([result, 'optionalAccess', _673 => _673.embeddings])) ? result.embeddings[0] : void 0;
28811
+ const embedding = Array.isArray(_optionalChain([result, 'optionalAccess', _705 => _705.embeddings])) ? result.embeddings[0] : void 0;
28447
28812
  return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
28448
28813
  }
28449
28814
  function extractOllamaResponseMetadata(result) {
28450
- return typeof _optionalChain([result, 'optionalAccess', _674 => _674.model]) === "string" ? { model: result.model } : void 0;
28815
+ return typeof _optionalChain([result, 'optionalAccess', _706 => _706.model]) === "string" ? { model: result.model } : void 0;
28451
28816
  }
28452
28817
  function extractOllamaMetrics(result) {
28453
28818
  const metrics = {};
28454
- const promptTokens = _optionalChain([result, 'optionalAccess', _675 => _675.prompt_eval_count]);
28455
- const completionTokens = _optionalChain([result, 'optionalAccess', _676 => _676.eval_count]);
28819
+ const promptTokens = _optionalChain([result, 'optionalAccess', _707 => _707.prompt_eval_count]);
28820
+ const completionTokens = _optionalChain([result, 'optionalAccess', _708 => _708.eval_count]);
28456
28821
  if (isNonNegativeNumber(promptTokens)) {
28457
28822
  metrics.prompt_tokens = promptTokens;
28458
28823
  }
@@ -28468,9 +28833,9 @@ function aggregateOllamaChatChunks(chunks, _result, event, _startTime) {
28468
28833
  const last = chunks.at(-1);
28469
28834
  const message = {
28470
28835
  role: "assistant",
28471
- content: chunks.map((chunk) => _nullishCoalesce(_optionalChain([chunk, 'access', _677 => _677.message, 'optionalAccess', _678 => _678.content]), () => ( ""))).join(""),
28472
- thinking: chunks.map((chunk) => _nullishCoalesce(_optionalChain([chunk, 'access', _679 => _679.message, 'optionalAccess', _680 => _680.thinking]), () => ( ""))).join(""),
28473
- tool_calls: chunks.flatMap((chunk) => _nullishCoalesce(_optionalChain([chunk, 'access', _681 => _681.message, 'optionalAccess', _682 => _682.tool_calls]), () => ( [])))
28836
+ content: chunks.map((chunk) => _nullishCoalesce(_optionalChain([chunk, 'access', _709 => _709.message, 'optionalAccess', _710 => _710.content]), () => ( ""))).join(""),
28837
+ thinking: chunks.map((chunk) => _nullishCoalesce(_optionalChain([chunk, 'access', _711 => _711.message, 'optionalAccess', _712 => _712.thinking]), () => ( ""))).join(""),
28838
+ tool_calls: chunks.flatMap((chunk) => _nullishCoalesce(_optionalChain([chunk, 'access', _713 => _713.message, 'optionalAccess', _714 => _714.tool_calls]), () => ( [])))
28474
28839
  };
28475
28840
  const response = {
28476
28841
  ...last,
@@ -28479,7 +28844,7 @@ function aggregateOllamaChatChunks(chunks, _result, event, _startTime) {
28479
28844
  return {
28480
28845
  output: extractOllamaChatOutput(
28481
28846
  response,
28482
- countOllamaToolCalls(_optionalChain([event, 'optionalAccess', _683 => _683.arguments, 'optionalAccess', _684 => _684[0], 'optionalAccess', _685 => _685.messages]))
28847
+ countOllamaToolCalls(_optionalChain([event, 'optionalAccess', _715 => _715.arguments, 'optionalAccess', _716 => _716[0], 'optionalAccess', _717 => _717.messages]))
28483
28848
  ),
28484
28849
  metrics: extractOllamaMetrics(_nullishCoalesce(last, () => ( {}))),
28485
28850
  metadata: extractOllamaResponseMetadata(_nullishCoalesce(last, () => ( {})))
@@ -28622,7 +28987,7 @@ var GoogleADKPlugin = (_class24 = class extends BasePlugin {constructor(...args6
28622
28987
  };
28623
28988
  tracingChannel.subscribe(handlers);
28624
28989
  this.unsubscribers.push(() => {
28625
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _686 => _686()]);
28990
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _718 => _718()]);
28626
28991
  tracingChannel.unsubscribe(handlers);
28627
28992
  });
28628
28993
  }
@@ -28730,7 +29095,7 @@ var GoogleADKPlugin = (_class24 = class extends BasePlugin {constructor(...args6
28730
29095
  };
28731
29096
  tracingChannel.subscribe(handlers);
28732
29097
  this.unsubscribers.push(() => {
28733
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _687 => _687()]);
29098
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _719 => _719()]);
28734
29099
  tracingChannel.unsubscribe(handlers);
28735
29100
  });
28736
29101
  }
@@ -28882,10 +29247,10 @@ function bindAsyncIterableToCurrentSpan(stream, span) {
28882
29247
  }
28883
29248
  function bindCurrentSpanStoreToStart3(tracingChannel, states, create) {
28884
29249
  const state = _internalGetGlobalState();
28885
- const contextManager = _optionalChain([state, 'optionalAccess', _688 => _688.contextManager]);
29250
+ const contextManager = _optionalChain([state, 'optionalAccess', _720 => _720.contextManager]);
28886
29251
  const startChannel = tracingChannel.start;
28887
29252
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
28888
- if (!_optionalChain([startChannel, 'optionalAccess', _689 => _689.bindStore]) || !currentSpanStore) {
29253
+ if (!_optionalChain([startChannel, 'optionalAccess', _721 => _721.bindStore]) || !currentSpanStore) {
28889
29254
  return void 0;
28890
29255
  }
28891
29256
  startChannel.bindStore(currentSpanStore, (event) => {
@@ -28897,7 +29262,7 @@ function bindCurrentSpanStoreToStart3(tracingChannel, states, create) {
28897
29262
  return contextManager.wrapSpanForStore(span);
28898
29263
  });
28899
29264
  return () => {
28900
- _optionalChain([startChannel, 'access', _690 => _690.unbindStore, 'optionalCall', _691 => _691(currentSpanStore)]);
29265
+ _optionalChain([startChannel, 'access', _722 => _722.unbindStore, 'optionalCall', _723 => _723(currentSpanStore)]);
28901
29266
  };
28902
29267
  }
28903
29268
  function extractRunnerContextKey(paramsOrContext) {
@@ -28910,9 +29275,9 @@ function extractRunnerContextKey(paramsOrContext) {
28910
29275
  return extractInvocationContextKey(invocationContext);
28911
29276
  }
28912
29277
  function extractInvocationContextKey(parentContext) {
28913
- const session = _optionalChain([parentContext, 'optionalAccess', _692 => _692.session]);
28914
- const userId = _optionalChain([session, 'optionalAccess', _693 => _693.userId]);
28915
- const sessionId = _optionalChain([session, 'optionalAccess', _694 => _694.id]);
29278
+ const session = _optionalChain([parentContext, 'optionalAccess', _724 => _724.session]);
29279
+ const userId = _optionalChain([session, 'optionalAccess', _725 => _725.userId]);
29280
+ const sessionId = _optionalChain([session, 'optionalAccess', _726 => _726.id]);
28916
29281
  if (typeof userId !== "string" || typeof sessionId !== "string") {
28917
29282
  return void 0;
28918
29283
  }
@@ -28969,27 +29334,27 @@ function extractRunnerMetadata(paramsOrContext) {
28969
29334
  metadata["google_adk.session_id"] = directSessionId;
28970
29335
  }
28971
29336
  const session = "session" in paramsOrContext ? paramsOrContext.session : void 0;
28972
- if (metadata["google_adk.user_id"] === void 0 && typeof _optionalChain([session, 'optionalAccess', _695 => _695.userId]) === "string") {
29337
+ if (metadata["google_adk.user_id"] === void 0 && typeof _optionalChain([session, 'optionalAccess', _727 => _727.userId]) === "string") {
28973
29338
  metadata["google_adk.user_id"] = session.userId;
28974
29339
  }
28975
- if (metadata["google_adk.session_id"] === void 0 && typeof _optionalChain([session, 'optionalAccess', _696 => _696.id]) === "string") {
29340
+ if (metadata["google_adk.session_id"] === void 0 && typeof _optionalChain([session, 'optionalAccess', _728 => _728.id]) === "string") {
28976
29341
  metadata["google_adk.session_id"] = session.id;
28977
29342
  }
28978
29343
  return metadata;
28979
29344
  }
28980
29345
  function extractAgentName(agent, parentContext) {
28981
- if (typeof _optionalChain([agent, 'optionalAccess', _697 => _697.name]) === "string" && agent.name.length > 0) {
29346
+ if (typeof _optionalChain([agent, 'optionalAccess', _729 => _729.name]) === "string" && agent.name.length > 0) {
28982
29347
  return agent.name;
28983
29348
  }
28984
29349
  if (!parentContext) {
28985
29350
  return void 0;
28986
29351
  }
28987
29352
  const contextAgent = parentContext.agent;
28988
- return typeof _optionalChain([contextAgent, 'optionalAccess', _698 => _698.name]) === "string" && contextAgent.name.length > 0 ? contextAgent.name : void 0;
29353
+ return typeof _optionalChain([contextAgent, 'optionalAccess', _730 => _730.name]) === "string" && contextAgent.name.length > 0 ? contextAgent.name : void 0;
28989
29354
  }
28990
29355
  function extractModelName(agent, parentContext) {
28991
- const modelAgent = _nullishCoalesce(agent, () => ( _optionalChain([parentContext, 'optionalAccess', _699 => _699.agent])));
28992
- if (!_optionalChain([modelAgent, 'optionalAccess', _700 => _700.model])) {
29356
+ const modelAgent = _nullishCoalesce(agent, () => ( _optionalChain([parentContext, 'optionalAccess', _731 => _731.agent])));
29357
+ if (!_optionalChain([modelAgent, 'optionalAccess', _732 => _732.model])) {
28993
29358
  return;
28994
29359
  }
28995
29360
  if (typeof modelAgent.model === "string") {
@@ -29002,30 +29367,30 @@ function extractModelName(agent, parentContext) {
29002
29367
  }
29003
29368
  function extractToolCallId(req) {
29004
29369
  const toolContext = req.toolContext;
29005
- return _optionalChain([toolContext, 'optionalAccess', _701 => _701.functionCallId]);
29370
+ return _optionalChain([toolContext, 'optionalAccess', _733 => _733.functionCallId]);
29006
29371
  }
29007
29372
  function extractToolName2(req, tool) {
29008
- if (typeof _optionalChain([tool, 'optionalAccess', _702 => _702.name]) === "string" && tool.name.length > 0) {
29373
+ if (typeof _optionalChain([tool, 'optionalAccess', _734 => _734.name]) === "string" && tool.name.length > 0) {
29009
29374
  return tool.name;
29010
29375
  }
29011
29376
  const toolContext = req.toolContext;
29012
- const invocationContext = _optionalChain([toolContext, 'optionalAccess', _703 => _703.invocationContext]);
29013
- const invocationTool = _optionalChain([invocationContext, 'optionalAccess', _704 => _704.tool]);
29014
- const toolName = _optionalChain([invocationTool, 'optionalAccess', _705 => _705.name]);
29377
+ const invocationContext = _optionalChain([toolContext, 'optionalAccess', _735 => _735.invocationContext]);
29378
+ const invocationTool = _optionalChain([invocationContext, 'optionalAccess', _736 => _736.tool]);
29379
+ const toolName = _optionalChain([invocationTool, 'optionalAccess', _737 => _737.name]);
29015
29380
  return typeof toolName === "string" && toolName.length > 0 ? toolName : void 0;
29016
29381
  }
29017
29382
  function extractToolAgentName(req) {
29018
29383
  const toolContext = req.toolContext;
29019
- const directName = _optionalChain([toolContext, 'optionalAccess', _706 => _706.agentName]);
29384
+ const directName = _optionalChain([toolContext, 'optionalAccess', _738 => _738.agentName]);
29020
29385
  if (typeof directName === "string" && directName.length > 0) {
29021
29386
  return directName;
29022
29387
  }
29023
- const invocationContext = _optionalChain([toolContext, 'optionalAccess', _707 => _707.invocationContext]);
29388
+ const invocationContext = _optionalChain([toolContext, 'optionalAccess', _739 => _739.invocationContext]);
29024
29389
  return extractAgentName(void 0, invocationContext);
29025
29390
  }
29026
29391
  function findToolParentSpan(req, activeAgentSpans, activeRunnerSpans) {
29027
29392
  const toolContext = req.toolContext;
29028
- const invocationContext = _optionalChain([toolContext, 'optionalAccess', _708 => _708.invocationContext]);
29393
+ const invocationContext = _optionalChain([toolContext, 'optionalAccess', _740 => _740.invocationContext]);
29029
29394
  const contextKey = extractInvocationContextKey(invocationContext);
29030
29395
  const agentName = extractToolAgentName(req);
29031
29396
  if (contextKey && agentName) {
@@ -29441,7 +29806,7 @@ function extractCohereResponseMetadata(result) {
29441
29806
  RESPONSE_METADATA_ALLOWLIST2
29442
29807
  );
29443
29808
  const meta = isObject(result.meta) ? result.meta : void 0;
29444
- const apiVersion = isObject(_optionalChain([meta, 'optionalAccess', _709 => _709.apiVersion])) && typeof meta.apiVersion.version === "string" && meta.apiVersion.version || isObject(_optionalChain([meta, 'optionalAccess', _710 => _710.api_version])) && typeof meta.api_version.version === "string" && meta.api_version.version;
29809
+ const apiVersion = isObject(_optionalChain([meta, 'optionalAccess', _741 => _741.apiVersion])) && typeof meta.apiVersion.version === "string" && meta.apiVersion.version || isObject(_optionalChain([meta, 'optionalAccess', _742 => _742.api_version])) && typeof meta.api_version.version === "string" && meta.api_version.version;
29445
29810
  const metadata = {
29446
29811
  ...responseMetadata,
29447
29812
  ...apiVersion ? { api_version: apiVersion } : {}
@@ -29602,13 +29967,13 @@ function getToolCallIndex2(toolCall, fallbackIndex) {
29602
29967
  return typeof toolCall.index === "number" && Number.isInteger(toolCall.index) ? toolCall.index : fallbackIndex;
29603
29968
  }
29604
29969
  function appendToolCallDelta(existing, incoming) {
29605
- const currentArguments = isObject(_optionalChain([existing, 'optionalAccess', _711 => _711.function])) && typeof existing.function.arguments === "string" ? existing.function.arguments : "";
29970
+ const currentArguments = isObject(_optionalChain([existing, 'optionalAccess', _743 => _743.function])) && typeof existing.function.arguments === "string" ? existing.function.arguments : "";
29606
29971
  const incomingArguments = isObject(incoming.function) && typeof incoming.function.arguments === "string" ? incoming.function.arguments : "";
29607
29972
  return {
29608
29973
  ...existing,
29609
29974
  ...incoming,
29610
29975
  function: {
29611
- ...isObject(_optionalChain([existing, 'optionalAccess', _712 => _712.function])) ? existing.function : {},
29976
+ ...isObject(_optionalChain([existing, 'optionalAccess', _744 => _744.function])) ? existing.function : {},
29612
29977
  ...isObject(incoming.function) ? incoming.function : {},
29613
29978
  ...incomingArguments ? { arguments: `${currentArguments}${incomingArguments}` } : {}
29614
29979
  }
@@ -29864,7 +30229,7 @@ function aggregateCohereChatStreamChunks(chunks) {
29864
30229
  ...mergedToolCalls.length > 0 ? { toolCalls: mergedToolCalls } : {}
29865
30230
  };
29866
30231
  } else if (mergedToolCalls.length > 0 || role || mergedText.length > 0 || aggregatedContentBlocks.length > 0) {
29867
- const textContent = mergedText.length > 0 ? mergedText : _optionalChain([aggregatedContentBlocks, 'access', _713 => _713[0], 'optionalAccess', _714 => _714.type]) === "text" ? aggregatedContentBlocks[0].text : void 0;
30232
+ const textContent = mergedText.length > 0 ? mergedText : _optionalChain([aggregatedContentBlocks, 'access', _745 => _745[0], 'optionalAccess', _746 => _746.type]) === "text" ? aggregatedContentBlocks[0].text : void 0;
29868
30233
  output = {
29869
30234
  ...role ? { role } : {},
29870
30235
  ...textContent ? { content: textContent } : {},
@@ -29915,7 +30280,7 @@ var GroqPlugin = class extends BasePlugin {
29915
30280
  metadata: { ...metadata, provider: "groq" }
29916
30281
  };
29917
30282
  },
29918
- extractOutput: (result) => _optionalChain([result, 'optionalAccess', _715 => _715.choices]),
30283
+ extractOutput: (result) => _optionalChain([result, 'optionalAccess', _747 => _747.choices]),
29919
30284
  extractMetrics: (result, startTime) => {
29920
30285
  const metrics = parseGroqMetrics(result);
29921
30286
  if (startTime) {
@@ -29938,7 +30303,7 @@ var GroqPlugin = class extends BasePlugin {
29938
30303
  };
29939
30304
  },
29940
30305
  extractOutput: (result) => {
29941
- const embedding = _optionalChain([result, 'optionalAccess', _716 => _716.data, 'optionalAccess', _717 => _717[0], 'optionalAccess', _718 => _718.embedding]);
30306
+ const embedding = _optionalChain([result, 'optionalAccess', _748 => _748.data, 'optionalAccess', _749 => _749[0], 'optionalAccess', _750 => _750.embedding]);
29942
30307
  return Array.isArray(embedding) ? { embedding_length: embedding.length } : void 0;
29943
30308
  },
29944
30309
  extractMetrics: (result) => parseGroqMetrics(result)
@@ -29950,8 +30315,8 @@ var GroqPlugin = class extends BasePlugin {
29950
30315
  }
29951
30316
  };
29952
30317
  function parseGroqMetrics(result) {
29953
- const metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _719 => _719.usage]));
29954
- const xGroq = _optionalChain([result, 'optionalAccess', _720 => _720.x_groq]);
30318
+ const metrics = parseMetricsFromUsage(_optionalChain([result, 'optionalAccess', _751 => _751.usage]));
30319
+ const xGroq = _optionalChain([result, 'optionalAccess', _752 => _752.x_groq]);
29955
30320
  if (!xGroq || typeof xGroq !== "object") {
29956
30321
  return metrics;
29957
30322
  }
@@ -29975,7 +30340,7 @@ function aggregateGroqChatCompletionChunks(chunks, streamResult, endEvent) {
29975
30340
  );
29976
30341
  const reasoning = aggregateGroqReasoning(chunks);
29977
30342
  if (reasoning !== void 0) {
29978
- const message = _optionalChain([aggregated, 'access', _721 => _721.output, 'access', _722 => _722[0], 'optionalAccess', _723 => _723.message]);
30343
+ const message = _optionalChain([aggregated, 'access', _753 => _753.output, 'access', _754 => _754[0], 'optionalAccess', _755 => _755.message]);
29979
30344
  if (message) {
29980
30345
  message.reasoning = reasoning;
29981
30346
  }
@@ -29988,8 +30353,8 @@ function aggregateGroqChatCompletionChunks(chunks, streamResult, endEvent) {
29988
30353
  function aggregateGroqReasoning(chunks) {
29989
30354
  let reasoning = "";
29990
30355
  for (const chunk of chunks) {
29991
- const delta = _optionalChain([chunk, 'access', _724 => _724.choices, 'optionalAccess', _725 => _725[0], 'optionalAccess', _726 => _726.delta]);
29992
- const deltaReasoning = _optionalChain([delta, 'optionalAccess', _727 => _727.reasoning]);
30356
+ const delta = _optionalChain([chunk, 'access', _756 => _756.choices, 'optionalAccess', _757 => _757[0], 'optionalAccess', _758 => _758.delta]);
30357
+ const deltaReasoning = _optionalChain([delta, 'optionalAccess', _759 => _759.reasoning]);
29993
30358
  if (typeof deltaReasoning === "string") {
29994
30359
  reasoning += deltaReasoning;
29995
30360
  }
@@ -30086,11 +30451,11 @@ function traceBedrockRuntimeClientSendChannel(channel2) {
30086
30451
  shouldTrace: ([command, optionsOrCb, cb]) => getBedrockRuntimeOperation(command) !== void 0 && typeof optionsOrCb !== "function" && typeof cb !== "function",
30087
30452
  type: "llm" /* LLM */,
30088
30453
  extractInput: ([command]) => extractBedrockRuntimeInput(command),
30089
- extractOutput: (result, endEvent) => extractBedrockRuntimeOutput(_optionalChain([endEvent, 'optionalAccess', _728 => _728.arguments, 'optionalAccess', _729 => _729[0]]), result),
30090
- extractMetadata: (result, endEvent) => extractBedrockRuntimeResponseMetadata(_optionalChain([endEvent, 'optionalAccess', _730 => _730.arguments, 'optionalAccess', _731 => _731[0]]), result),
30454
+ extractOutput: (result, endEvent) => extractBedrockRuntimeOutput(_optionalChain([endEvent, 'optionalAccess', _760 => _760.arguments, 'optionalAccess', _761 => _761[0]]), result),
30455
+ extractMetadata: (result, endEvent) => extractBedrockRuntimeResponseMetadata(_optionalChain([endEvent, 'optionalAccess', _762 => _762.arguments, 'optionalAccess', _763 => _763[0]]), result),
30091
30456
  extractMetrics: (result) => extractBedrockRuntimeResponseMetrics(result),
30092
30457
  patchResult: ({ endEvent, result, span, startTime }) => patchBedrockRuntimeStreamingResult({
30093
- command: _optionalChain([endEvent, 'access', _732 => _732.arguments, 'optionalAccess', _733 => _733[0]]),
30458
+ command: _optionalChain([endEvent, 'access', _764 => _764.arguments, 'optionalAccess', _765 => _765[0]]),
30094
30459
  result,
30095
30460
  span,
30096
30461
  startTime
@@ -30111,8 +30476,8 @@ function extractBedrockRuntimeInput(command) {
30111
30476
  const converseRequest = isObject(request) ? request : void 0;
30112
30477
  return {
30113
30478
  input: sanitizeBedrockValue({
30114
- messages: _optionalChain([converseRequest, 'optionalAccess', _734 => _734.messages]),
30115
- system: _optionalChain([converseRequest, 'optionalAccess', _735 => _735.system])
30479
+ messages: _optionalChain([converseRequest, 'optionalAccess', _766 => _766.messages]),
30480
+ system: _optionalChain([converseRequest, 'optionalAccess', _767 => _767.system])
30116
30481
  }),
30117
30482
  metadata
30118
30483
  };
@@ -30120,7 +30485,7 @@ function extractBedrockRuntimeInput(command) {
30120
30485
  if (operation === "invokeModel" || operation === "invokeModelWithBidirectionalStream" || operation === "invokeModelWithResponseStream") {
30121
30486
  const invokeRequest = isObject(request) ? request : void 0;
30122
30487
  return {
30123
- input: _nullishCoalesce(parseJsonBody(_optionalChain([invokeRequest, 'optionalAccess', _736 => _736.body])), () => ( summarizeBody(_optionalChain([invokeRequest, 'optionalAccess', _737 => _737.body])))),
30488
+ input: _nullishCoalesce(parseJsonBody(_optionalChain([invokeRequest, 'optionalAccess', _768 => _768.body])), () => ( summarizeBody(_optionalChain([invokeRequest, 'optionalAccess', _769 => _769.body])))),
30124
30489
  metadata
30125
30490
  };
30126
30491
  }
@@ -30159,12 +30524,12 @@ function extractBedrockRuntimeOutput(command, result) {
30159
30524
  const operation = getBedrockRuntimeOperation(command);
30160
30525
  if (operation === "converse") {
30161
30526
  return sanitizeBedrockValue(
30162
- _optionalChain([result, 'optionalAccess', _738 => _738.output, 'optionalAccess', _739 => _739.message])
30527
+ _optionalChain([result, 'optionalAccess', _770 => _770.output, 'optionalAccess', _771 => _771.message])
30163
30528
  );
30164
30529
  }
30165
30530
  if (operation === "invokeModel") {
30166
30531
  const response = isObject(result) ? result : void 0;
30167
- return _nullishCoalesce(parseJsonBody(_optionalChain([response, 'optionalAccess', _740 => _740.body])), () => ( summarizeBody(_optionalChain([response, 'optionalAccess', _741 => _741.body]))));
30532
+ return _nullishCoalesce(parseJsonBody(_optionalChain([response, 'optionalAccess', _772 => _772.body])), () => ( summarizeBody(_optionalChain([response, 'optionalAccess', _773 => _773.body]))));
30168
30533
  }
30169
30534
  return sanitizeBedrockValue(result);
30170
30535
  }
@@ -30201,8 +30566,8 @@ function extractBedrockRuntimeResponseMetrics(result) {
30201
30566
  if (isObject(parsedBody)) {
30202
30567
  const metadata = isObject(parsedBody.metadata) ? parsedBody.metadata : void 0;
30203
30568
  const metrics = parseBedrockRuntimeMetrics(
30204
- _nullishCoalesce(parsedBody.usage, () => ( _optionalChain([metadata, 'optionalAccess', _742 => _742.usage]))),
30205
- _nullishCoalesce(parsedBody.metrics, () => ( _optionalChain([metadata, 'optionalAccess', _743 => _743.metrics])))
30569
+ _nullishCoalesce(parsedBody.usage, () => ( _optionalChain([metadata, 'optionalAccess', _774 => _774.usage]))),
30570
+ _nullishCoalesce(parsedBody.metrics, () => ( _optionalChain([metadata, 'optionalAccess', _775 => _775.metrics])))
30206
30571
  );
30207
30572
  if (Object.keys(metrics).length > 0) {
30208
30573
  return metrics;
@@ -30367,42 +30732,42 @@ function aggregateBedrockConverseStreamChunks(chunks) {
30367
30732
  if (exception) {
30368
30733
  return exception;
30369
30734
  }
30370
- if (typeof _optionalChain([chunk, 'access', _744 => _744.messageStart, 'optionalAccess', _745 => _745.role]) === "string") {
30735
+ if (typeof _optionalChain([chunk, 'access', _776 => _776.messageStart, 'optionalAccess', _777 => _777.role]) === "string") {
30371
30736
  role = chunk.messageStart.role;
30372
30737
  }
30373
- const startIndex = _optionalChain([chunk, 'access', _746 => _746.contentBlockStart, 'optionalAccess', _747 => _747.contentBlockIndex]);
30738
+ const startIndex = _optionalChain([chunk, 'access', _778 => _778.contentBlockStart, 'optionalAccess', _779 => _779.contentBlockIndex]);
30374
30739
  if (typeof startIndex === "number") {
30375
30740
  contentByIndex.set(startIndex, {
30376
30741
  ..._nullishCoalesce(contentByIndex.get(startIndex), () => ( {})),
30377
- ...sanitizeRecord(_optionalChain([chunk, 'access', _748 => _748.contentBlockStart, 'optionalAccess', _749 => _749.start]))
30742
+ ...sanitizeRecord(_optionalChain([chunk, 'access', _780 => _780.contentBlockStart, 'optionalAccess', _781 => _781.start]))
30378
30743
  });
30379
30744
  }
30380
- const deltaIndex = _optionalChain([chunk, 'access', _750 => _750.contentBlockDelta, 'optionalAccess', _751 => _751.contentBlockIndex]);
30381
- const delta = _optionalChain([chunk, 'access', _752 => _752.contentBlockDelta, 'optionalAccess', _753 => _753.delta]);
30745
+ const deltaIndex = _optionalChain([chunk, 'access', _782 => _782.contentBlockDelta, 'optionalAccess', _783 => _783.contentBlockIndex]);
30746
+ const delta = _optionalChain([chunk, 'access', _784 => _784.contentBlockDelta, 'optionalAccess', _785 => _785.delta]);
30382
30747
  if (typeof deltaIndex === "number" && isObject(delta)) {
30383
30748
  const existing = _nullishCoalesce(contentByIndex.get(deltaIndex), () => ( {}));
30384
30749
  contentByIndex.set(deltaIndex, mergeContentBlockDelta(existing, delta));
30385
30750
  }
30386
- if (typeof _optionalChain([chunk, 'access', _754 => _754.messageStop, 'optionalAccess', _755 => _755.stopReason]) === "string") {
30751
+ if (typeof _optionalChain([chunk, 'access', _786 => _786.messageStop, 'optionalAccess', _787 => _787.stopReason]) === "string") {
30387
30752
  stopReason = chunk.messageStop.stopReason;
30388
30753
  }
30389
- if (_optionalChain([chunk, 'access', _756 => _756.messageStop, 'optionalAccess', _757 => _757.additionalModelResponseFields]) !== void 0) {
30754
+ if (_optionalChain([chunk, 'access', _788 => _788.messageStop, 'optionalAccess', _789 => _789.additionalModelResponseFields]) !== void 0) {
30390
30755
  metadata.additionalModelResponseFields = sanitizeBedrockValue(
30391
30756
  chunk.messageStop.additionalModelResponseFields
30392
30757
  );
30393
30758
  }
30394
- if (_optionalChain([chunk, 'access', _758 => _758.metadata, 'optionalAccess', _759 => _759.usage]) !== void 0) {
30759
+ if (_optionalChain([chunk, 'access', _790 => _790.metadata, 'optionalAccess', _791 => _791.usage]) !== void 0) {
30395
30760
  usage = chunk.metadata.usage;
30396
30761
  }
30397
- if (_optionalChain([chunk, 'access', _760 => _760.metadata, 'optionalAccess', _761 => _761.metrics]) !== void 0) {
30762
+ if (_optionalChain([chunk, 'access', _792 => _792.metadata, 'optionalAccess', _793 => _793.metrics]) !== void 0) {
30398
30763
  responseMetrics = chunk.metadata.metrics;
30399
30764
  }
30400
- if (_optionalChain([chunk, 'access', _762 => _762.metadata, 'optionalAccess', _763 => _763.performanceConfig]) !== void 0) {
30765
+ if (_optionalChain([chunk, 'access', _794 => _794.metadata, 'optionalAccess', _795 => _795.performanceConfig]) !== void 0) {
30401
30766
  metadata.performanceConfig = sanitizeBedrockValue(
30402
30767
  chunk.metadata.performanceConfig
30403
30768
  );
30404
30769
  }
30405
- if (_optionalChain([chunk, 'access', _764 => _764.metadata, 'optionalAccess', _765 => _765.serviceTier]) !== void 0) {
30770
+ if (_optionalChain([chunk, 'access', _796 => _796.metadata, 'optionalAccess', _797 => _797.serviceTier]) !== void 0) {
30406
30771
  metadata.serviceTier = chunk.metadata.serviceTier;
30407
30772
  }
30408
30773
  }
@@ -30426,11 +30791,11 @@ function aggregateInvokeModelResponseStreamChunks(chunks) {
30426
30791
  return exception;
30427
30792
  }
30428
30793
  }
30429
- const parsedChunks = chunks.map((chunk) => parseJsonBody(_optionalChain([chunk, 'access', _766 => _766.chunk, 'optionalAccess', _767 => _767.bytes]))).filter((chunk) => chunk !== void 0);
30794
+ const parsedChunks = chunks.map((chunk) => parseJsonBody(_optionalChain([chunk, 'access', _798 => _798.chunk, 'optionalAccess', _799 => _799.bytes]))).filter((chunk) => chunk !== void 0);
30430
30795
  const jsonLikeChunks = parsedChunks.filter(isObject);
30431
30796
  const text = parsedChunks.map(extractTextFromJsonLike).join("");
30432
30797
  const lastMetadataChunk = jsonLikeChunks.slice().reverse().find((chunk) => isObject(chunk.metadata));
30433
- const metadata = isObject(_optionalChain([lastMetadataChunk, 'optionalAccess', _768 => _768.metadata])) ? sanitizeRecord(lastMetadataChunk.metadata) : void 0;
30798
+ const metadata = isObject(_optionalChain([lastMetadataChunk, 'optionalAccess', _800 => _800.metadata])) ? sanitizeRecord(lastMetadataChunk.metadata) : void 0;
30434
30799
  let usage;
30435
30800
  for (const chunk of jsonLikeChunks) {
30436
30801
  const message = chunk.message;
@@ -30712,8 +31077,8 @@ var GenkitPlugin = class extends BasePlugin {
30712
31077
  type: "llm" /* LLM */,
30713
31078
  extractInput: ([input]) => extractGenerateInput(input),
30714
31079
  extractOutput: extractGenerateOutput,
30715
- extractMetadata: (result, event) => extractGenerateResponseMetadata(result, _optionalChain([event, 'optionalAccess', _769 => _769.arguments, 'optionalAccess', _770 => _770[0]])),
30716
- extractMetrics: (result) => parseGenkitUsageMetrics(_optionalChain([result, 'optionalAccess', _771 => _771.usage]))
31080
+ extractMetadata: (result, event) => extractGenerateResponseMetadata(result, _optionalChain([event, 'optionalAccess', _801 => _801.arguments, 'optionalAccess', _802 => _802[0]])),
31081
+ extractMetrics: (result) => parseGenkitUsageMetrics(_optionalChain([result, 'optionalAccess', _803 => _803.usage]))
30717
31082
  })
30718
31083
  );
30719
31084
  this.unsubscribers.push(
@@ -30730,7 +31095,7 @@ var GenkitPlugin = class extends BasePlugin {
30730
31095
  type: "function" /* FUNCTION */,
30731
31096
  extractInput: ([params]) => extractEmbedInput(params),
30732
31097
  extractOutput: (result) => summarizeEmbeddingResult(result),
30733
- extractMetadata: (_result, event) => extractEmbedMetadata(_optionalChain([event, 'optionalAccess', _772 => _772.arguments, 'optionalAccess', _773 => _773[0]])),
31098
+ extractMetadata: (_result, event) => extractEmbedMetadata(_optionalChain([event, 'optionalAccess', _804 => _804.arguments, 'optionalAccess', _805 => _805[0]])),
30734
31099
  extractMetrics: () => ({})
30735
31100
  })
30736
31101
  );
@@ -30740,7 +31105,7 @@ var GenkitPlugin = class extends BasePlugin {
30740
31105
  type: "function" /* FUNCTION */,
30741
31106
  extractInput: ([params]) => extractEmbedManyInput(params),
30742
31107
  extractOutput: summarizeEmbeddingResult,
30743
- extractMetadata: (_result, event) => extractEmbedMetadata(_optionalChain([event, 'optionalAccess', _774 => _774.arguments, 'optionalAccess', _775 => _775[0]])),
31108
+ extractMetadata: (_result, event) => extractEmbedMetadata(_optionalChain([event, 'optionalAccess', _806 => _806.arguments, 'optionalAccess', _807 => _807[0]])),
30744
31109
  extractMetrics: () => ({})
30745
31110
  })
30746
31111
  );
@@ -30791,7 +31156,7 @@ var GenkitPlugin = class extends BasePlugin {
30791
31156
  };
30792
31157
  tracingChannel.subscribe(handlers);
30793
31158
  this.unsubscribers.push(() => {
30794
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _776 => _776()]);
31159
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _808 => _808()]);
30795
31160
  tracingChannel.unsubscribe(handlers);
30796
31161
  });
30797
31162
  }
@@ -30839,7 +31204,7 @@ var GenkitPlugin = class extends BasePlugin {
30839
31204
  };
30840
31205
  tracingChannel.subscribe(handlers);
30841
31206
  this.unsubscribers.push(() => {
30842
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _777 => _777()]);
31207
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _809 => _809()]);
30843
31208
  tracingChannel.unsubscribe(handlers);
30844
31209
  });
30845
31210
  }
@@ -30911,10 +31276,10 @@ function ensureActionSpanState(states, event, create) {
30911
31276
  }
30912
31277
  function bindActionCurrentSpanStoreToStart(tracingChannel, states, create) {
30913
31278
  const state = _internalGetGlobalState();
30914
- const contextManager = _optionalChain([state, 'optionalAccess', _778 => _778.contextManager]);
31279
+ const contextManager = _optionalChain([state, 'optionalAccess', _810 => _810.contextManager]);
30915
31280
  const startChannel = tracingChannel.start;
30916
31281
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
30917
- if (!_optionalChain([startChannel, 'optionalAccess', _779 => _779.bindStore]) || !currentSpanStore) {
31282
+ if (!_optionalChain([startChannel, 'optionalAccess', _811 => _811.bindStore]) || !currentSpanStore) {
30918
31283
  return void 0;
30919
31284
  }
30920
31285
  startChannel.bindStore(currentSpanStore, (event) => {
@@ -30926,7 +31291,7 @@ function bindActionCurrentSpanStoreToStart(tracingChannel, states, create) {
30926
31291
  return state2 ? contextManager.wrapSpanForStore(state2.span) : currentSpanStore.getStore();
30927
31292
  });
30928
31293
  return () => {
30929
- _optionalChain([startChannel, 'access', _780 => _780.unbindStore, 'optionalCall', _781 => _781(currentSpanStore)]);
31294
+ _optionalChain([startChannel, 'access', _812 => _812.unbindStore, 'optionalCall', _813 => _813(currentSpanStore)]);
30930
31295
  };
30931
31296
  }
30932
31297
  function normalizeInput(input) {
@@ -30973,25 +31338,25 @@ function extractGenerateOutput(result) {
30973
31338
  }
30974
31339
  function extractGenerateResponseMetadata(result, input) {
30975
31340
  const normalized = input ? normalizeInput(input) : void 0;
30976
- const request = isObject(_optionalChain([result, 'optionalAccess', _782 => _782.request])) ? _optionalChain([result, 'optionalAccess', _783 => _783.request]) : isObject(normalized) ? normalized : void 0;
31341
+ const request = isObject(_optionalChain([result, 'optionalAccess', _814 => _814.request])) ? _optionalChain([result, 'optionalAccess', _815 => _815.request]) : isObject(normalized) ? normalized : void 0;
30977
31342
  return {
30978
31343
  ...genkitProviderMetadata(),
30979
31344
  ...pickDefined({
30980
- model: modelName(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _784 => _784.model]), () => ( _optionalChain([request, 'optionalAccess', _785 => _785.model])))),
30981
- finishReason: _optionalChain([result, 'optionalAccess', _786 => _786.finishReason]),
30982
- finishMessage: _optionalChain([result, 'optionalAccess', _787 => _787.finishMessage])
31345
+ model: modelName(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _816 => _816.model]), () => ( _optionalChain([request, 'optionalAccess', _817 => _817.model])))),
31346
+ finishReason: _optionalChain([result, 'optionalAccess', _818 => _818.finishReason]),
31347
+ finishMessage: _optionalChain([result, 'optionalAccess', _819 => _819.finishMessage])
30983
31348
  })
30984
31349
  };
30985
31350
  }
30986
31351
  function extractEmbedInput(params) {
30987
31352
  return {
30988
- input: processInputAttachments(_optionalChain([params, 'optionalAccess', _788 => _788.content])),
31353
+ input: processInputAttachments(_optionalChain([params, 'optionalAccess', _820 => _820.content])),
30989
31354
  metadata: extractEmbedMetadata(params)
30990
31355
  };
30991
31356
  }
30992
31357
  function extractEmbedManyInput(params) {
30993
31358
  return {
30994
- input: processInputAttachments(_optionalChain([params, 'optionalAccess', _789 => _789.content])),
31359
+ input: processInputAttachments(_optionalChain([params, 'optionalAccess', _821 => _821.content])),
30995
31360
  metadata: extractEmbedMetadata(params)
30996
31361
  };
30997
31362
  }
@@ -30999,7 +31364,7 @@ function extractEmbedMetadata(params) {
30999
31364
  return {
31000
31365
  ...genkitProviderMetadata(),
31001
31366
  ...pickDefined({
31002
- model: modelName(_optionalChain([params, 'optionalAccess', _790 => _790.embedder]))
31367
+ model: modelName(_optionalChain([params, 'optionalAccess', _822 => _822.embedder]))
31003
31368
  })
31004
31369
  };
31005
31370
  }
@@ -31007,7 +31372,7 @@ function summarizeEmbeddingResult(result) {
31007
31372
  if (Array.isArray(result)) {
31008
31373
  return {
31009
31374
  embedding_count: result.length,
31010
- dimensions: Array.isArray(result[0]) || Array.isArray(_optionalChain([result, 'access', _791 => _791[0], 'optionalAccess', _792 => _792.embedding])) ? result[0].length || _optionalChain([result, 'access', _793 => _793[0], 'optionalAccess', _794 => _794.embedding, 'optionalAccess', _795 => _795.length]) : void 0
31375
+ dimensions: Array.isArray(result[0]) || Array.isArray(_optionalChain([result, 'access', _823 => _823[0], 'optionalAccess', _824 => _824.embedding])) ? result[0].length || _optionalChain([result, 'access', _825 => _825[0], 'optionalAccess', _826 => _826.embedding, 'optionalAccess', _827 => _827.length]) : void 0
31011
31376
  };
31012
31377
  }
31013
31378
  if (isObject(result) && Array.isArray(result.embeddings)) {
@@ -31034,7 +31399,7 @@ function patchGenerateStreamResult(result, span, startTime) {
31034
31399
  finishSpan(async () => {
31035
31400
  const streamedText = chunks.map((chunk) => safeGet(chunk, "text")).join("");
31036
31401
  const response = await result.response;
31037
- const metrics = parseGenkitUsageMetrics(_optionalChain([response, 'optionalAccess', _796 => _796.usage]));
31402
+ const metrics = parseGenkitUsageMetrics(_optionalChain([response, 'optionalAccess', _828 => _828.usage]));
31038
31403
  if (firstChunkTime !== void 0) {
31039
31404
  metrics.time_to_first_token = firstChunkTime - startTime;
31040
31405
  }
@@ -31127,22 +31492,22 @@ function extractActionMetadata(self) {
31127
31492
  }
31128
31493
  function extractActionSpanMetadata(args) {
31129
31494
  const options = extractRunInNewSpanOptions(args);
31130
- const labels = isObject(_optionalChain([options, 'optionalAccess', _797 => _797.labels])) ? options.labels : void 0;
31131
- const metadata = isObject(_optionalChain([options, 'optionalAccess', _798 => _798.metadata])) ? options.metadata : void 0;
31132
- const actionType = stringValue(_optionalChain([labels, 'optionalAccess', _799 => _799["genkit:metadata:subtype"]]));
31133
- const name = stringValue(_optionalChain([metadata, 'optionalAccess', _800 => _800.name]));
31495
+ const labels = isObject(_optionalChain([options, 'optionalAccess', _829 => _829.labels])) ? options.labels : void 0;
31496
+ const metadata = isObject(_optionalChain([options, 'optionalAccess', _830 => _830.metadata])) ? options.metadata : void 0;
31497
+ const actionType = stringValue(_optionalChain([labels, 'optionalAccess', _831 => _831["genkit:metadata:subtype"]]));
31498
+ const name = stringValue(_optionalChain([metadata, 'optionalAccess', _832 => _832.name]));
31134
31499
  if (!actionType || !name) {
31135
31500
  return void 0;
31136
31501
  }
31137
31502
  return {
31138
31503
  actionType,
31139
- key: stringValue(_optionalChain([labels, 'optionalAccess', _801 => _801["genkit:key"]])),
31504
+ key: stringValue(_optionalChain([labels, 'optionalAccess', _833 => _833["genkit:key"]])),
31140
31505
  name
31141
31506
  };
31142
31507
  }
31143
31508
  function extractActionSpanInput(args) {
31144
31509
  const options = extractRunInNewSpanOptions(args);
31145
- if (!isObject(_optionalChain([options, 'optionalAccess', _802 => _802.metadata]))) {
31510
+ if (!isObject(_optionalChain([options, 'optionalAccess', _834 => _834.metadata]))) {
31146
31511
  return void 0;
31147
31512
  }
31148
31513
  return options.metadata.input;
@@ -31155,7 +31520,7 @@ function shouldTraceAction(metadata, runStepName) {
31155
31520
  if (runStepName) {
31156
31521
  return true;
31157
31522
  }
31158
- switch (_optionalChain([metadata, 'optionalAccess', _803 => _803.actionType])) {
31523
+ switch (_optionalChain([metadata, 'optionalAccess', _835 => _835.actionType])) {
31159
31524
  case "model":
31160
31525
  case "background-model":
31161
31526
  case "embedder":
@@ -31165,8 +31530,8 @@ function shouldTraceAction(metadata, runStepName) {
31165
31530
  }
31166
31531
  }
31167
31532
  function actionSpanName(metadata, runStepName) {
31168
- const actionType = _optionalChain([metadata, 'optionalAccess', _804 => _804.actionType]);
31169
- const name = _optionalChain([metadata, 'optionalAccess', _805 => _805.name]);
31533
+ const actionType = _optionalChain([metadata, 'optionalAccess', _836 => _836.actionType]);
31534
+ const name = _optionalChain([metadata, 'optionalAccess', _837 => _837.name]);
31170
31535
  if (actionType && name) {
31171
31536
  return `genkit.${actionType}: ${name}`;
31172
31537
  }
@@ -31179,7 +31544,7 @@ function actionSpanName(metadata, runStepName) {
31179
31544
  return "genkit.action";
31180
31545
  }
31181
31546
  function actionSpanType(metadata) {
31182
- switch (_optionalChain([metadata, 'optionalAccess', _806 => _806.actionType])) {
31547
+ switch (_optionalChain([metadata, 'optionalAccess', _838 => _838.actionType])) {
31183
31548
  case "tool":
31184
31549
  case "tool.v2":
31185
31550
  return "tool" /* TOOL */;
@@ -31194,9 +31559,9 @@ function actionMetadataForLog(metadata, runStepName) {
31194
31559
  return {
31195
31560
  ...genkitProviderMetadata(),
31196
31561
  ...pickDefined({
31197
- "genkit.action_type": _optionalChain([metadata, 'optionalAccess', _807 => _807.actionType]),
31198
- "genkit.action_name": _optionalChain([metadata, 'optionalAccess', _808 => _808.name]),
31199
- "genkit.action_key": _optionalChain([metadata, 'optionalAccess', _809 => _809.key]),
31562
+ "genkit.action_type": _optionalChain([metadata, 'optionalAccess', _839 => _839.actionType]),
31563
+ "genkit.action_name": _optionalChain([metadata, 'optionalAccess', _840 => _840.name]),
31564
+ "genkit.action_key": _optionalChain([metadata, 'optionalAccess', _841 => _841.key]),
31200
31565
  "genkit.run_name": runStepName
31201
31566
  })
31202
31567
  };
@@ -31680,10 +32045,10 @@ function injectTracingHooks2(config, state) {
31680
32045
  const existingHooks = _nullishCoalesce(config.hooks, () => ( {}));
31681
32046
  const onSessionEnd = async (input, invocation) => {
31682
32047
  try {
31683
- await _optionalChain([existingHooks, 'access', _810 => _810.onSessionEnd, 'optionalCall', _811 => _811(input, invocation)]);
32048
+ await _optionalChain([existingHooks, 'access', _842 => _842.onSessionEnd, 'optionalCall', _843 => _843(input, invocation)]);
31684
32049
  } finally {
31685
32050
  handleSessionEnd(state, input.reason, input.error);
31686
- _optionalChain([state, 'access', _812 => _812.unsubscribeEvents, 'optionalCall', _813 => _813()]);
32051
+ _optionalChain([state, 'access', _844 => _844.unsubscribeEvents, 'optionalCall', _845 => _845()]);
31687
32052
  }
31688
32053
  };
31689
32054
  config.hooks = {
@@ -31727,7 +32092,7 @@ function makeSessionHandlers(sessionStates, configArgIndex, includeProviderMetad
31727
32092
  if (config.model) {
31728
32093
  metadata["github_copilot.model"] = config.model;
31729
32094
  }
31730
- if (includeProviderMetadata && _optionalChain([config, 'access', _814 => _814.provider, 'optionalAccess', _815 => _815.type])) {
32095
+ if (includeProviderMetadata && _optionalChain([config, 'access', _846 => _846.provider, 'optionalAccess', _847 => _847.type])) {
31731
32096
  metadata["github_copilot.provider_type"] = config.provider.type;
31732
32097
  }
31733
32098
  if (Object.keys(metadata).length > 0) {
@@ -31929,7 +32294,7 @@ function subscribeToFlueContext(value, state) {
31929
32294
  }
31930
32295
  released = true;
31931
32296
  try {
31932
- _optionalChain([unsubscribe, 'optionalCall', _816 => _816()]);
32297
+ _optionalChain([unsubscribe, 'optionalCall', _848 => _848()]);
31933
32298
  } catch (error) {
31934
32299
  logInstrumentationError3("Flue context unsubscribe", error);
31935
32300
  }
@@ -31961,7 +32326,7 @@ function isAutoContextTerminalEvent(event, ctx) {
31961
32326
  if (type !== "operation") {
31962
32327
  return false;
31963
32328
  }
31964
- return !_optionalChain([ctx, 'optionalAccess', _817 => _817.runId]) && typeof Reflect.get(event, "runId") !== "string";
32329
+ return !_optionalChain([ctx, 'optionalAccess', _849 => _849.runId]) && typeof Reflect.get(event, "runId") !== "string";
31965
32330
  }
31966
32331
  function isObservableFlueContext(value) {
31967
32332
  return isObjectLike(value) && typeof Reflect.get(value, "subscribeEvent") === "function";
@@ -32029,13 +32394,13 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32029
32394
  case "workflow":
32030
32395
  return this.ensureWorkflowSpanForExecution(operation, executionContext);
32031
32396
  case "agent":
32032
- return _optionalChain([this, 'access', _818 => _818.operationsById, 'access', _819 => _819.get, 'call', _820 => _820(operation.operationId), 'optionalAccess', _821 => _821.span]);
32397
+ return _optionalChain([this, 'access', _850 => _850.operationsById, 'access', _851 => _851.get, 'call', _852 => _852(operation.operationId), 'optionalAccess', _853 => _853.span]);
32033
32398
  case "model":
32034
- return _optionalChain([this, 'access', _822 => _822.turnsByKey, 'access', _823 => _823.get, 'call', _824 => _824(operation.turnId), 'optionalAccess', _825 => _825.span]);
32399
+ return _optionalChain([this, 'access', _854 => _854.turnsByKey, 'access', _855 => _855.get, 'call', _856 => _856(operation.turnId), 'optionalAccess', _857 => _857.span]);
32035
32400
  case "tool":
32036
32401
  return this.spanForToolExecution(operation, executionContext);
32037
32402
  case "task":
32038
- return _optionalChain([this, 'access', _826 => _826.tasksById, 'access', _827 => _827.get, 'call', _828 => _828(operation.taskId), 'optionalAccess', _829 => _829.span]);
32403
+ return _optionalChain([this, 'access', _858 => _858.tasksById, 'access', _859 => _859.get, 'call', _860 => _860(operation.taskId), 'optionalAccess', _861 => _861.span]);
32039
32404
  default:
32040
32405
  return void 0;
32041
32406
  }
@@ -32077,7 +32442,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32077
32442
  ctx
32078
32443
  );
32079
32444
  }
32080
- return _optionalChain([this, 'access', _830 => _830.runsById, 'access', _831 => _831.get, 'call', _832 => _832(operation.runId), 'optionalAccess', _833 => _833.span]);
32445
+ return _optionalChain([this, 'access', _862 => _862.runsById, 'access', _863 => _863.get, 'call', _864 => _864(operation.runId), 'optionalAccess', _865 => _865.span]);
32081
32446
  }
32082
32447
  spanForToolExecution(operation, executionContext) {
32083
32448
  const contextual = this.toolsByKey.get(
@@ -32148,7 +32513,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32148
32513
  if (!event.runId) {
32149
32514
  return;
32150
32515
  }
32151
- const workflowName = _nullishCoalesce(_nullishCoalesce(event.workflowName, () => ( _optionalChain([event, 'access', _834 => _834.owner, 'optionalAccess', _835 => _835.workflowName]))), () => ( (typeof _optionalChain([ctx, 'optionalAccess', _836 => _836.id]) === "string" ? ctx.id : "unknown")));
32516
+ const workflowName = _nullishCoalesce(_nullishCoalesce(event.workflowName, () => ( _optionalChain([event, 'access', _866 => _866.owner, 'optionalAccess', _867 => _867.workflowName]))), () => ( (typeof _optionalChain([ctx, 'optionalAccess', _868 => _868.id]) === "string" ? ctx.id : "unknown")));
32152
32517
  const input = flueRunInput(event);
32153
32518
  const metadata = {
32154
32519
  ...extractPayloadMetadata(input),
@@ -32182,7 +32547,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32182
32547
  if (!event.runId) {
32183
32548
  return;
32184
32549
  }
32185
- const workflowName = _nullishCoalesce(event.workflowName, () => ( (typeof _optionalChain([ctx, 'optionalAccess', _837 => _837.id]) === "string" ? ctx.id : "unknown")));
32550
+ const workflowName = _nullishCoalesce(event.workflowName, () => ( (typeof _optionalChain([ctx, 'optionalAccess', _869 => _869.id]) === "string" ? ctx.id : "unknown")));
32186
32551
  const metadata = {
32187
32552
  ...extractEventMetadata(event, ctx),
32188
32553
  ...workflowName ? { "flue.workflow_name": workflowName } : {},
@@ -32234,7 +32599,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32234
32599
  return;
32235
32600
  }
32236
32601
  const metadata = {
32237
- ...event.runId ? _optionalChain([this, 'access', _838 => _838.runsById, 'access', _839 => _839.get, 'call', _840 => _840(event.runId), 'optionalAccess', _841 => _841.metadata]) : {},
32602
+ ...event.runId ? _optionalChain([this, 'access', _870 => _870.runsById, 'access', _871 => _871.get, 'call', _872 => _872(event.runId), 'optionalAccess', _873 => _873.metadata]) : {},
32238
32603
  ...extractEventMetadata(event),
32239
32604
  "flue.operation": event.operationKind,
32240
32605
  provider: "flue"
@@ -32246,7 +32611,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32246
32611
  startTime: eventTime(event.timestamp),
32247
32612
  event: { metadata }
32248
32613
  };
32249
- const runSpan = event.runId ? _optionalChain([this, 'access', _842 => _842.runsById, 'access', _843 => _843.get, 'call', _844 => _844(event.runId), 'optionalAccess', _845 => _845.span]) : void 0;
32614
+ const runSpan = event.runId ? _optionalChain([this, 'access', _874 => _874.runsById, 'access', _875 => _875.get, 'call', _876 => _876(event.runId), 'optionalAccess', _877 => _877.span]) : void 0;
32250
32615
  const span = event.operationKind === "prompt" && (!parent || parent === runSpan) ? startFlueRootSpan(args) : startFlueSpan(parent, args);
32251
32616
  this.operationsById.set(event.operationId, { metadata, span });
32252
32617
  }
@@ -32311,7 +32676,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32311
32676
  });
32312
32677
  this.logOperationInput(
32313
32678
  event.operationId,
32314
- latestUserMessageInput(_optionalChain([input, 'optionalAccess', _846 => _846.messages]))
32679
+ latestUserMessageInput(_optionalChain([input, 'optionalAccess', _878 => _878.messages]))
32315
32680
  );
32316
32681
  this.turnsByKey.set(key, { metadata, span });
32317
32682
  }
@@ -32524,7 +32889,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32524
32889
  }
32525
32890
  }
32526
32891
  if (event.runId) {
32527
- return _optionalChain([this, 'access', _847 => _847.runsById, 'access', _848 => _848.get, 'call', _849 => _849(event.runId), 'optionalAccess', _850 => _850.span]);
32892
+ return _optionalChain([this, 'access', _879 => _879.runsById, 'access', _880 => _880.get, 'call', _881 => _881(event.runId), 'optionalAccess', _882 => _882.span]);
32528
32893
  }
32529
32894
  return void 0;
32530
32895
  }
@@ -32542,7 +32907,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32542
32907
  }
32543
32908
  }
32544
32909
  if (event.runId) {
32545
- return _optionalChain([this, 'access', _851 => _851.runsById, 'access', _852 => _852.get, 'call', _853 => _853(event.runId), 'optionalAccess', _854 => _854.span]);
32910
+ return _optionalChain([this, 'access', _883 => _883.runsById, 'access', _884 => _884.get, 'call', _885 => _885(event.runId), 'optionalAccess', _886 => _886.span]);
32546
32911
  }
32547
32912
  return void 0;
32548
32913
  }
@@ -32559,7 +32924,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32559
32924
  }
32560
32925
  startSyntheticOperation(event) {
32561
32926
  const metadata = {
32562
- ...event.runId ? _optionalChain([this, 'access', _855 => _855.runsById, 'access', _856 => _856.get, 'call', _857 => _857(event.runId), 'optionalAccess', _858 => _858.metadata]) : {},
32927
+ ...event.runId ? _optionalChain([this, 'access', _887 => _887.runsById, 'access', _888 => _888.get, 'call', _889 => _889(event.runId), 'optionalAccess', _890 => _890.metadata]) : {},
32563
32928
  ...extractEventMetadata(event),
32564
32929
  "flue.operation": event.operationKind,
32565
32930
  provider: "flue"
@@ -32571,7 +32936,7 @@ var FlueObserveBridge = (_class25 = class {constructor() { _class25.prototype.__
32571
32936
  event: { metadata }
32572
32937
  };
32573
32938
  const parent = this.parentSpanForEvent(event);
32574
- const runSpan = event.runId ? _optionalChain([this, 'access', _859 => _859.runsById, 'access', _860 => _860.get, 'call', _861 => _861(event.runId), 'optionalAccess', _862 => _862.span]) : void 0;
32939
+ const runSpan = event.runId ? _optionalChain([this, 'access', _891 => _891.runsById, 'access', _892 => _892.get, 'call', _893 => _893(event.runId), 'optionalAccess', _894 => _894.span]) : void 0;
32575
32940
  const span = event.operationKind === "prompt" && (!parent || parent === runSpan) ? startFlueRootSpan(args) : startFlueSpan(parent, args);
32576
32941
  return { metadata, span };
32577
32942
  }
@@ -32731,8 +33096,8 @@ function extractEventMetadata(event, ctx) {
32731
33096
  ...event.taskId ? { "flue.task_id": event.taskId } : {},
32732
33097
  ...event.operationId ? { "flue.operation_id": event.operationId } : {},
32733
33098
  ...event.turnId ? { "flue.turn_id": event.turnId } : {},
32734
- ...typeof _optionalChain([ctx, 'optionalAccess', _863 => _863.id]) === "string" ? { "flue.context_id": ctx.id } : {},
32735
- ...typeof _optionalChain([ctx, 'optionalAccess', _864 => _864.runId]) === "string" ? { "flue.context_run_id": ctx.runId } : {}
33099
+ ...typeof _optionalChain([ctx, 'optionalAccess', _895 => _895.id]) === "string" ? { "flue.context_id": ctx.id } : {},
33100
+ ...typeof _optionalChain([ctx, 'optionalAccess', _896 => _896.runId]) === "string" ? { "flue.context_run_id": ctx.runId } : {}
32736
33101
  };
32737
33102
  }
32738
33103
  function extractPayloadMetadata(payload) {
@@ -32749,27 +33114,27 @@ function flueRunInput(event) {
32749
33114
  return event.input !== void 0 ? event.input : event.payload;
32750
33115
  }
32751
33116
  function flueTurnRequestInput(event) {
32752
- return _nullishCoalesce(_optionalChain([event, 'access', _865 => _865.request, 'optionalAccess', _866 => _866.input]), () => ( event.input));
33117
+ return _nullishCoalesce(_optionalChain([event, 'access', _897 => _897.request, 'optionalAccess', _898 => _898.input]), () => ( event.input));
32753
33118
  }
32754
33119
  function prepareFlueTurnInput(event, input, operation) {
32755
- const messages = _optionalChain([input, 'optionalAccess', _867 => _867.messages]);
32756
- const tracksUserTurn = event.purpose === "agent" && _optionalChain([operation, 'optionalAccess', _868 => _868.metadata, 'access', _869 => _869["flue.operation"]]) === "prompt" && Array.isArray(messages);
33120
+ const messages = _optionalChain([input, 'optionalAccess', _899 => _899.messages]);
33121
+ const tracksUserTurn = event.purpose === "agent" && _optionalChain([operation, 'optionalAccess', _900 => _900.metadata, 'access', _901 => _901["flue.operation"]]) === "prompt" && Array.isArray(messages);
32757
33122
  if (!tracksUserTurn) {
32758
33123
  return {
32759
33124
  messages,
32760
33125
  metadata: {
32761
- ..._optionalChain([input, 'optionalAccess', _870 => _870.systemPrompt]) ? { "flue.system_prompt": input.systemPrompt } : {},
32762
- ..._optionalChain([input, 'optionalAccess', _871 => _871.tools]) ? { tools: input.tools } : {}
33126
+ ..._optionalChain([input, 'optionalAccess', _902 => _902.systemPrompt]) ? { "flue.system_prompt": input.systemPrompt } : {},
33127
+ ..._optionalChain([input, 'optionalAccess', _903 => _903.tools]) ? { tools: input.tools } : {}
32763
33128
  }
32764
33129
  };
32765
33130
  }
32766
33131
  const previous = operation.turnInputState;
32767
- const previousMessageCount = _nullishCoalesce(_optionalChain([previous, 'optionalAccess', _872 => _872.messageCount]), () => ( 0));
33132
+ const previousMessageCount = _nullishCoalesce(_optionalChain([previous, 'optionalAccess', _904 => _904.messageCount]), () => ( 0));
32768
33133
  const boundaryFingerprint = messages.length > 0 ? fingerprintJsonValue(messages[messages.length - 1]) : void 0;
32769
33134
  const continuesPreviousInput = previous !== void 0 && messages.length >= previousMessageCount && (previousMessageCount === 0 || previous.boundaryFingerprint !== void 0 && previous.boundaryFingerprint === fingerprintJsonValue(messages[previousMessageCount - 1]));
32770
33135
  const inputMode = previous === void 0 ? "full" : continuesPreviousInput ? "delta" : "reset";
32771
- const systemPromptFingerprint = fingerprintJsonValue(_optionalChain([input, 'optionalAccess', _873 => _873.systemPrompt]));
32772
- const toolsFingerprint = fingerprintJsonValue(_optionalChain([input, 'optionalAccess', _874 => _874.tools]));
33136
+ const systemPromptFingerprint = fingerprintJsonValue(_optionalChain([input, 'optionalAccess', _905 => _905.systemPrompt]));
33137
+ const toolsFingerprint = fingerprintJsonValue(_optionalChain([input, 'optionalAccess', _906 => _906.tools]));
32773
33138
  operation.turnInputState = {
32774
33139
  ...boundaryFingerprint !== void 0 ? { boundaryFingerprint } : {},
32775
33140
  messageCount: messages.length,
@@ -32781,8 +33146,8 @@ function prepareFlueTurnInput(event, input, operation) {
32781
33146
  metadata: {
32782
33147
  "flue.input_mode": inputMode,
32783
33148
  ...continuesPreviousInput ? { "flue.input_message_offset": previousMessageCount } : {},
32784
- ..._optionalChain([input, 'optionalAccess', _875 => _875.systemPrompt]) && (!continuesPreviousInput || systemPromptFingerprint !== _optionalChain([previous, 'optionalAccess', _876 => _876.systemPromptFingerprint])) ? { "flue.system_prompt": input.systemPrompt } : {},
32785
- ..._optionalChain([input, 'optionalAccess', _877 => _877.tools]) && (!continuesPreviousInput || toolsFingerprint !== _optionalChain([previous, 'optionalAccess', _878 => _878.toolsFingerprint])) ? { tools: input.tools } : {}
33149
+ ..._optionalChain([input, 'optionalAccess', _907 => _907.systemPrompt]) && (!continuesPreviousInput || systemPromptFingerprint !== _optionalChain([previous, 'optionalAccess', _908 => _908.systemPromptFingerprint])) ? { "flue.system_prompt": input.systemPrompt } : {},
33150
+ ..._optionalChain([input, 'optionalAccess', _909 => _909.tools]) && (!continuesPreviousInput || toolsFingerprint !== _optionalChain([previous, 'optionalAccess', _910 => _910.toolsFingerprint])) ? { tools: input.tools } : {}
32786
33151
  }
32787
33152
  };
32788
33153
  }
@@ -32814,40 +33179,40 @@ function latestUserMessageInput(messages) {
32814
33179
  return void 0;
32815
33180
  }
32816
33181
  function flueOperationInput(event) {
32817
- return typeof _optionalChain([event, 'access', _879 => _879.agentInput, 'optionalAccess', _880 => _880.text]) === "string" ? [{ content: event.agentInput.text, role: "user" }] : void 0;
33182
+ return typeof _optionalChain([event, 'access', _911 => _911.agentInput, 'optionalAccess', _912 => _912.text]) === "string" ? [{ content: event.agentInput.text, role: "user" }] : void 0;
32818
33183
  }
32819
33184
  function flueTurnRequestModel(event) {
32820
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _881 => _881.request, 'optionalAccess', _882 => _882.requestedModel]), () => ( _optionalChain([event, 'access', _883 => _883.request, 'optionalAccess', _884 => _884.model]))), () => ( event.model));
33185
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _913 => _913.request, 'optionalAccess', _914 => _914.requestedModel]), () => ( _optionalChain([event, 'access', _915 => _915.request, 'optionalAccess', _916 => _916.model]))), () => ( event.model));
32821
33186
  }
32822
33187
  function flueTurnRequestProvider(event) {
32823
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _885 => _885.request, 'optionalAccess', _886 => _886.providerName]), () => ( event.provider)), () => ( _optionalChain([event, 'access', _887 => _887.request, 'optionalAccess', _888 => _888.providerId])));
33188
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _917 => _917.request, 'optionalAccess', _918 => _918.providerName]), () => ( event.provider)), () => ( _optionalChain([event, 'access', _919 => _919.request, 'optionalAccess', _920 => _920.providerId])));
32824
33189
  }
32825
33190
  function flueTurnRequestApi(event) {
32826
- return _nullishCoalesce(_optionalChain([event, 'access', _889 => _889.request, 'optionalAccess', _890 => _890.api]), () => ( event.api));
33191
+ return _nullishCoalesce(_optionalChain([event, 'access', _921 => _921.request, 'optionalAccess', _922 => _922.api]), () => ( event.api));
32827
33192
  }
32828
33193
  function flueTurnRequestReasoning(event) {
32829
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _891 => _891.request, 'optionalAccess', _892 => _892.reasoningLevel]), () => ( _optionalChain([event, 'access', _893 => _893.request, 'optionalAccess', _894 => _894.reasoning]))), () => ( event.reasoning));
33194
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _923 => _923.request, 'optionalAccess', _924 => _924.reasoningLevel]), () => ( _optionalChain([event, 'access', _925 => _925.request, 'optionalAccess', _926 => _926.reasoning]))), () => ( event.reasoning));
32830
33195
  }
32831
33196
  function flueTurnModel(event) {
32832
- return _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _895 => _895.response, 'optionalAccess', _896 => _896.responseModel]), () => ( _optionalChain([event, 'access', _897 => _897.request, 'optionalAccess', _898 => _898.requestedModel]))), () => ( _optionalChain([event, 'access', _899 => _899.request, 'optionalAccess', _900 => _900.model]))), () => ( event.model));
33197
+ return _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _927 => _927.response, 'optionalAccess', _928 => _928.responseModel]), () => ( _optionalChain([event, 'access', _929 => _929.request, 'optionalAccess', _930 => _930.requestedModel]))), () => ( _optionalChain([event, 'access', _931 => _931.request, 'optionalAccess', _932 => _932.model]))), () => ( event.model));
32833
33198
  }
32834
33199
  function flueTurnProvider(event) {
32835
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _901 => _901.request, 'optionalAccess', _902 => _902.providerName]), () => ( event.provider)), () => ( _optionalChain([event, 'access', _903 => _903.request, 'optionalAccess', _904 => _904.providerId])));
33200
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _933 => _933.request, 'optionalAccess', _934 => _934.providerName]), () => ( event.provider)), () => ( _optionalChain([event, 'access', _935 => _935.request, 'optionalAccess', _936 => _936.providerId])));
32836
33201
  }
32837
33202
  function flueTurnApi(event) {
32838
- return _nullishCoalesce(_optionalChain([event, 'access', _905 => _905.request, 'optionalAccess', _906 => _906.api]), () => ( event.api));
33203
+ return _nullishCoalesce(_optionalChain([event, 'access', _937 => _937.request, 'optionalAccess', _938 => _938.api]), () => ( event.api));
32839
33204
  }
32840
33205
  function flueTurnUsage(event) {
32841
- return _nullishCoalesce(_optionalChain([event, 'access', _907 => _907.response, 'optionalAccess', _908 => _908.usage]), () => ( event.usage));
33206
+ return _nullishCoalesce(_optionalChain([event, 'access', _939 => _939.response, 'optionalAccess', _940 => _940.usage]), () => ( event.usage));
32842
33207
  }
32843
33208
  function flueTurnOutput(event) {
32844
- return _nullishCoalesce(_optionalChain([event, 'access', _909 => _909.response, 'optionalAccess', _910 => _910.output]), () => ( event.output));
33209
+ return _nullishCoalesce(_optionalChain([event, 'access', _941 => _941.response, 'optionalAccess', _942 => _942.output]), () => ( event.output));
32845
33210
  }
32846
33211
  function flueTurnStopReason(event) {
32847
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _911 => _911.response, 'optionalAccess', _912 => _912.finishReason]), () => ( _optionalChain([event, 'access', _913 => _913.response, 'optionalAccess', _914 => _914.stopReason]))), () => ( event.stopReason));
33212
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _943 => _943.response, 'optionalAccess', _944 => _944.finishReason]), () => ( _optionalChain([event, 'access', _945 => _945.response, 'optionalAccess', _946 => _946.stopReason]))), () => ( event.stopReason));
32848
33213
  }
32849
33214
  function flueTurnError(event) {
32850
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _915 => _915.response, 'optionalAccess', _916 => _916.error]), () => ( _optionalChain([event, 'access', _917 => _917.response, 'optionalAccess', _918 => _918.errorInfo, 'optionalAccess', _919 => _919.message]))), () => ( event.error));
33215
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([event, 'access', _947 => _947.response, 'optionalAccess', _948 => _948.error]), () => ( _optionalChain([event, 'access', _949 => _949.response, 'optionalAccess', _950 => _950.errorInfo, 'optionalAccess', _951 => _951.message]))), () => ( event.error));
32851
33216
  }
32852
33217
  function flueToolInput(event) {
32853
33218
  if (event.args !== void 0) {
@@ -32865,7 +33230,7 @@ function flueToolOutput(event) {
32865
33230
  return event.output !== void 0 ? event.output : event.result;
32866
33231
  }
32867
33232
  function flueToolError(event) {
32868
- return _nullishCoalesce(_nullishCoalesce(event.error, () => ( _optionalChain([event, 'access', _920 => _920.errorInfo, 'optionalAccess', _921 => _921.message]))), () => ( flueToolOutput(event)));
33233
+ return _nullishCoalesce(_nullishCoalesce(event.error, () => ( _optionalChain([event, 'access', _952 => _952.errorInfo, 'optionalAccess', _953 => _953.message]))), () => ( flueToolOutput(event)));
32869
33234
  }
32870
33235
  function operationOutput(event) {
32871
33236
  if (event.operationKind === "prompt" || event.operationKind === "skill") {
@@ -32874,10 +33239,10 @@ function operationOutput(event) {
32874
33239
  return _nullishCoalesce(event.result, () => ( (event.operationKind === "compact" ? { completed: true } : void 0)));
32875
33240
  }
32876
33241
  function outputFromAgentInvocation(output) {
32877
- if (_optionalChain([output, 'optionalAccess', _922 => _922.type]) === "text") {
33242
+ if (_optionalChain([output, 'optionalAccess', _954 => _954.type]) === "text") {
32878
33243
  return output.text;
32879
33244
  }
32880
- if (_optionalChain([output, 'optionalAccess', _923 => _923.type]) === "data") {
33245
+ if (_optionalChain([output, 'optionalAccess', _955 => _955.type]) === "data") {
32881
33246
  return output.data;
32882
33247
  }
32883
33248
  return void 0;
@@ -32990,9 +33355,9 @@ function startFlueRootSpan(args) {
32990
33355
  }
32991
33356
  function runWithCurrentSpanStore(span, next) {
32992
33357
  const state = _internalGetGlobalState();
32993
- const contextManager = _optionalChain([state, 'optionalAccess', _924 => _924.contextManager]);
33358
+ const contextManager = _optionalChain([state, 'optionalAccess', _956 => _956.contextManager]);
32994
33359
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
32995
- if (contextManager && typeof _optionalChain([currentSpanStore, 'optionalAccess', _925 => _925.run]) === "function") {
33360
+ if (contextManager && typeof _optionalChain([currentSpanStore, 'optionalAccess', _957 => _957.run]) === "function") {
32996
33361
  return currentSpanStore.run(contextManager.wrapSpanForStore(span), next);
32997
33362
  }
32998
33363
  return withCurrent(span, () => next());
@@ -33028,11 +33393,11 @@ var BraintrustLangChainCallbackHandler = (_class26 = class {
33028
33393
  __init87() {this.firstTokenTimes = /* @__PURE__ */ new Map()}
33029
33394
  __init88() {this.ttftMs = /* @__PURE__ */ new Map()}
33030
33395
  constructor(options) {;_class26.prototype.__init83.call(this);_class26.prototype.__init84.call(this);_class26.prototype.__init85.call(this);_class26.prototype.__init86.call(this);_class26.prototype.__init87.call(this);_class26.prototype.__init88.call(this);
33031
- this.parent = _optionalChain([options, 'optionalAccess', _926 => _926.parent]);
33396
+ this.parent = _optionalChain([options, 'optionalAccess', _958 => _958.parent]);
33032
33397
  this.options = {
33033
- debug: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _927 => _927.debug]), () => ( false)),
33034
- excludeMetadataProps: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _928 => _928.excludeMetadataProps]), () => ( /^(l[sc]_|langgraph_|__pregel_|checkpoint_ns)/)),
33035
- logger: _optionalChain([options, 'optionalAccess', _929 => _929.logger])
33398
+ debug: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _959 => _959.debug]), () => ( false)),
33399
+ excludeMetadataProps: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _960 => _960.excludeMetadataProps]), () => ( /^(l[sc]_|langgraph_|__pregel_|checkpoint_ns)/)),
33400
+ logger: _optionalChain([options, 'optionalAccess', _961 => _961.logger])
33036
33401
  };
33037
33402
  }
33038
33403
  startSpan({
@@ -33046,7 +33411,7 @@ var BraintrustLangChainCallbackHandler = (_class26 = class {
33046
33411
  if (!parentRunId) {
33047
33412
  this.rootRunId = runId;
33048
33413
  }
33049
- const tags = _optionalChain([args, 'access', _930 => _930.event, 'optionalAccess', _931 => _931.tags]);
33414
+ const tags = _optionalChain([args, 'access', _962 => _962.event, 'optionalAccess', _963 => _963.tags]);
33050
33415
  const spanAttributes = args.spanAttributes || {};
33051
33416
  spanAttributes.type = args.type || spanAttributes.type || "task";
33052
33417
  args.type = spanAttributes.type;
@@ -33066,7 +33431,7 @@ var BraintrustLangChainCallbackHandler = (_class26 = class {
33066
33431
  tags: void 0,
33067
33432
  metadata: {
33068
33433
  ...tags ? { tags } : {},
33069
- ..._optionalChain([args, 'access', _932 => _932.event, 'optionalAccess', _933 => _933.metadata]),
33434
+ ..._optionalChain([args, 'access', _964 => _964.event, 'optionalAccess', _965 => _965.metadata]),
33070
33435
  braintrust: {
33071
33436
  integration_name: "langchain-js",
33072
33437
  sdk_language: "javascript"
@@ -33172,7 +33537,7 @@ var BraintrustLangChainCallbackHandler = (_class26 = class {
33172
33537
  });
33173
33538
  }
33174
33539
  async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, runName) {
33175
- if (_optionalChain([tags, 'optionalAccess', _934 => _934.includes, 'call', _935 => _935("langsmith:hidden")])) {
33540
+ if (_optionalChain([tags, 'optionalAccess', _966 => _966.includes, 'call', _967 => _967("langsmith:hidden")])) {
33176
33541
  this.skippedRuns.add(runId);
33177
33542
  return;
33178
33543
  }
@@ -33282,7 +33647,7 @@ function getSerializedName(serialized) {
33282
33647
  if (typeof serialized.name === "string") {
33283
33648
  return serialized.name;
33284
33649
  }
33285
- const lastIdPart = _optionalChain([serialized, 'access', _936 => _936.id, 'optionalAccess', _937 => _937.at, 'call', _938 => _938(-1)]);
33650
+ const lastIdPart = _optionalChain([serialized, 'access', _968 => _968.id, 'optionalAccess', _969 => _969.at, 'call', _970 => _970(-1)]);
33286
33651
  return typeof lastIdPart === "string" ? lastIdPart : void 0;
33287
33652
  }
33288
33653
  function cleanObject(obj) {
@@ -33350,14 +33715,17 @@ function getMetricsFromResponse(response) {
33350
33715
  if (!isRecord(usageMetadata)) {
33351
33716
  continue;
33352
33717
  }
33353
- const inputTokenDetails = usageMetadata.input_token_details;
33718
+ const inputTokenDetails = isRecord(usageMetadata.input_token_details) ? usageMetadata.input_token_details : {};
33354
33719
  const outputTokenDetails = usageMetadata.output_token_details;
33355
33720
  return normalizeTokenMetrics({
33356
33721
  total_tokens: usageMetadata.total_tokens,
33357
33722
  prompt_tokens: usageMetadata.input_tokens,
33358
33723
  completion_tokens: usageMetadata.output_tokens,
33359
- prompt_cache_creation_tokens: isRecord(inputTokenDetails) ? inputTokenDetails.cache_creation : void 0,
33360
- prompt_cached_tokens: isRecord(inputTokenDetails) ? inputTokenDetails.cache_read : void 0,
33724
+ // Prefer TTL-specific cache writes over the aggregate when available.
33725
+ prompt_cache_creation_tokens: inputTokenDetails.ephemeral_5m_input_tokens == null && inputTokenDetails.ephemeral_1h_input_tokens == null ? inputTokenDetails.cache_creation : void 0,
33726
+ prompt_cache_creation_5m_tokens: inputTokenDetails.ephemeral_5m_input_tokens,
33727
+ prompt_cache_creation_1h_tokens: inputTokenDetails.ephemeral_1h_input_tokens,
33728
+ prompt_cached_tokens: inputTokenDetails.cache_read,
33361
33729
  completion_reasoning_tokens: isRecord(outputTokenDetails) ? outputTokenDetails.reasoning : void 0
33362
33730
  });
33363
33731
  }
@@ -33447,7 +33815,7 @@ function isCallbackManager(value) {
33447
33815
  return typeof maybeManager.addHandler === "function";
33448
33816
  }
33449
33817
  function hasBraintrustHandler(manager) {
33450
- return _nullishCoalesce(_optionalChain([manager, 'access', _939 => _939.handlers, 'optionalAccess', _940 => _940.some, 'call', _941 => _941((handler) => {
33818
+ return _nullishCoalesce(_optionalChain([manager, 'access', _971 => _971.handlers, 'optionalAccess', _972 => _972.some, 'call', _973 => _973((handler) => {
33451
33819
  if (typeof handler !== "object" || handler === null) {
33452
33820
  return false;
33453
33821
  }
@@ -33643,7 +34011,7 @@ var LangSmithPlugin = (_class28 = class extends BasePlugin {
33643
34011
  }
33644
34012
  if (this.shouldSkipLangChainRun(run)) {
33645
34013
  const active2 = this.activeRuns.get(id);
33646
- _optionalChain([active2, 'optionalAccess', _942 => _942.span, 'access', _943 => _943.end, 'call', _944 => _944()]);
34014
+ _optionalChain([active2, 'optionalAccess', _974 => _974.span, 'access', _975 => _975.end, 'call', _976 => _976()]);
33647
34015
  this.activeRuns.delete(id);
33648
34016
  this.completedRuns.set(id, true);
33649
34017
  return;
@@ -34023,18 +34391,18 @@ function finishPiPromptCall(state) {
34023
34391
  }
34024
34392
  function startPiPromptRun(event, onFinalize) {
34025
34393
  const session = extractSession(event);
34026
- const agent = _optionalChain([session, 'optionalAccess', _945 => _945.agent]);
34394
+ const agent = _optionalChain([session, 'optionalAccess', _977 => _977.agent]);
34027
34395
  if (!session || !isPiAgent(agent)) {
34028
34396
  return void 0;
34029
34397
  }
34030
34398
  installPiAgentInstrumentation(agent);
34031
- wrapPiToolExecutors(_optionalChain([agent, 'access', _946 => _946.state, 'optionalAccess', _947 => _947.tools]));
34399
+ wrapPiToolExecutors(_optionalChain([agent, 'access', _978 => _978.state, 'optionalAccess', _979 => _979.tools]));
34032
34400
  const metadata = {
34033
34401
  ...extractSessionMetadata(session),
34034
34402
  ...extractPromptOptionsMetadata(event.arguments[1]),
34035
34403
  "pi_coding_agent.operation": "AgentSession.prompt",
34036
- provider: _nullishCoalesce(_nullishCoalesce(_optionalChain([session, 'access', _948 => _948.model, 'optionalAccess', _949 => _949.provider]), () => ( _optionalChain([agent, 'access', _950 => _950.state, 'optionalAccess', _951 => _951.model, 'optionalAccess', _952 => _952.provider]))), () => ( "pi")),
34037
- ..._optionalChain([session, 'access', _953 => _953.model, 'optionalAccess', _954 => _954.id]) || _optionalChain([agent, 'access', _955 => _955.state, 'optionalAccess', _956 => _956.model, 'optionalAccess', _957 => _957.id]) ? { model: _nullishCoalesce(_optionalChain([session, 'access', _958 => _958.model, 'optionalAccess', _959 => _959.id]), () => ( _optionalChain([agent, 'access', _960 => _960.state, 'optionalAccess', _961 => _961.model, 'optionalAccess', _962 => _962.id]))) } : {},
34404
+ provider: _nullishCoalesce(_nullishCoalesce(_optionalChain([session, 'access', _980 => _980.model, 'optionalAccess', _981 => _981.provider]), () => ( _optionalChain([agent, 'access', _982 => _982.state, 'optionalAccess', _983 => _983.model, 'optionalAccess', _984 => _984.provider]))), () => ( "pi")),
34405
+ ..._optionalChain([session, 'access', _985 => _985.model, 'optionalAccess', _986 => _986.id]) || _optionalChain([agent, 'access', _987 => _987.state, 'optionalAccess', _988 => _988.model, 'optionalAccess', _989 => _989.id]) ? { model: _nullishCoalesce(_optionalChain([session, 'access', _990 => _990.model, 'optionalAccess', _991 => _991.id]), () => ( _optionalChain([agent, 'access', _992 => _992.state, 'optionalAccess', _993 => _993.model, 'optionalAccess', _994 => _994.id]))) } : {},
34038
34406
  ...event.moduleVersion ? { "pi_coding_agent.version": event.moduleVersion } : {}
34039
34407
  };
34040
34408
  const span = startSpan(
@@ -34056,7 +34424,7 @@ function startPiPromptRun(event, onFinalize) {
34056
34424
  activeToolSpans: /* @__PURE__ */ new Map(),
34057
34425
  agent,
34058
34426
  collectedLlmUsageMetrics: false,
34059
- deferCompletionUntilTurnEnd: _optionalChain([options, 'optionalAccess', _963 => _963.streamingBehavior]) === "followUp" || _optionalChain([options, 'optionalAccess', _964 => _964.streamingBehavior]) === "steer",
34427
+ deferCompletionUntilTurnEnd: _optionalChain([options, 'optionalAccess', _995 => _995.streamingBehavior]) === "followUp" || _optionalChain([options, 'optionalAccess', _996 => _996.streamingBehavior]) === "steer",
34060
34428
  finalized: false,
34061
34429
  metadata,
34062
34430
  metrics: {},
@@ -34392,12 +34760,12 @@ function finishPiPromptRun(state, error) {
34392
34760
  return;
34393
34761
  }
34394
34762
  state.finalized = true;
34395
- _optionalChain([state, 'access', _965 => _965.onFinalize, 'optionalCall', _966 => _966(state)]);
34763
+ _optionalChain([state, 'access', _997 => _997.onFinalize, 'optionalCall', _998 => _998(state)]);
34396
34764
  finishOpenLlmSpans(state, error);
34397
34765
  finishOpenToolSpans(state, error);
34398
34766
  const metadata = {
34399
34767
  ...state.metadata,
34400
- ...extractModelMetadata2(_optionalChain([state, 'access', _967 => _967.agent, 'access', _968 => _968.state, 'optionalAccess', _969 => _969.model]))
34768
+ ...extractModelMetadata2(_optionalChain([state, 'access', _999 => _999.agent, 'access', _1000 => _1000.state, 'optionalAccess', _1001 => _1001.model]))
34401
34769
  };
34402
34770
  try {
34403
34771
  safeLog4(state.span, {
@@ -34428,13 +34796,13 @@ function finishPiLlmSpan(promptState, llmState, message, error) {
34428
34796
  }
34429
34797
  llmState.finalized = true;
34430
34798
  promptState.activeLlmSpans.delete(llmState);
34431
- const messageError = _optionalChain([message, 'optionalAccess', _970 => _970.stopReason]) === "error" && message.errorMessage;
34799
+ const messageError = _optionalChain([message, 'optionalAccess', _1002 => _1002.stopReason]) === "error" && message.errorMessage;
34432
34800
  const metrics = {
34433
- ...extractUsageMetrics2(_optionalChain([message, 'optionalAccess', _971 => _971.usage])),
34801
+ ...extractUsageMetrics2(_optionalChain([message, 'optionalAccess', _1003 => _1003.usage])),
34434
34802
  ...cleanMetrics5(llmState.metrics),
34435
34803
  ...buildDurationMetrics3(llmState.startTime)
34436
34804
  };
34437
- const usageMetrics = extractUsageMetrics2(_optionalChain([message, 'optionalAccess', _972 => _972.usage]));
34805
+ const usageMetrics = extractUsageMetrics2(_optionalChain([message, 'optionalAccess', _1004 => _1004.usage]));
34438
34806
  if (Object.keys(usageMetrics).length > 0) {
34439
34807
  promptState.collectedLlmUsageMetrics = true;
34440
34808
  addMetrics(promptState.metrics, usageMetrics);
@@ -34569,7 +34937,7 @@ function normalizeStopReason(reason) {
34569
34937
  }
34570
34938
  }
34571
34939
  function extractPromptInput(text, options) {
34572
- const images = _optionalChain([options, 'optionalAccess', _973 => _973.images]);
34940
+ const images = _optionalChain([options, 'optionalAccess', _1005 => _1005.images]);
34573
34941
  if (!images || images.length === 0) {
34574
34942
  return text;
34575
34943
  }
@@ -34879,7 +35247,7 @@ function instrumentStrandsStreamInvocation(options) {
34879
35247
  return result;
34880
35248
  }
34881
35249
  function startAgentStream(input, agent, activeChildParents) {
34882
- const model = _optionalChain([agent, 'optionalAccess', _974 => _974.model]);
35250
+ const model = _optionalChain([agent, 'optionalAccess', _1006 => _1006.model]);
34883
35251
  const metadata = {
34884
35252
  ...extractAgentMetadata2(agent),
34885
35253
  ...extractModelMetadata3(model),
@@ -34930,7 +35298,7 @@ function startMultiAgentStream(input, orchestrator, operation, activeChildParent
34930
35298
  const metadata = {
34931
35299
  "strands.operation": operation,
34932
35300
  provider: "strands",
34933
- ..._optionalChain([orchestrator, 'optionalAccess', _975 => _975.id]) ? { "strands.orchestrator.id": orchestrator.id } : {}
35301
+ ..._optionalChain([orchestrator, 'optionalAccess', _1007 => _1007.id]) ? { "strands.orchestrator.id": orchestrator.id } : {}
34934
35302
  };
34935
35303
  const parentSpan = orchestrator ? getOnlyChildParent(activeChildParents, orchestrator) : void 0;
34936
35304
  const processedInput = processStrandsInputAttachments(input);
@@ -35002,7 +35370,7 @@ function handleAgentStreamEvent(state, event) {
35002
35370
  },
35003
35371
  metrics: {
35004
35372
  ...buildDurationMetrics4(state.startTime),
35005
- ...parseUsage(_optionalChain([event, 'access', _976 => _976.result, 'optionalAccess', _977 => _977.metrics, 'optionalAccess', _978 => _978.accumulatedUsage]))
35373
+ ...parseUsage(_optionalChain([event, 'access', _1008 => _1008.result, 'optionalAccess', _1009 => _1009.metrics, 'optionalAccess', _1010 => _1010.accumulatedUsage]))
35006
35374
  },
35007
35375
  output: extractAgentResultOutput(event.result)
35008
35376
  });
@@ -35038,7 +35406,7 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
35038
35406
  },
35039
35407
  metrics: {
35040
35408
  ...buildDurationMetrics4(state.startTime),
35041
- ...parseUsage(_optionalChain([event, 'access', _979 => _979.result, 'optionalAccess', _980 => _980.usage]))
35409
+ ...parseUsage(_optionalChain([event, 'access', _1011 => _1011.result, 'optionalAccess', _1012 => _1012.usage]))
35042
35410
  },
35043
35411
  output: extractMultiAgentResultOutput(event.result)
35044
35412
  });
@@ -35051,8 +35419,8 @@ function handleMultiAgentStreamEvent(state, event, activeChildParents) {
35051
35419
  }
35052
35420
  }
35053
35421
  function buildModelSpanInput(event, attachmentCache) {
35054
- const systemPrompt = typeof _optionalChain([event, 'access', _981 => _981.agent, 'optionalAccess', _982 => _982.systemPrompt]) === "string" && event.agent.systemPrompt.length > 0 ? event.agent.systemPrompt : void 0;
35055
- const processedMessages = Array.isArray(_optionalChain([event, 'access', _983 => _983.agent, 'optionalAccess', _984 => _984.messages])) ? processStrandsInputAttachments(event.agent.messages, attachmentCache) : void 0;
35422
+ const systemPrompt = typeof _optionalChain([event, 'access', _1013 => _1013.agent, 'optionalAccess', _1014 => _1014.systemPrompt]) === "string" && event.agent.systemPrompt.length > 0 ? event.agent.systemPrompt : void 0;
35423
+ const processedMessages = Array.isArray(_optionalChain([event, 'access', _1015 => _1015.agent, 'optionalAccess', _1016 => _1016.messages])) ? processStrandsInputAttachments(event.agent.messages, attachmentCache) : void 0;
35056
35424
  if (!systemPrompt) {
35057
35425
  return processedMessages;
35058
35426
  }
@@ -35063,7 +35431,7 @@ function startModelSpan(state, event) {
35063
35431
  if (state.activeModel) {
35064
35432
  finalizeModelSpan(state);
35065
35433
  }
35066
- const model = _nullishCoalesce(event.model, () => ( _optionalChain([event, 'access', _985 => _985.agent, 'optionalAccess', _986 => _986.model])));
35434
+ const model = _nullishCoalesce(event.model, () => ( _optionalChain([event, 'access', _1017 => _1017.agent, 'optionalAccess', _1018 => _1018.model])));
35067
35435
  const metadata = {
35068
35436
  ...extractModelMetadata3(model),
35069
35437
  "strands.operation": "model.stream",
@@ -35094,7 +35462,7 @@ function startModelSpan(state, event) {
35094
35462
  };
35095
35463
  }
35096
35464
  function collectModelStreamMetadata(state, event) {
35097
- if (!state.activeModel || _optionalChain([event, 'access', _987 => _987.event, 'optionalAccess', _988 => _988.type]) !== "modelMetadataEvent") {
35465
+ if (!state.activeModel || _optionalChain([event, 'access', _1019 => _1019.event, 'optionalAccess', _1020 => _1020.type]) !== "modelMetadataEvent") {
35098
35466
  return;
35099
35467
  }
35100
35468
  Object.assign(state.activeModel.metrics, parseUsage(event.event.usage));
@@ -35111,18 +35479,18 @@ function finalizeModelSpan(state, event) {
35111
35479
  state.activeModel = void 0;
35112
35480
  const metadata = {
35113
35481
  ...modelState.metadata,
35114
- ..._optionalChain([event, 'optionalAccess', _989 => _989.attemptCount]) ? { "strands.model.attempt": event.attemptCount } : {},
35115
- ..._optionalChain([event, 'optionalAccess', _990 => _990.stopData, 'optionalAccess', _991 => _991.stopReason]) ? { "strands.stop_reason": event.stopData.stopReason } : {}
35482
+ ..._optionalChain([event, 'optionalAccess', _1021 => _1021.attemptCount]) ? { "strands.model.attempt": event.attemptCount } : {},
35483
+ ..._optionalChain([event, 'optionalAccess', _1022 => _1022.stopData, 'optionalAccess', _1023 => _1023.stopReason]) ? { "strands.stop_reason": event.stopData.stopReason } : {}
35116
35484
  };
35117
35485
  const metrics = {
35118
35486
  ...buildDurationMetrics4(modelState.startTime),
35119
35487
  ...modelState.metrics
35120
35488
  };
35121
35489
  safeLog5(modelState.span, {
35122
- ..._optionalChain([event, 'optionalAccess', _992 => _992.error]) ? { error: toLoggedError(event.error) } : {},
35490
+ ..._optionalChain([event, 'optionalAccess', _1024 => _1024.error]) ? { error: toLoggedError(event.error) } : {},
35123
35491
  metadata,
35124
35492
  metrics: cleanMetrics6(metrics),
35125
- output: _optionalChain([event, 'optionalAccess', _993 => _993.stopData, 'optionalAccess', _994 => _994.message])
35493
+ output: _optionalChain([event, 'optionalAccess', _1025 => _1025.stopData, 'optionalAccess', _1026 => _1026.message])
35126
35494
  });
35127
35495
  modelState.span.end();
35128
35496
  }
@@ -35140,9 +35508,9 @@ function startToolSpan2(state, event) {
35140
35508
  withSpanInstrumentationName(
35141
35509
  {
35142
35510
  event: {
35143
- input: _optionalChain([toolUse, 'optionalAccess', _995 => _995.input]),
35511
+ input: _optionalChain([toolUse, 'optionalAccess', _1027 => _1027.input]),
35144
35512
  metadata: {
35145
- "gen_ai.tool.call.id": _optionalChain([toolUse, 'optionalAccess', _996 => _996.toolUseId]),
35513
+ "gen_ai.tool.call.id": _optionalChain([toolUse, 'optionalAccess', _1028 => _1028.toolUseId]),
35146
35514
  "gen_ai.tool.name": name,
35147
35515
  "strands.operation": "tool.call",
35148
35516
  "strands.tool.name": name,
@@ -35198,8 +35566,8 @@ function finalizeToolSpanState(toolState, data = {}) {
35198
35566
  safeLog5(toolState.span, {
35199
35567
  ...data.error ? { error: toLoggedError(data.error) } : {},
35200
35568
  metadata: {
35201
- ..._nullishCoalesce(_optionalChain([data, 'access', _997 => _997.toolUse, 'optionalAccess', _998 => _998.toolUseId]), () => ( _optionalChain([toolState, 'access', _999 => _999.toolUse, 'optionalAccess', _1000 => _1000.toolUseId]))) ? {
35202
- "gen_ai.tool.call.id": _nullishCoalesce(_optionalChain([data, 'access', _1001 => _1001.toolUse, 'optionalAccess', _1002 => _1002.toolUseId]), () => ( _optionalChain([toolState, 'access', _1003 => _1003.toolUse, 'optionalAccess', _1004 => _1004.toolUseId])))
35569
+ ..._nullishCoalesce(_optionalChain([data, 'access', _1029 => _1029.toolUse, 'optionalAccess', _1030 => _1030.toolUseId]), () => ( _optionalChain([toolState, 'access', _1031 => _1031.toolUse, 'optionalAccess', _1032 => _1032.toolUseId]))) ? {
35570
+ "gen_ai.tool.call.id": _nullishCoalesce(_optionalChain([data, 'access', _1033 => _1033.toolUse, 'optionalAccess', _1034 => _1034.toolUseId]), () => ( _optionalChain([toolState, 'access', _1035 => _1035.toolUse, 'optionalAccess', _1036 => _1036.toolUseId])))
35203
35571
  } : {},
35204
35572
  ...extractToolName3(_nullishCoalesce(data.toolUse, () => ( toolState.toolUse))) ? {
35205
35573
  "gen_ai.tool.name": extractToolName3(
@@ -35219,7 +35587,7 @@ function startNodeSpan(state, event, activeChildParents) {
35219
35587
  const child = extractNodeChild(node);
35220
35588
  const metadata = {
35221
35589
  "strands.node.id": nodeId,
35222
- ..._optionalChain([node, 'optionalAccess', _1005 => _1005.type]) ? { "strands.node.type": node.type } : {},
35590
+ ..._optionalChain([node, 'optionalAccess', _1037 => _1037.type]) ? { "strands.node.type": node.type } : {},
35223
35591
  "strands.operation": "node.call",
35224
35592
  provider: "strands"
35225
35593
  };
@@ -35247,21 +35615,21 @@ function startNodeSpan(state, event, activeChildParents) {
35247
35615
  }
35248
35616
  }
35249
35617
  function logNodeResult(state, event) {
35250
- const nodeId = _nullishCoalesce(_nullishCoalesce(event.nodeId, () => ( _optionalChain([event, 'access', _1006 => _1006.result, 'optionalAccess', _1007 => _1007.nodeId]))), () => ( "unknown"));
35618
+ const nodeId = _nullishCoalesce(_nullishCoalesce(event.nodeId, () => ( _optionalChain([event, 'access', _1038 => _1038.result, 'optionalAccess', _1039 => _1039.nodeId]))), () => ( "unknown"));
35251
35619
  const nodeState = state.activeNodes.get(nodeId);
35252
35620
  if (!nodeState) {
35253
35621
  return;
35254
35622
  }
35255
35623
  safeLog5(nodeState.span, {
35256
- ..._optionalChain([event, 'access', _1008 => _1008.result, 'optionalAccess', _1009 => _1009.error]) ? { error: toLoggedError(event.result.error) } : {},
35624
+ ..._optionalChain([event, 'access', _1040 => _1040.result, 'optionalAccess', _1041 => _1041.error]) ? { error: toLoggedError(event.result.error) } : {},
35257
35625
  metadata: {
35258
35626
  ...event.nodeType ? { "strands.node.type": event.nodeType } : {},
35259
- ..._optionalChain([event, 'access', _1010 => _1010.result, 'optionalAccess', _1011 => _1011.status]) ? { "strands.node.status": event.result.status } : {}
35627
+ ..._optionalChain([event, 'access', _1042 => _1042.result, 'optionalAccess', _1043 => _1043.status]) ? { "strands.node.status": event.result.status } : {}
35260
35628
  },
35261
35629
  metrics: {
35262
35630
  ...buildDurationMetrics4(nodeState.startTime),
35263
- ...typeof _optionalChain([event, 'access', _1012 => _1012.result, 'optionalAccess', _1013 => _1013.duration]) === "number" ? { "strands.node.duration_ms": event.result.duration } : {},
35264
- ...parseUsage(_optionalChain([event, 'access', _1014 => _1014.result, 'optionalAccess', _1015 => _1015.usage]))
35631
+ ...typeof _optionalChain([event, 'access', _1044 => _1044.result, 'optionalAccess', _1045 => _1045.duration]) === "number" ? { "strands.node.duration_ms": event.result.duration } : {},
35632
+ ...parseUsage(_optionalChain([event, 'access', _1046 => _1046.result, 'optionalAccess', _1047 => _1047.usage]))
35265
35633
  },
35266
35634
  output: extractNodeResultOutput(event.result)
35267
35635
  });
@@ -35334,9 +35702,9 @@ function extractOrchestrator(orchestrator, self) {
35334
35702
  }
35335
35703
  function extractAgentMetadata2(agent) {
35336
35704
  return {
35337
- ..._optionalChain([agent, 'optionalAccess', _1016 => _1016.id]) ? { "strands.agent.id": agent.id } : {},
35338
- ..._optionalChain([agent, 'optionalAccess', _1017 => _1017.name]) ? { "strands.agent.name": agent.name } : {},
35339
- ..._optionalChain([agent, 'optionalAccess', _1018 => _1018.description]) ? { "strands.agent.description": agent.description } : {}
35705
+ ..._optionalChain([agent, 'optionalAccess', _1048 => _1048.id]) ? { "strands.agent.id": agent.id } : {},
35706
+ ..._optionalChain([agent, 'optionalAccess', _1049 => _1049.name]) ? { "strands.agent.name": agent.name } : {},
35707
+ ..._optionalChain([agent, 'optionalAccess', _1050 => _1050.description]) ? { "strands.agent.description": agent.description } : {}
35340
35708
  };
35341
35709
  }
35342
35710
  function extractModelMetadata3(model) {
@@ -35344,28 +35712,28 @@ function extractModelMetadata3(model) {
35344
35712
  const modelName2 = extractModelName2(model);
35345
35713
  return {
35346
35714
  ...modelName2 ? { model: modelName2 } : {},
35347
- ..._optionalChain([config, 'optionalAccess', _1019 => _1019.api]) ? { "strands.model.api": config.api } : {},
35348
- ..._optionalChain([model, 'optionalAccess', _1020 => _1020.stateful]) !== void 0 ? { "strands.model.stateful": model.stateful } : {}
35715
+ ..._optionalChain([config, 'optionalAccess', _1051 => _1051.api]) ? { "strands.model.api": config.api } : {},
35716
+ ..._optionalChain([model, 'optionalAccess', _1052 => _1052.stateful]) !== void 0 ? { "strands.model.stateful": model.stateful } : {}
35349
35717
  };
35350
35718
  }
35351
35719
  function extractAgentResultMetadata(result) {
35352
35720
  return {
35353
- ..._optionalChain([result, 'optionalAccess', _1021 => _1021.stopReason]) ? { "strands.stop_reason": result.stopReason } : {},
35354
- ...typeof _optionalChain([result, 'optionalAccess', _1022 => _1022.metrics, 'optionalAccess', _1023 => _1023.latestContextSize]) === "number" ? { "strands.context_size": result.metrics.latestContextSize } : {},
35355
- ...typeof _optionalChain([result, 'optionalAccess', _1024 => _1024.metrics, 'optionalAccess', _1025 => _1025.projectedContextSize]) === "number" ? {
35721
+ ..._optionalChain([result, 'optionalAccess', _1053 => _1053.stopReason]) ? { "strands.stop_reason": result.stopReason } : {},
35722
+ ...typeof _optionalChain([result, 'optionalAccess', _1054 => _1054.metrics, 'optionalAccess', _1055 => _1055.latestContextSize]) === "number" ? { "strands.context_size": result.metrics.latestContextSize } : {},
35723
+ ...typeof _optionalChain([result, 'optionalAccess', _1056 => _1056.metrics, 'optionalAccess', _1057 => _1057.projectedContextSize]) === "number" ? {
35356
35724
  "strands.projected_context_size": result.metrics.projectedContextSize
35357
35725
  } : {}
35358
35726
  };
35359
35727
  }
35360
35728
  function extractMultiAgentResultMetadata(result) {
35361
35729
  return {
35362
- ..._optionalChain([result, 'optionalAccess', _1026 => _1026.status]) ? { "strands.status": result.status } : {},
35363
- ...typeof _optionalChain([result, 'optionalAccess', _1027 => _1027.duration]) === "number" ? { "strands.duration_ms": result.duration } : {}
35730
+ ..._optionalChain([result, 'optionalAccess', _1058 => _1058.status]) ? { "strands.status": result.status } : {},
35731
+ ...typeof _optionalChain([result, 'optionalAccess', _1059 => _1059.duration]) === "number" ? { "strands.duration_ms": result.duration } : {}
35364
35732
  };
35365
35733
  }
35366
35734
  function extractProvider(model) {
35367
35735
  const config = getModelConfig(model);
35368
- if (typeof _optionalChain([config, 'optionalAccess', _1028 => _1028.provider]) === "string") {
35736
+ if (typeof _optionalChain([config, 'optionalAccess', _1060 => _1060.provider]) === "string") {
35369
35737
  return config.provider;
35370
35738
  }
35371
35739
  const constructorName = getConstructorName(model).toLowerCase();
@@ -35388,13 +35756,13 @@ function extractProvider(model) {
35388
35756
  }
35389
35757
  function extractModelName2(model) {
35390
35758
  const config = getModelConfig(model);
35391
- if (typeof _optionalChain([model, 'optionalAccess', _1029 => _1029.modelId]) === "string") {
35759
+ if (typeof _optionalChain([model, 'optionalAccess', _1061 => _1061.modelId]) === "string") {
35392
35760
  return model.modelId;
35393
35761
  }
35394
- if (typeof _optionalChain([config, 'optionalAccess', _1030 => _1030.modelId]) === "string") {
35762
+ if (typeof _optionalChain([config, 'optionalAccess', _1062 => _1062.modelId]) === "string") {
35395
35763
  return config.modelId;
35396
35764
  }
35397
- if (typeof _optionalChain([config, 'optionalAccess', _1031 => _1031.model]) === "string") {
35765
+ if (typeof _optionalChain([config, 'optionalAccess', _1063 => _1063.model]) === "string") {
35398
35766
  return config.model;
35399
35767
  }
35400
35768
  return void 0;
@@ -35411,7 +35779,7 @@ function getModelConfig(model) {
35411
35779
  }
35412
35780
  }
35413
35781
  function formatAgentSpanName(agent) {
35414
- return _optionalChain([agent, 'optionalAccess', _1032 => _1032.name]) ? `Agent: ${agent.name}` : "Strands Agent";
35782
+ return _optionalChain([agent, 'optionalAccess', _1064 => _1064.name]) ? `Agent: ${agent.name}` : "Strands Agent";
35415
35783
  }
35416
35784
  function formatModelSpanName(model) {
35417
35785
  const modelName2 = extractModelName2(model);
@@ -35588,7 +35956,7 @@ function createStrandsMediaAttachment(mediaKey, media, cache) {
35588
35956
  function getOrCreateStrandsAttachment(data, filename, contentType, cache) {
35589
35957
  const key = `${contentType}\0${filename}`;
35590
35958
  const attachments = typeof data === "string" ? cache.strings.get(data) : isObject(data) ? cache.objects.get(data) : void 0;
35591
- const cached = _optionalChain([attachments, 'optionalAccess', _1033 => _1033.get, 'call', _1034 => _1034(key)]);
35959
+ const cached = _optionalChain([attachments, 'optionalAccess', _1065 => _1065.get, 'call', _1066 => _1066(key)]);
35592
35960
  if (cached) {
35593
35961
  return cached;
35594
35962
  }
@@ -35616,24 +35984,24 @@ function normalizeContentBlocks(blocks) {
35616
35984
  }
35617
35985
  function parseUsage(usage) {
35618
35986
  const metrics = {};
35619
- assignMetric(metrics, "prompt_tokens", _optionalChain([usage, 'optionalAccess', _1035 => _1035.inputTokens]));
35620
- assignMetric(metrics, "completion_tokens", _optionalChain([usage, 'optionalAccess', _1036 => _1036.outputTokens]));
35621
- assignMetric(metrics, "tokens", _optionalChain([usage, 'optionalAccess', _1037 => _1037.totalTokens]));
35622
- assignMetric(metrics, "prompt_cached_tokens", _optionalChain([usage, 'optionalAccess', _1038 => _1038.cacheReadInputTokens]));
35987
+ assignMetric(metrics, "prompt_tokens", _optionalChain([usage, 'optionalAccess', _1067 => _1067.inputTokens]));
35988
+ assignMetric(metrics, "completion_tokens", _optionalChain([usage, 'optionalAccess', _1068 => _1068.outputTokens]));
35989
+ assignMetric(metrics, "tokens", _optionalChain([usage, 'optionalAccess', _1069 => _1069.totalTokens]));
35990
+ assignMetric(metrics, "prompt_cached_tokens", _optionalChain([usage, 'optionalAccess', _1070 => _1070.cacheReadInputTokens]));
35623
35991
  assignMetric(
35624
35992
  metrics,
35625
35993
  "prompt_cache_creation_tokens",
35626
- _optionalChain([usage, 'optionalAccess', _1039 => _1039.cacheWriteInputTokens])
35994
+ _optionalChain([usage, 'optionalAccess', _1071 => _1071.cacheWriteInputTokens])
35627
35995
  );
35628
35996
  return metrics;
35629
35997
  }
35630
35998
  function parseModelMetrics(metrics) {
35631
35999
  const parsed = {};
35632
- assignMetric(parsed, "strands.latency_ms", _optionalChain([metrics, 'optionalAccess', _1040 => _1040.latencyMs]));
36000
+ assignMetric(parsed, "strands.latency_ms", _optionalChain([metrics, 'optionalAccess', _1072 => _1072.latencyMs]));
35633
36001
  assignMetric(
35634
36002
  parsed,
35635
36003
  "strands.time_to_first_byte_ms",
35636
- _optionalChain([metrics, 'optionalAccess', _1041 => _1041.timeToFirstByteMs])
36004
+ _optionalChain([metrics, 'optionalAccess', _1073 => _1073.timeToFirstByteMs])
35637
36005
  );
35638
36006
  return parsed;
35639
36007
  }
@@ -35660,20 +36028,20 @@ function cleanMetrics6(metrics) {
35660
36028
  return cleaned;
35661
36029
  }
35662
36030
  function extractToolName3(toolUse, tool) {
35663
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([toolUse, 'optionalAccess', _1042 => _1042.name]), () => ( _optionalChain([tool, 'optionalAccess', _1043 => _1043.name]))), () => ( "unknown"));
36031
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([toolUse, 'optionalAccess', _1074 => _1074.name]), () => ( _optionalChain([tool, 'optionalAccess', _1075 => _1075.name]))), () => ( "unknown"));
35664
36032
  }
35665
36033
  function toolKey2(toolUse) {
35666
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([toolUse, 'optionalAccess', _1044 => _1044.toolUseId]), () => ( _optionalChain([toolUse, 'optionalAccess', _1045 => _1045.name]))), () => ( "unknown"));
36034
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([toolUse, 'optionalAccess', _1076 => _1076.toolUseId]), () => ( _optionalChain([toolUse, 'optionalAccess', _1077 => _1077.name]))), () => ( "unknown"));
35667
36035
  }
35668
36036
  function findNode(orchestrator, nodeId) {
35669
36037
  try {
35670
- return _optionalChain([orchestrator, 'optionalAccess', _1046 => _1046.nodes, 'optionalAccess', _1047 => _1047.get, 'call', _1048 => _1048(nodeId)]);
36038
+ return _optionalChain([orchestrator, 'optionalAccess', _1078 => _1078.nodes, 'optionalAccess', _1079 => _1079.get, 'call', _1080 => _1080(nodeId)]);
35671
36039
  } catch (e97) {
35672
36040
  return void 0;
35673
36041
  }
35674
36042
  }
35675
36043
  function extractNodeChild(node) {
35676
- const child = _nullishCoalesce(_optionalChain([node, 'optionalAccess', _1049 => _1049.agent]), () => ( _optionalChain([node, 'optionalAccess', _1050 => _1050.orchestrator])));
36044
+ const child = _nullishCoalesce(_optionalChain([node, 'optionalAccess', _1081 => _1081.agent]), () => ( _optionalChain([node, 'optionalAccess', _1082 => _1082.orchestrator])));
35677
36045
  return isObject(child) ? child : void 0;
35678
36046
  }
35679
36047
  function pushChildParent(activeChildParents, child, span) {
@@ -35716,6 +36084,477 @@ function logInstrumentationError5(context, error) {
35716
36084
  debugLogger.debug(`${context}:`, error);
35717
36085
  }
35718
36086
 
36087
+ // src/instrumentation/plugins/elevenlabs-channels.ts
36088
+ var elevenLabsChannels = defineChannels(
36089
+ "@elevenlabs/elevenlabs-js",
36090
+ {
36091
+ convert: channel({
36092
+ channelName: "textToSpeech.convert",
36093
+ kind: "async"
36094
+ }),
36095
+ stream: channel({
36096
+ channelName: "textToSpeech.stream",
36097
+ kind: "async"
36098
+ }),
36099
+ convertWithTimestamps: channel({ channelName: "textToSpeech.convertWithTimestamps", kind: "async" }),
36100
+ streamWithTimestamps: channel({ channelName: "textToSpeech.streamWithTimestamps", kind: "async" }),
36101
+ transcribe: channel({ channelName: "speechToText.convert", kind: "async" })
36102
+ },
36103
+ { instrumentationName: INSTRUMENTATION_NAMES.ELEVENLABS }
36104
+ );
36105
+
36106
+ // src/instrumentation/plugins/elevenlabs-plugin.ts
36107
+ var ElevenLabsPlugin = class extends BasePlugin {
36108
+ onEnable() {
36109
+ for (const method of [
36110
+ "convert",
36111
+ "stream",
36112
+ "convertWithTimestamps",
36113
+ "streamWithTimestamps"
36114
+ ]) {
36115
+ this.unsubscribers.push(
36116
+ interceptCall2(
36117
+ elevenLabsChannels[method],
36118
+ `elevenlabs.textToSpeech.${method}`,
36119
+ ([voice, request]) => ({
36120
+ input: {
36121
+ operation: "speech",
36122
+ prompt: request.text,
36123
+ parameters: {
36124
+ voice,
36125
+ format: request.outputFormat,
36126
+ language: request.languageCode,
36127
+ speed: _optionalChain([request, 'access', _1083 => _1083.voiceSettings, 'optionalAccess', _1084 => _1084.speed])
36128
+ }
36129
+ },
36130
+ metadata: {
36131
+ provider: "elevenlabs",
36132
+ model: _nullishCoalesce(request.modelId, () => ( "eleven_multilingual_v2"))
36133
+ }
36134
+ }),
36135
+ (value, args, span, finish, headers, started) => captureSpeech(
36136
+ value,
36137
+ args[1],
36138
+ method,
36139
+ span,
36140
+ finish,
36141
+ started,
36142
+ headers
36143
+ )
36144
+ )
36145
+ );
36146
+ }
36147
+ this.unsubscribers.push(
36148
+ interceptCall2(
36149
+ elevenLabsChannels.transcribe,
36150
+ "elevenlabs.speechToText.convert",
36151
+ ([request]) => {
36152
+ if (request.webhook) return void 0;
36153
+ const file = request.file;
36154
+ const filename = typeof File !== "undefined" && file instanceof File ? file.name : "audio";
36155
+ const contentType = file instanceof Blob ? file.type || "application/octet-stream" : "application/octet-stream";
36156
+ const blob = file instanceof Blob ? file : file instanceof Uint8Array ? new Blob([new Uint8Array(file)], { type: contentType }) : file instanceof ArrayBuffer ? new Blob([file.slice(0)], { type: contentType }) : void 0;
36157
+ const fileData = blob ? new Attachment({ data: blob, filename, contentType }) : request.cloudStorageUrl;
36158
+ return {
36159
+ input: {
36160
+ operation: "transcribe",
36161
+ content: fileData ? [{ type: "file", file: { filename, file_data: fileData } }] : [],
36162
+ parameters: {
36163
+ language: request.languageCode,
36164
+ timestamp_granularities: request.timestampsGranularity
36165
+ }
36166
+ },
36167
+ metadata: { provider: "elevenlabs", model: request.modelId }
36168
+ };
36169
+ },
36170
+ (value, _args, span, finish) => {
36171
+ const result = value;
36172
+ const transcripts = _nullishCoalesce(result.transcripts, () => ( [result]));
36173
+ span.log({
36174
+ output: {
36175
+ content: transcripts.flatMap(
36176
+ (transcript) => typeof transcript.text === "string" ? [{ type: "text", text: transcript.text }] : []
36177
+ ),
36178
+ annotations: {
36179
+ language: result.languageCode,
36180
+ words: _nullishCoalesce(result.words, () => ( (result.transcripts ? result.transcripts.flatMap(
36181
+ (transcript) => _nullishCoalesce(transcript.words, () => ( []))
36182
+ ) : void 0)))
36183
+ }
36184
+ }
36185
+ });
36186
+ finish();
36187
+ },
36188
+ ([request], span) => {
36189
+ const file = request.file;
36190
+ if (!isAsyncIterable(file)) return;
36191
+ const chunks = [];
36192
+ const filename = isObject(file) && typeof file.path === "string" ? file.path.split(/[\\/]/).pop() || "audio" : "audio";
36193
+ observeAudioStream(
36194
+ file,
36195
+ (chunk) => chunks.push(new Uint8Array(chunk)),
36196
+ () => {
36197
+ const contentType = "application/octet-stream";
36198
+ const data = new Blob(chunks, {
36199
+ type: contentType
36200
+ });
36201
+ chunks.length = 0;
36202
+ span.log({
36203
+ input: {
36204
+ content: [
36205
+ {
36206
+ type: "file",
36207
+ file: {
36208
+ filename,
36209
+ file_data: new Attachment({
36210
+ data,
36211
+ filename,
36212
+ contentType
36213
+ })
36214
+ }
36215
+ }
36216
+ ]
36217
+ }
36218
+ });
36219
+ },
36220
+ () => {
36221
+ chunks.length = 0;
36222
+ },
36223
+ span
36224
+ );
36225
+ }
36226
+ )
36227
+ );
36228
+ }
36229
+ onDisable() {
36230
+ this.unsubscribers = unsubscribeAll(this.unsubscribers);
36231
+ }
36232
+ };
36233
+ function interceptCall2(channel2, name, input, output, beforeInvoke) {
36234
+ return channel2.intercept((target, self, args) => {
36235
+ const invoke2 = () => Reflect.apply(target, self, args);
36236
+ if (isAutoInstrumentationSuppressed()) return invoke2();
36237
+ const started = Date.now() / 1e3;
36238
+ let span;
36239
+ try {
36240
+ const event = input(args);
36241
+ if (event !== void 0)
36242
+ span = startSpan(
36243
+ withSpanInstrumentationName(
36244
+ {
36245
+ name,
36246
+ spanAttributes: { type: "llm" /* LLM */ },
36247
+ event
36248
+ },
36249
+ INSTRUMENTATION_NAMES.ELEVENLABS
36250
+ )
36251
+ );
36252
+ } catch (error) {
36253
+ debugLogger.error("Error starting ElevenLabs span", error);
36254
+ return invoke2();
36255
+ }
36256
+ if (!span) return invoke2();
36257
+ const activeSpan = span;
36258
+ let ended = false;
36259
+ const finish = (error) => {
36260
+ if (ended) return;
36261
+ ended = true;
36262
+ try {
36263
+ if (error !== void 0) activeSpan.log({ error });
36264
+ activeSpan.end();
36265
+ } catch (loggingError) {
36266
+ debugLogger.error("Error ending ElevenLabs span", loggingError);
36267
+ }
36268
+ };
36269
+ try {
36270
+ _optionalChain([beforeInvoke, 'optionalCall', _1085 => _1085(args, span)]);
36271
+ } catch (error) {
36272
+ debugLogger.error("Error observing ElevenLabs input", error);
36273
+ }
36274
+ let result;
36275
+ try {
36276
+ result = withCurrent(
36277
+ span,
36278
+ () => runWithAutoInstrumentationSuppressed(invoke2)
36279
+ );
36280
+ } catch (error) {
36281
+ finish(error);
36282
+ throw error;
36283
+ }
36284
+ const capture = (value, headers) => {
36285
+ try {
36286
+ output(value, args, span, finish, headers, started);
36287
+ } catch (error) {
36288
+ debugLogger.error("Error capturing ElevenLabs output", error);
36289
+ finish();
36290
+ }
36291
+ };
36292
+ try {
36293
+ if (isObject(result) && typeof result.withRawResponse === "function") {
36294
+ void result.withRawResponse().then(
36295
+ ({
36296
+ data,
36297
+ rawResponse
36298
+ }) => capture(data, _optionalChain([rawResponse, 'optionalAccess', _1086 => _1086.headers])),
36299
+ finish
36300
+ );
36301
+ } else {
36302
+ void Promise.resolve(result).then((value) => capture(value), finish);
36303
+ }
36304
+ } catch (error) {
36305
+ debugLogger.error("Error observing ElevenLabs result", error);
36306
+ finish();
36307
+ }
36308
+ return result;
36309
+ });
36310
+ }
36311
+ function captureSpeech(value, request, method, span, finish, started, headers) {
36312
+ const format = _nullishCoalesce(request.outputFormat, () => ( "mp3_44100_128"));
36313
+ const formatType = format.startsWith("mp3_") ? "audio/mpeg" : format.startsWith("pcm_") ? "audio/pcm" : format.startsWith("opus_") ? "audio/ogg" : format.startsWith("ulaw_") ? "audio/basic" : format.startsWith("alaw_") ? "audio/x-alaw" : void 0;
36314
+ const headerType = _optionalChain([headers, 'optionalAccess', _1087 => _1087.get, 'call', _1088 => _1088("content-type"), 'optionalAccess', _1089 => _1089.split, 'call', _1090 => _1090(";"), 'access', _1091 => _1091[0]]);
36315
+ const contentType = _optionalChain([headerType, 'optionalAccess', _1092 => _1092.startsWith, 'call', _1093 => _1093("audio/")]) ? headerType : formatType;
36316
+ const disposition = _optionalChain([headers, 'optionalAccess', _1094 => _1094.get, 'call', _1095 => _1095("content-disposition")]);
36317
+ const headerFilename = _optionalChain([disposition, 'optionalAccess', _1096 => _1096.match, 'call', _1097 => _1097(
36318
+ /filename="([^"]+)"|filename=([^;]+)/i
36319
+ )]);
36320
+ const filename = _nullishCoalesce(_nullishCoalesce(_optionalChain([headerFilename, 'optionalAccess', _1098 => _1098[1]]), () => ( _optionalChain([headerFilename, 'optionalAccess', _1099 => _1099[2], 'optionalAccess', _1100 => _1100.trim, 'call', _1101 => _1101()]))), () => ( `speech.${contentType ? getExtensionFromMediaType(contentType) : "bin"}`));
36321
+ const chunks = [];
36322
+ const alignments = [];
36323
+ let bytes = 0;
36324
+ let first = true;
36325
+ let stopped = false;
36326
+ const observe = (chunk) => {
36327
+ if (stopped || chunk.byteLength === 0) return;
36328
+ if (first && method.startsWith("stream")) {
36329
+ span.log({
36330
+ metrics: { time_to_first_token: Date.now() / 1e3 - started }
36331
+ });
36332
+ }
36333
+ first = false;
36334
+ chunks.push(new Uint8Array(chunk));
36335
+ bytes += chunk.byteLength;
36336
+ };
36337
+ const complete = () => {
36338
+ if (stopped) return;
36339
+ stopped = true;
36340
+ try {
36341
+ const content = [];
36342
+ if (contentType && bytes) {
36343
+ const data = new Uint8Array(bytes);
36344
+ let offset = 0;
36345
+ for (const chunk of chunks) {
36346
+ data.set(chunk, offset);
36347
+ offset += chunk.length;
36348
+ }
36349
+ content.push({
36350
+ type: "file",
36351
+ file: {
36352
+ filename,
36353
+ byte_size: bytes,
36354
+ file_data: new Attachment({
36355
+ data: new Blob([data], { type: contentType }),
36356
+ filename,
36357
+ contentType
36358
+ })
36359
+ }
36360
+ });
36361
+ }
36362
+ span.log({
36363
+ output: {
36364
+ content,
36365
+ ...alignments.length ? { annotations: alignments } : {}
36366
+ }
36367
+ });
36368
+ } finally {
36369
+ chunks.length = 0;
36370
+ finish();
36371
+ }
36372
+ };
36373
+ const cancel = (error) => {
36374
+ stopped = true;
36375
+ chunks.length = 0;
36376
+ finish(error);
36377
+ };
36378
+ const timestampChunk = (chunk) => {
36379
+ const binary = atob(chunk.audioBase64);
36380
+ observe(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
36381
+ if (chunk.alignment || chunk.normalizedAlignment)
36382
+ alignments.push({
36383
+ alignment: chunk.alignment,
36384
+ normalized_alignment: chunk.normalizedAlignment
36385
+ });
36386
+ };
36387
+ if (method === "convertWithTimestamps") {
36388
+ timestampChunk(value);
36389
+ complete();
36390
+ } else if (method === "streamWithTimestamps") {
36391
+ patchStreamIfNeeded(value, {
36392
+ shouldCollect: (chunk) => {
36393
+ try {
36394
+ timestampChunk(chunk);
36395
+ } catch (error) {
36396
+ debugLogger.error("Error collecting ElevenLabs timestamps", error);
36397
+ cancel();
36398
+ }
36399
+ return false;
36400
+ },
36401
+ onComplete: complete,
36402
+ onCancel: () => cancel(),
36403
+ onError: cancel,
36404
+ aroundNext: (next) => withCurrent(span, next)
36405
+ });
36406
+ } else {
36407
+ observeAudioStream(value, observe, complete, cancel, span);
36408
+ }
36409
+ }
36410
+ function observeAudioStream(value, observe, complete, cancel, span) {
36411
+ let ended = false;
36412
+ const safeObserve = (chunk) => {
36413
+ if (ended) return;
36414
+ try {
36415
+ observe(chunk);
36416
+ } catch (error) {
36417
+ debugLogger.error("Error collecting ElevenLabs audio", error);
36418
+ end(false);
36419
+ }
36420
+ };
36421
+ const end = (success, error) => {
36422
+ if (ended) return;
36423
+ ended = true;
36424
+ try {
36425
+ if (success) complete();
36426
+ else cancel(error);
36427
+ } catch (loggingError) {
36428
+ debugLogger.error("Error logging ElevenLabs audio", loggingError);
36429
+ cancel();
36430
+ }
36431
+ };
36432
+ if (!isObject(value) || !Object.isExtensible(value)) {
36433
+ end(false);
36434
+ return;
36435
+ }
36436
+ if (typeof value.read === "function" && typeof value.on === "function") {
36437
+ value.on("end", () => end(true));
36438
+ value.on("close", () => end(false));
36439
+ const emit2 = value.emit;
36440
+ if (typeof emit2 === "function")
36441
+ value.emit = function(event, ...args) {
36442
+ if (event === "data" && args[0] instanceof Uint8Array)
36443
+ safeObserve(args[0]);
36444
+ if (event === "error") end(false, args[0]);
36445
+ return Reflect.apply(emit2, this, [event, ...args]);
36446
+ };
36447
+ return;
36448
+ }
36449
+ if (typeof value.getReader === "function") {
36450
+ const webStream = value;
36451
+ const pipeTo = webStream.pipeTo;
36452
+ const pipeThrough = webStream.pipeThrough;
36453
+ webStream.pipeTo = function(destination, options) {
36454
+ if (!isObject(destination) || this.locked || destination.locked)
36455
+ return pipeTo.call(this, destination, options);
36456
+ const tap = new TransformStream({
36457
+ transform(chunk, controller) {
36458
+ safeObserve(chunk);
36459
+ controller.enqueue(chunk);
36460
+ },
36461
+ flush() {
36462
+ end(true);
36463
+ }
36464
+ });
36465
+ const observed = pipeThrough.call(
36466
+ this,
36467
+ tap,
36468
+ options
36469
+ );
36470
+ return observed.pipeTo(destination, options).catch((error) => {
36471
+ end(false, error);
36472
+ throw error;
36473
+ });
36474
+ };
36475
+ webStream.pipeThrough = function(transform, options) {
36476
+ if (this.locked || transform.writable.locked || transform.readable.locked)
36477
+ return pipeThrough.call(this, transform, options);
36478
+ const result = webStream.pipeTo.call(this, transform.writable, options);
36479
+ void result.catch(() => {
36480
+ });
36481
+ return transform.readable;
36482
+ };
36483
+ const getReader = value.getReader;
36484
+ value.getReader = function(...args) {
36485
+ const reader = Reflect.apply(getReader, this, args);
36486
+ const read2 = reader.read;
36487
+ reader.read = function(...readArgs) {
36488
+ return Promise.resolve(
36489
+ withCurrent(span, () => Reflect.apply(read2, this, readArgs))
36490
+ ).then(
36491
+ (result) => {
36492
+ if (result.value) safeObserve(result.value);
36493
+ if (result.done) end(true);
36494
+ return result;
36495
+ },
36496
+ (error) => {
36497
+ end(false, error);
36498
+ throw error;
36499
+ }
36500
+ );
36501
+ };
36502
+ const readerCancel = reader.cancel;
36503
+ reader.cancel = function(...cancelArgs) {
36504
+ const result = Reflect.apply(readerCancel, this, cancelArgs);
36505
+ end(false);
36506
+ return result;
36507
+ };
36508
+ return reader;
36509
+ };
36510
+ const streamCancel = value.cancel;
36511
+ if (typeof streamCancel === "function")
36512
+ value.cancel = function(...args) {
36513
+ const result = Reflect.apply(streamCancel, this, args);
36514
+ void Promise.resolve(result).then(
36515
+ () => end(false),
36516
+ () => {
36517
+ }
36518
+ );
36519
+ return result;
36520
+ };
36521
+ }
36522
+ if (typeof value.getReader === "function" && typeof value.values === "function") {
36523
+ const values = value.values;
36524
+ const iterate = function(...args) {
36525
+ const iterator = Reflect.apply(values, this, args);
36526
+ patchStreamIfNeeded(iterator, {
36527
+ shouldCollect(chunk) {
36528
+ safeObserve(chunk);
36529
+ return false;
36530
+ },
36531
+ onComplete: () => end(true),
36532
+ onCancel: () => end(false),
36533
+ onError: (error) => end(false, error),
36534
+ aroundNext: (next) => withCurrent(span, next)
36535
+ });
36536
+ return iterator;
36537
+ };
36538
+ value.values = iterate;
36539
+ Object.defineProperty(value, Symbol.asyncIterator, {
36540
+ configurable: true,
36541
+ writable: true,
36542
+ value: iterate
36543
+ });
36544
+ } else if (isAsyncIterable(value)) {
36545
+ patchStreamIfNeeded(value, {
36546
+ shouldCollect: (chunk) => {
36547
+ safeObserve(chunk);
36548
+ return false;
36549
+ },
36550
+ onComplete: () => end(true),
36551
+ onCancel: () => end(false),
36552
+ onError: (error) => end(false, error),
36553
+ aroundNext: (next) => withCurrent(span, next)
36554
+ });
36555
+ } else if (typeof value.getReader !== "function") end(false);
36556
+ }
36557
+
35719
36558
  // src/instrumentation/plugins/voyageai-channels.ts
35720
36559
  var voyageAIChannels = defineChannels(
35721
36560
  "voyageai",
@@ -35783,7 +36622,7 @@ var VoyageAIPlugin = class extends BasePlugin {
35783
36622
  this.unsubscribers = unsubscribeAll(this.unsubscribers);
35784
36623
  }
35785
36624
  };
35786
- function interceptVoyageAICall(channel2, name, extractInput2, extractOutput2, extractMetrics2 = extractUsageMetrics3) {
36625
+ function interceptVoyageAICall(channel2, name, extractInput3, extractOutput2, extractMetrics2 = extractUsageMetrics3) {
35787
36626
  return channel2.intercept((target, thisArg, args) => {
35788
36627
  const invokeTarget = () => Reflect.apply(target, thisArg, args);
35789
36628
  if (isAutoInstrumentationSuppressed()) {
@@ -35791,7 +36630,7 @@ function interceptVoyageAICall(channel2, name, extractInput2, extractOutput2, ex
35791
36630
  }
35792
36631
  let span;
35793
36632
  try {
35794
- const { input, metadata } = extractInput2(args);
36633
+ const { input, metadata } = extractInput3(args);
35795
36634
  span = startSpan(
35796
36635
  withSpanInstrumentationName(
35797
36636
  {
@@ -35871,7 +36710,7 @@ function pickMetadata(request, allowlist) {
35871
36710
  };
35872
36711
  }
35873
36712
  function buildEmbeddingInput(inputs, request) {
35874
- const outputDimensions = _optionalChain([request, 'optionalAccess', _1051 => _1051.outputDimension]);
36713
+ const outputDimensions = _optionalChain([request, 'optionalAccess', _1102 => _1102.outputDimension]);
35875
36714
  return {
35876
36715
  inputs,
35877
36716
  ...typeof outputDimensions === "number" && Number.isFinite(outputDimensions) ? { output_dimensions: outputDimensions } : {}
@@ -35879,13 +36718,13 @@ function buildEmbeddingInput(inputs, request) {
35879
36718
  }
35880
36719
  function embeddingMetadata(request) {
35881
36720
  return {
35882
- ...typeof _optionalChain([request, 'optionalAccess', _1052 => _1052.model]) === "string" ? { model: request.model } : {},
36721
+ ...typeof _optionalChain([request, 'optionalAccess', _1103 => _1103.model]) === "string" ? { model: request.model } : {},
35883
36722
  provider: "voyage"
35884
36723
  };
35885
36724
  }
35886
36725
  function extractTextEmbeddingInput(args) {
35887
36726
  const request = getRequestArg2(args);
35888
- const rawInput = _optionalChain([request, 'optionalAccess', _1053 => _1053.input]);
36727
+ const rawInput = _optionalChain([request, 'optionalAccess', _1104 => _1104.input]);
35889
36728
  const values = Array.isArray(rawInput) ? rawInput : [rawInput];
35890
36729
  return {
35891
36730
  input: buildEmbeddingInput(
@@ -35899,7 +36738,7 @@ function extractTextEmbeddingInput(args) {
35899
36738
  }
35900
36739
  function extractContextualizedEmbeddingInput(args) {
35901
36740
  const request = getRequestArg2(args);
35902
- const rawInputs = _optionalChain([request, 'optionalAccess', _1054 => _1054.inputs]);
36741
+ const rawInputs = _optionalChain([request, 'optionalAccess', _1105 => _1105.inputs]);
35903
36742
  const values = Array.isArray(rawInputs) ? rawInputs.flatMap((value) => Array.isArray(value) ? value : [value]) : [];
35904
36743
  return {
35905
36744
  input: buildEmbeddingInput(
@@ -35913,7 +36752,7 @@ function extractContextualizedEmbeddingInput(args) {
35913
36752
  }
35914
36753
  function extractMultimodalEmbeddingInput(args) {
35915
36754
  const request = getRequestArg2(args);
35916
- const rawInputs = _optionalChain([request, 'optionalAccess', _1055 => _1055.inputs]);
36755
+ const rawInputs = _optionalChain([request, 'optionalAccess', _1106 => _1106.inputs]);
35917
36756
  const inputs = Array.isArray(rawInputs) ? rawInputs.map((rawInput) => {
35918
36757
  const rawContent = isObject(rawInput) ? rawInput.content : void 0;
35919
36758
  return {
@@ -35960,11 +36799,11 @@ function hasInlineEmbeddingMedia(input) {
35960
36799
  }
35961
36800
  function extractRerankInput(args) {
35962
36801
  const request = getRequestArg2(args);
35963
- const documents = _optionalChain([request, 'optionalAccess', _1056 => _1056.documents]);
36802
+ const documents = _optionalChain([request, 'optionalAccess', _1107 => _1107.documents]);
35964
36803
  return {
35965
36804
  input: {
35966
36805
  documents,
35967
- query: _optionalChain([request, 'optionalAccess', _1057 => _1057.query])
36806
+ query: _optionalChain([request, 'optionalAccess', _1108 => _1108.query])
35968
36807
  },
35969
36808
  metadata: {
35970
36809
  ...pickMetadata(request, RERANK_METADATA_ALLOWLIST),
@@ -35977,7 +36816,7 @@ function extractResponseMetadata3(result) {
35977
36816
  return void 0;
35978
36817
  }
35979
36818
  const rawResponse = isObject(result.rawResponse) ? result.rawResponse : void 0;
35980
- const model = typeof result.model === "string" ? result.model : typeof _optionalChain([rawResponse, 'optionalAccess', _1058 => _1058.model]) === "string" ? rawResponse.model : void 0;
36819
+ const model = typeof result.model === "string" ? result.model : typeof _optionalChain([rawResponse, 'optionalAccess', _1109 => _1109.model]) === "string" ? rawResponse.model : void 0;
35981
36820
  return model ? { model } : void 0;
35982
36821
  }
35983
36822
  function summarizeEmbeddingOutput(result) {
@@ -36025,8 +36864,8 @@ function extractUsageMetrics3(result) {
36025
36864
  return {};
36026
36865
  }
36027
36866
  const rawResponse = isObject(result.rawResponse) ? result.rawResponse : void 0;
36028
- const usage = isObject(result.usage) ? result.usage : isObject(_optionalChain([rawResponse, 'optionalAccess', _1059 => _1059.usage])) ? rawResponse.usage : void 0;
36029
- const tokens = typeof result.totalTokens === "number" ? result.totalTokens : _nullishCoalesce(_optionalChain([usage, 'optionalAccess', _1060 => _1060.totalTokens]), () => ( _optionalChain([usage, 'optionalAccess', _1061 => _1061.total_tokens])));
36867
+ const usage = isObject(result.usage) ? result.usage : isObject(_optionalChain([rawResponse, 'optionalAccess', _1110 => _1110.usage])) ? rawResponse.usage : void 0;
36868
+ const tokens = typeof result.totalTokens === "number" ? result.totalTokens : _nullishCoalesce(_optionalChain([usage, 'optionalAccess', _1111 => _1111.totalTokens]), () => ( _optionalChain([usage, 'optionalAccess', _1112 => _1112.total_tokens])));
36030
36869
  return typeof tokens === "number" && Number.isFinite(tokens) && tokens >= 0 ? { tokens } : {};
36031
36870
  }
36032
36871
 
@@ -36076,8 +36915,8 @@ function instrumentCloudflareAIChatResponseHook(agent) {
36076
36915
  function defineWrappedMethod(target, property, original, wrapped) {
36077
36916
  const ownDescriptor = Object.getOwnPropertyDescriptor(target, property);
36078
36917
  Object.defineProperty(target, property, {
36079
- configurable: _nullishCoalesce(_optionalChain([ownDescriptor, 'optionalAccess', _1062 => _1062.configurable]), () => ( true)),
36080
- enumerable: _nullishCoalesce(_optionalChain([ownDescriptor, 'optionalAccess', _1063 => _1063.enumerable]), () => ( false)),
36918
+ configurable: _nullishCoalesce(_optionalChain([ownDescriptor, 'optionalAccess', _1113 => _1113.configurable]), () => ( true)),
36919
+ enumerable: _nullishCoalesce(_optionalChain([ownDescriptor, 'optionalAccess', _1114 => _1114.enumerable]), () => ( false)),
36081
36920
  value: wrapped,
36082
36921
  writable: ownDescriptor && "writable" in ownDescriptor ? ownDescriptor.writable : true
36083
36922
  });
@@ -36127,7 +36966,7 @@ var CloudflareAIChatPlugin = (_class31 = class extends BasePlugin {constructor(.
36127
36966
  };
36128
36967
  tracingChannel.subscribe(handlers);
36129
36968
  this.unsubscribers.push(() => {
36130
- _optionalChain([unbindCurrentSpanStore, 'optionalCall', _1064 => _1064()]);
36969
+ _optionalChain([unbindCurrentSpanStore, 'optionalCall', _1115 => _1115()]);
36131
36970
  tracingChannel.unsubscribe(handlers);
36132
36971
  });
36133
36972
  }
@@ -36150,8 +36989,8 @@ var CloudflareAIChatPlugin = (_class31 = class extends BasePlugin {constructor(.
36150
36989
  const output = serializeMessage(ownValue2(result, "message"));
36151
36990
  const status = stringValue3(ownValue2(result, "status"));
36152
36991
  const error = ownValue2(result, "error");
36153
- const input = ownValue2(result, "continuation") === true ? state.input : _optionalChain([serializeMessages, 'call', _1065 => _1065(readProperty(agent, "messages")), 'optionalAccess', _1066 => _1066.filter, 'call', _1067 => _1067(
36154
- (message) => typeof _optionalChain([output, 'optionalAccess', _1068 => _1068.id]) !== "string" || message.id !== output.id
36992
+ const input = ownValue2(result, "continuation") === true ? state.input : _optionalChain([serializeMessages, 'call', _1116 => _1116(readProperty(agent, "messages")), 'optionalAccess', _1117 => _1117.filter, 'call', _1118 => _1118(
36993
+ (message) => typeof _optionalChain([output, 'optionalAccess', _1119 => _1119.id]) !== "string" || message.id !== output.id
36155
36994
  )]);
36156
36995
  state.span.log({
36157
36996
  ...input !== void 0 ? { input } : {},
@@ -36164,7 +37003,7 @@ var CloudflareAIChatPlugin = (_class31 = class extends BasePlugin {constructor(.
36164
37003
  error
36165
37004
  );
36166
37005
  } finally {
36167
- if (_optionalChain([state, 'optionalAccess', _1069 => _1069.settled])) {
37006
+ if (_optionalChain([state, 'optionalAccess', _1120 => _1120.settled])) {
36168
37007
  this.cleanupState(state);
36169
37008
  }
36170
37009
  }
@@ -36175,7 +37014,7 @@ var CloudflareAIChatPlugin = (_class31 = class extends BasePlugin {constructor(.
36175
37014
  }
36176
37015
  bindCurrentSpanStore(tracingChannel) {
36177
37016
  const globalState = _internalGetGlobalState();
36178
- const contextManager = _optionalChain([globalState, 'optionalAccess', _1070 => _1070.contextManager]);
37017
+ const contextManager = _optionalChain([globalState, 'optionalAccess', _1121 => _1121.contextManager]);
36179
37018
  const startChannel = tracingChannel.start;
36180
37019
  const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
36181
37020
  if (!startChannel || !currentSpanStore || !contextManager) {
@@ -36198,7 +37037,7 @@ var CloudflareAIChatPlugin = (_class31 = class extends BasePlugin {constructor(.
36198
37037
  const requestId = stringValue3(event.arguments[0]);
36199
37038
  const key = _nullishCoalesce(requestId, () => ( /* @__PURE__ */ Symbol("cloudflare-ai-chat-turn")));
36200
37039
  const activeForAgent = agent ? this.getActiveTurns(agent) : void 0;
36201
- const existing = _optionalChain([activeForAgent, 'optionalAccess', _1071 => _1071.get, 'call', _1072 => _1072(key)]);
37040
+ const existing = _optionalChain([activeForAgent, 'optionalAccess', _1122 => _1122.get, 'call', _1123 => _1123(key)]);
36202
37041
  const state = existing && !existing.settled ? existing : this.createTurnState(agent, key);
36203
37042
  if (existing && !existing.settled) {
36204
37043
  state.depth += 1;
@@ -36323,7 +37162,7 @@ var CloudflareAIChatPlugin = (_class31 = class extends BasePlugin {constructor(.
36323
37162
  this.activeStates.delete(state);
36324
37163
  if (state.agent) {
36325
37164
  const activeForAgent = this.activeTurns.get(state.agent);
36326
- if (_optionalChain([activeForAgent, 'optionalAccess', _1073 => _1073.get, 'call', _1074 => _1074(state.key)]) === state) {
37165
+ if (_optionalChain([activeForAgent, 'optionalAccess', _1124 => _1124.get, 'call', _1125 => _1125(state.key)]) === state) {
36327
37166
  activeForAgent.delete(state.key);
36328
37167
  }
36329
37168
  }
@@ -36567,29 +37406,31 @@ var BraintrustPlugin = (_class32 = class extends BasePlugin {
36567
37406
  __init102() {this.cloudflareThinkPlugin = null}
36568
37407
  __init103() {this.cursorSDKPlugin = null}
36569
37408
  __init104() {this.openAIAgentsPlugin = null}
36570
- __init105() {this.googleGenAIPlugin = null}
36571
- __init106() {this.huggingFacePlugin = null}
36572
- __init107() {this.huggingFaceTransformersPlugin = null}
36573
- __init108() {this.openRouterPlugin = null}
36574
- __init109() {this.openRouterAgentPlugin = null}
36575
- __init110() {this.mistralPlugin = null}
36576
- __init111() {this.ollamaPlugin = null}
36577
- __init112() {this.googleADKPlugin = null}
36578
- __init113() {this.coherePlugin = null}
36579
- __init114() {this.groqPlugin = null}
36580
- __init115() {this.bedrockRuntimePlugin = null}
36581
- __init116() {this.genkitPlugin = null}
36582
- __init117() {this.gitHubCopilotPlugin = null}
36583
- __init118() {this.fluePlugin = null}
36584
- __init119() {this.langChainPlugin = null}
36585
- __init120() {this.langSmithPlugin = null}
36586
- __init121() {this.piCodingAgentPlugin = null}
36587
- __init122() {this.strandsAgentSDKPlugin = null}
36588
- __init123() {this.voyageAIPlugin = null}
36589
- __init124() {this.cloudflareAIChatPlugin = null}
36590
- __init125() {this.cloudflareAgentsPlugin = null}
37409
+ __init105() {this.googleGenerativeAIPlugin = null}
37410
+ __init106() {this.googleGenAIPlugin = null}
37411
+ __init107() {this.huggingFacePlugin = null}
37412
+ __init108() {this.huggingFaceTransformersPlugin = null}
37413
+ __init109() {this.openRouterPlugin = null}
37414
+ __init110() {this.openRouterAgentPlugin = null}
37415
+ __init111() {this.mistralPlugin = null}
37416
+ __init112() {this.ollamaPlugin = null}
37417
+ __init113() {this.googleADKPlugin = null}
37418
+ __init114() {this.coherePlugin = null}
37419
+ __init115() {this.groqPlugin = null}
37420
+ __init116() {this.bedrockRuntimePlugin = null}
37421
+ __init117() {this.genkitPlugin = null}
37422
+ __init118() {this.gitHubCopilotPlugin = null}
37423
+ __init119() {this.fluePlugin = null}
37424
+ __init120() {this.langChainPlugin = null}
37425
+ __init121() {this.langSmithPlugin = null}
37426
+ __init122() {this.piCodingAgentPlugin = null}
37427
+ __init123() {this.strandsAgentSDKPlugin = null}
37428
+ __init124() {this.elevenLabsPlugin = null}
37429
+ __init125() {this.voyageAIPlugin = null}
37430
+ __init126() {this.cloudflareAIChatPlugin = null}
37431
+ __init127() {this.cloudflareAgentsPlugin = null}
36591
37432
  constructor(config = {}) {
36592
- super();_class32.prototype.__init97.call(this);_class32.prototype.__init98.call(this);_class32.prototype.__init99.call(this);_class32.prototype.__init100.call(this);_class32.prototype.__init101.call(this);_class32.prototype.__init102.call(this);_class32.prototype.__init103.call(this);_class32.prototype.__init104.call(this);_class32.prototype.__init105.call(this);_class32.prototype.__init106.call(this);_class32.prototype.__init107.call(this);_class32.prototype.__init108.call(this);_class32.prototype.__init109.call(this);_class32.prototype.__init110.call(this);_class32.prototype.__init111.call(this);_class32.prototype.__init112.call(this);_class32.prototype.__init113.call(this);_class32.prototype.__init114.call(this);_class32.prototype.__init115.call(this);_class32.prototype.__init116.call(this);_class32.prototype.__init117.call(this);_class32.prototype.__init118.call(this);_class32.prototype.__init119.call(this);_class32.prototype.__init120.call(this);_class32.prototype.__init121.call(this);_class32.prototype.__init122.call(this);_class32.prototype.__init123.call(this);_class32.prototype.__init124.call(this);_class32.prototype.__init125.call(this);;
37433
+ super();_class32.prototype.__init97.call(this);_class32.prototype.__init98.call(this);_class32.prototype.__init99.call(this);_class32.prototype.__init100.call(this);_class32.prototype.__init101.call(this);_class32.prototype.__init102.call(this);_class32.prototype.__init103.call(this);_class32.prototype.__init104.call(this);_class32.prototype.__init105.call(this);_class32.prototype.__init106.call(this);_class32.prototype.__init107.call(this);_class32.prototype.__init108.call(this);_class32.prototype.__init109.call(this);_class32.prototype.__init110.call(this);_class32.prototype.__init111.call(this);_class32.prototype.__init112.call(this);_class32.prototype.__init113.call(this);_class32.prototype.__init114.call(this);_class32.prototype.__init115.call(this);_class32.prototype.__init116.call(this);_class32.prototype.__init117.call(this);_class32.prototype.__init118.call(this);_class32.prototype.__init119.call(this);_class32.prototype.__init120.call(this);_class32.prototype.__init121.call(this);_class32.prototype.__init122.call(this);_class32.prototype.__init123.call(this);_class32.prototype.__init124.call(this);_class32.prototype.__init125.call(this);_class32.prototype.__init126.call(this);_class32.prototype.__init127.call(this);;
36593
37434
  this.config = config;
36594
37435
  }
36595
37436
  onEnable() {
@@ -36626,6 +37467,10 @@ var BraintrustPlugin = (_class32 = class extends BasePlugin {
36626
37467
  this.openAIAgentsPlugin = new OpenAIAgentsPlugin();
36627
37468
  this.openAIAgentsPlugin.enable();
36628
37469
  }
37470
+ if (integrations.googleGenerativeAI !== false) {
37471
+ this.googleGenerativeAIPlugin = new GoogleGenerativeAIPlugin();
37472
+ this.googleGenerativeAIPlugin.enable();
37473
+ }
36629
37474
  if (integrations.googleGenAI !== false && integrations.google !== false) {
36630
37475
  this.googleGenAIPlugin = new GoogleGenAIPlugin();
36631
37476
  this.googleGenAIPlugin.enable();
@@ -36660,6 +37505,10 @@ var BraintrustPlugin = (_class32 = class extends BasePlugin {
36660
37505
  this.coherePlugin = new CoherePlugin();
36661
37506
  this.coherePlugin.enable();
36662
37507
  }
37508
+ if (integrations.elevenlabs !== false) {
37509
+ this.elevenLabsPlugin = new ElevenLabsPlugin();
37510
+ this.elevenLabsPlugin.enable();
37511
+ }
36663
37512
  if (integrations.voyageai !== false) {
36664
37513
  this.voyageAIPlugin = new VoyageAIPlugin();
36665
37514
  this.voyageAIPlugin.enable();
@@ -36744,6 +37593,10 @@ var BraintrustPlugin = (_class32 = class extends BasePlugin {
36744
37593
  this.openAIAgentsPlugin.disable();
36745
37594
  this.openAIAgentsPlugin = null;
36746
37595
  }
37596
+ if (this.googleGenerativeAIPlugin) {
37597
+ this.googleGenerativeAIPlugin.disable();
37598
+ this.googleGenerativeAIPlugin = null;
37599
+ }
36747
37600
  if (this.googleGenAIPlugin) {
36748
37601
  this.googleGenAIPlugin.disable();
36749
37602
  this.googleGenAIPlugin = null;
@@ -36780,6 +37633,10 @@ var BraintrustPlugin = (_class32 = class extends BasePlugin {
36780
37633
  this.coherePlugin.disable();
36781
37634
  this.coherePlugin = null;
36782
37635
  }
37636
+ if (this.elevenLabsPlugin) {
37637
+ this.elevenLabsPlugin.disable();
37638
+ this.elevenLabsPlugin = null;
37639
+ }
36783
37640
  if (this.voyageAIPlugin) {
36784
37641
  this.voyageAIPlugin.disable();
36785
37642
  this.voyageAIPlugin = null;
@@ -36873,6 +37730,8 @@ var envIntegrationAliases = {
36873
37730
  "openai-agents-core": "openAIAgents",
36874
37731
  openaiagentscore: "openAIAgents",
36875
37732
  google: "google",
37733
+ "google-generative-ai": "googleGenerativeAI",
37734
+ googlegenerativeai: "googleGenerativeAI",
36876
37735
  "google-genai": "googleGenAI",
36877
37736
  googlegenai: "googleGenAI",
36878
37737
  huggingface: "huggingface",
@@ -36906,7 +37765,9 @@ var envIntegrationAliases = {
36906
37765
  langsmith: "langsmith",
36907
37766
  voyage: "voyageai",
36908
37767
  "voyage-ai": "voyageai",
36909
- voyageai: "voyageai"
37768
+ voyageai: "voyageai",
37769
+ elevenlabs: "elevenlabs",
37770
+ "@elevenlabs/elevenlabs-js": "elevenlabs"
36910
37771
  };
36911
37772
  function getDefaultInstrumentationIntegrations() {
36912
37773
  return {
@@ -36917,6 +37778,7 @@ function getDefaultInstrumentationIntegrations() {
36917
37778
  aisdk: true,
36918
37779
  google: true,
36919
37780
  googleGenAI: true,
37781
+ googleGenerativeAI: true,
36920
37782
  googleADK: true,
36921
37783
  huggingface: true,
36922
37784
  claudeAgentSDK: true,
@@ -36942,6 +37804,7 @@ function getDefaultInstrumentationIntegrations() {
36942
37804
  langgraph: true,
36943
37805
  langsmith: true,
36944
37806
  voyageai: true,
37807
+ elevenlabs: true,
36945
37808
  piCodingAgent: true,
36946
37809
  strandsAgentSDK: true,
36947
37810
  cloudflareAgents: true
@@ -36961,7 +37824,7 @@ function readDisabledInstrumentationEnvConfig(disabledList) {
36961
37824
  return { integrations };
36962
37825
  }
36963
37826
  function isInstrumentationIntegrationDisabled(integrations, ...names) {
36964
- return names.some((name) => _optionalChain([integrations, 'optionalAccess', _1075 => _1075[name]]) === false);
37827
+ return names.some((name) => _optionalChain([integrations, 'optionalAccess', _1126 => _1126[name]]) === false);
36965
37828
  }
36966
37829
 
36967
37830
  // src/instrumentation/registry.ts
@@ -36972,10 +37835,10 @@ function getSharedState() {
36972
37835
  const state = globalThis[/* @__PURE__ */ Symbol.for("braintrust-state")];
36973
37836
  return state && typeof state === "object" ? state : void 0;
36974
37837
  }
36975
- var PluginRegistry = (_class33 = class {constructor() { _class33.prototype.__init126.call(this);_class33.prototype.__init127.call(this);_class33.prototype.__init128.call(this); }
36976
- __init126() {this.braintrustPlugin = null}
36977
- __init127() {this.config = {}}
36978
- __init128() {this.enabled = false}
37838
+ var PluginRegistry = (_class33 = class {constructor() { _class33.prototype.__init128.call(this);_class33.prototype.__init129.call(this);_class33.prototype.__init130.call(this); }
37839
+ __init128() {this.braintrustPlugin = null}
37840
+ __init129() {this.config = {}}
37841
+ __init130() {this.enabled = false}
36979
37842
  /**
36980
37843
  * Configure which integrations should be enabled.
36981
37844
  * This must be called before any SDK imports to take effect.
@@ -37217,8 +38080,8 @@ function buildMetadata(exported) {
37217
38080
  return out;
37218
38081
  }
37219
38082
  var BraintrustObservabilityExporter = (_class34 = class {
37220
- __init129() {this.name = MASTRA_BRAINTRUST_EXPORTER_NAME}
37221
- __init130() {this.spans = /* @__PURE__ */ new Map()}
38083
+ __init131() {this.name = MASTRA_BRAINTRUST_EXPORTER_NAME}
38084
+ __init132() {this.spans = /* @__PURE__ */ new Map()}
37222
38085
  // Captured at the first SPAN_STARTED event. Mastra's observability bus may
37223
38086
  // dispatch later events outside the user's AsyncLocalStorage context, where
37224
38087
  // `currentSpan()` returns NOOP_SPAN — which would make our `startSpan()`
@@ -37226,7 +38089,7 @@ var BraintrustObservabilityExporter = (_class34 = class {
37226
38089
  // we observe while still in-context keeps the whole Mastra subtree under
37227
38090
  // the user's traced scenario.
37228
38091
 
37229
- constructor() {;_class34.prototype.__init129.call(this);_class34.prototype.__init130.call(this);
38092
+ constructor() {;_class34.prototype.__init131.call(this);_class34.prototype.__init132.call(this);
37230
38093
  _internalSetInitialState();
37231
38094
  }
37232
38095
  async exportTracingEvent(event) {
@@ -37349,16 +38212,16 @@ function configureNode() {
37349
38212
  isomorph_default.getEnv = (name) => {
37350
38213
  const value = process.env[name];
37351
38214
  if (name === "BRAINTRUST_API_KEY") {
37352
- return _optionalChain([value, 'optionalAccess', _1076 => _1076.trim, 'call', _1077 => _1077()]) ? value : void 0;
38215
+ return _optionalChain([value, 'optionalAccess', _1127 => _1127.trim, 'call', _1128 => _1128()]) ? value : void 0;
37353
38216
  }
37354
- if ((name === "BRAINTRUST_ENVIRONMENT_TYPE" || name === "BRAINTRUST_ENVIRONMENT_NAME") && !_optionalChain([value, 'optionalAccess', _1078 => _1078.trim, 'call', _1079 => _1079()])) {
38217
+ if ((name === "BRAINTRUST_ENVIRONMENT_TYPE" || name === "BRAINTRUST_ENVIRONMENT_NAME") && !_optionalChain([value, 'optionalAccess', _1129 => _1129.trim, 'call', _1130 => _1130()])) {
37355
38218
  return getNearestBraintrustEnvValue(name);
37356
38219
  }
37357
38220
  return value;
37358
38221
  };
37359
38222
  isomorph_default.getBraintrustApiKey = async () => {
37360
38223
  const value = process.env.BRAINTRUST_API_KEY;
37361
- if (_optionalChain([value, 'optionalAccess', _1080 => _1080.trim, 'call', _1081 => _1081()])) {
38224
+ if (_optionalChain([value, 'optionalAccess', _1131 => _1131.trim, 'call', _1132 => _1132()])) {
37362
38225
  return value;
37363
38226
  }
37364
38227
  const envPaths = [];
@@ -37389,7 +38252,7 @@ function configureNode() {
37389
38252
  if ("contents" in nearestResult) {
37390
38253
  const parsed = dotenv.parse(nearestResult.contents);
37391
38254
  const apiKey = parsed.BRAINTRUST_API_KEY;
37392
- return _optionalChain([apiKey, 'optionalAccess', _1082 => _1082.trim, 'call', _1083 => _1083()]) ? apiKey : void 0;
38255
+ return _optionalChain([apiKey, 'optionalAccess', _1133 => _1133.trim, 'call', _1134 => _1134()]) ? apiKey : void 0;
37393
38256
  }
37394
38257
  const e = nearestResult.error;
37395
38258
  if (typeof e === "object" && e !== null && "code" in e && e.code === "ENOENT") {
@@ -37449,7 +38312,7 @@ function getNearestBraintrustEnvValue(name) {
37449
38312
  try {
37450
38313
  const parsed = dotenv.parse(fsSync.readFileSync(envPath, "utf8"));
37451
38314
  const value = parsed[name];
37452
- return _optionalChain([value, 'optionalAccess', _1084 => _1084.trim, 'call', _1085 => _1085()]) ? value : void 0;
38315
+ return _optionalChain([value, 'optionalAccess', _1135 => _1135.trim, 'call', _1136 => _1136()]) ? value : void 0;
37453
38316
  } catch (e) {
37454
38317
  if (typeof e !== "object" || e === null || !("code" in e) || e.code !== "ENOENT") {
37455
38318
  return void 0;
@@ -38654,10 +39517,10 @@ var SpanFetcher = class _SpanFetcher extends ObjectFetcher {
38654
39517
  }
38655
39518
  };
38656
39519
  var CachedSpanFetcher = (_class35 = class {
38657
- __init131() {this.spanCache = /* @__PURE__ */ new Map()}
38658
- __init132() {this.allFetched = false}
39520
+ __init133() {this.spanCache = /* @__PURE__ */ new Map()}
39521
+ __init134() {this.allFetched = false}
38659
39522
 
38660
- constructor(objectTypeOrFetchFn, objectId, rootSpanId, getState, brainstoreRealtime = true) {;_class35.prototype.__init131.call(this);_class35.prototype.__init132.call(this);
39523
+ constructor(objectTypeOrFetchFn, objectId, rootSpanId, getState, brainstoreRealtime = true) {;_class35.prototype.__init133.call(this);_class35.prototype.__init134.call(this);
38661
39524
  if (typeof objectTypeOrFetchFn === "function") {
38662
39525
  this.fetchFn = (spanType) => objectTypeOrFetchFn(spanType);
38663
39526
  } else {
@@ -38721,7 +39584,7 @@ var CachedSpanFetcher = (_class35 = class {
38721
39584
  async fetchSpans(spanType) {
38722
39585
  const spans = await this.fetchFn(spanType, false);
38723
39586
  for (const span of spans) {
38724
- const type = _nullishCoalesce(_optionalChain([span, 'access', _1086 => _1086.span_attributes, 'optionalAccess', _1087 => _1087.type]), () => ( ""));
39587
+ const type = _nullishCoalesce(_optionalChain([span, 'access', _1137 => _1137.span_attributes, 'optionalAccess', _1138 => _1138.type]), () => ( ""));
38725
39588
  const existing = _nullishCoalesce(this.spanCache.get(type), () => ( []));
38726
39589
  existing.push(span);
38727
39590
  this.spanCache.set(type, existing);
@@ -38745,17 +39608,17 @@ var LocalTrace = (_class36 = class {
38745
39608
 
38746
39609
 
38747
39610
 
38748
- __init133() {this.spansFlushed = false}
38749
- __init134() {this.spansFlushPromise = null}
39611
+ __init135() {this.spansFlushed = false}
39612
+ __init136() {this.spansFlushPromise = null}
38750
39613
 
38751
- __init135() {this.threadCache = /* @__PURE__ */ new Map()}
39614
+ __init137() {this.threadCache = /* @__PURE__ */ new Map()}
38752
39615
  constructor({
38753
39616
  objectType,
38754
39617
  objectId,
38755
39618
  rootSpanId,
38756
39619
  ensureSpansFlushed,
38757
39620
  state
38758
- }) {;_class36.prototype.__init133.call(this);_class36.prototype.__init134.call(this);_class36.prototype.__init135.call(this);
39621
+ }) {;_class36.prototype.__init135.call(this);_class36.prototype.__init136.call(this);_class36.prototype.__init137.call(this);
38759
39622
  this.objectType = objectType;
38760
39623
  this.objectId = objectId;
38761
39624
  this.rootSpanId = rootSpanId;
@@ -38804,11 +39667,11 @@ var LocalTrace = (_class36 = class {
38804
39667
  const cachedSpans = this.state.spanCache.getByRootSpanId(this.rootSpanId);
38805
39668
  if (cachedSpans && cachedSpans.length > 0) {
38806
39669
  let spans = includeScorers ? cachedSpans : cachedSpans.filter(
38807
- (span) => _optionalChain([span, 'access', _1088 => _1088.span_attributes, 'optionalAccess', _1089 => _1089.purpose]) !== "scorer"
39670
+ (span) => _optionalChain([span, 'access', _1139 => _1139.span_attributes, 'optionalAccess', _1140 => _1140.purpose]) !== "scorer"
38808
39671
  );
38809
39672
  if (spanType && spanType.length > 0) {
38810
39673
  spans = spans.filter(
38811
- (span) => spanType.includes(_nullishCoalesce(_optionalChain([span, 'access', _1090 => _1090.span_attributes, 'optionalAccess', _1091 => _1091.type]), () => ( "")))
39674
+ (span) => spanType.includes(_nullishCoalesce(_optionalChain([span, 'access', _1141 => _1141.span_attributes, 'optionalAccess', _1142 => _1142.type]), () => ( "")))
38812
39675
  );
38813
39676
  }
38814
39677
  return spans.map((span) => ({
@@ -38833,7 +39696,7 @@ var LocalTrace = (_class36 = class {
38833
39696
  * Calls the API with the project_default preprocessor (which falls back to "thread").
38834
39697
  */
38835
39698
  async getThread(options) {
38836
- const cacheKey = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _1092 => _1092.preprocessor]), () => ( "project_default"));
39699
+ const cacheKey = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _1143 => _1143.preprocessor]), () => ( "project_default"));
38837
39700
  if (!this.threadCache.has(cacheKey)) {
38838
39701
  const promise = this.fetchThread(options);
38839
39702
  this.threadCache.set(cacheKey, promise);
@@ -38844,7 +39707,7 @@ var LocalTrace = (_class36 = class {
38844
39707
  await this.ensureSpansReady();
38845
39708
  await this.state.login({});
38846
39709
  const result = await invoke({
38847
- globalFunction: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _1093 => _1093.preprocessor]), () => ( "project_default")),
39710
+ globalFunction: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _1144 => _1144.preprocessor]), () => ( "project_default")),
38848
39711
  functionType: "preprocessor",
38849
39712
  input: {
38850
39713
  trace_ref: {
@@ -39020,10 +39883,10 @@ function validateParametersWithJsonSchema(parameters, schema) {
39020
39883
  const ajv = new (0, _ajv2.default)({ coerceTypes: true, useDefaults: true, strict: false });
39021
39884
  const validate = ajv.compile(schema);
39022
39885
  if (!validate(parameters)) {
39023
- const errorMessages = _optionalChain([validate, 'access', _1094 => _1094.errors, 'optionalAccess', _1095 => _1095.map, 'call', _1096 => _1096((err) => {
39886
+ const errorMessages = _optionalChain([validate, 'access', _1145 => _1145.errors, 'optionalAccess', _1146 => _1146.map, 'call', _1147 => _1147((err) => {
39024
39887
  const path3 = err.instancePath || "root";
39025
39888
  return `${path3}: ${err.message}`;
39026
- }), 'access', _1097 => _1097.join, 'call', _1098 => _1098(", ")]);
39889
+ }), 'access', _1148 => _1148.join, 'call', _1149 => _1149(", ")]);
39027
39890
  throw Error(`Invalid parameters: ${errorMessages}`);
39028
39891
  }
39029
39892
  return rehydrateRemoteParameters(parameters, schema);
@@ -39371,19 +40234,29 @@ function buildSpanScores(results) {
39371
40234
  function _internalPrepareEvaluatorScore(scoreValue, name) {
39372
40235
  if (scoreValue === null) return { results: null };
39373
40236
  if (Array.isArray(scoreValue)) {
40237
+ const names = /* @__PURE__ */ new Set();
39374
40238
  for (const score of scoreValue) {
39375
40239
  if (!(typeof score === "object" && !isEmpty2(score))) {
39376
40240
  throw new Error(
39377
40241
  `When returning an array of scores, each score must be a non-empty object. Got: ${JSON.stringify(score)}`
39378
40242
  );
39379
40243
  }
40244
+ if (typeof score.name !== "string") {
40245
+ throw new Error(
40246
+ `When returning an array of scores, each score must have a name. Got: ${JSON.stringify(score)}`
40247
+ );
40248
+ }
40249
+ if (names.has(score.name)) {
40250
+ throw new Error(`Duplicate score name '${score.name}' in score array`);
40251
+ }
40252
+ names.add(score.name);
39380
40253
  }
39381
40254
  }
39382
40255
  let results;
39383
40256
  if (Array.isArray(scoreValue)) {
39384
40257
  results = scoreValue;
39385
40258
  } else if (typeof scoreValue === "object" && !isEmpty2(scoreValue)) {
39386
- results = [scoreValue];
40259
+ results = [{ ...scoreValue, name: _nullishCoalesce(scoreValue.name, () => ( name)) }];
39387
40260
  } else {
39388
40261
  results = [{ name, score: scoreValue }];
39389
40262
  }
@@ -39501,7 +40374,7 @@ async function runEvaluator(experiment, evaluator, progressReporter, filters, st
39501
40374
  }
39502
40375
  async function runEvaluatorInternal(experiment, evaluator, progressReporter, filters, stream, parameters, collectResults, enableCache) {
39503
40376
  if (enableCache) {
39504
- _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _1099 => _1099.spanCache, 'optionalAccess', _1100 => _1100.start, 'call', _1101 => _1101()]);
40377
+ _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _1150 => _1150.spanCache, 'optionalAccess', _1151 => _1151.start, 'call', _1152 => _1152()]);
39505
40378
  }
39506
40379
  try {
39507
40380
  parameters = await validateParameters(
@@ -39541,7 +40414,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
39541
40414
  _xact_id: datum._xact_id
39542
40415
  } : void 0;
39543
40416
  const parsedDatumOrigin = ObjectReference.safeParse(datum.origin);
39544
- const origin = _nullishCoalesce(inlineDatasetOrigin, () => ( (_optionalChain([parsedDatumOrigin, 'optionalAccess', _1102 => _1102.success]) ? parsedDatumOrigin.data : void 0)));
40417
+ const origin = _nullishCoalesce(inlineDatasetOrigin, () => ( (_optionalChain([parsedDatumOrigin, 'optionalAccess', _1153 => _1153.success]) ? parsedDatumOrigin.data : void 0)));
39545
40418
  const baseEvent = {
39546
40419
  name: "eval",
39547
40420
  spanAttributes: {
@@ -39575,7 +40448,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
39575
40448
  objectType: parentComponents ? spanObjectTypeV3ToTypedString(
39576
40449
  parentComponents.data.object_type
39577
40450
  ) : "experiment",
39578
- objectId: await _asyncNullishCoalesce(await _asyncOptionalChain([parentComponents, 'optionalAccess', async _1103 => _1103.data, 'access', async _1104 => _1104.object_id]), async () => ( (experimentIdPromise ? await _asyncNullishCoalesce(await experimentIdPromise, async () => ( "")) : ""))),
40451
+ objectId: await _asyncNullishCoalesce(await _asyncOptionalChain([parentComponents, 'optionalAccess', async _1154 => _1154.data, 'access', async _1155 => _1155.object_id]), async () => ( (experimentIdPromise ? await _asyncNullishCoalesce(await experimentIdPromise, async () => ( "")) : ""))),
39579
40452
  rootSpanId: rootSpan.rootSpanId,
39580
40453
  ensureSpansFlushed,
39581
40454
  state
@@ -39601,10 +40474,10 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
39601
40474
  _nullishCoalesce(parameters, () => ( {})),
39602
40475
  span,
39603
40476
  (event) => {
39604
- _optionalChain([stream, 'optionalCall', _1105 => _1105({
40477
+ _optionalChain([stream, 'optionalCall', _1156 => _1156({
39605
40478
  ...event,
39606
40479
  id: rootSpan.id,
39607
- origin: _optionalChain([baseEvent, 'access', _1106 => _1106.event, 'optionalAccess', _1107 => _1107.origin]),
40480
+ origin: _optionalChain([baseEvent, 'access', _1157 => _1157.event, 'optionalAccess', _1158 => _1158.origin]),
39608
40481
  name: evaluator.evalName,
39609
40482
  object_type: "task"
39610
40483
  })]);
@@ -39756,7 +40629,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
39756
40629
  tags: tags.length ? tags : void 0,
39757
40630
  metadata,
39758
40631
  error,
39759
- origin: _optionalChain([baseEvent, 'access', _1108 => _1108.event, 'optionalAccess', _1109 => _1109.origin])
40632
+ origin: _optionalChain([baseEvent, 'access', _1159 => _1159.event, 'optionalAccess', _1160 => _1160.origin])
39760
40633
  };
39761
40634
  collectedResults.push({
39762
40635
  ...baseResult,
@@ -39796,7 +40669,7 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
39796
40669
  break;
39797
40670
  }
39798
40671
  scheduledTrials++;
39799
- _optionalChain([progressReporter, 'access', _1110 => _1110.setTotal, 'optionalCall', _1111 => _1111(evaluator.evalName, scheduledTrials)]);
40672
+ _optionalChain([progressReporter, 'access', _1161 => _1161.setTotal, 'optionalCall', _1162 => _1162(evaluator.evalName, scheduledTrials)]);
39800
40673
  q.pushAsync({ datum, trialIndex }).catch((e) => {
39801
40674
  if (queueErrors.length < 5) {
39802
40675
  queueErrors.push(e);
@@ -39888,9 +40761,9 @@ async function runEvaluatorInternal(experiment, evaluator, progressReporter, fil
39888
40761
  );
39889
40762
  } finally {
39890
40763
  if (enableCache) {
39891
- const spanCache = _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _1112 => _1112.spanCache]);
39892
- _optionalChain([spanCache, 'optionalAccess', _1113 => _1113.dispose, 'call', _1114 => _1114()]);
39893
- _optionalChain([spanCache, 'optionalAccess', _1115 => _1115.stop, 'call', _1116 => _1116()]);
40764
+ const spanCache = _optionalChain([(_nullishCoalesce(evaluator.state, () => ( _internalGetGlobalState()))), 'optionalAccess', _1163 => _1163.spanCache]);
40765
+ _optionalChain([spanCache, 'optionalAccess', _1164 => _1164.dispose, 'call', _1165 => _1165()]);
40766
+ _optionalChain([spanCache, 'optionalAccess', _1166 => _1166.stop, 'call', _1167 => _1167()]);
39894
40767
  }
39895
40768
  }
39896
40769
  }
@@ -40130,7 +41003,7 @@ async function cachedLogin(options) {
40130
41003
  }
40131
41004
  function makeCheckAuthorized(allowedOrgName) {
40132
41005
  return async (req, _res, next) => {
40133
- if (!_optionalChain([req, 'access', _1117 => _1117.ctx, 'optionalAccess', _1118 => _1118.token])) {
41006
+ if (!_optionalChain([req, 'access', _1168 => _1168.ctx, 'optionalAccess', _1169 => _1169.token])) {
40134
41007
  return next(_httperrors2.default.call(void 0, 401, "Unauthorized"));
40135
41008
  }
40136
41009
  try {
@@ -40143,7 +41016,7 @@ function makeCheckAuthorized(allowedOrgName) {
40143
41016
  return next(_httperrors2.default.call(void 0, 403, errorMessage2));
40144
41017
  }
40145
41018
  const state = await cachedLogin({
40146
- apiKey: _optionalChain([req, 'access', _1119 => _1119.ctx, 'optionalAccess', _1120 => _1120.token]),
41019
+ apiKey: _optionalChain([req, 'access', _1170 => _1170.ctx, 'optionalAccess', _1171 => _1171.token]),
40147
41020
  orgName
40148
41021
  });
40149
41022
  req.ctx.state = state;
@@ -40343,10 +41216,10 @@ var Project2 = (_class37 = class {
40343
41216
 
40344
41217
 
40345
41218
 
40346
- __init136() {this._publishableCodeFunctions = []}
40347
- __init137() {this._publishablePrompts = []}
40348
- __init138() {this._publishableParameters = []}
40349
- constructor(args) {;_class37.prototype.__init136.call(this);_class37.prototype.__init137.call(this);_class37.prototype.__init138.call(this);
41219
+ __init138() {this._publishableCodeFunctions = []}
41220
+ __init139() {this._publishablePrompts = []}
41221
+ __init140() {this._publishableParameters = []}
41222
+ constructor(args) {;_class37.prototype.__init138.call(this);_class37.prototype.__init139.call(this);_class37.prototype.__init140.call(this);
40350
41223
  _initializeSpanContext();
40351
41224
  this.name = "name" in args ? args.name : void 0;
40352
41225
  this.id = "id" in args ? args.id : void 0;
@@ -40401,11 +41274,11 @@ var Project2 = (_class37 = class {
40401
41274
  }
40402
41275
  }, _class37);
40403
41276
  var ToolBuilder = (_class38 = class {
40404
- constructor(project) {;_class38.prototype.__init139.call(this);
41277
+ constructor(project) {;_class38.prototype.__init141.call(this);
40405
41278
  this.project = project;
40406
41279
  }
40407
41280
 
40408
- __init139() {this.taskCounter = 0}
41281
+ __init141() {this.taskCounter = 0}
40409
41282
  // This type definition is just a catch all so that the implementation can be
40410
41283
  // less specific than the two more specific declarations above.
40411
41284
  create(opts) {
@@ -40432,11 +41305,11 @@ var ToolBuilder = (_class38 = class {
40432
41305
  }
40433
41306
  }, _class38);
40434
41307
  var ScorerBuilder = (_class39 = class {
40435
- constructor(project) {;_class39.prototype.__init140.call(this);
41308
+ constructor(project) {;_class39.prototype.__init142.call(this);
40436
41309
  this.project = project;
40437
41310
  }
40438
41311
 
40439
- __init140() {this.taskCounter = 0}
41312
+ __init142() {this.taskCounter = 0}
40440
41313
  create(opts) {
40441
41314
  this.taskCounter++;
40442
41315
  let resolvedName = opts.name;
@@ -40492,11 +41365,11 @@ var ScorerBuilder = (_class39 = class {
40492
41365
  }
40493
41366
  }, _class39);
40494
41367
  var ClassifierBuilder = (_class40 = class {
40495
- constructor(project) {;_class40.prototype.__init141.call(this);
41368
+ constructor(project) {;_class40.prototype.__init143.call(this);
40496
41369
  this.project = project;
40497
41370
  }
40498
41371
 
40499
- __init141() {this.taskCounter = 0}
41372
+ __init143() {this.taskCounter = 0}
40500
41373
  create(opts) {
40501
41374
  this.taskCounter++;
40502
41375
  let resolvedName = _nullishCoalesce(opts.name, () => ( opts.handler.name));
@@ -40818,9 +41691,9 @@ function serializeRemoteEvalParametersContainer(parameters) {
40818
41691
  source: null
40819
41692
  };
40820
41693
  }
40821
- var ProjectNameIdMap = (_class41 = class {constructor() { _class41.prototype.__init142.call(this);_class41.prototype.__init143.call(this); }
40822
- __init142() {this.nameToId = {}}
40823
- __init143() {this.idToName = {}}
41694
+ var ProjectNameIdMap = (_class41 = class {constructor() { _class41.prototype.__init144.call(this);_class41.prototype.__init145.call(this); }
41695
+ __init144() {this.nameToId = {}}
41696
+ __init145() {this.idToName = {}}
40824
41697
  async getId(projectName) {
40825
41698
  if (!(projectName in this.nameToId)) {
40826
41699
  const response = await _internalGetGlobalState().appConn().post_json("api/project/register", {
@@ -40928,7 +41801,7 @@ function runDevServer(evaluators, opts) {
40928
41801
  scores,
40929
41802
  stream
40930
41803
  } = evalBodySchema.parse(req.body);
40931
- if (!_optionalChain([req, 'access', _1121 => _1121.ctx, 'optionalAccess', _1122 => _1122.state])) {
41804
+ if (!_optionalChain([req, 'access', _1172 => _1172.ctx, 'optionalAccess', _1173 => _1173.state])) {
40932
41805
  res.status(500).json({ error: "Braintrust state not initialized in request" });
40933
41806
  return;
40934
41807
  }
@@ -40979,12 +41852,12 @@ function runDevServer(evaluators, opts) {
40979
41852
  ...evaluator,
40980
41853
  data: evalData.data,
40981
41854
  scores: (_nullishCoalesce(evaluator.scores, () => ( []))).concat(
40982
- _nullishCoalesce(_optionalChain([scores, 'optionalAccess', _1123 => _1123.map, 'call', _1124 => _1124(
41855
+ _nullishCoalesce(_optionalChain([scores, 'optionalAccess', _1174 => _1174.map, 'call', _1175 => _1175(
40983
41856
  (score) => makeScorer(
40984
41857
  state,
40985
41858
  score.name,
40986
41859
  score.function_id,
40987
- _optionalChain([req, 'access', _1125 => _1125.ctx, 'optionalAccess', _1126 => _1126.projectId])
41860
+ _optionalChain([req, 'access', _1176 => _1176.ctx, 'optionalAccess', _1177 => _1177.projectId])
40988
41861
  )
40989
41862
  )]), () => ( []))
40990
41863
  ),