@voltagent/core 2.6.10 → 2.6.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -287,7 +287,7 @@ __export(index_exports, {
287
287
  context: () => import_api9.context,
288
288
  convertUsage: () => convertUsage,
289
289
  cosineSimilarity: () => cosineSimilarity,
290
- createAsyncIterableStream: () => import_utils40.createAsyncIterableStream,
290
+ createAsyncIterableStream: () => import_utils41.createAsyncIterableStream,
291
291
  createDefaultInputSafetyGuardrails: () => createDefaultInputSafetyGuardrails,
292
292
  createDefaultPIIGuardrails: () => createDefaultPIIGuardrails,
293
293
  createDefaultSafetyGuardrails: () => createDefaultSafetyGuardrails,
@@ -12693,7 +12693,7 @@ __name(createWorkflowChain, "createWorkflowChain");
12693
12693
  // src/agent/agent.ts
12694
12694
  var import_node_util = require("util");
12695
12695
  var import_api16 = require("@opentelemetry/api");
12696
- var import_utils33 = require("@voltagent/internal/utils");
12696
+ var import_utils34 = require("@voltagent/internal/utils");
12697
12697
  var import_ai7 = require("ai");
12698
12698
  var import_zod7 = require("zod");
12699
12699
 
@@ -24925,6 +24925,41 @@ function createScorerSpanAttributes(host, descriptor, config, storagePayload, me
24925
24925
  if (metrics.datasetMetadata?.datasetItemHash) {
24926
24926
  attributes["eval.dataset.item_hash"] = metrics.datasetMetadata.datasetItemHash;
24927
24927
  }
24928
+ const judgeTelemetry = extractJudgeTelemetry(metrics.combinedMetadata);
24929
+ if (judgeTelemetry?.modelName) {
24930
+ attributes["ai.model.name"] = judgeTelemetry.modelName;
24931
+ const provider = judgeTelemetry.modelName.includes("/") ? judgeTelemetry.modelName.split("/")[0] : void 0;
24932
+ if (provider) {
24933
+ attributes["ai.model.provider"] = provider;
24934
+ }
24935
+ }
24936
+ if (judgeTelemetry?.promptTokens !== void 0) {
24937
+ attributes["usage.prompt_tokens"] = judgeTelemetry.promptTokens;
24938
+ }
24939
+ if (judgeTelemetry?.completionTokens !== void 0) {
24940
+ attributes["usage.completion_tokens"] = judgeTelemetry.completionTokens;
24941
+ }
24942
+ if (judgeTelemetry?.totalTokens !== void 0) {
24943
+ attributes["usage.total_tokens"] = judgeTelemetry.totalTokens;
24944
+ }
24945
+ if (judgeTelemetry?.cachedTokens !== void 0) {
24946
+ attributes["usage.cached_tokens"] = judgeTelemetry.cachedTokens;
24947
+ }
24948
+ if (judgeTelemetry?.reasoningTokens !== void 0) {
24949
+ attributes["usage.reasoning_tokens"] = judgeTelemetry.reasoningTokens;
24950
+ }
24951
+ if (judgeTelemetry?.providerCost?.cost !== void 0) {
24952
+ attributes["usage.cost"] = judgeTelemetry.providerCost.cost;
24953
+ }
24954
+ if (judgeTelemetry?.providerCost?.upstreamInferenceCost !== void 0) {
24955
+ attributes["usage.cost_details.upstream_inference_cost"] = judgeTelemetry.providerCost.upstreamInferenceCost;
24956
+ }
24957
+ if (judgeTelemetry?.providerCost?.upstreamInferenceInputCost !== void 0) {
24958
+ attributes["usage.cost_details.upstream_inference_input_cost"] = judgeTelemetry.providerCost.upstreamInferenceInputCost;
24959
+ }
24960
+ if (judgeTelemetry?.providerCost?.upstreamInferenceOutputCost !== void 0) {
24961
+ attributes["usage.cost_details.upstream_inference_output_cost"] = judgeTelemetry.providerCost.upstreamInferenceOutputCost;
24962
+ }
24928
24963
  if (storagePayload.userId) {
24929
24964
  attributes["user.id"] = storagePayload.userId;
24930
24965
  }
@@ -25807,6 +25842,64 @@ function extractErrorMessage(error) {
25807
25842
  }
25808
25843
  }
25809
25844
  __name(extractErrorMessage, "extractErrorMessage");
25845
+ function extractJudgeTelemetry(metadata) {
25846
+ const record = isPlainRecord(metadata) ? metadata : void 0;
25847
+ if (!record) {
25848
+ return void 0;
25849
+ }
25850
+ const sources = [];
25851
+ if (isPlainRecord(record.voltAgent)) {
25852
+ sources.push(record.voltAgent);
25853
+ }
25854
+ if (isPlainRecord(record.scorer)) {
25855
+ sources.push(record.scorer);
25856
+ }
25857
+ if (isPlainRecord(record.payload)) {
25858
+ sources.push(record.payload);
25859
+ }
25860
+ for (const source of sources) {
25861
+ const judge = isPlainRecord(source?.judge) ? source?.judge : void 0;
25862
+ if (!judge) {
25863
+ continue;
25864
+ }
25865
+ const usage = isPlainRecord(judge.usage) ? judge.usage : void 0;
25866
+ const providerCost = isPlainRecord(judge.providerCost) ? judge.providerCost : void 0;
25867
+ const telemetry = {
25868
+ modelName: readString(judge.model),
25869
+ promptTokens: readNumber(usage?.promptTokens),
25870
+ completionTokens: readNumber(usage?.completionTokens),
25871
+ totalTokens: readNumber(usage?.totalTokens),
25872
+ cachedTokens: readNumber(usage?.cachedInputTokens ?? usage?.cachedTokens),
25873
+ reasoningTokens: readNumber(usage?.reasoningTokens),
25874
+ providerCost: providerCost ? {
25875
+ cost: readNumber(providerCost.cost),
25876
+ upstreamInferenceCost: readNumber(providerCost.upstreamInferenceCost),
25877
+ upstreamInferenceInputCost: readNumber(providerCost.upstreamInferenceInputCost),
25878
+ upstreamInferenceOutputCost: readNumber(providerCost.upstreamInferenceOutputCost)
25879
+ } : void 0
25880
+ };
25881
+ if (telemetry.modelName || telemetry.promptTokens !== void 0 || telemetry.completionTokens !== void 0 || telemetry.totalTokens !== void 0 || telemetry.cachedTokens !== void 0 || telemetry.reasoningTokens !== void 0 || telemetry.providerCost?.cost !== void 0 || telemetry.providerCost?.upstreamInferenceCost !== void 0 || telemetry.providerCost?.upstreamInferenceInputCost !== void 0 || telemetry.providerCost?.upstreamInferenceOutputCost !== void 0) {
25882
+ return telemetry;
25883
+ }
25884
+ }
25885
+ return void 0;
25886
+ }
25887
+ __name(extractJudgeTelemetry, "extractJudgeTelemetry");
25888
+ function readString(value) {
25889
+ return typeof value === "string" && value.length > 0 ? value : void 0;
25890
+ }
25891
+ __name(readString, "readString");
25892
+ function readNumber(value) {
25893
+ if (typeof value === "number") {
25894
+ return Number.isFinite(value) ? value : void 0;
25895
+ }
25896
+ if (typeof value === "string") {
25897
+ const parsed = Number(value);
25898
+ return Number.isFinite(parsed) ? parsed : void 0;
25899
+ }
25900
+ return void 0;
25901
+ }
25902
+ __name(readNumber, "readNumber");
25810
25903
  async function invokeEvalResultCallback(host, config, result) {
25811
25904
  if (!config.onResult) {
25812
25905
  return;
@@ -26428,6 +26521,172 @@ function addModelAttributesToSpan(span, modelName, options, defaultMaxOutputToke
26428
26521
  }
26429
26522
  __name(addModelAttributesToSpan, "addModelAttributesToSpan");
26430
26523
 
26524
+ // src/agent/prompt-context-usage.ts
26525
+ var import_utils29 = require("@voltagent/internal/utils");
26526
+ var ESTIMATED_CHARS_PER_TOKEN = 4;
26527
+ var BINARY_PART_TYPES = /* @__PURE__ */ new Set([
26528
+ "audio",
26529
+ "file",
26530
+ "image",
26531
+ "input_audio",
26532
+ "input_image",
26533
+ "media"
26534
+ ]);
26535
+ var LARGE_BINARY_KEYS = /* @__PURE__ */ new Set(["audio", "base64", "bytes", "data", "image"]);
26536
+ function estimatePromptContextUsage(params) {
26537
+ let systemTokensEstimated = 0;
26538
+ let messageTokensEstimated = 0;
26539
+ let nonSystemMessageTokensEstimated = 0;
26540
+ let systemMessageCount = 0;
26541
+ for (const message of params.messages ?? []) {
26542
+ const serializedMessage = serializePromptMessage(message);
26543
+ if (!serializedMessage) {
26544
+ continue;
26545
+ }
26546
+ const estimatedTokens = estimateTokensFromText(serializedMessage);
26547
+ messageTokensEstimated += estimatedTokens;
26548
+ if (message.role === "system") {
26549
+ systemTokensEstimated += estimatedTokens;
26550
+ systemMessageCount += 1;
26551
+ continue;
26552
+ }
26553
+ nonSystemMessageTokensEstimated += estimatedTokens;
26554
+ }
26555
+ const serializedTools = Object.entries(params.tools ?? {}).map(
26556
+ ([name, tool2]) => serializeToolDefinition(name, tool2)
26557
+ );
26558
+ const toolTokensEstimated = serializedTools.length > 0 ? estimateTokensFromText((0, import_utils29.safeStringify)(serializedTools)) : 0;
26559
+ const totalTokensEstimated = messageTokensEstimated + toolTokensEstimated;
26560
+ if (totalTokensEstimated === 0) {
26561
+ return void 0;
26562
+ }
26563
+ return {
26564
+ systemTokensEstimated,
26565
+ messageTokensEstimated,
26566
+ nonSystemMessageTokensEstimated,
26567
+ toolTokensEstimated,
26568
+ totalTokensEstimated,
26569
+ systemMessageCount,
26570
+ toolCount: serializedTools.length
26571
+ };
26572
+ }
26573
+ __name(estimatePromptContextUsage, "estimatePromptContextUsage");
26574
+ function promptContextUsageEstimateToAttributes(estimate) {
26575
+ return {
26576
+ "usage.prompt_context.system_tokens_estimated": estimate.systemTokensEstimated,
26577
+ "usage.prompt_context.message_tokens_estimated": estimate.messageTokensEstimated,
26578
+ "usage.prompt_context.non_system_message_tokens_estimated": estimate.nonSystemMessageTokensEstimated,
26579
+ "usage.prompt_context.tool_tokens_estimated": estimate.toolTokensEstimated,
26580
+ "usage.prompt_context.total_tokens_estimated": estimate.totalTokensEstimated,
26581
+ "usage.prompt_context.system_message_count": estimate.systemMessageCount,
26582
+ "usage.prompt_context.tool_count": estimate.toolCount
26583
+ };
26584
+ }
26585
+ __name(promptContextUsageEstimateToAttributes, "promptContextUsageEstimateToAttributes");
26586
+ function estimateTokensFromText(text) {
26587
+ if (!text) {
26588
+ return 0;
26589
+ }
26590
+ return Math.ceil(text.length / ESTIMATED_CHARS_PER_TOKEN);
26591
+ }
26592
+ __name(estimateTokensFromText, "estimateTokensFromText");
26593
+ function serializePromptMessage(message) {
26594
+ const content = serializePromptValue(message.content).trim();
26595
+ if (!content) {
26596
+ return "";
26597
+ }
26598
+ const role = typeof message.role === "string" ? message.role.toUpperCase() : "MESSAGE";
26599
+ return `${role}:
26600
+ ${content}`;
26601
+ }
26602
+ __name(serializePromptMessage, "serializePromptMessage");
26603
+ function serializePromptValue(value) {
26604
+ if (typeof value === "string") {
26605
+ return value;
26606
+ }
26607
+ if (typeof value === "number" || typeof value === "boolean") {
26608
+ return String(value);
26609
+ }
26610
+ if (Array.isArray(value)) {
26611
+ return value.map((entry) => serializePromptValue(entry)).filter((entry) => entry.trim().length > 0).join("\n");
26612
+ }
26613
+ if (!value || typeof value !== "object") {
26614
+ return "";
26615
+ }
26616
+ const record = value;
26617
+ const type = typeof record.type === "string" ? record.type : void 0;
26618
+ if (typeof record.text === "string") {
26619
+ return record.text;
26620
+ }
26621
+ if (type && BINARY_PART_TYPES.has(type)) {
26622
+ return `[${type}]`;
26623
+ }
26624
+ if (type === "tool-call") {
26625
+ const toolName = typeof record.toolName === "string" ? record.toolName : "tool";
26626
+ const input = serializePromptValue(record.input);
26627
+ return input ? `tool-call ${toolName}: ${input}` : `tool-call ${toolName}`;
26628
+ }
26629
+ if (type === "tool-result") {
26630
+ const toolName = typeof record.toolName === "string" ? record.toolName : "tool";
26631
+ const output = serializePromptValue(record.output);
26632
+ return output ? `tool-result ${toolName}: ${output}` : `tool-result ${toolName}`;
26633
+ }
26634
+ if ("content" in record) {
26635
+ const nestedContent = serializePromptValue(record.content);
26636
+ if (nestedContent) {
26637
+ return nestedContent;
26638
+ }
26639
+ }
26640
+ return (0, import_utils29.safeStringify)(sanitizeRecord(record));
26641
+ }
26642
+ __name(serializePromptValue, "serializePromptValue");
26643
+ function sanitizeRecord(record) {
26644
+ const sanitized = {};
26645
+ for (const [key, value] of Object.entries(record)) {
26646
+ sanitized[key] = LARGE_BINARY_KEYS.has(key) ? "[omitted]" : value;
26647
+ }
26648
+ return sanitized;
26649
+ }
26650
+ __name(sanitizeRecord, "sanitizeRecord");
26651
+ function serializeToolDefinition(name, tool2) {
26652
+ if (!tool2 || typeof tool2 !== "object") {
26653
+ return { name };
26654
+ }
26655
+ const candidate = tool2;
26656
+ return {
26657
+ name,
26658
+ ...typeof candidate.type === "string" ? { type: candidate.type } : {},
26659
+ ...typeof candidate.id === "string" ? { id: candidate.id } : {},
26660
+ ...typeof candidate.description === "string" ? { description: candidate.description } : {},
26661
+ ...candidate.inputSchema || candidate.parameters || candidate.input_schema || candidate.schema ? {
26662
+ inputSchema: normalizeSchema(
26663
+ candidate.inputSchema ?? candidate.parameters ?? candidate.input_schema ?? candidate.schema
26664
+ )
26665
+ } : {},
26666
+ ...candidate.outputSchema || candidate.output_schema ? {
26667
+ outputSchema: normalizeSchema(candidate.outputSchema ?? candidate.output_schema)
26668
+ } : {},
26669
+ ...candidate.providerOptions ? { providerOptions: candidate.providerOptions } : {},
26670
+ ...candidate.args ? { args: sanitizeRecord(candidate.args) } : {},
26671
+ ...candidate.needsApproval !== void 0 ? { needsApproval: candidate.needsApproval } : {}
26672
+ };
26673
+ }
26674
+ __name(serializeToolDefinition, "serializeToolDefinition");
26675
+ function normalizeSchema(schema) {
26676
+ if (!schema || typeof schema !== "object") {
26677
+ return schema;
26678
+ }
26679
+ try {
26680
+ if ("_def" in schema) {
26681
+ return zodSchemaToJsonUI(schema);
26682
+ }
26683
+ } catch (_error) {
26684
+ return schema;
26685
+ }
26686
+ return schema;
26687
+ }
26688
+ __name(normalizeSchema, "normalizeSchema");
26689
+
26431
26690
  // src/agent/tool-input-coercion.ts
26432
26691
  var isPathSegment = /* @__PURE__ */ __name((value) => typeof value === "string" || typeof value === "number", "isPathSegment");
26433
26692
  var isRecord2 = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isRecord");
@@ -26546,7 +26805,7 @@ var coerceStringifiedJsonToolArgs = /* @__PURE__ */ __name((rawArgs, issues) =>
26546
26805
  var import_ts_pattern2 = require("ts-pattern");
26547
26806
 
26548
26807
  // src/agent/apply-summarization.ts
26549
- var import_utils29 = require("@voltagent/internal/utils");
26808
+ var import_utils30 = require("@voltagent/internal/utils");
26550
26809
  var import_ai5 = require("ai");
26551
26810
  var SUMMARY_METADATA_KEY = "agent";
26552
26811
  var SUMMARY_STATE_CACHE_KEY = Symbol("agentSummaryState");
@@ -26659,7 +26918,7 @@ var applySummarization = /* @__PURE__ */ __name(async ({
26659
26918
  }
26660
26919
  } catch (error) {
26661
26920
  oc.logger.debug("[Agent] Failed to summarize conversation", {
26662
- error: (0, import_utils29.safeStringify)(error)
26921
+ error: (0, import_utils30.safeStringify)(error)
26663
26922
  });
26664
26923
  if (summarySpan) {
26665
26924
  oc.traceContext.endChildSpan(summarySpan, "error", {
@@ -26742,7 +27001,7 @@ async function loadAgentSummaryState(agent, context8) {
26742
27001
  state = readSummaryStateFromMetadata(conversation?.metadata);
26743
27002
  } catch (error) {
26744
27003
  context8.logger.debug("[Agent] Failed to load summary state from memory", {
26745
- error: (0, import_utils29.safeStringify)(error)
27004
+ error: (0, import_utils30.safeStringify)(error)
26746
27005
  });
26747
27006
  }
26748
27007
  }
@@ -26772,7 +27031,7 @@ async function updateAgentSummaryState(agent, context8, updater) {
26772
27031
  }
26773
27032
  } catch (error) {
26774
27033
  context8.logger.debug("[Agent] Failed to persist summary state", {
26775
- error: (0, import_utils29.safeStringify)(error)
27034
+ error: (0, import_utils30.safeStringify)(error)
26776
27035
  });
26777
27036
  }
26778
27037
  }
@@ -26805,11 +27064,11 @@ function removeSystemMessagesWithMarker(messages, marker) {
26805
27064
  });
26806
27065
  }
26807
27066
  __name(removeSystemMessagesWithMarker, "removeSystemMessagesWithMarker");
26808
- function estimateTokensFromText(text) {
27067
+ function estimateTokensFromText2(text) {
26809
27068
  if (!text) return 0;
26810
27069
  return Math.ceil(text.length / SUMMARY_CHAR_PER_TOKEN);
26811
27070
  }
26812
- __name(estimateTokensFromText, "estimateTokensFromText");
27071
+ __name(estimateTokensFromText2, "estimateTokensFromText");
26813
27072
  function summarizePartValue(value) {
26814
27073
  if (typeof value === "string") {
26815
27074
  return truncateText2(value, SUMMARY_MAX_PART_CHARS);
@@ -26817,7 +27076,7 @@ function summarizePartValue(value) {
26817
27076
  if (value === null || value === void 0) {
26818
27077
  return "";
26819
27078
  }
26820
- return truncateText2((0, import_utils29.safeStringify)(value), SUMMARY_MAX_PART_CHARS);
27079
+ return truncateText2((0, import_utils30.safeStringify)(value), SUMMARY_MAX_PART_CHARS);
26821
27080
  }
26822
27081
  __name(summarizePartValue, "summarizePartValue");
26823
27082
  function extractSummaryText(message) {
@@ -26872,7 +27131,7 @@ function estimateTokensFromMessages(messages) {
26872
27131
  for (const message of messages) {
26873
27132
  const formatted = formatMessageForSummary(message);
26874
27133
  if (formatted) {
26875
- total += estimateTokensFromText(formatted);
27134
+ total += estimateTokensFromText2(formatted);
26876
27135
  }
26877
27136
  }
26878
27137
  return total;
@@ -28319,7 +28578,7 @@ var collapseRedundantStepStarts = /* @__PURE__ */ __name((parts) => {
28319
28578
 
28320
28579
  // src/agent/middleware.ts
28321
28580
  var import_api13 = require("@opentelemetry/api");
28322
- var import_utils30 = require("@voltagent/internal/utils");
28581
+ var import_utils31 = require("@voltagent/internal/utils");
28323
28582
  function createInputMiddleware(options) {
28324
28583
  return {
28325
28584
  id: options.id,
@@ -28398,7 +28657,7 @@ function serializeMiddlewareValue(value) {
28398
28657
  if (typeof value === "string") {
28399
28658
  return value;
28400
28659
  }
28401
- return (0, import_utils30.safeStringify)(value);
28660
+ return (0, import_utils31.safeStringify)(value);
28402
28661
  }
28403
28662
  __name(serializeMiddlewareValue, "serializeMiddlewareValue");
28404
28663
  async function runInputMiddlewares(input, oc, middlewares, operation, agent, retryCount) {
@@ -28422,8 +28681,8 @@ async function runInputMiddlewares(input, oc, middlewares, operation, agent, ret
28422
28681
  ...middleware.id ? { "middleware.id": middleware.id } : {},
28423
28682
  "middleware.name": middleware.name,
28424
28683
  ...middleware.description ? { "middleware.description": middleware.description } : {},
28425
- ...middleware.tags && middleware.tags.length > 0 ? { "middleware.tags": (0, import_utils30.safeStringify)(middleware.tags) } : {},
28426
- ...middleware.metadata ? { "middleware.metadata": (0, import_utils30.safeStringify)(middleware.metadata) } : {},
28684
+ ...middleware.tags && middleware.tags.length > 0 ? { "middleware.tags": (0, import_utils31.safeStringify)(middleware.tags) } : {},
28685
+ ...middleware.metadata ? { "middleware.metadata": (0, import_utils31.safeStringify)(middleware.metadata) } : {},
28427
28686
  "middleware.retry_count": retryCount,
28428
28687
  "middleware.input.original": serializeMiddlewareValue(originalInput),
28429
28688
  "middleware.input.current": serializeMiddlewareValue(currentInput)
@@ -28491,8 +28750,8 @@ async function runOutputMiddlewares(output, oc, middlewares, operation, agent, r
28491
28750
  ...middleware.id ? { "middleware.id": middleware.id } : {},
28492
28751
  "middleware.name": middleware.name,
28493
28752
  ...middleware.description ? { "middleware.description": middleware.description } : {},
28494
- ...middleware.tags && middleware.tags.length > 0 ? { "middleware.tags": (0, import_utils30.safeStringify)(middleware.tags) } : {},
28495
- ...middleware.metadata ? { "middleware.metadata": (0, import_utils30.safeStringify)(middleware.metadata) } : {},
28753
+ ...middleware.tags && middleware.tags.length > 0 ? { "middleware.tags": (0, import_utils31.safeStringify)(middleware.tags) } : {},
28754
+ ...middleware.metadata ? { "middleware.metadata": (0, import_utils31.safeStringify)(middleware.metadata) } : {},
28496
28755
  "middleware.retry_count": retryCount,
28497
28756
  "middleware.output.original": serializeMiddlewareValue(originalOutput),
28498
28757
  "middleware.output.current": serializeMiddlewareValue(currentOutput)
@@ -28500,13 +28759,13 @@ async function runOutputMiddlewares(output, oc, middlewares, operation, agent, r
28500
28759
  }
28501
28760
  );
28502
28761
  if (metadata?.usage !== void 0) {
28503
- span.setAttribute("middleware.usage", (0, import_utils30.safeStringify)(metadata.usage));
28762
+ span.setAttribute("middleware.usage", (0, import_utils31.safeStringify)(metadata.usage));
28504
28763
  }
28505
28764
  if (metadata?.finishReason !== void 0 && metadata.finishReason !== null) {
28506
28765
  span.setAttribute("middleware.finish_reason", metadata.finishReason);
28507
28766
  }
28508
28767
  if (metadata?.warnings && metadata.warnings.length > 0) {
28509
- span.setAttribute("middleware.warnings", (0, import_utils30.safeStringify)(metadata.warnings));
28768
+ span.setAttribute("middleware.warnings", (0, import_utils31.safeStringify)(metadata.warnings));
28510
28769
  }
28511
28770
  try {
28512
28771
  const abort = /* @__PURE__ */ __name((reason, options) => {
@@ -28554,7 +28813,7 @@ var import_ai6 = require("ai");
28554
28813
 
28555
28814
  // src/agent/streaming/output-guardrail-stream-runner.ts
28556
28815
  var import_api14 = require("@opentelemetry/api");
28557
- var import_utils31 = require("@voltagent/internal/utils");
28816
+ var import_utils32 = require("@voltagent/internal/utils");
28558
28817
  var isTextDelta = /* @__PURE__ */ __name((part) => part.type === "text-delta", "isTextDelta");
28559
28818
  var extractChunkText = /* @__PURE__ */ __name((part) => {
28560
28819
  if (!isTextDelta(part)) {
@@ -28809,8 +29068,8 @@ var OutputGuardrailStreamRunner = class {
28809
29068
  "guardrail.name": guardrail.name,
28810
29069
  ...guardrail.description ? { "guardrail.description": guardrail.description } : {},
28811
29070
  ...guardrail.severity ? { "guardrail.severity": guardrail.severity } : {},
28812
- ...guardrail.tags && guardrail.tags.length > 0 ? { "guardrail.tags": (0, import_utils31.safeStringify)(guardrail.tags) } : {},
28813
- ...guardrail.metadata ? { "guardrail.metadata": (0, import_utils31.safeStringify)(guardrail.metadata) } : {}
29071
+ ...guardrail.tags && guardrail.tags.length > 0 ? { "guardrail.tags": (0, import_utils32.safeStringify)(guardrail.tags) } : {},
29072
+ ...guardrail.metadata ? { "guardrail.metadata": (0, import_utils32.safeStringify)(guardrail.metadata) } : {}
28814
29073
  }
28815
29074
  }
28816
29075
  );
@@ -29338,7 +29597,7 @@ __name(convertFullStreamChunkToUIMessageStream, "convertFullStreamChunkToUIMessa
29338
29597
 
29339
29598
  // src/agent/subagent/index.ts
29340
29599
  var import_api15 = require("@opentelemetry/api");
29341
- var import_utils32 = require("@voltagent/internal/utils");
29600
+ var import_utils33 = require("@voltagent/internal/utils");
29342
29601
  var import_zod6 = require("zod");
29343
29602
 
29344
29603
  // src/agent/subagent/types.ts
@@ -29644,7 +29903,7 @@ ${guidelinesText}
29644
29903
  taskContent = `Task handed off from ${sourceAgent?.name || this.agentName} to ${targetAgent.name}:
29645
29904
  ${task}
29646
29905
 
29647
- Context: ${(0, import_utils32.safeStringify)(contextObj, { indentation: 2 })}`;
29906
+ Context: ${(0, import_utils33.safeStringify)(contextObj, { indentation: 2 })}`;
29648
29907
  }
29649
29908
  const taskMessage = {
29650
29909
  id: crypto.randomUUID(),
@@ -29702,7 +29961,7 @@ Context: ${(0, import_utils32.safeStringify)(contextObj, { indentation: 2 })}`;
29702
29961
  options2
29703
29962
  );
29704
29963
  const finalObject = await response.object;
29705
- finalResult = (0, import_utils32.safeStringify)(finalObject);
29964
+ finalResult = (0, import_utils33.safeStringify)(finalObject);
29706
29965
  finalMessages = [taskMessage, this.createAssistantMessage(finalResult)];
29707
29966
  } else if (this.isGenerateObjectConfig(targetAgentConfig)) {
29708
29967
  const options2 = { ...baseOptions, ...targetAgentConfig.options };
@@ -29711,7 +29970,7 @@ Context: ${(0, import_utils32.safeStringify)(contextObj, { indentation: 2 })}`;
29711
29970
  targetAgentConfig.schema,
29712
29971
  options2
29713
29972
  );
29714
- finalResult = (0, import_utils32.safeStringify)(response);
29973
+ finalResult = (0, import_utils33.safeStringify)(response);
29715
29974
  usage = response.usage;
29716
29975
  finalMessages = [taskMessage, this.createAssistantMessage(finalResult)];
29717
29976
  } else {
@@ -30146,6 +30405,27 @@ var extractOpenRouterUsageCost = /* @__PURE__ */ __name((providerMetadata) => {
30146
30405
  };
30147
30406
  return Object.values(result).some((value) => value !== void 0) ? result : void 0;
30148
30407
  }, "extractOpenRouterUsageCost");
30408
+ var toLanguageModelUsage = /* @__PURE__ */ __name((value) => isPlainObject(value) ? value : void 0, "toLanguageModelUsage");
30409
+ var extractGenerationErrorDetails = /* @__PURE__ */ __name((error) => {
30410
+ const metadata = isRecord4(error) && isPlainObject(error.metadata) ? error.metadata : void 0;
30411
+ const originalError = isRecord4(error) ? error.originalError : void 0;
30412
+ const usage = firstDefined(
30413
+ isRecord4(error) ? toLanguageModelUsage(error.usage) : void 0,
30414
+ metadata ? toLanguageModelUsage(metadata.usage) : void 0,
30415
+ isRecord4(originalError) ? toLanguageModelUsage(originalError.usage) : void 0
30416
+ );
30417
+ const providerMetadata = firstDefined(
30418
+ metadata?.providerMetadata,
30419
+ isRecord4(error) ? error.providerMetadata : void 0,
30420
+ isRecord4(originalError) ? originalError.providerMetadata : void 0
30421
+ );
30422
+ const finishReason = firstNonBlank(
30423
+ isRecord4(error) ? error.finishReason : void 0,
30424
+ metadata?.finishReason,
30425
+ isRecord4(originalError) ? originalError.finishReason : void 0
30426
+ );
30427
+ return { usage, providerMetadata, finishReason };
30428
+ }, "extractGenerationErrorDetails");
30149
30429
  var isAssistantContentPart = /* @__PURE__ */ __name((value) => {
30150
30430
  if (!isRecord4(value)) {
30151
30431
  return false;
@@ -30595,12 +30875,12 @@ var Agent = class {
30595
30875
  );
30596
30876
  const contextMap = Object.fromEntries(oc.context.entries());
30597
30877
  if (Object.keys(contextMap).length > 0) {
30598
- rootSpan.setAttribute("agent.context", (0, import_utils33.safeStringify)(contextMap));
30878
+ rootSpan.setAttribute("agent.context", (0, import_utils34.safeStringify)(contextMap));
30599
30879
  }
30600
- rootSpan.setAttribute("agent.messages", (0, import_utils33.safeStringify)(messages));
30601
- rootSpan.setAttribute("agent.messages.ui", (0, import_utils33.safeStringify)(uiMessages));
30880
+ rootSpan.setAttribute("agent.messages", (0, import_utils34.safeStringify)(messages));
30881
+ rootSpan.setAttribute("agent.messages.ui", (0, import_utils34.safeStringify)(uiMessages));
30602
30882
  const agentState = this.getFullState();
30603
- rootSpan.setAttribute("agent.stateSnapshot", (0, import_utils33.safeStringify)(agentState));
30883
+ rootSpan.setAttribute("agent.stateSnapshot", (0, import_utils34.safeStringify)(agentState));
30604
30884
  methodLogger.debug(
30605
30885
  buildAgentLogMessage(
30606
30886
  this.name,
@@ -30705,7 +30985,7 @@ var Agent = class {
30705
30985
  onStepFinish: this.createStepHandler(oc, options)
30706
30986
  })
30707
30987
  );
30708
- this.ensureStructuredOutputGenerated({
30988
+ await this.ensureStructuredOutputGenerated({
30709
30989
  result: response,
30710
30990
  output,
30711
30991
  tools,
@@ -30719,7 +30999,13 @@ var Agent = class {
30719
30999
  });
30720
31000
  return response;
30721
31001
  } catch (error) {
30722
- finalizeLLMSpan(import_api16.SpanStatusCode.ERROR, { message: error.message });
31002
+ const errorDetails = extractGenerationErrorDetails(error);
31003
+ finalizeLLMSpan(import_api16.SpanStatusCode.ERROR, {
31004
+ message: error.message,
31005
+ usage: errorDetails.usage,
31006
+ finishReason: errorDetails.finishReason,
31007
+ providerMetadata: errorDetails.providerMetadata
31008
+ });
30723
31009
  throw error;
30724
31010
  }
30725
31011
  }, "run")
@@ -30815,7 +31101,7 @@ var Agent = class {
30815
31101
  operation: "generateText",
30816
31102
  metadata: {
30817
31103
  finishReason: result.finishReason,
30818
- usage: usageForFinish ? JSON.parse((0, import_utils33.safeStringify)(usageForFinish)) : void 0,
31104
+ usage: usageForFinish ? JSON.parse((0, import_utils34.safeStringify)(usageForFinish)) : void 0,
30819
31105
  toolCalls: aggregatedToolCalls
30820
31106
  }
30821
31107
  });
@@ -30882,7 +31168,7 @@ var Agent = class {
30882
31168
  maxMiddlewareRetries,
30883
31169
  middlewareId: retryError.middlewareId ?? null,
30884
31170
  reason: retryError.message ?? "middleware retry",
30885
- metadata: retryError.metadata !== void 0 ? (0, import_utils33.safeStringify)(retryError.metadata) : void 0
31171
+ metadata: retryError.metadata !== void 0 ? (0, import_utils34.safeStringify)(retryError.metadata) : void 0
30886
31172
  });
30887
31173
  this.storeMiddlewareRetryFeedback(oc, retryError.message, retryError.metadata);
30888
31174
  middlewareRetryCount += 1;
@@ -31063,7 +31349,7 @@ var Agent = class {
31063
31349
  maxMiddlewareRetries,
31064
31350
  middlewareId: retryError.middlewareId ?? null,
31065
31351
  reason: retryError.message ?? "middleware retry",
31066
- metadata: retryError.metadata !== void 0 ? (0, import_utils33.safeStringify)(retryError.metadata) : void 0
31352
+ metadata: retryError.metadata !== void 0 ? (0, import_utils34.safeStringify)(retryError.metadata) : void 0
31067
31353
  });
31068
31354
  this.storeMiddlewareRetryFeedback(oc, retryError.message, retryError.metadata);
31069
31355
  middlewareRetryCount += 1;
@@ -31097,12 +31383,12 @@ var Agent = class {
31097
31383
  );
31098
31384
  const contextMap = Object.fromEntries(oc.context.entries());
31099
31385
  if (Object.keys(contextMap).length > 0) {
31100
- rootSpan2.setAttribute("agent.context", (0, import_utils33.safeStringify)(contextMap));
31386
+ rootSpan2.setAttribute("agent.context", (0, import_utils34.safeStringify)(contextMap));
31101
31387
  }
31102
- rootSpan2.setAttribute("agent.messages", (0, import_utils33.safeStringify)(messages));
31103
- rootSpan2.setAttribute("agent.messages.ui", (0, import_utils33.safeStringify)(uiMessages));
31388
+ rootSpan2.setAttribute("agent.messages", (0, import_utils34.safeStringify)(messages));
31389
+ rootSpan2.setAttribute("agent.messages.ui", (0, import_utils34.safeStringify)(uiMessages));
31104
31390
  const agentState = this.getFullState();
31105
- rootSpan2.setAttribute("agent.stateSnapshot", (0, import_utils33.safeStringify)(agentState));
31391
+ rootSpan2.setAttribute("agent.stateSnapshot", (0, import_utils34.safeStringify)(agentState));
31106
31392
  }
31107
31393
  methodLogger.debug(
31108
31394
  buildAgentLogMessage(
@@ -31384,7 +31670,7 @@ var Agent = class {
31384
31670
  operation: "streamText",
31385
31671
  metadata: {
31386
31672
  finishReason: finalResult.finishReason,
31387
- usage: usageForFinish ? JSON.parse((0, import_utils33.safeStringify)(usageForFinish)) : void 0,
31673
+ usage: usageForFinish ? JSON.parse((0, import_utils34.safeStringify)(usageForFinish)) : void 0,
31388
31674
  toolCalls: finalResult.toolCalls
31389
31675
  }
31390
31676
  });
@@ -31771,12 +32057,12 @@ var Agent = class {
31771
32057
  );
31772
32058
  const contextMap = Object.fromEntries(oc.context.entries());
31773
32059
  if (Object.keys(contextMap).length > 0) {
31774
- rootSpan.setAttribute("agent.context", (0, import_utils33.safeStringify)(contextMap));
32060
+ rootSpan.setAttribute("agent.context", (0, import_utils34.safeStringify)(contextMap));
31775
32061
  }
31776
- rootSpan.setAttribute("agent.messages", (0, import_utils33.safeStringify)(messages));
31777
- rootSpan.setAttribute("agent.messages.ui", (0, import_utils33.safeStringify)(uiMessages));
32062
+ rootSpan.setAttribute("agent.messages", (0, import_utils34.safeStringify)(messages));
32063
+ rootSpan.setAttribute("agent.messages.ui", (0, import_utils34.safeStringify)(uiMessages));
31778
32064
  const agentState = this.getFullState();
31779
- rootSpan.setAttribute("agent.stateSnapshot", (0, import_utils33.safeStringify)(agentState));
32065
+ rootSpan.setAttribute("agent.stateSnapshot", (0, import_utils34.safeStringify)(agentState));
31780
32066
  methodLogger.debug(
31781
32067
  buildAgentLogMessage(
31782
32068
  this.name,
@@ -31885,7 +32171,7 @@ var Agent = class {
31885
32171
  parts: [
31886
32172
  {
31887
32173
  type: "text",
31888
- text: (0, import_utils33.safeStringify)(finalObject)
32174
+ text: (0, import_utils34.safeStringify)(finalObject)
31889
32175
  }
31890
32176
  ]
31891
32177
  };
@@ -31893,7 +32179,7 @@ var Agent = class {
31893
32179
  const step = {
31894
32180
  id: randomUUID(),
31895
32181
  type: "text",
31896
- content: (0, import_utils33.safeStringify)(finalObject),
32182
+ content: (0, import_utils34.safeStringify)(finalObject),
31897
32183
  role: "assistant",
31898
32184
  usage: usageInfo
31899
32185
  };
@@ -31907,7 +32193,7 @@ var Agent = class {
31907
32193
  operation: "generateObject",
31908
32194
  metadata: {
31909
32195
  finishReason: result.finishReason,
31910
- usage: usageForFinish ? JSON.parse((0, import_utils33.safeStringify)(usageForFinish)) : void 0,
32196
+ usage: usageForFinish ? JSON.parse((0, import_utils34.safeStringify)(usageForFinish)) : void 0,
31911
32197
  schemaName
31912
32198
  }
31913
32199
  });
@@ -31966,7 +32252,7 @@ var Agent = class {
31966
32252
  maxMiddlewareRetries,
31967
32253
  middlewareId: retryError.middlewareId ?? null,
31968
32254
  reason: retryError.message ?? "middleware retry",
31969
- metadata: retryError.metadata !== void 0 ? (0, import_utils33.safeStringify)(retryError.metadata) : void 0
32255
+ metadata: retryError.metadata !== void 0 ? (0, import_utils34.safeStringify)(retryError.metadata) : void 0
31970
32256
  });
31971
32257
  this.storeMiddlewareRetryFeedback(oc, retryError.message, retryError.metadata);
31972
32258
  middlewareRetryCount += 1;
@@ -32036,7 +32322,7 @@ var Agent = class {
32036
32322
  maxMiddlewareRetries,
32037
32323
  middlewareId: retryError.middlewareId ?? null,
32038
32324
  reason: retryError.message ?? "middleware retry",
32039
- metadata: retryError.metadata !== void 0 ? (0, import_utils33.safeStringify)(retryError.metadata) : void 0
32325
+ metadata: retryError.metadata !== void 0 ? (0, import_utils34.safeStringify)(retryError.metadata) : void 0
32040
32326
  });
32041
32327
  this.storeMiddlewareRetryFeedback(oc, retryError.message, retryError.metadata);
32042
32328
  middlewareRetryCount += 1;
@@ -32067,12 +32353,12 @@ var Agent = class {
32067
32353
  );
32068
32354
  const contextMap = Object.fromEntries(oc.context.entries());
32069
32355
  if (Object.keys(contextMap).length > 0) {
32070
- rootSpan.setAttribute("agent.context", (0, import_utils33.safeStringify)(contextMap));
32356
+ rootSpan.setAttribute("agent.context", (0, import_utils34.safeStringify)(contextMap));
32071
32357
  }
32072
- rootSpan.setAttribute("agent.messages", (0, import_utils33.safeStringify)(messages));
32073
- rootSpan.setAttribute("agent.messages.ui", (0, import_utils33.safeStringify)(uiMessages));
32358
+ rootSpan.setAttribute("agent.messages", (0, import_utils34.safeStringify)(messages));
32359
+ rootSpan.setAttribute("agent.messages.ui", (0, import_utils34.safeStringify)(uiMessages));
32074
32360
  const agentState = this.getFullState();
32075
- rootSpan.setAttribute("agent.stateSnapshot", (0, import_utils33.safeStringify)(agentState));
32361
+ rootSpan.setAttribute("agent.stateSnapshot", (0, import_utils34.safeStringify)(agentState));
32076
32362
  methodLogger.debug(
32077
32363
  buildAgentLogMessage(
32078
32364
  this.name,
@@ -32235,7 +32521,7 @@ var Agent = class {
32235
32521
  parts: [
32236
32522
  {
32237
32523
  type: "text",
32238
- text: (0, import_utils33.safeStringify)(finalObject)
32524
+ text: (0, import_utils34.safeStringify)(finalObject)
32239
32525
  }
32240
32526
  ]
32241
32527
  };
@@ -32243,7 +32529,7 @@ var Agent = class {
32243
32529
  const step = {
32244
32530
  id: randomUUID(),
32245
32531
  type: "text",
32246
- content: (0, import_utils33.safeStringify)(finalObject),
32532
+ content: (0, import_utils34.safeStringify)(finalObject),
32247
32533
  role: "assistant",
32248
32534
  usage: usageInfo
32249
32535
  };
@@ -32290,7 +32576,7 @@ var Agent = class {
32290
32576
  operation: "streamObject",
32291
32577
  metadata: {
32292
32578
  finishReason: finalResult.finishReason,
32293
- usage: usageForFinish ? JSON.parse((0, import_utils33.safeStringify)(usageForFinish)) : void 0,
32579
+ usage: usageForFinish ? JSON.parse((0, import_utils34.safeStringify)(usageForFinish)) : void 0,
32294
32580
  schemaName
32295
32581
  }
32296
32582
  });
@@ -32409,7 +32695,7 @@ var Agent = class {
32409
32695
  let feedback = `[Middleware Feedback] ${baseReason} Please retry with the feedback in mind.`;
32410
32696
  if (metadata !== void 0) {
32411
32697
  feedback = `${feedback}
32412
- Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32698
+ Metadata: ${(0, import_utils34.safeStringify)(metadata)}`;
32413
32699
  }
32414
32700
  oc.systemContext.set(MIDDLEWARE_RETRY_FEEDBACK_KEY, feedback);
32415
32701
  }
@@ -32471,7 +32757,7 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32471
32757
  toolResults: stepToolResults.length > 0 ? stepToolResults : result.toolResults ?? []
32472
32758
  };
32473
32759
  }
32474
- ensureStructuredOutputGenerated(params) {
32760
+ async ensureStructuredOutputGenerated(params) {
32475
32761
  const { result, output, tools, maxSteps } = params;
32476
32762
  if (!output) {
32477
32763
  return;
@@ -32488,6 +32774,13 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32488
32774
  const stepCount = result.steps?.length ?? 0;
32489
32775
  const finishReason = result.finishReason ?? "unknown";
32490
32776
  const reachedMaxSteps = stepCount >= maxSteps;
32777
+ const providerMetadata = result.providerMetadata;
32778
+ const providerUsage = result.usage ? await Promise.resolve(result.usage) : void 0;
32779
+ const usageForFinish = resolveFinishUsage({
32780
+ providerMetadata,
32781
+ usage: providerUsage,
32782
+ totalUsage: result.totalUsage
32783
+ });
32491
32784
  const guidance = configuredToolCount > 0 || toolCalls.length > 0 ? "When tools are enabled, ensure the model emits a final non-tool response that matches the output schema, or split this into two calls (tools first, schema formatting second)." : "Ensure the model emits a final response that matches the requested output schema.";
32492
32785
  const maxStepHint = reachedMaxSteps ? ` Generation stopped after ${stepCount} steps (maxSteps=${maxSteps}).` : "";
32493
32786
  throw createVoltAgentError(
@@ -32501,7 +32794,9 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32501
32794
  stepCount,
32502
32795
  maxSteps,
32503
32796
  configuredToolCount,
32504
- toolCallCount: toolCalls.length
32797
+ toolCallCount: toolCalls.length,
32798
+ usage: usageForFinish ? JSON.parse((0, import_utils34.safeStringify)(usageForFinish)) : void 0,
32799
+ providerMetadata: providerMetadata !== void 0 ? JSON.parse((0, import_utils34.safeStringify)(providerMetadata)) : void 0
32505
32800
  }
32506
32801
  }
32507
32802
  );
@@ -32763,7 +33058,7 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32763
33058
  for (const responseMessage of responseMessages) {
32764
33059
  const normalizedMessage = responseMessage.role === "assistant" ? { ...responseMessage, id: fallbackAssistantMessageId } : responseMessage;
32765
33060
  const fingerprintMessageId = normalizedMessage.role === "assistant" ? fallbackAssistantMessageId : normalizedMessage.id ?? null;
32766
- const fingerprint = (0, import_utils33.safeStringify)({
33061
+ const fingerprint = (0, import_utils34.safeStringify)({
32767
33062
  role: normalizedMessage.role,
32768
33063
  id: fingerprintMessageId,
32769
33064
  content: normalizedMessage.content
@@ -32838,7 +33133,14 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32838
33133
  }
32839
33134
  createLLMSpan(oc, params) {
32840
33135
  const { label, ...spanParams } = params;
32841
- const attributes = this.buildLLMSpanAttributes(spanParams);
33136
+ const promptContextUsageEstimate = estimatePromptContextUsage({
33137
+ messages: params.messages,
33138
+ tools: params.tools
33139
+ });
33140
+ const attributes = {
33141
+ ...this.buildLLMSpanAttributes(spanParams),
33142
+ ...promptContextUsageEstimate ? promptContextUsageEstimateToAttributes(promptContextUsageEstimate) : {}
33143
+ };
32842
33144
  const span = oc.traceContext.createChildSpan(`llm:${params.operation}`, "llm", {
32843
33145
  kind: import_api16.SpanKind.CLIENT,
32844
33146
  label,
@@ -32920,12 +33222,12 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32920
33222
  attrs["llm.top_p"] = topP;
32921
33223
  }
32922
33224
  if (callOptions.stop !== void 0) {
32923
- attrs["llm.stop_condition"] = (0, import_utils33.safeStringify)(callOptions.stop);
33225
+ attrs["llm.stop_condition"] = (0, import_utils34.safeStringify)(callOptions.stop);
32924
33226
  }
32925
33227
  if (params.messages && params.messages.length > 0) {
32926
33228
  attrs["llm.messages.count"] = params.messages.length;
32927
33229
  const trimmedMessages = params.messages.slice(-10);
32928
- attrs["llm.messages"] = (0, import_utils33.safeStringify)(
33230
+ attrs["llm.messages"] = (0, import_utils34.safeStringify)(
32929
33231
  trimmedMessages.map((msg) => ({
32930
33232
  role: msg.role,
32931
33233
  content: msg.content
@@ -32940,7 +33242,7 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32940
33242
  }
32941
33243
  }
32942
33244
  if (params.providerOptions) {
32943
- attrs["llm.provider_options"] = (0, import_utils33.safeStringify)(params.providerOptions);
33245
+ attrs["llm.provider_options"] = (0, import_utils34.safeStringify)(params.providerOptions);
32944
33246
  }
32945
33247
  return attrs;
32946
33248
  }
@@ -32952,7 +33254,7 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32952
33254
  if (!normalizedUsage) {
32953
33255
  return;
32954
33256
  }
32955
- const { promptTokens, completionTokens, totalTokens } = normalizedUsage;
33257
+ const { promptTokens, completionTokens, totalTokens, cachedInputTokens, reasoningTokens } = normalizedUsage;
32956
33258
  if (promptTokens !== void 0) {
32957
33259
  span.setAttribute("llm.usage.prompt_tokens", promptTokens);
32958
33260
  }
@@ -32962,6 +33264,12 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
32962
33264
  if (totalTokens !== void 0) {
32963
33265
  span.setAttribute("llm.usage.total_tokens", totalTokens);
32964
33266
  }
33267
+ if (cachedInputTokens !== void 0) {
33268
+ span.setAttribute("llm.usage.cached_tokens", cachedInputTokens);
33269
+ }
33270
+ if (reasoningTokens !== void 0) {
33271
+ span.setAttribute("llm.usage.reasoning_tokens", reasoningTokens);
33272
+ }
32965
33273
  }
32966
33274
  recordProviderCost(span, providerMetadata) {
32967
33275
  const openRouterUsageCost = extractOpenRouterUsageCost(providerMetadata);
@@ -33207,7 +33515,7 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
33207
33515
  }
33208
33516
  } catch (error) {
33209
33517
  context8.logger.debug("[Memory] Failed to generate conversation title", {
33210
- error: (0, import_utils33.safeStringify)(error)
33518
+ error: (0, import_utils34.safeStringify)(error)
33211
33519
  });
33212
33520
  return null;
33213
33521
  }
@@ -33243,7 +33551,7 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
33243
33551
  attributes: {
33244
33552
  "memory.operation": "read",
33245
33553
  "memory.semantic": isSemanticSearch,
33246
- input: (0, import_utils33.safeStringify)(spanInput),
33554
+ input: (0, import_utils34.safeStringify)(spanInput),
33247
33555
  ...isSemanticSearch && {
33248
33556
  "memory.semantic.limit": semanticLimit,
33249
33557
  "memory.semantic.threshold": semanticThreshold,
@@ -33465,10 +33773,10 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
33465
33773
  rootSpan.setAttribute("prompt.version", metadata.version);
33466
33774
  }
33467
33775
  if (metadata.labels && metadata.labels.length > 0) {
33468
- rootSpan.setAttribute("prompt.labels", (0, import_utils33.safeStringify)(metadata.labels));
33776
+ rootSpan.setAttribute("prompt.labels", (0, import_utils34.safeStringify)(metadata.labels));
33469
33777
  }
33470
33778
  if (metadata.tags && metadata.tags.length > 0) {
33471
- rootSpan.setAttribute("prompt.tags", (0, import_utils33.safeStringify)(metadata.tags));
33779
+ rootSpan.setAttribute("prompt.tags", (0, import_utils34.safeStringify)(metadata.tags));
33472
33780
  }
33473
33781
  if (metadata.source) {
33474
33782
  rootSpan.setAttribute("prompt.source", metadata.source);
@@ -33480,7 +33788,7 @@ Metadata: ${(0, import_utils33.safeStringify)(metadata)}`;
33480
33788
  rootSpan.setAttribute("prompt.outdated", metadata.outdated);
33481
33789
  }
33482
33790
  if (metadata.config) {
33483
- rootSpan.setAttribute("prompt.config", (0, import_utils33.safeStringify)(metadata.config));
33791
+ rootSpan.setAttribute("prompt.config", (0, import_utils34.safeStringify)(metadata.config));
33484
33792
  }
33485
33793
  }
33486
33794
  }
@@ -33681,7 +33989,7 @@ ${retrieverContext}`;
33681
33989
  label: this.retriever.tool.name || "Retriever",
33682
33990
  attributes: {
33683
33991
  "retriever.name": this.retriever.tool.name || "Retriever",
33684
- input: typeof input === "string" ? input : (0, import_utils33.safeStringify)(input),
33992
+ input: typeof input === "string" ? input : (0, import_utils34.safeStringify)(input),
33685
33993
  ...this.getRetrieverObservabilityAttributes()
33686
33994
  }
33687
33995
  });
@@ -33928,7 +34236,7 @@ ${retrieverContext}`;
33928
34236
  nextModelIndex: nextCandidate ? index + 1 : void 0
33929
34237
  });
33930
34238
  logger.warn(`[Agent:${this.name}] - Failed to resolve model, falling back`, {
33931
- error: (0, import_utils33.safeStringify)(error),
34239
+ error: (0, import_utils34.safeStringify)(error),
33932
34240
  modelIndex: index,
33933
34241
  operation
33934
34242
  });
@@ -33973,7 +34281,7 @@ ${retrieverContext}`;
33973
34281
  retryEligible,
33974
34282
  isRetryable: error?.isRetryable,
33975
34283
  statusCode: error?.statusCode,
33976
- error: (0, import_utils33.safeStringify)(error)
34284
+ error: (0, import_utils34.safeStringify)(error)
33977
34285
  });
33978
34286
  await hooks.onRetry?.({
33979
34287
  agent: this,
@@ -34005,7 +34313,7 @@ ${retrieverContext}`;
34005
34313
  fallbackEligible,
34006
34314
  retryEligible,
34007
34315
  isLastModel,
34008
- error: (0, import_utils33.safeStringify)(error)
34316
+ error: (0, import_utils34.safeStringify)(error)
34009
34317
  });
34010
34318
  throw error;
34011
34319
  }
@@ -34025,7 +34333,7 @@ ${retrieverContext}`;
34025
34333
  nextModelIndex: nextCandidate ? index + 1 : void 0
34026
34334
  });
34027
34335
  logger.warn(`[Agent:${this.name}] - Model failed, trying fallback`, {
34028
- error: (0, import_utils33.safeStringify)(error),
34336
+ error: (0, import_utils34.safeStringify)(error),
34029
34337
  modelName,
34030
34338
  modelIndex: index,
34031
34339
  operation,
@@ -34245,9 +34553,9 @@ ${retrieverContext}`;
34245
34553
  "tool.name": tool2.name,
34246
34554
  "tool.call.id": toolCallId,
34247
34555
  "tool.description": tool2.description,
34248
- ...toolTags && toolTags.length > 0 ? { "tool.tags": (0, import_utils33.safeStringify)(toolTags) } : {},
34249
- "tool.parameters": (0, import_utils33.safeStringify)(tool2.parameters),
34250
- input: args ? (0, import_utils33.safeStringify)(args) : void 0
34556
+ ...toolTags && toolTags.length > 0 ? { "tool.tags": (0, import_utils34.safeStringify)(toolTags) } : {},
34557
+ "tool.parameters": (0, import_utils34.safeStringify)(tool2.parameters),
34558
+ input: args ? (0, import_utils34.safeStringify)(args) : void 0
34251
34559
  },
34252
34560
  kind: import_api16.SpanKind.CLIENT
34253
34561
  });
@@ -34688,7 +34996,7 @@ ${retrieverContext}`;
34688
34996
  output: selections,
34689
34997
  attributes: {
34690
34998
  "tool.search.selection.count": selections.length,
34691
- "tool.search.selection.names": (0, import_utils33.safeStringify)(
34999
+ "tool.search.selection.names": (0, import_utils34.safeStringify)(
34692
35000
  selections.map((selection) => selection.name)
34693
35001
  )
34694
35002
  }
@@ -34696,7 +35004,7 @@ ${retrieverContext}`;
34696
35004
  oc.logger.debug("Tool search selections computed", {
34697
35005
  tool: TOOL_ROUTING_SEARCH_TOOL_NAME,
34698
35006
  query,
34699
- selections: (0, import_utils33.safeStringify)(selections)
35007
+ selections: (0, import_utils34.safeStringify)(selections)
34700
35008
  });
34701
35009
  } catch (error) {
34702
35010
  oc.traceContext.endChildSpan(selectionSpan, "error", {
@@ -34842,7 +35150,7 @@ ${retrieverContext}`;
34842
35150
  const tools = {
34843
35151
  [tool2.name]: tool2
34844
35152
  };
34845
- const argsInstruction = `Use these tool arguments exactly: ${(0, import_utils33.safeStringify)(args)}`;
35153
+ const argsInstruction = `Use these tool arguments exactly: ${(0, import_utils34.safeStringify)(args)}`;
34846
35154
  const result = await this.runInternalGenerateText({
34847
35155
  oc,
34848
35156
  messages: [
@@ -35187,7 +35495,7 @@ ${retrieverContext}`;
35187
35495
  oc.conversationSteps?.push({
35188
35496
  id: toolCall.toolCallId || randomUUID(),
35189
35497
  type: "tool_call",
35190
- content: (0, import_utils33.safeStringify)(toolCall.input ?? {}),
35498
+ content: (0, import_utils34.safeStringify)(toolCall.input ?? {}),
35191
35499
  role: "assistant",
35192
35500
  name: toolCall.toolName,
35193
35501
  arguments: toolCall.input || {},
@@ -35219,7 +35527,7 @@ ${retrieverContext}`;
35219
35527
  oc.conversationSteps?.push({
35220
35528
  id: toolResult.toolCallId || randomUUID(),
35221
35529
  type: "tool_result",
35222
- content: (0, import_utils33.safeStringify)(toolResult.output),
35530
+ content: (0, import_utils34.safeStringify)(toolResult.output),
35223
35531
  role: "assistant",
35224
35532
  name: toolResult.toolName,
35225
35533
  result: toolResult.output,
@@ -35410,7 +35718,18 @@ ${retrieverContext}`;
35410
35718
  if (!oc.isActive && oc.cancellationError) {
35411
35719
  throw oc.cancellationError;
35412
35720
  }
35413
- const voltagentError = createVoltAgentError(error);
35721
+ const voltagentError = isVoltAgentError(error) ? error : createVoltAgentError(error);
35722
+ const errorDetails = extractGenerationErrorDetails(voltagentError);
35723
+ if (errorDetails.usage || errorDetails.providerMetadata !== void 0) {
35724
+ this.recordRootSpanUsageAndProviderCost(
35725
+ oc.traceContext,
35726
+ errorDetails.usage,
35727
+ errorDetails.providerMetadata
35728
+ );
35729
+ }
35730
+ if (errorDetails.finishReason) {
35731
+ oc.traceContext.setFinishReason(errorDetails.finishReason);
35732
+ }
35414
35733
  oc.traceContext.end("error", error);
35415
35734
  const hooks = this.getMergedHooks(options);
35416
35735
  await hooks.onEnd?.({
@@ -36090,7 +36409,7 @@ ${retrieverContext}`;
36090
36409
  };
36091
36410
 
36092
36411
  // src/planagent/plan-agent.ts
36093
- var import_utils38 = require("@voltagent/internal/utils");
36412
+ var import_utils39 = require("@voltagent/internal/utils");
36094
36413
  var import_zod10 = require("zod");
36095
36414
 
36096
36415
  // src/planagent/context-keys.ts
@@ -36102,7 +36421,7 @@ var import_internal11 = require("@voltagent/internal");
36102
36421
  var import_zod8 = require("zod");
36103
36422
 
36104
36423
  // src/planagent/state.ts
36105
- var import_utils35 = require("@voltagent/internal/utils");
36424
+ var import_utils36 = require("@voltagent/internal/utils");
36106
36425
  var PLANAGENT_METADATA_KEY = "planagent";
36107
36426
  var STATE_CACHE_KEY = Symbol("planagentState");
36108
36427
  var fallbackState = /* @__PURE__ */ new Map();
@@ -36114,13 +36433,13 @@ function readStateFromMetadata(metadata) {
36114
36433
  if (!metadata) return null;
36115
36434
  const entry = metadata[PLANAGENT_METADATA_KEY];
36116
36435
  if (!entry || typeof entry !== "object") return null;
36117
- return (0, import_utils35.deepClone)(entry);
36436
+ return (0, import_utils36.deepClone)(entry);
36118
36437
  }
36119
36438
  __name(readStateFromMetadata, "readStateFromMetadata");
36120
36439
  async function loadPlanAgentState(agent, context8) {
36121
36440
  const cached = context8.systemContext.get(STATE_CACHE_KEY);
36122
36441
  if (cached) {
36123
- return (0, import_utils35.deepClone)(cached);
36442
+ return (0, import_utils36.deepClone)(cached);
36124
36443
  }
36125
36444
  let state = null;
36126
36445
  const memory = agent.getMemory();
@@ -36130,23 +36449,23 @@ async function loadPlanAgentState(agent, context8) {
36130
36449
  state = readStateFromMetadata(conversation?.metadata);
36131
36450
  } catch (error) {
36132
36451
  context8.logger.debug("[PlanAgent] Failed to load state from memory", {
36133
- error: (0, import_utils35.safeStringify)(error)
36452
+ error: (0, import_utils36.safeStringify)(error)
36134
36453
  });
36135
36454
  }
36136
36455
  }
36137
36456
  if (!state) {
36138
- state = (0, import_utils35.deepClone)(fallbackState.get(getConversationKey(context8)) || {});
36457
+ state = (0, import_utils36.deepClone)(fallbackState.get(getConversationKey(context8)) || {});
36139
36458
  }
36140
36459
  context8.systemContext.set(STATE_CACHE_KEY, state);
36141
- return (0, import_utils35.deepClone)(state);
36460
+ return (0, import_utils36.deepClone)(state);
36142
36461
  }
36143
36462
  __name(loadPlanAgentState, "loadPlanAgentState");
36144
36463
  async function updatePlanAgentState(agent, context8, updater) {
36145
36464
  const current = await loadPlanAgentState(agent, context8);
36146
- const nextState = updater((0, import_utils35.deepClone)(current));
36465
+ const nextState = updater((0, import_utils36.deepClone)(current));
36147
36466
  const normalized = nextState || {};
36148
36467
  context8.systemContext.set(STATE_CACHE_KEY, normalized);
36149
- fallbackState.set(getConversationKey(context8), (0, import_utils35.deepClone)(normalized));
36468
+ fallbackState.set(getConversationKey(context8), (0, import_utils36.deepClone)(normalized));
36150
36469
  const memory = agent.getMemory();
36151
36470
  if (memory && context8.conversationId) {
36152
36471
  try {
@@ -36154,17 +36473,17 @@ async function updatePlanAgentState(agent, context8, updater) {
36154
36473
  if (conversation) {
36155
36474
  const metadata = {
36156
36475
  ...conversation.metadata,
36157
- [PLANAGENT_METADATA_KEY]: (0, import_utils35.deepClone)(normalized)
36476
+ [PLANAGENT_METADATA_KEY]: (0, import_utils36.deepClone)(normalized)
36158
36477
  };
36159
36478
  await memory.updateConversation(context8.conversationId, { metadata });
36160
36479
  }
36161
36480
  } catch (error) {
36162
36481
  context8.logger.debug("[PlanAgent] Failed to persist state", {
36163
- error: (0, import_utils35.safeStringify)(error)
36482
+ error: (0, import_utils36.safeStringify)(error)
36164
36483
  });
36165
36484
  }
36166
36485
  }
36167
- return (0, import_utils35.deepClone)(normalized);
36486
+ return (0, import_utils36.deepClone)(normalized);
36168
36487
  }
36169
36488
  __name(updatePlanAgentState, "updatePlanAgentState");
36170
36489
 
@@ -36574,7 +36893,7 @@ function createToolResultEvictor(options) {
36574
36893
  __name(createToolResultEvictor, "createToolResultEvictor");
36575
36894
 
36576
36895
  // src/planagent/planning/index.ts
36577
- var import_utils37 = require("@voltagent/internal/utils");
36896
+ var import_utils38 = require("@voltagent/internal/utils");
36578
36897
  var import_zod9 = require("zod");
36579
36898
 
36580
36899
  // src/planagent/planning/backend.ts
@@ -36718,7 +37037,7 @@ function createPlanningToolkit(agent, options = {}) {
36718
37037
  toolSpan.setAttribute("planagent.todos.done", doneCount);
36719
37038
  toolSpan.setAttribute("planagent.todos.truncated", snapshot.truncated);
36720
37039
  toolSpan.setAttribute("planagent.todos.blocked_done", blockedCount);
36721
- toolSpan.setAttribute("planagent.todos", (0, import_utils37.safeStringify)(snapshot.todos));
37040
+ toolSpan.setAttribute("planagent.todos", (0, import_utils38.safeStringify)(snapshot.todos));
36722
37041
  }
36723
37042
  return {
36724
37043
  todos: guardedTodos,
@@ -37294,7 +37613,7 @@ function createTaskToolkit(options) {
37294
37613
  parentSpan: toolSpan
37295
37614
  });
37296
37615
  if (toolSpan) {
37297
- const responsePreview = typeof result.result === "string" ? truncateText3(result.result, 500) : truncateText3((0, import_utils38.safeStringify)(result.result), 500);
37616
+ const responsePreview = typeof result.result === "string" ? truncateText3(result.result, 500) : truncateText3((0, import_utils39.safeStringify)(result.result), 500);
37298
37617
  toolSpan.setAttribute("planagent.task.status", result.bailed ? "bailed" : "completed");
37299
37618
  toolSpan.setAttribute("planagent.task.response_preview", responsePreview);
37300
37619
  }
@@ -41027,7 +41346,7 @@ var import_node_crypto = __toESM(require("crypto"));
41027
41346
  var import_node_fs3 = __toESM(require("fs"));
41028
41347
  var import_node_os = __toESM(require("os"));
41029
41348
  var import_node_path3 = __toESM(require("path"));
41030
- var import_utils39 = require("@voltagent/internal/utils");
41349
+ var import_utils40 = require("@voltagent/internal/utils");
41031
41350
  var getEnvPaths = /* @__PURE__ */ __name((name) => {
41032
41351
  const homedir = import_node_os.default.homedir();
41033
41352
  const tmpdir = import_node_os.default.tmpdir();
@@ -41097,7 +41416,7 @@ var writeUpdateCache = /* @__PURE__ */ __name(async (projectPath, cache) => {
41097
41416
  try {
41098
41417
  ensureCacheDir();
41099
41418
  const cacheFilePath = getCacheFilePath(projectPath);
41100
- import_node_fs3.default.writeFileSync(cacheFilePath, (0, import_utils39.safeStringify)(cache, { indentation: 2 }), "utf8");
41419
+ import_node_fs3.default.writeFileSync(cacheFilePath, (0, import_utils40.safeStringify)(cache, { indentation: 2 }), "utf8");
41101
41420
  } catch (error) {
41102
41421
  const logger = new LoggerProxy({ component: "update-cache" });
41103
41422
  logger.error("Error writing update cache", { error });
@@ -42152,7 +42471,7 @@ var VoltAgent = class {
42152
42471
  };
42153
42472
 
42154
42473
  // src/index.ts
42155
- var import_utils40 = require("@voltagent/internal/utils");
42474
+ var import_utils41 = require("@voltagent/internal/utils");
42156
42475
  var import_ai9 = require("ai");
42157
42476
  // Annotate the CommonJS export names for ESM import in node:
42158
42477
  0 && (module.exports = {