Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/parallel-input-guardrails.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"@voltagent/core": minor
---

Add parallel input guardrails for `streamText` so async input checks can run while the model starts, buffer streamed output until they pass, and replace blocked streams without persisting generated assistant output.

UI streams produced with `toUIMessageStreamResponse()` or consumed by AI SDK `useChat` receive a blocked parallel input guardrail as replacement assistant text, so existing chat UIs can render it without using an error callback:

```tsx
const INPUT_BLOCKED_MESSAGE = "This request cannot be answered.";

const blocked =
message.role === "assistant" &&
message.parts?.some((part) => part.type === "text" && part.text === INPUT_BLOCKED_MESSAGE);
```
82 changes: 82 additions & 0 deletions packages/core/src/agent/agent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { ModelProviderRegistry } from "../registries/model-provider-registry";
import { Tool } from "../tool";
import { Workspace } from "../workspace";
import { Agent, renameProviderOptions } from "./agent";
import { SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY } from "./context-keys";
import { ConversationBuffer } from "./conversation-buffer";
import { ToolDeniedError } from "./errors";
import { createHooks } from "./hooks";
Expand Down Expand Up @@ -1660,6 +1661,87 @@ Use pandas and summarize findings.`.split("\n"),
operationContext.traceContext.end("completed");
});

it("waits for parallel input guardrails before executing server-side tools", async () => {
let releaseGuardrail!: () => void;
const guardrailWait = new Promise<{ status: "passed" }>((resolve) => {
releaseGuardrail = () => resolve({ status: "passed" });
});
const toolExecute = vi.fn(async () => "tool output");
const agent = new Agent({
name: "TestAgent",
instructions: "Test",
model: mockModel as any,
});
const tool = new Tool({
name: "guarded-tool",
description: "Must wait for input guardrail.",
parameters: z.object({}),
execute: toolExecute,
});

const operationContext = (agent as any).createOperationContext("input");
operationContext.systemContext.set(SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY, {
wait: vi.fn(() => guardrailWait),
hasPassed: vi.fn(() => false),
});
const executeFactory = (agent as any).createToolExecutionFactory(
operationContext,
agent.hooks,
);

const resultPromise = executeFactory(tool)({});
await Promise.resolve();

expect(toolExecute).not.toHaveBeenCalled();
releaseGuardrail();

await expect(resultPromise).resolves.toBe("tool output");
expect(toolExecute).toHaveBeenCalledTimes(1);

operationContext.traceContext.end("completed");
});

it("does not execute server-side tools when a parallel input guardrail blocks", async () => {
const toolExecute = vi.fn(async () => "tool output");
const agent = new Agent({
name: "TestAgent",
instructions: "Test",
model: mockModel as any,
});
const tool = new Tool({
name: "blocked-tool",
description: "Must not run after input block.",
parameters: z.object({}),
execute: toolExecute,
});
const guardrailError = new Error("Input blocked by policy.");

const operationContext = (agent as any).createOperationContext("input");
operationContext.systemContext.set(SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY, {
wait: vi.fn(async () => ({
status: "blocked",
error: guardrailError,
message: guardrailError.message,
})),
hasPassed: vi.fn(() => false),
});
const executeFactory = (agent as any).createToolExecutionFactory(
operationContext,
agent.hooks,
);

const result = await executeFactory(tool)({});

expect(toolExecute).not.toHaveBeenCalled();
expect(result).toMatchObject({
error: true,
message: "Input blocked by policy.",
toolName: "blocked-tool",
});

operationContext.traceContext.end("completed");
});

it("supports tool-level hooks for start and end", async () => {
const toolOnStart = vi.fn();
const toolOnEnd = vi.fn().mockResolvedValue({ output: "tool-hook" });
Expand Down
110 changes: 103 additions & 7 deletions packages/core/src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ import { applySummarization } from "./apply-summarization";
import {
AGENT_REF_CONTEXT_KEY,
FORCED_TOOL_CHOICE_CONTEXT_KEY,
SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY,
TOOL_ROUTING_CONTEXT_KEY,
TOOL_ROUTING_SEARCHED_TOOLS_CONTEXT_KEY,
} from "./context-keys";
Expand Down Expand Up @@ -174,6 +175,12 @@ import {
createAsyncIterableReadable,
createGuardrailPipeline,
} from "./streaming/guardrail-stream";
import {
SpeculativeInputGuardrailRun,
applySpeculativeInputGuardrailToFullStream,
applySpeculativeInputGuardrailToTextStream,
applySpeculativeInputGuardrailToUIStream,
} from "./streaming/input-guardrail-stream";
import { SubAgentManager } from "./subagent";
import type { SubAgentConfig } from "./subagent/types";
import type { VoltAgentTextStreamPart } from "./subagent/types";
Expand Down Expand Up @@ -1803,6 +1810,7 @@ export class Agent {
resolveFeedbackDeferred(null);
}
let effectiveInput: typeof input = input;
let speculativeInputGuardrail: SpeculativeInputGuardrailRun | null = null;
try {
while (true) {
try {
Expand Down Expand Up @@ -1852,14 +1860,36 @@ export class Agent {
}
}

const blockingInputGuardrails = guardrailSet.input.filter(
(guardrail) => guardrail.execution !== "parallel",
);
const parallelInputGuardrails = guardrailSet.input.filter(
(guardrail) => guardrail.execution === "parallel",
);

effectiveInput = await executeInputGuardrails(
effectiveInput,
oc,
guardrailSet.input,
blockingInputGuardrails,
"streamText",
this,
);

if (parallelInputGuardrails.length > 0) {
speculativeInputGuardrail = new SpeculativeInputGuardrailRun({
input: effectiveInput,
operationContext: oc,
guardrails: parallelInputGuardrails,
operation: "streamText",
agent: this,
buffer,
onBlock: () => {
resolveFeedbackDeferred(null);
},
});
oc.systemContext.set(SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY, speculativeInputGuardrail);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

// No need to initialize stream collection anymore - we'll use UIMessageStreamWriter

const { messages, uiMessages, modelName, tools, maxSteps } = await this.prepareExecution(
Expand Down Expand Up @@ -2138,6 +2168,13 @@ export class Agent {
providerMetadata: finalResult.providerMetadata,
});

if (speculativeInputGuardrail) {
const inputGuardrailDecision = await speculativeInputGuardrail.wait();
if (inputGuardrailDecision.status === "blocked") {
return;
}
}

const usage = convertUsage(usageForFinish);
const persistedAssistantMetadata = this.buildPersistedAssistantMessageMetadata({
oc,
Expand Down Expand Up @@ -2513,6 +2550,19 @@ export class Agent {
: undefined;

const createSanitizedTextPromise = (): Promise<string> => {
if (speculativeInputGuardrail) {
return speculativeInputGuardrail.wait().then((decision) => {
if (decision.status === "blocked") {
return decision.message;
}
return createSanitizedTextPromiseWithoutInputGate();
});
}

return createSanitizedTextPromiseWithoutInputGate();
};

const createSanitizedTextPromiseWithoutInputGate = (): Promise<string> => {
if (guardrailPipeline) {
return guardrailPipeline.finalizePromise.then(async () => {
const sanitized = guardrailPipeline?.runner?.getSanitizedText();
Expand Down Expand Up @@ -2563,25 +2613,47 @@ export class Agent {

const getGuardrailAwareFullStream = (): AsyncIterable<VoltAgentTextStreamPart> => {
if (guardrailPipeline) {
return guardrailPipeline.fullStream;
return applySpeculativeInputGuardrailToFullStream({
baseStream: guardrailPipeline.fullStream,
guardrail: speculativeInputGuardrail,
responseMessageId: responseMessageId ?? undefined,
});
}
return createBaseFullStream();
return applySpeculativeInputGuardrailToFullStream({
baseStream: createBaseFullStream(),
guardrail: speculativeInputGuardrail,
responseMessageId: responseMessageId ?? undefined,
});
};

const getGuardrailAwareTextStream = (): AsyncIterableStream<string> => {
if (guardrailPipeline) {
return guardrailPipeline.textStream;
return applySpeculativeInputGuardrailToTextStream({
baseStream: guardrailPipeline.textStream,
guardrail: speculativeInputGuardrail,
});
}
return result.textStream;
return applySpeculativeInputGuardrailToTextStream({
baseStream: result.textStream,
guardrail: speculativeInputGuardrail,
});
};

const getGuardrailAwareUIStream = (
streamOptions?: ToUIMessageStreamOptions,
): ToUIMessageStreamReturn => {
if (!guardrailPipeline) {
return result.toUIMessageStream(streamOptions);
return applySpeculativeInputGuardrailToUIStream({
baseStream: result.toUIMessageStream(streamOptions),
guardrail: speculativeInputGuardrail,
responseMessageId: responseMessageId ?? undefined,
});
}
return guardrailPipeline.createUIStream(streamOptions) as ToUIMessageStreamReturn;
return applySpeculativeInputGuardrailToUIStream({
baseStream: guardrailPipeline.createUIStream(streamOptions) as ToUIMessageStreamReturn,
guardrail: speculativeInputGuardrail,
responseMessageId: responseMessageId ?? undefined,
});
Comment thread
omeraplak marked this conversation as resolved.
Resolved
};

const createMergedUIStream = (
Expand Down Expand Up @@ -6456,6 +6528,7 @@ export class Agent {
if (execute && isAsyncGeneratorFunction(execute)) {
return async function* (this: Agent): AsyncGenerator<any, void, void> {
try {
await this.waitForSpeculativeInputGuardrail(oc);
Comment thread
omeraplak marked this conversation as resolved.
Resolved
Comment thread
omeraplak marked this conversation as resolved.
Resolved
await oc.traceContext.withSpan(toolSpan, async () => {
await runToolStartHooks();
});
Expand Down Expand Up @@ -6516,6 +6589,7 @@ export class Agent {

return oc.traceContext.withSpan(toolSpan, async () => {
try {
await this.waitForSpeculativeInputGuardrail(oc);
// Call tool start hook - can throw ToolDeniedError
await runToolStartHooks();

Expand Down Expand Up @@ -7229,6 +7303,26 @@ export class Agent {
}
}

private getSpeculativeInputGuardrail(oc: OperationContext): SpeculativeInputGuardrailRun | null {
return (
(oc.systemContext.get(SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY) as
| SpeculativeInputGuardrailRun
| undefined) ?? null
);
}

private async waitForSpeculativeInputGuardrail(oc: OperationContext): Promise<void> {
const guardrail = this.getSpeculativeInputGuardrail(oc);
if (!guardrail) {
return;
}

const decision = await guardrail.wait();
if (decision.status === "blocked") {
throw decision.error;
}
}

/**
* Create step handler for memory and hooks
*/
Expand All @@ -7239,6 +7333,7 @@ export class Agent {
const conversationPersistence = this.getConversationPersistenceOptionsForContext(oc);

return async (event: StepResult<ToolSet>) => {
const speculativeInputGuardrail = this.getSpeculativeInputGuardrail(oc);
const { shouldFlushForToolCompletion, bailedResult } = this.processStepContent(oc, event);

const responseMessages = this.normalizeStepResponseMessages(
Expand All @@ -7264,6 +7359,7 @@ export class Agent {
if (
shouldPersistMemory &&
persistQueue &&
(!speculativeInputGuardrail || speculativeInputGuardrail.hasPassed()) &&
conversationPersistence.mode === "step" &&
(hasResponseMessages || shouldFlushStepPersistence)
) {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/agent/context-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export const FORCED_TOOL_CHOICE_CONTEXT_KEY = Symbol("forcedToolChoice");
export const AGENT_REF_CONTEXT_KEY = Symbol("agentRef");
export const TOOL_ROUTING_CONTEXT_KEY = Symbol("toolRoutingConfig");
export const TOOL_ROUTING_SEARCHED_TOOLS_CONTEXT_KEY = Symbol("toolRoutingSearchedTools");
export const SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY = Symbol("speculativeInputGuardrail");
31 changes: 31 additions & 0 deletions packages/core/src/agent/conversation-buffer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,4 +253,35 @@ describe("ConversationBuffer", () => {
const historyMessage = all.find((message) => message.id === "assistant-1");
expect(historyMessage?.metadata).toBeUndefined();
});

it("restores response messages and pending state from a checkpoint", () => {
const buffer = new ConversationBuffer();
buffer.ingestUIMessages(
[
{
id: "user-1",
role: "user",
parts: [{ type: "text", text: "hello" }],
},
],
false,
);
const checkpoint = buffer.createCheckpoint();

buffer.addModelMessages([assistantToolCall, toolResult, assistantText], "response");
expect(buffer.getAllMessages().some((message) => message.role === "assistant")).toBe(true);

buffer.restoreCheckpoint(checkpoint);

expect(buffer.getAllMessages()).toEqual([
{
id: "user-1",
role: "user",
parts: [{ type: "text", text: "hello" }],
},
]);
const pending = buffer.drainPendingMessages();
expect(pending).toHaveLength(1);
expect(pending[0]?.id).toBe("user-1");
});
});
Loading
Loading