@voltagent/core 0.1.65 → 0.1.67

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.d.ts CHANGED
@@ -130,7 +130,7 @@ declare class ToolManager {
130
130
  /**
131
131
  * Prepare tools for text generation (includes tools from toolkits).
132
132
  */
133
- prepareToolsForGeneration(dynamicTools?: BaseTool[]): BaseTool[];
133
+ prepareToolsForGeneration(dynamicTools?: (BaseTool | Toolkit)[]): BaseTool[];
134
134
  /**
135
135
  * Get agent's tools (including those in toolkits) for API exposure.
136
136
  */
@@ -4600,6 +4600,10 @@ declare class Agent<TProvider extends {
4600
4600
  * Add step to history immediately and to conversation steps
4601
4601
  */
4602
4602
  private addStepToHistory;
4603
+ /**
4604
+ * Handle tool execution errors by creating appropriate events and steps
4605
+ */
4606
+ private handleToolError;
4603
4607
  /**
4604
4608
  * Update history entry
4605
4609
  */
package/dist/index.js CHANGED
@@ -5060,22 +5060,27 @@ var LibSQLStorage = class {
5060
5060
  if (conditions.length > 0) {
5061
5061
  sql += ` WHERE ${conditions.join(" AND ")}`;
5062
5062
  }
5063
- sql += " ORDER BY m.created_at ASC";
5064
5063
  if (limit && limit > 0) {
5065
- sql += " LIMIT ?";
5064
+ sql += " ORDER BY m.created_at DESC LIMIT ?";
5066
5065
  args.push(limit);
5066
+ } else {
5067
+ sql += " ORDER BY m.created_at ASC";
5067
5068
  }
5068
5069
  const result = await this.client.execute({
5069
5070
  sql,
5070
5071
  args
5071
5072
  });
5072
- return result.rows.map((row) => ({
5073
+ const messages = result.rows.map((row) => ({
5073
5074
  id: row.message_id,
5074
5075
  role: row.role,
5075
5076
  content: row.content,
5076
5077
  type: row.type,
5077
5078
  createdAt: row.created_at
5078
5079
  }));
5080
+ if (limit && limit > 0) {
5081
+ return messages.reverse();
5082
+ }
5083
+ return messages;
5079
5084
  } catch (error) {
5080
5085
  this.debug("Error getting messages:", error);
5081
5086
  throw new Error("Failed to get messages from LibSQL database");
@@ -7978,7 +7983,7 @@ var InMemoryStorage = class {
7978
7983
  );
7979
7984
  }
7980
7985
  filteredMessages.sort((a, b) => {
7981
- return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
7986
+ return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
7982
7987
  });
7983
7988
  if (limit && limit > 0 && filteredMessages.length > limit) {
7984
7989
  filteredMessages = filteredMessages.slice(-limit);
@@ -9459,16 +9464,10 @@ var ToolManager = class {
9459
9464
  prepareToolsForGeneration(dynamicTools) {
9460
9465
  let toolsToUse = this.getTools();
9461
9466
  if (dynamicTools?.length) {
9462
- const validDynamicTools = dynamicTools.filter(
9463
- (dt) => dt?.name && dt?.parameters && typeof dt?.execute === "function"
9464
- // Apply optional chaining
9465
- );
9466
- if (validDynamicTools.length !== dynamicTools.length) {
9467
- this.logger.warn(
9468
- "[ToolManager] Some dynamic tools provided to prepareToolsForGeneration were invalid and ignored."
9469
- );
9470
- }
9471
- toolsToUse = [...toolsToUse, ...validDynamicTools];
9467
+ const tempManager = new ToolManager([], this.logger);
9468
+ tempManager.addItems(dynamicTools);
9469
+ const dynamicToolsList = tempManager.getTools();
9470
+ toolsToUse = [...toolsToUse, ...dynamicToolsList];
9472
9471
  }
9473
9472
  return toolsToUse;
9474
9473
  }
@@ -12160,6 +12159,25 @@ ${retrieverContext}`;
12160
12159
  const baseTools = this.toolManager.prepareToolsForGeneration(
12161
12160
  allTools.length > 0 ? allTools : void 0
12162
12161
  );
12162
+ if (this.dynamicTools && resolvedTools.length > 0) {
12163
+ const allToolsForUpdate = baseTools.map((tool2) => ({
12164
+ name: tool2.name,
12165
+ description: tool2.description,
12166
+ parameters: tool2.parameters ? zodSchemaToJsonUI(tool2.parameters) : void 0
12167
+ }));
12168
+ if (historyEntryId && this.historyManager) {
12169
+ const updatedAgentSnapshot = this.getFullState();
12170
+ this.historyManager.updateEntry(historyEntryId, {
12171
+ metadata: {
12172
+ agentSnapshot: {
12173
+ ...updatedAgentSnapshot,
12174
+ tools: allToolsForUpdate
12175
+ // Include resolved tools in the snapshot
12176
+ }
12177
+ }
12178
+ });
12179
+ }
12180
+ }
12163
12181
  if (!operationContext) {
12164
12182
  this.logger.warn(
12165
12183
  "Missing operationContext in prepareTextOptions. Tool execution context might be incomplete.",
@@ -12415,6 +12433,107 @@ ${retrieverContext}`;
12415
12433
  };
12416
12434
  context.conversationSteps.push(finalStep);
12417
12435
  }
12436
+ /**
12437
+ * Handle tool execution errors by creating appropriate events and steps
12438
+ */
12439
+ async handleToolError(error, operationContext, options) {
12440
+ if (!error.toolError) {
12441
+ return;
12442
+ }
12443
+ const { userId, conversationId, internalOptions } = options;
12444
+ const { toolCallId, toolName } = error.toolError;
12445
+ try {
12446
+ const toolStartInfo = operationContext.userContext.get(`tool_${toolCallId}`) || { eventId: void 0, startTime: (/* @__PURE__ */ new Date()).toISOString() };
12447
+ const toolErrorEvent = {
12448
+ id: crypto.randomUUID(),
12449
+ name: "tool:error",
12450
+ type: "tool",
12451
+ startTime: toolStartInfo.startTime,
12452
+ endTime: (/* @__PURE__ */ new Date()).toISOString(),
12453
+ status: "error",
12454
+ level: "ERROR",
12455
+ input: null,
12456
+ output: null,
12457
+ statusMessage: {
12458
+ message: error.message,
12459
+ code: error.code,
12460
+ ...error.toolError && { toolError: error.toolError }
12461
+ },
12462
+ metadata: {
12463
+ displayName: toolName,
12464
+ id: toolName,
12465
+ agentId: this.id
12466
+ },
12467
+ traceId: operationContext.historyEntry.id,
12468
+ parentEventId: toolStartInfo.eventId
12469
+ };
12470
+ this.publishTimelineEvent(operationContext, toolErrorEvent);
12471
+ const toolErrorStep = {
12472
+ id: toolCallId,
12473
+ type: "tool_result",
12474
+ name: toolName,
12475
+ result: {
12476
+ error
12477
+ },
12478
+ content: JSON.stringify([
12479
+ {
12480
+ type: "tool-result",
12481
+ toolCallId,
12482
+ toolName,
12483
+ result: {
12484
+ error: {
12485
+ message: error.message,
12486
+ code: error.code
12487
+ }
12488
+ }
12489
+ }
12490
+ ]),
12491
+ role: "assistant"
12492
+ };
12493
+ this.addStepToHistory(toolErrorStep, operationContext);
12494
+ if (userId) {
12495
+ const onStepFinish = this.memoryManager.createStepFinishHandler(
12496
+ operationContext,
12497
+ userId,
12498
+ conversationId
12499
+ );
12500
+ await onStepFinish(toolErrorStep);
12501
+ }
12502
+ const tool2 = this.toolManager.getToolByName(toolName);
12503
+ if (tool2 && internalOptions) {
12504
+ await this.getMergedHooks(internalOptions).onToolEnd?.({
12505
+ agent: this,
12506
+ tool: tool2,
12507
+ output: void 0,
12508
+ error,
12509
+ context: operationContext
12510
+ });
12511
+ }
12512
+ const methodLogger = operationContext.logger || this.logger;
12513
+ methodLogger.error(
12514
+ buildAgentLogMessage(this.name, "toolCall" /* TOOL_CALL */, `Tool ${toolName} failed`),
12515
+ {
12516
+ event: LogEvents.TOOL_EXECUTION_FAILED,
12517
+ toolName,
12518
+ toolCallId,
12519
+ error: {
12520
+ message: error.message,
12521
+ code: error.code
12522
+ }
12523
+ }
12524
+ );
12525
+ } catch (updateError) {
12526
+ const methodLogger = operationContext.logger || this.logger;
12527
+ methodLogger.error(
12528
+ `Failed to update tool event to error status for ${toolName} (${toolCallId})`,
12529
+ {
12530
+ toolName,
12531
+ toolCallId,
12532
+ error: updateError
12533
+ }
12534
+ );
12535
+ }
12536
+ }
12418
12537
  /**
12419
12538
  * Update history entry
12420
12539
  */
@@ -13022,6 +13141,13 @@ ${retrieverContext}`;
13022
13141
  return extendedResponse;
13023
13142
  } catch (error) {
13024
13143
  const voltagentError = error;
13144
+ if (voltagentError.toolError) {
13145
+ await this.handleToolError(voltagentError, operationContext, {
13146
+ userId,
13147
+ conversationId: finalConversationId,
13148
+ internalOptions
13149
+ });
13150
+ }
13025
13151
  const agentErrorStartInfo = {
13026
13152
  startTime: operationContext.userContext.get("agent_start_time") || (/* @__PURE__ */ new Date()).toISOString(),
13027
13153
  eventId: operationContext.userContext.get("agent_start_event_id")
@@ -13527,53 +13653,11 @@ ${retrieverContext}`;
13527
13653
  },
13528
13654
  onError: async (error) => {
13529
13655
  if (error.toolError) {
13530
- const { toolCallId, toolName } = error.toolError;
13531
- try {
13532
- const toolStartInfo = operationContext.userContext.get(`tool_${toolCallId}`) || { eventId: void 0, startTime: (/* @__PURE__ */ new Date()).toISOString() };
13533
- const toolErrorEvent = {
13534
- id: crypto.randomUUID(),
13535
- name: "tool:error",
13536
- type: "tool",
13537
- startTime: toolStartInfo.startTime,
13538
- endTime: (/* @__PURE__ */ new Date()).toISOString(),
13539
- status: "error",
13540
- level: "ERROR",
13541
- input: null,
13542
- output: null,
13543
- statusMessage: {
13544
- message: error.message,
13545
- code: error.code,
13546
- ...error.toolError && { toolError: error.toolError }
13547
- },
13548
- metadata: {
13549
- displayName: toolName,
13550
- id: toolName,
13551
- agentId: this.id
13552
- },
13553
- traceId: operationContext.historyEntry.id,
13554
- parentEventId: toolStartInfo.eventId
13555
- };
13556
- this.publishTimelineEvent(operationContext, toolErrorEvent);
13557
- } catch (updateError) {
13558
- methodLogger.error(
13559
- `Failed to update tool event to error status for ${toolName} (${toolCallId})`,
13560
- {
13561
- toolName,
13562
- toolCallId,
13563
- error: updateError
13564
- }
13565
- );
13566
- }
13567
- const tool2 = this.toolManager.getToolByName(toolName);
13568
- if (tool2) {
13569
- await this.getMergedHooks(internalOptions).onToolEnd?.({
13570
- agent: this,
13571
- tool: tool2,
13572
- output: void 0,
13573
- error,
13574
- context: operationContext
13575
- });
13576
- }
13656
+ await this.handleToolError(error, operationContext, {
13657
+ userId,
13658
+ conversationId: finalConversationId,
13659
+ internalOptions
13660
+ });
13577
13661
  }
13578
13662
  const agentErrorStartInfo = {
13579
13663
  startTime: operationContext.userContext.get("agent_start_time") || (/* @__PURE__ */ new Date()).toISOString(),
@@ -14183,19 +14267,6 @@ ${retrieverContext}`;
14183
14267
  }
14184
14268
  },
14185
14269
  onError: async (error) => {
14186
- if (error.toolError) {
14187
- const { toolName } = error.toolError;
14188
- const tool2 = this.toolManager.getToolByName(toolName);
14189
- if (tool2) {
14190
- await this.getMergedHooks(internalOptions).onToolEnd?.({
14191
- agent: this,
14192
- tool: tool2,
14193
- output: void 0,
14194
- error,
14195
- context: operationContext
14196
- });
14197
- }
14198
- }
14199
14270
  const agentErrorStartInfo = {
14200
14271
  startTime: operationContext.userContext.get("agent_start_time") || (/* @__PURE__ */ new Date()).toISOString(),
14201
14272
  eventId: operationContext.userContext.get("agent_start_event_id")