From 8e48355d71f9e7c99c459f41c812f11fb4aa858f Mon Sep 17 00:00:00 2001 From: Omer Aplak Date: Fri, 13 Feb 2026 10:32:07 -0800 Subject: [PATCH] fix(core): add step-level conversation persistence checkpoints --- .changeset/four-drinks-rush.md | 13 + packages/core/src/agent/agent.ts | 368 +++++++++++++----- .../core/src/agent/step-persistence.spec.ts | 130 +++++++ packages/core/src/agent/types.ts | 22 ++ packages/core/src/index.ts | 2 + packages/core/src/types.ts | 5 + packages/core/src/voltagent.spec.ts | 53 +++ packages/core/src/voltagent.ts | 11 + website/docs/agents/memory/overview.md | 3 + website/docs/agents/overview.md | 29 ++ website/docs/agents/voltagent-instance.md | 24 +- website/docs/api/endpoints/agents.md | 8 + website/docs/ui/ai-sdk-integration.md | 29 +- 13 files changed, 593 insertions(+), 104 deletions(-) create mode 100644 .changeset/four-drinks-rush.md create mode 100644 packages/core/src/agent/step-persistence.spec.ts diff --git a/.changeset/four-drinks-rush.md b/.changeset/four-drinks-rush.md new file mode 100644 index 000000000..bfc775def --- /dev/null +++ b/.changeset/four-drinks-rush.md @@ -0,0 +1,13 @@ +--- +"@voltagent/core": patch +--- + +fix: persist conversation progress incrementally during multi-step runs + +- Added step-level conversation persistence checkpoints so completed steps are no longer only saved at turn finish. +- Tool completion steps (`tool-result` / `tool-error`) now trigger immediate persistence flushes in step mode. +- Added configurable agent persistence options: + - `conversationPersistence.mode` (`"step"` or `"finish"`) + - `conversationPersistence.debounceMs` + - `conversationPersistence.flushOnToolResult` +- Added global VoltAgent default `agentConversationPersistence` and wiring to registered agents. diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index c255a2af5..9b8e25e40 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -167,6 +167,8 @@ import { SubAgentManager } from "./subagent"; import type { SubAgentConfig } from "./subagent/types"; import type { VoltAgentTextStreamPart } from "./subagent/types"; import type { + AgentConversationPersistenceMode, + AgentConversationPersistenceOptions, AgentEvalConfig, AgentEvalOperationType, AgentFeedbackHandle, @@ -194,6 +196,7 @@ import type { const BUFFER_CONTEXT_KEY = Symbol("conversationBuffer"); const QUEUE_CONTEXT_KEY = Symbol("memoryPersistQueue"); +const CONVERSATION_PERSISTENCE_OPTIONS_KEY = Symbol("conversationPersistenceOptions"); const STEP_PERSIST_COUNT_KEY = Symbol("persistedStepCount"); const ABORT_LISTENER_ATTACHED_KEY = Symbol("abortListenerAttached"); const MIDDLEWARE_RETRY_FEEDBACK_KEY = Symbol("middlewareRetryFeedback"); @@ -209,6 +212,18 @@ const DEFAULT_CONVERSATION_TITLE_MAX_CHARS = 80; const CONVERSATION_TITLE_INPUT_MAX_CHARS = 2000; const DEFAULT_TOOL_SEARCH_TOP_K = 1; +type ResolvedConversationPersistenceOptions = { + mode: AgentConversationPersistenceMode; + debounceMs: number; + flushOnToolResult: boolean; +}; + +const DEFAULT_CONVERSATION_PERSISTENCE_OPTIONS: ResolvedConversationPersistenceOptions = { + mode: "step", + debounceMs: 200, + flushOnToolResult: true, +}; + type ResponseMessage = AssistantModelMessage | ToolModelMessage; const isRecord = (value: unknown): value is Record => @@ -684,6 +699,7 @@ export interface BaseGenerationOptions= 0 + ? options.debounceMs + : DEFAULT_CONVERSATION_PERSISTENCE_OPTIONS.debounceMs; + + return { + mode, + debounceMs, + flushOnToolResult: + options?.flushOnToolResult ?? DEFAULT_CONVERSATION_PERSISTENCE_OPTIONS.flushOnToolResult, + }; + } + + private resolveConversationPersistenceOptions( + options?: BaseGenerationOptions, + ): ResolvedConversationPersistenceOptions { + if (!options?.conversationPersistence) { + return { ...this.conversationPersistence }; + } + + return this.normalizeConversationPersistenceOptions({ + mode: options.conversationPersistence.mode ?? this.conversationPersistence.mode, + debounceMs: + options.conversationPersistence.debounceMs ?? this.conversationPersistence.debounceMs, + flushOnToolResult: + options.conversationPersistence.flushOnToolResult ?? + this.conversationPersistence.flushOnToolResult, + }); + } + + private getConversationPersistenceOptionsForContext( + oc: OperationContext, + ): ResolvedConversationPersistenceOptions { + const fromContext = oc.systemContext.get(CONVERSATION_PERSISTENCE_OPTIONS_KEY) as + | ResolvedConversationPersistenceOptions + | undefined; + + if (fromContext) { + return fromContext; + } + + const resolved = { ...this.conversationPersistence }; + oc.systemContext.set(CONVERSATION_PERSISTENCE_OPTIONS_KEY, resolved); + return resolved; + } + /** * Create only the OperationContext (sync) * Transitional helper to gradually adopt OperationContext across methods @@ -3428,11 +3506,16 @@ export class Agent { }); } + const conversationPersistence = this.resolveConversationPersistenceOptions(options); const systemContext = new Map(); systemContext.set(BUFFER_CONTEXT_KEY, new ConversationBuffer(undefined, logger)); + systemContext.set(CONVERSATION_PERSISTENCE_OPTIONS_KEY, conversationPersistence); systemContext.set( QUEUE_CONTEXT_KEY, - new MemoryPersistQueue(this.memoryManager, { debounceMs: 200, logger }), + new MemoryPersistQueue(this.memoryManager, { + debounceMs: conversationPersistence.debounceMs, + logger, + }), ); systemContext.set(AGENT_METADATA_CONTEXT_KEY, { agentId: this.id, @@ -3463,10 +3546,14 @@ export class Agent { } private resetOperationAttemptState(oc: OperationContext): void { + const conversationPersistence = this.getConversationPersistenceOptionsForContext(oc); oc.systemContext.set(BUFFER_CONTEXT_KEY, new ConversationBuffer(undefined, oc.logger)); oc.systemContext.set( QUEUE_CONTEXT_KEY, - new MemoryPersistQueue(this.memoryManager, { debounceMs: 200, logger: oc.logger }), + new MemoryPersistQueue(this.memoryManager, { + debounceMs: conversationPersistence.debounceMs, + logger: oc.logger, + }), ); oc.systemContext.delete(STEP_PERSIST_COUNT_KEY); oc.systemContext.delete("conversationSteps"); @@ -3488,7 +3575,11 @@ export class Agent { private getMemoryPersistQueue(oc: OperationContext): MemoryPersistQueue { let queue = oc.systemContext.get(QUEUE_CONTEXT_KEY) as MemoryPersistQueue | undefined; if (!queue) { - queue = new MemoryPersistQueue(this.memoryManager, { logger: oc.logger }); + const conversationPersistence = this.getConversationPersistenceOptionsForContext(oc); + queue = new MemoryPersistQueue(this.memoryManager, { + debounceMs: conversationPersistence.debounceMs, + logger: oc.logger, + }); oc.systemContext.set(QUEUE_CONTEXT_KEY, queue); } return queue; @@ -6252,103 +6343,51 @@ export class Agent { */ private createStepHandler(oc: OperationContext, options?: BaseGenerationOptions) { const buffer = this.getConversationBuffer(oc); + const persistQueue = this.getMemoryPersistQueue(oc); + const conversationPersistence = this.getConversationPersistenceOptionsForContext(oc); return async (event: StepResult) => { - // Instead of saving immediately, collect steps in context for batch processing in onFinish - if (event.content && Array.isArray(event.content)) { - // Store the step content in context for later processing - if (!oc.systemContext.has("conversationSteps")) { - oc.systemContext.set("conversationSteps", []); - } - const conversationSteps = oc.systemContext.get( - "conversationSteps", - ) as StepResult[]; - conversationSteps.push(event); - - // Log each content part - for (const part of event.content) { - if (part.type === "text") { - oc.logger.debug("Step: Text generated", { - event: LogEvents.AGENT_STEP_TEXT, - textPreview: part.text.substring(0, 100), - length: part.text.length, - }); - } else if (part.type === "reasoning") { - oc.logger.debug("Step: Reasoning generated", { - event: LogEvents.AGENT_STEP_TEXT, - textPreview: part.text.substring(0, 100), - length: part.text.length, - }); - } else if (part.type === "tool-call") { - oc.logger.debug(`Step: Calling tool '${part.toolName}'`, { - event: LogEvents.AGENT_STEP_TOOL_CALL, - toolName: part.toolName, - toolCallId: part.toolCallId, - arguments: part.input, - }); - - oc.logger.debug( - buildAgentLogMessage(this.name, ActionType.TOOL_CALL, `Executing ${part.toolName}`), - { - event: LogEvents.TOOL_EXECUTION_STARTED, - toolName: part.toolName, - toolCallId: part.toolCallId, - args: part.input, - }, - ); - } else if (part.type === "tool-result") { - oc.logger.debug(`Step: Tool '${part.toolName}' completed`, { - event: LogEvents.AGENT_STEP_TOOL_RESULT, - toolName: part.toolName, - toolCallId: part.toolCallId, - result: part.output, - hasError: Boolean( - part.output && typeof part.output === "object" && "error" in part.output, - ), - }); - - // Check if this tool result indicates a subagent bail (early termination) - const toolResult = part.output; - if (Array.isArray(toolResult)) { - // Check for bailed result in results array - const bailedResult = toolResult.find((r: any) => r.bailed === true); + const { shouldFlushForToolCompletion, bailedResult } = this.processStepContent(oc, event); - if (bailedResult) { - const agentName = bailedResult.agentName || "unknown"; - const response = String(bailedResult.response || ""); + const responseMessages = filterResponseMessages(event.response?.messages); + const hasResponseMessages = Boolean(responseMessages && responseMessages.length > 0); + if (hasResponseMessages && responseMessages) { + buffer.addModelMessages(responseMessages, "response"); + } - oc.logger.info("Subagent bailed during stream - aborting supervisor stream", { - event: LogEvents.AGENT_STEP_TOOL_RESULT, - agentName, - bailed: true, - }); + const shouldFlushStepPersistence = + conversationPersistence.mode === "step" && + conversationPersistence.flushOnToolResult && + (shouldFlushForToolCompletion || Boolean(bailedResult)); - // Store bailed result for retrieval in onFinish - oc.systemContext.set("bailedResult", { - agentName, - response, - }); + if (conversationPersistence.mode === "step") { + await this.recordStepResults(undefined, oc, { + awaitPersistence: shouldFlushStepPersistence, + }); + } - // Abort the stream with BailError to signal early termination - oc.abortController.abort(createBailError(agentName, response)); - return; // Stop processing this step - } - } - } else if (part.type === "tool-error") { - oc.logger.debug(`Step: Tool '${part.toolName}' error`, { - event: LogEvents.AGENT_STEP_TOOL_RESULT, - toolName: part.toolName, - toolCallId: part.toolCallId, - error: part.error, - hasError: true, - }); + if ( + conversationPersistence.mode === "step" && + (hasResponseMessages || shouldFlushStepPersistence) + ) { + try { + if (shouldFlushStepPersistence) { + await persistQueue.flush(buffer, oc); + } else { + persistQueue.scheduleSave(buffer, oc); } + } catch (error) { + oc.logger.debug("Failed to persist step checkpoint", { + error, + conversationId: oc.conversationId, + userId: oc.userId, + }); } } - const responseMessages = filterResponseMessages(event.response?.messages); - if (responseMessages && responseMessages.length > 0) { - buffer.addModelMessages(responseMessages, "response"); + if (bailedResult) { + oc.abortController.abort(createBailError(bailedResult.agentName, bailedResult.response)); + return; } // Call hooks @@ -6357,16 +6396,129 @@ export class Agent { }; } + private processStepContent( + oc: OperationContext, + event: StepResult, + ): { + shouldFlushForToolCompletion: boolean; + bailedResult?: { agentName: string; response: string }; + } { + if (!event.content || !Array.isArray(event.content)) { + return { shouldFlushForToolCompletion: false }; + } + + if (!oc.systemContext.has("conversationSteps")) { + oc.systemContext.set("conversationSteps", []); + } + + const conversationSteps = oc.systemContext.get("conversationSteps") as StepResult[]; + conversationSteps.push(event); + + let shouldFlushForToolCompletion = false; + let bailedResult: { agentName: string; response: string } | undefined; + + for (const part of event.content) { + if (part.type === "text" || part.type === "reasoning") { + oc.logger.debug("Step: Text generated", { + event: LogEvents.AGENT_STEP_TEXT, + textPreview: part.text.substring(0, 100), + length: part.text.length, + }); + continue; + } + + if (part.type === "tool-call") { + oc.logger.debug(`Step: Calling tool '${part.toolName}'`, { + event: LogEvents.AGENT_STEP_TOOL_CALL, + toolName: part.toolName, + toolCallId: part.toolCallId, + arguments: part.input, + }); + + oc.logger.debug( + buildAgentLogMessage(this.name, ActionType.TOOL_CALL, `Executing ${part.toolName}`), + { + event: LogEvents.TOOL_EXECUTION_STARTED, + toolName: part.toolName, + toolCallId: part.toolCallId, + args: part.input, + }, + ); + continue; + } + + if (part.type === "tool-result") { + shouldFlushForToolCompletion = true; + oc.logger.debug(`Step: Tool '${part.toolName}' completed`, { + event: LogEvents.AGENT_STEP_TOOL_RESULT, + toolName: part.toolName, + toolCallId: part.toolCallId, + result: part.output, + hasError: Boolean( + part.output && typeof part.output === "object" && "error" in part.output, + ), + }); + + const bailFromToolResult = this.resolveBailedResultFromToolOutput(part.output); + if (bailFromToolResult) { + oc.logger.info("Subagent bailed during stream - aborting supervisor stream", { + event: LogEvents.AGENT_STEP_TOOL_RESULT, + agentName: bailFromToolResult.agentName, + bailed: true, + }); + oc.systemContext.set("bailedResult", bailFromToolResult); + bailedResult = bailFromToolResult; + } + continue; + } + + if (part.type === "tool-error") { + shouldFlushForToolCompletion = true; + oc.logger.debug(`Step: Tool '${part.toolName}' error`, { + event: LogEvents.AGENT_STEP_TOOL_RESULT, + toolName: part.toolName, + toolCallId: part.toolCallId, + error: part.error, + hasError: true, + }); + } + } + + return { + shouldFlushForToolCompletion, + bailedResult, + }; + } + + private resolveBailedResultFromToolOutput( + toolOutput: unknown, + ): { agentName: string; response: string } | undefined { + if (!Array.isArray(toolOutput)) { + return undefined; + } + + const bailedToolResult = toolOutput.find((result: any) => result?.bailed === true); + if (!bailedToolResult) { + return undefined; + } + + return { + agentName: String(bailedToolResult.agentName || "unknown"), + response: String(bailedToolResult.response || ""), + }; + } + private recordStepResults( steps: ReadonlyArray> | undefined, oc: OperationContext, - ): void { + options?: { awaitPersistence?: boolean }, + ): Promise { const storedSteps = (steps && steps.length > 0 ? steps : undefined) || (oc.systemContext.get("conversationSteps") as StepResult[] | undefined); if (!storedSteps?.length) { - return; + return Promise.resolve(); } if (!oc.conversationSteps) { @@ -6378,7 +6530,7 @@ export class Agent { const newSteps = storedSteps.slice(previouslyPersistedCount); if (!newSteps.length) { - return; + return Promise.resolve(); } oc.systemContext.set(STEP_PERSIST_COUNT_KEY, previouslyPersistedCount + newSteps.length); @@ -6511,7 +6663,7 @@ export class Agent { }); if (stepRecords.length > 0 && oc.userId && oc.conversationId) { - void this.memoryManager + const persistStepsPromise = this.memoryManager .saveConversationSteps(oc, stepRecords, oc.userId, oc.conversationId) .catch((error) => { oc.logger.debug("Failed to persist conversation steps", { @@ -6520,7 +6672,15 @@ export class Agent { userId: oc.userId, }); }); + + if (options?.awaitPersistence) { + return persistStepsPromise; + } + + void persistStepsPromise; } + + return Promise.resolve(); } /** @@ -7202,6 +7362,20 @@ export class Agent { this.memoryManager.setMemory(memory); } + /** + * Internal: apply default conversation persistence when none was configured explicitly. + */ + public __setDefaultConversationPersistence( + conversationPersistence: AgentConversationPersistenceOptions, + ): void { + if (this.conversationPersistenceConfigured) { + return; + } + + this.conversationPersistence = + this.normalizeConversationPersistenceOptions(conversationPersistence); + } + /** * Internal: apply a default tool routing config when none was configured explicitly. */ diff --git a/packages/core/src/agent/step-persistence.spec.ts b/packages/core/src/agent/step-persistence.spec.ts new file mode 100644 index 000000000..247c3610d --- /dev/null +++ b/packages/core/src/agent/step-persistence.spec.ts @@ -0,0 +1,130 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { Agent } from "./agent"; +import type { AgentConversationPersistenceOptions } from "./types"; + +type QueueMock = { + scheduleSave: ReturnType; + flush: ReturnType; +}; + +const createOperationContext = () => + ({ + operationId: "op-step-persist", + systemContext: new Map(), + logger: { + debug: vi.fn(), + info: vi.fn(), + }, + abortController: new AbortController(), + userId: "user-1", + conversationId: "conv-1", + }) as any; + +const createStepEvent = (content: any[]) => + ({ + content, + response: { + messages: [ + { + role: "assistant", + content: [{ type: "text", text: "checkpoint" }], + }, + ], + }, + }) as any; + +const createHarness = (overrides: AgentConversationPersistenceOptions) => { + const agent = new Agent({ + name: "step-persistence-agent", + instructions: "Test", + model: "openai/gpt-4o-mini", + }); + + const queue: QueueMock = { + scheduleSave: vi.fn(), + flush: vi.fn().mockResolvedValue(undefined), + }; + + const buffer = { + addModelMessages: vi.fn(), + }; + + const oc = createOperationContext(); + + const persistence = { + mode: "step" as const, + debounceMs: 200, + flushOnToolResult: true, + ...overrides, + }; + + vi.spyOn(agent as any, "getConversationBuffer").mockReturnValue(buffer); + vi.spyOn(agent as any, "getMemoryPersistQueue").mockReturnValue(queue); + vi.spyOn(agent as any, "getConversationPersistenceOptionsForContext").mockReturnValue( + persistence, + ); + const recordStepResultsSpy = vi + .spyOn(agent as any, "recordStepResults") + .mockResolvedValue(undefined); + + const handler = (agent as any).createStepHandler(oc, undefined) as (event: any) => Promise; + + return { + queue, + oc, + handler, + recordStepResultsSpy, + }; +}; + +describe("Step-level persistence", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("schedules debounced persistence for non-tool steps in step mode", async () => { + const { handler, queue, oc, recordStepResultsSpy } = createHarness({ mode: "step" }); + + await handler(createStepEvent([{ type: "text", text: "hello" }])); + + expect(queue.scheduleSave).toHaveBeenCalledTimes(1); + expect(queue.scheduleSave).toHaveBeenCalledWith(expect.anything(), oc); + expect(queue.flush).not.toHaveBeenCalled(); + expect(recordStepResultsSpy).toHaveBeenCalledWith(undefined, oc, { + awaitPersistence: false, + }); + }); + + it("flushes immediately when a tool result arrives in step mode", async () => { + const { handler, queue, oc, recordStepResultsSpy } = createHarness({ mode: "step" }); + + await handler( + createStepEvent([ + { + type: "tool-result", + toolName: "search", + toolCallId: "call-1", + output: { ok: true }, + }, + ]), + ); + + expect(queue.flush).toHaveBeenCalledTimes(1); + expect(queue.flush).toHaveBeenCalledWith(expect.anything(), oc); + expect(queue.scheduleSave).not.toHaveBeenCalled(); + expect(recordStepResultsSpy).toHaveBeenCalledWith(undefined, oc, { + awaitPersistence: true, + }); + }); + + it("keeps finish mode behavior without incremental checkpoints", async () => { + const { handler, queue, recordStepResultsSpy } = createHarness({ mode: "finish" }); + + await handler(createStepEvent([{ type: "text", text: "hello" }])); + + expect(queue.scheduleSave).not.toHaveBeenCalled(); + expect(queue.flush).not.toHaveBeenCalled(); + expect(recordStepResultsSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/agent/types.ts b/packages/core/src/agent/types.ts index f5f54dd20..47e2d0a08 100644 --- a/packages/core/src/agent/types.ts +++ b/packages/core/src/agent/types.ts @@ -601,6 +601,27 @@ export type AgentSummarizationOptions = { model?: AgentModelValue; }; +export type AgentConversationPersistenceMode = "finish" | "step"; + +export type AgentConversationPersistenceOptions = { + /** + * `finish` persists only at operation completion. + * `step` checkpoints after each step (debounced) and flushes on tool completion by default. + * @default "step" + */ + mode?: AgentConversationPersistenceMode; + /** + * Debounce duration (ms) for step-level persistence scheduling. + * @default 200 + */ + debounceMs?: number; + /** + * When true in `step` mode, tool-result/tool-error steps trigger an immediate flush. + * @default true + */ + flushOnToolResult?: boolean; +}; + /** * Agent configuration options */ @@ -632,6 +653,7 @@ export type AgentOptions = { workspaceSkillsPrompt?: WorkspaceSkillsPromptOptions | boolean; memory?: Memory | false; summarization?: AgentSummarizationOptions | false; + conversationPersistence?: AgentConversationPersistenceOptions; // Retriever/RAG retriever?: BaseRetriever; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 552dbbd78..48d2226ed 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -175,6 +175,8 @@ export type { EmbeddingRouterModelId } from "./registries/embedding-model-router export * from "./events/types"; export type { AgentOptions, + AgentConversationPersistenceMode, + AgentConversationPersistenceOptions, AgentSummarizationOptions, AgentModelReference, AgentModelConfig, diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index d1fc4d0e3..d988dd84e 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -8,6 +8,7 @@ import type { MCPServerFactory, MCPServerLike } from "@voltagent/internal/mcp"; import type { DangerouslyAllowAny } from "@voltagent/internal/types"; import type { A2AServerRegistry } from "./a2a"; import type { Agent } from "./agent/agent"; +import type { AgentConversationPersistenceOptions } from "./agent/types"; import type { AgentStatus } from "./agent/types"; import type { MCPServerRegistry } from "./mcp"; import type { Memory } from "./memory"; @@ -234,6 +235,10 @@ export type VoltAgentOptions = { * When enabled, agents expose searchTools/callTool and hide pool tools from the model. */ toolRouting?: ToolRoutingConfig; + /** + * Default conversation persistence behavior for agents that don't define one. + */ + agentConversationPersistence?: AgentConversationPersistenceOptions; /** * Optional global workspace instance or configuration. * Agents inherit this workspace unless they explicitly provide their own workspace or set it to false. diff --git a/packages/core/src/voltagent.spec.ts b/packages/core/src/voltagent.spec.ts index d646d478d..3cf65112a 100644 --- a/packages/core/src/voltagent.spec.ts +++ b/packages/core/src/voltagent.spec.ts @@ -108,4 +108,57 @@ describe("VoltAgent defaults", () => { expect(agent.getMemory()).toBe(sharedMemory); expect(workflow.memory).toBe(sharedMemory); }); + + it("applies default agent conversation persistence when agent does not configure it", () => { + const agent = new Agent({ + name: "assistant", + instructions: "Be helpful.", + model: "openai/gpt-4o-mini", + }); + + new VoltAgent({ + agents: { assistant: agent }, + agentConversationPersistence: { + mode: "finish", + debounceMs: 10, + flushOnToolResult: false, + }, + checkDependencies: false, + }); + + expect((agent as any).conversationPersistence).toMatchObject({ + mode: "finish", + debounceMs: 10, + flushOnToolResult: false, + }); + }); + + it("preserves explicit agent conversation persistence config", () => { + const agent = new Agent({ + name: "assistant", + instructions: "Be helpful.", + model: "openai/gpt-4o-mini", + conversationPersistence: { + mode: "step", + debounceMs: 25, + flushOnToolResult: true, + }, + }); + + new VoltAgent({ + agents: { assistant: agent }, + agentConversationPersistence: { + mode: "finish", + debounceMs: 0, + flushOnToolResult: false, + }, + checkDependencies: false, + }); + + expect((agent as any).conversationPersistence).toMatchObject({ + mode: "step", + debounceMs: 25, + flushOnToolResult: true, + }); + }); }); diff --git a/packages/core/src/voltagent.ts b/packages/core/src/voltagent.ts index 381b1b50f..6428dbc4d 100644 --- a/packages/core/src/voltagent.ts +++ b/packages/core/src/voltagent.ts @@ -4,6 +4,7 @@ import type { MCPServerDeps, MCPServerFactory, MCPServerLike } from "@voltagent/ import type { DangerouslyAllowAny } from "@voltagent/internal/types"; import { A2AServerRegistry } from "./a2a"; import type { Agent } from "./agent/agent"; +import type { AgentConversationPersistenceOptions } from "./agent/types"; import { getGlobalLogger } from "./logger"; import { MCPServerRegistry } from "./mcp"; import type { Memory } from "./memory"; @@ -36,6 +37,7 @@ export class VoltAgent { private observability?: VoltAgentObservability; private defaultAgentMemory?: Memory; private defaultWorkflowMemory?: Memory; + private readonly defaultAgentConversationPersistence?: AgentConversationPersistenceOptions; private readonly mcpServers = new Set(); private readonly mcpServerRegistry = new MCPServerRegistry(); private readonly a2aServers = new Set(); @@ -56,6 +58,7 @@ export class VoltAgent { this.agentRefs = options.agents ?? {}; this.defaultAgentMemory = options.agentMemory ?? options.memory; this.defaultWorkflowMemory = options.workflowMemory ?? options.memory; + this.defaultAgentConversationPersistence = options.agentConversationPersistence; if (options.memory) { this.registry.setGlobalMemory(options.memory); } @@ -440,6 +443,13 @@ export class VoltAgent { agent.__setDefaultMemory(this.defaultAgentMemory); } + private applyDefaultConversationPersistenceToAgent(agent: Agent): void { + if (!this.defaultAgentConversationPersistence) { + return; + } + agent.__setDefaultConversationPersistence?.(this.defaultAgentConversationPersistence); + } + private applyDefaultMemoryToWorkflow( workflow: Workflow< DangerouslyAllowAny, @@ -460,6 +470,7 @@ export class VoltAgent { public registerAgent(agent: Agent): void { // Register the agent this.applyDefaultMemoryToAgent(agent); + this.applyDefaultConversationPersistenceToAgent(agent); agent.__setDefaultToolRouting?.(this.registry.getGlobalToolRouting()); this.registry.registerAgent(agent); } diff --git a/website/docs/agents/memory/overview.md b/website/docs/agents/memory/overview.md index 1660a364b..60048baa3 100644 --- a/website/docs/agents/memory/overview.md +++ b/website/docs/agents/memory/overview.md @@ -68,6 +68,9 @@ Notes: - VoltOps Observability consumes these records to render the Memory Explorer “Steps” tab and to correlate traces/logs with memory. - Adapters that implement the step APIs persist sub-agent activity alongside primary agent steps, so hierarchies stay visible. - If an adapter does not support steps, the console warns with “Conversation steps are not supported by this memory adapter.” +- By default, agents checkpoint conversation progress during multi-step runs (`conversationPersistence.mode: "step"`). +- Tool completion events (`tool-result`, `tool-error`) trigger immediate flushes by default (`flushOnToolResult: true`), reducing history loss risk on crashes or process interruption. +- Use `conversationPersistence.mode: "finish"` if you want end-of-turn persistence only. ### Semantic Search (Optional) diff --git a/website/docs/agents/overview.md b/website/docs/agents/overview.md index c719f1d5c..fe4fa88a5 100644 --- a/website/docs/agents/overview.md +++ b/website/docs/agents/overview.md @@ -212,6 +212,35 @@ console.log(haiku.output); Summarization inserts a system summary and keeps the last N non-system messages before each model call. Configure it with the `summarization` option on the agent. See [Summarization](./summarization.md) for configuration and storage details. +### Conversation Persistence + +VoltAgent persists conversation messages and step records while a run is executing. By default, it uses step-level checkpoints, which is safer for long multi-step tool chains. + +```ts +const agent = new Agent({ + name: "Assistant", + instructions: "Help users reliably.", + model: "openai/gpt-4o-mini", + conversationPersistence: { + mode: "step", // "step" (default) or "finish" + debounceMs: 200, // default + flushOnToolResult: true, // default + }, +}); +``` + +You can also override this per call: + +```ts +await agent.generateText("Run the workflow", { + conversationPersistence: { + mode: "finish", + }, +}); +``` + +`mode: "step"` schedules persistence during execution and flushes immediately on tool completion by default. `mode: "finish"` keeps the legacy behavior of persisting only at operation completion. + ### Input Types All methods accept either a string or an array of messages: diff --git a/website/docs/agents/voltagent-instance.md b/website/docs/agents/voltagent-instance.md index 9c399c08f..163130fbf 100644 --- a/website/docs/agents/voltagent-instance.md +++ b/website/docs/agents/voltagent-instance.md @@ -28,7 +28,7 @@ new VoltAgent({ ## What VoltAgent Manages - Registers agents and workflows for API access and observability. -- Applies global defaults (logger, observability, memory). +- Applies global defaults (logger, observability, memory, conversation persistence). - Boots HTTP or serverless providers. - Registers triggers, MCP servers, and A2A servers. - Coordinates graceful shutdown for servers and telemetry. @@ -85,6 +85,28 @@ new VoltAgent({ See [Memory Overview](/docs/agents/memory/overview) for adapter options. +## Conversation Persistence Defaults + +Set a default persistence strategy for agents that do not explicitly define `conversationPersistence`. + +```ts +new VoltAgent({ + agents: { assistant }, + agentConversationPersistence: { + mode: "step", // default + debounceMs: 200, // default + flushOnToolResult: true, // default + }, +}); +``` + +**Precedence** + +- Per-call `options.conversationPersistence` +- Agent `conversationPersistence` +- VoltAgent `agentConversationPersistence` +- Built-in defaults (`mode: "step"`, `debounceMs: 200`, `flushOnToolResult: true`) + ## Observability and Logging VoltAgent creates an OpenTelemetry-based observability instance by default. You can provide your own instance or logger if you want full control. diff --git a/website/docs/api/endpoints/agents.md b/website/docs/api/endpoints/agents.md index dc1c1d750..9739117e7 100644 --- a/website/docs/api/endpoints/agents.md +++ b/website/docs/api/endpoints/agents.md @@ -103,6 +103,11 @@ Generate a text response from an agent synchronously. "context": { "role": "admin", "tier": "premium" + }, + "conversationPersistence": { + "mode": "step", + "debounceMs": 200, + "flushOnToolResult": true } } } @@ -183,6 +188,9 @@ Generate a text response from an agent synchronously. | `stopSequences` | string[] | - | Stop generation sequences | | `providerOptions` | object | - | Provider-specific options | | `context` | object | - | Dynamic agent context | +| `conversationPersistence.mode` | string | `"step"` | Persistence strategy: `"step"` or `"finish"` | +| `conversationPersistence.debounceMs` | number | `200` | Debounce interval for step checkpoint persistence | +| `conversationPersistence.flushOnToolResult` | boolean | `true` | Flush immediately on `tool-result`/`tool-error` in step mode | **Response:** diff --git a/website/docs/ui/ai-sdk-integration.md b/website/docs/ui/ai-sdk-integration.md index 17c2576a4..0e86fd395 100644 --- a/website/docs/ui/ai-sdk-integration.md +++ b/website/docs/ui/ai-sdk-integration.md @@ -341,12 +341,29 @@ export function ChatInterface() { ### VoltAgent Specific -| Option | Type | Description | -| ---------------- | ------ | -------------------------------------------------- | -| `userId` | string | User identifier for memory persistence | -| `conversationId` | string | Conversation thread ID | -| `context` | object | Dynamic context (converted to Map internally) | -| `contextLimit` | number | Number of previous messages to include from memory | +| Option | Type | Description | +| ------------------------------------------- | ------- | ------------------------------------------------------------------------------ | +| `userId` | string | User identifier for memory persistence | +| `conversationId` | string | Conversation thread ID | +| `context` | object | Dynamic context (converted to Map internally) | +| `contextLimit` | number | Number of previous messages to include from memory | +| `conversationPersistence.mode` | string | `"step"` (default) or `"finish"` | +| `conversationPersistence.debounceMs` | number | Debounce window in milliseconds (default: `200`) | +| `conversationPersistence.flushOnToolResult` | boolean | Flush immediately on `tool-result`/`tool-error` in step mode (default: `true`) | + +Example: + +```ts +options: { + userId, + conversationId, + conversationPersistence: { + mode: "step", + debounceMs: 200, + flushOnToolResult: true, + }, +} +``` ### AI SDK Core Options