Skip to content
5 changes: 5 additions & 0 deletions .changeset/olive-wolves-approve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@voltagent/core": patch
---

fix(core): persist client approval decisions onto buffered tool parts so restored conversations keep `approval-responded` state instead of re-validating stale parts and throwing `AI_TypeValidationError`
13 changes: 13 additions & 0 deletions packages/core/src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5075,6 +5075,11 @@ export class Agent {
},
);
buffer.ingestUIMessages(memMessages, true);
// Apply approval decisions carried by the input so buffered
// approval-requested parts don't keep a stale `approval`.
if (Array.isArray(resolvedInput) && (resolvedInput as any[])[0]?.parts) {
buffer.applyApprovalResponses(resolvedInput as UIMessage[]);
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
return memMessages;
}
// Regular memory context
Expand Down Expand Up @@ -5103,6 +5108,14 @@ export class Agent {

buffer.ingestUIMessages(result.messages, true);

// Apply approval decisions carried by the input so buffered
// approval-requested parts don't keep a stale `approval`
// (otherwise a later `output-available` part fails AI SDK
// validation and breaks every subsequent turn).
if (Array.isArray(inputForMemory)) {
buffer.applyApprovalResponses(inputForMemory);
}

if (
shouldPersistMemory &&
speculativeInputGuardrail &&
Expand Down
139 changes: 139 additions & 0 deletions packages/core/src/agent/approval-persistence.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/**
* Regression tests for https://github.com/VoltAgent/voltagent/issues/1535
*
* After a `needsApproval` tool call is approved and runs, memory must store
* the tool part as `state: "output-available"` WITH `approval.approved`
* preserved. Previously the buffer was seeded only from stored memory (which
* still held the pre-approval part, `approval: { id }`), the approval
* response in the input never reached the buffer, and the flush overwrote
* the input message - so the stored part lost `approved: true` and every
* later `generateText` on the conversation threw AI_TypeValidationError.
*/
import { MockLanguageModelV3 } from "ai/test";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { Memory } from "../memory";
import { InMemoryStorageAdapter } from "../memory/adapters/storage/in-memory";
import { createTool } from "../tool";
import { Agent } from "./agent";

const usage = {
inputTokens: 10,
outputTokens: 5,
totalTokens: 15,
inputTokenDetails: {
noCacheTokens: 10,
cacheReadTokens: 0,
cacheWriteTokens: 0,
},
outputTokenDetails: {
textTokens: 5,
reasoningTokens: 0,
},
};

const makeAgent = (storage: InMemoryStorageAdapter) => {
const model = new MockLanguageModelV3({
modelId: "test-model",
doGenerate: async ({ prompt }) => {
await new Promise((r) => setTimeout(r, 1));
return prompt.some((m: any) => m.role === "tool")
? {
content: [{ type: "text" as const, text: "Refund done." }],
finishReason: { unified: "stop" as const, raw: "stop" },
usage,
warnings: [],
}
: {
content: [
{
type: "tool-call" as const,
toolCallId: "call_1",
toolName: "refund",
input: '{"amount":50}',
},
],
finishReason: { unified: "tool-calls" as const, raw: "tool_use" },
usage,
warnings: [],
};
},
});

return new Agent({
name: "a",
instructions: "x",
model: model as any,
memory: new Memory({ storage }),
tools: [
createTool({
name: "refund",
description: "refund",
parameters: z.object({ amount: z.number() }),
needsApproval: true,
execute: async () => ({ refunded: true }),
}),
],
});
};

const memory = { userId: "u", conversationId: "c" };

const storedToolParts = async (storage: InMemoryStorageAdapter) => {
const stored = await storage.getMessages("u", "c");
return stored.flatMap((m: any) => m.parts ?? []).filter((p: any) => p.type === "tool-refund");
};

describe("needsApproval persistence (issue #1535)", () => {
it("keeps approval.approved when an approved tool's result is persisted, and later turns work", async () => {
const storage = new InMemoryStorageAdapter();
const agent = makeAgent(storage);

// Turn 1: model calls the tool, agent asks for approval.
await agent.generateText("refund 50", { memory });

const stored1 = await storage.getMessages("u", "c");
const msg = structuredClone(stored1.at(-1)) as any;
const part = msg.parts.find((p: any) => p.type === "tool-refund");
expect(part.state).toBe("approval-requested");

// Client approves (shape produced by the AI SDK's addToolApprovalResponse).
part.state = "approval-responded";
part.approval = { id: part.approval.id, approved: true };

// Turn 2: tool runs.
await agent.generateText([msg], { memory });

const parts2 = await storedToolParts(storage);
expect(parts2).toHaveLength(1);
expect(parts2[0].state).toBe("output-available");
expect(parts2[0].output).toBeDefined();
expect(parts2[0].approval).toMatchObject({ approved: true });

// Turn 3: a plain follow-up must not fail AI SDK UI message validation.
const result = await agent.generateText("did it go through?", { memory });
expect(result.text).toBeDefined();
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
}, 30000);

it("keeps approval.approved === false when the client denies the tool", async () => {
const storage = new InMemoryStorageAdapter();
const agent = makeAgent(storage);

await agent.generateText("refund 50", { memory });

const stored1 = await storage.getMessages("u", "c");
const msg = structuredClone(stored1.at(-1)) as any;
const part = msg.parts.find((p: any) => p.type === "tool-refund");

// Client denies.
part.state = "approval-responded";
part.approval = { id: part.approval.id, approved: false };

await agent.generateText([msg], { memory });

const parts2 = await storedToolParts(storage);
expect(parts2).toHaveLength(1);
// The client's denial decision is preserved, never rewritten to an approval.
expect(parts2[0].approval?.approved).toBe(false);
}, 30000);
});
66 changes: 66 additions & 0 deletions packages/core/src/agent/conversation-buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,72 @@ export class ConversationBuffer {
}
}

/**
* Apply approval responses carried by incoming UI messages to the buffered
* conversation.
*
* The buffer is seeded from stored memory, which still holds the
* pre-approval tool part (`approval: { id }`, no `approved`). The client's
* approval decision only travels with the input message, so without this
* merge the buffered (and later persisted) part keeps the stale approval
* once the tool result flips its state to `output-available` — and the AI
* SDK's UIMessage schema then rejects it (`output-available` requires
* `approval.approved === true`), breaking every later turn.
*
* Only parts that carry an actual client decision (`approval.approved` is
* a boolean) are applied; nothing is inferred from outputs or states.
*/
applyApprovalResponses(messages: ReadonlyArray<UIMessage>): void {
for (const message of messages) {
if (!Array.isArray(message.parts)) continue;
for (const part of message.parts) {
const approval = (part as any)?.approval as
| { id?: string; approved?: boolean; reason?: string }
| undefined;
if (!approval || typeof approval.approved !== "boolean") continue;

const toolCallId = (part as any).toolCallId as string | undefined;
const indexed = toolCallId ? this.toolPartIndex.get(toolCallId) : undefined;
let target: any;
if (indexed && this.messages[indexed.messageIndex]) {
target = this.messages[indexed.messageIndex].parts[indexed.partIndex];
} else if (approval.id) {
target = this.findToolPartByApprovalId(approval.id);
}
if (!target) continue;

// Preserve the client's decision verbatim (id, approved, reason).
target.approval = { ...(target.approval ?? {}), ...approval };
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

// Reflect the responded state unless the part already reached a
// terminal output state.
const state = target.state as string | undefined;
const respondedState = (part as any).state as string | undefined;
if (
respondedState === "approval-responded" &&
state !== "output-available" &&
state !== "output-error" &&
state !== "output-denied"
) {
target.state = "approval-responded";
}
}
}
}

private findToolPartByApprovalId(approvalId: string): any {
for (const message of this.messages) {
if (!Array.isArray(message.parts)) continue;
for (const part of message.parts) {
const approval = (part as any)?.approval as { id?: string } | undefined;
if (approval?.id === approvalId) {
return part;
}
}
}
return undefined;
}

createCheckpoint(): ConversationBufferCheckpoint {
return {
messages: this.messages.map((message) => this.cloneMessage(message)),
Expand Down