diff --git a/.changeset/parallel-input-guardrails.md b/.changeset/parallel-input-guardrails.md new file mode 100644 index 000000000..e485b0117 --- /dev/null +++ b/.changeset/parallel-input-guardrails.md @@ -0,0 +1,13 @@ +--- +"@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 `data-input-guardrail-blocked` event before the replacement assistant text, so UIs can translate the block state without string-matching the fallback message: + +```tsx +const blocked = + message.role === "assistant" && + message.parts?.some((part) => part.type === "data-input-guardrail-blocked"); +``` diff --git a/packages/core/src/agent/agent.spec.ts b/packages/core/src/agent/agent.spec.ts index e78773075..203b41304 100644 --- a/packages/core/src/agent/agent.spec.ts +++ b/packages/core/src/agent/agent.spec.ts @@ -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"; @@ -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" }); diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index df3f7a64c..c7fd9bb49 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -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"; @@ -174,6 +175,13 @@ import { createAsyncIterableReadable, createGuardrailPipeline, } from "./streaming/guardrail-stream"; +import { + SpeculativeInputGuardrailRun, + applySpeculativeInputGuardrailToFullStream, + applySpeculativeInputGuardrailToPartialOutputStream, + applySpeculativeInputGuardrailToTextStream, + applySpeculativeInputGuardrailToUIStream, +} from "./streaming/input-guardrail-stream"; import { SubAgentManager } from "./subagent"; import type { SubAgentConfig } from "./subagent/types"; import type { VoltAgentTextStreamPart } from "./subagent/types"; @@ -1736,6 +1744,7 @@ export class Agent { let feedbackResolved = false; let feedbackFinalizeRequested = false; let feedbackApplied = false; + let feedbackCancelled = false; let latestResponseMessages: ModelMessage[] | undefined; const resolveFeedbackDeferred = (value: AgentFeedbackMetadata | null) => { if (!feedbackDeferred || feedbackResolved) { @@ -1782,6 +1791,10 @@ export class Agent { if (feedbackPromise) { feedbackPromise .then((metadata) => { + if (feedbackCancelled) { + resolveFeedbackDeferred(null); + return; + } feedbackMetadataValue = metadata; feedbackValue = metadata ? createFeedbackHandleHelper({ @@ -1803,6 +1816,7 @@ export class Agent { resolveFeedbackDeferred(null); } let effectiveInput: typeof input = input; + let speculativeInputGuardrail: SpeculativeInputGuardrailRun | null = null; try { while (true) { try { @@ -1852,14 +1866,39 @@ 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: () => { + feedbackCancelled = true; + feedbackMetadataValue = null; + feedbackValue = null; + resolveFeedbackDeferred(null); + }, + }); + oc.systemContext.set(SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY, speculativeInputGuardrail); + } + // No need to initialize stream collection anymore - we'll use UIMessageStreamWriter const { messages, uiMessages, modelName, tools, maxSteps } = await this.prepareExecution( @@ -2138,6 +2177,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, @@ -2513,6 +2559,19 @@ export class Agent { : undefined; const createSanitizedTextPromise = (): Promise => { + if (speculativeInputGuardrail) { + return speculativeInputGuardrail.wait().then((decision) => { + if (decision.status === "blocked") { + return decision.message; + } + return createSanitizedTextPromiseWithoutInputGate(); + }); + } + + return createSanitizedTextPromiseWithoutInputGate(); + }; + + const createSanitizedTextPromiseWithoutInputGate = (): Promise => { if (guardrailPipeline) { return guardrailPipeline.finalizePromise.then(async () => { const sanitized = guardrailPipeline?.runner?.getSanitizedText(); @@ -2563,25 +2622,58 @@ export class Agent { const getGuardrailAwareFullStream = (): AsyncIterable => { 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 => { 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, + }); + }; + + const getGuardrailAwarePartialOutputStream = (): typeof result.partialOutputStream => { + const partialOutputStream = result.partialOutputStream; + if (!partialOutputStream) { + return partialOutputStream; + } + return applySpeculativeInputGuardrailToPartialOutputStream({ + baseStream: partialOutputStream, + guardrail: speculativeInputGuardrail, + }) as typeof result.partialOutputStream; }; const createMergedUIStream = ( @@ -2706,7 +2798,7 @@ export class Agent { return result.finishReason; }, get partialOutputStream() { - return result.partialOutputStream; + return getGuardrailAwarePartialOutputStream(); }, toUIMessageStream: toUIMessageStreamSanitized as typeof result.toUIMessageStream, toUIMessageStreamResponse: @@ -4886,6 +4978,9 @@ export class Agent { const resolvedMemory = this.resolveMemoryRuntimeOptions(options, oc); const canIUseMemory = Boolean(resolvedMemory.userId); const shouldPersistMemory = resolvedMemory.readOnly !== true; + const speculativeInputGuardrail = this.getSpeculativeInputGuardrail(oc); + const shouldPersistInputImmediately = + shouldPersistMemory && (!speculativeInputGuardrail || speculativeInputGuardrail.hasPassed()); const memoryContextMessages: UIMessage[] = []; // Load memory context if available (already returns UIMessages) @@ -4965,7 +5060,7 @@ export class Agent { oc.userId, oc.conversationId, resolvedMemory.contextLimit, - { persistInput: shouldPersistMemory }, + { persistInput: shouldPersistInputImmediately }, ); // Update conversation ID @@ -4976,6 +5071,18 @@ export class Agent { buffer.ingestUIMessages(result.messages, true); + if ( + shouldPersistMemory && + speculativeInputGuardrail && + !shouldPersistInputImmediately + ) { + this.queueSaveInputWhenSpeculativeInputGuardrailPasses( + speculativeInputGuardrail, + oc, + inputForMemory, + ); + } + return result.messages; }); @@ -5008,7 +5115,15 @@ export class Agent { : Array.isArray(resolvedInput) && (resolvedInput as any[])[0]?.parts ? (resolvedInput as UIMessage[]) : convertModelMessagesToUIMessages(resolvedInput as BaseMessage[]); - this.memoryManager.queueSaveInput(oc, inputForMemory, oc.userId, oc.conversationId); + if (!speculativeInputGuardrail || speculativeInputGuardrail.hasPassed()) { + this.memoryManager.queueSaveInput(oc, inputForMemory, oc.userId, oc.conversationId); + } else { + this.queueSaveInputWhenSpeculativeInputGuardrailPasses( + speculativeInputGuardrail, + oc, + inputForMemory, + ); + } } catch (_e) { // Non-fatal: background persistence should not block message preparation } @@ -5159,6 +5274,24 @@ export class Agent { } } + private queueSaveInputWhenSpeculativeInputGuardrailPasses( + guardrail: SpeculativeInputGuardrailRun, + oc: OperationContext, + inputForMemory: string | UIMessage[], + ): void { + void guardrail + .wait() + .then((decision) => { + if (decision.status !== "passed" || !oc.userId || !oc.conversationId) { + return; + } + this.memoryManager.queueSaveInput(oc, inputForMemory, oc.userId, oc.conversationId); + }) + .catch((error) => { + oc.logger?.debug?.("Failed to persist input after speculative guardrail", { error }); + }); + } + /** * Get system message with dynamic instructions and retriever context */ @@ -6456,6 +6589,7 @@ export class Agent { if (execute && isAsyncGeneratorFunction(execute)) { return async function* (this: Agent): AsyncGenerator { try { + await this.waitForSpeculativeInputGuardrail(oc); await oc.traceContext.withSpan(toolSpan, async () => { await runToolStartHooks(); }); @@ -6516,6 +6650,7 @@ export class Agent { return oc.traceContext.withSpan(toolSpan, async () => { try { + await this.waitForSpeculativeInputGuardrail(oc); // Call tool start hook - can throw ToolDeniedError await runToolStartHooks(); @@ -7229,6 +7364,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 { + 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 */ @@ -7239,6 +7394,7 @@ export class Agent { const conversationPersistence = this.getConversationPersistenceOptionsForContext(oc); return async (event: StepResult) => { + const speculativeInputGuardrail = this.getSpeculativeInputGuardrail(oc); const { shouldFlushForToolCompletion, bailedResult } = this.processStepContent(oc, event); const responseMessages = this.normalizeStepResponseMessages( @@ -7255,7 +7411,10 @@ export class Agent { conversationPersistence.flushOnToolResult && (shouldFlushForToolCompletion || Boolean(bailedResult)); - if (conversationPersistence.mode === "step") { + if ( + conversationPersistence.mode === "step" && + (!speculativeInputGuardrail || speculativeInputGuardrail.hasPassed()) + ) { await this.recordStepResults(undefined, oc, { awaitPersistence: shouldFlushStepPersistence, }); @@ -7264,6 +7423,7 @@ export class Agent { if ( shouldPersistMemory && persistQueue && + (!speculativeInputGuardrail || speculativeInputGuardrail.hasPassed()) && conversationPersistence.mode === "step" && (hasResponseMessages || shouldFlushStepPersistence) ) { diff --git a/packages/core/src/agent/context-keys.ts b/packages/core/src/agent/context-keys.ts index 8141d2cbf..5c6c2c493 100644 --- a/packages/core/src/agent/context-keys.ts +++ b/packages/core/src/agent/context-keys.ts @@ -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"); diff --git a/packages/core/src/agent/conversation-buffer.spec.ts b/packages/core/src/agent/conversation-buffer.spec.ts index 39d380545..b05808d21 100644 --- a/packages/core/src/agent/conversation-buffer.spec.ts +++ b/packages/core/src/agent/conversation-buffer.spec.ts @@ -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"); + }); }); diff --git a/packages/core/src/agent/conversation-buffer.ts b/packages/core/src/agent/conversation-buffer.ts index 04ba65238..02e428c6f 100644 --- a/packages/core/src/agent/conversation-buffer.ts +++ b/packages/core/src/agent/conversation-buffer.ts @@ -12,6 +12,12 @@ interface PendingMessage { message: UIMessage; } +export interface ConversationBufferCheckpoint { + messages: UIMessage[]; + pendingMessageIds: string[]; + activeAssistantMessageId?: string; +} + const extractOpenAIItemId = (metadata: unknown): string => { if (!metadata || typeof metadata !== "object") { return ""; @@ -111,6 +117,25 @@ export class ConversationBuffer { } } + createCheckpoint(): ConversationBufferCheckpoint { + return { + messages: this.messages.map((message) => this.cloneMessage(message)), + pendingMessageIds: Array.from(this.pendingMessageIds), + activeAssistantMessageId: this.activeAssistantMessageId, + }; + } + + restoreCheckpoint(checkpoint: ConversationBufferCheckpoint): void { + this.messages = checkpoint.messages.map((message) => this.cloneMessage(message)); + this.pendingMessageIds = new Set(checkpoint.pendingMessageIds); + this.activeAssistantMessageId = checkpoint.activeAssistantMessageId; + this.rebuildToolPartIndex(); + this.log("restore-checkpoint", { + count: this.messages.length, + pending: this.pendingMessageIds.size, + }); + } + drainPendingMessages(): UIMessage[] { if (this.pendingMessageIds.size === 0) { return []; @@ -371,6 +396,13 @@ export class ConversationBuffer { } } + private rebuildToolPartIndex(): void { + this.toolPartIndex.clear(); + for (let index = 0; index < this.messages.length; index++) { + this.registerToolParts(index); + } + } + private findLastAssistantIndex(options?: { pendingOnly?: boolean }): number { for (let i = this.messages.length - 1; i >= 0; i--) { if (this.messages[i].role === "assistant") { diff --git a/packages/core/src/agent/guardrail.integration.spec.ts b/packages/core/src/agent/guardrail.integration.spec.ts index fcba10de4..0bc47265f 100644 --- a/packages/core/src/agent/guardrail.integration.spec.ts +++ b/packages/core/src/agent/guardrail.integration.spec.ts @@ -1,7 +1,9 @@ import { describe, expect, it, vi } from "vitest"; +import { Memory } from "../memory"; +import { InMemoryStorageAdapter } from "../memory/adapters/storage/in-memory"; import { convertUsage } from "../utils/usage-converter"; import { Agent } from "./agent"; -import { createOutputGuardrail } from "./guardrail"; +import { createInputGuardrail, createOutputGuardrail } from "./guardrail"; import type { VoltAgentTextStreamPart } from "./subagent/types"; import { collectStream, @@ -13,6 +15,30 @@ import { import type { OutputGuardrailStreamArgs } from "./types"; describe("Agent guardrail integration", () => { + const createStreamingModel = (text: string) => + createMockLanguageModel({ + doStream: () => ({ + stream: convertArrayToReadableStream([ + { type: "text-start" as const, id: "text-1" }, + { + type: "text-delta" as const, + id: "text-1", + delta: text, + text, + }, + { + type: "finish" as const, + finishReason: "stop", + usage: defaultMockResponse.usage, + totalUsage: defaultMockResponse.usage, + }, + ]), + rawCall: { rawPrompt: null, rawSettings: {} }, + usage: Promise.resolve(defaultMockResponse.usage), + warnings: [], + }), + }); + it("sanitizes generateText output and forwards metadata to guardrails", async () => { const primaryGuardrail = createOutputGuardrail({ id: "funding-filter", @@ -157,4 +183,275 @@ describe("Agent guardrail integration", () => { expect(normalizedUsage).toEqual(convertUsage(defaultMockResponse.usage)); expect(callArgs.finishReason).toBe("stop"); }); + + it("holds streamed output until parallel input guardrails pass", async () => { + let releaseGuardrail!: () => void; + let markGuardrailStarted!: () => void; + const guardrailStarted = new Promise((resolve) => { + markGuardrailStarted = resolve; + }); + const inputGuardrail = createInputGuardrail({ + name: "async-input-check", + execution: "parallel", + handler: vi.fn(async () => { + markGuardrailStarted(); + await new Promise((release) => { + releaseGuardrail = release; + }); + return { pass: true }; + }), + }); + + const model = createMockLanguageModel({ + doStream: { + stream: convertArrayToReadableStream([ + { type: "text-start" as const, id: "text-1" }, + { + type: "text-delta" as const, + id: "text-1", + delta: "guarded output", + text: "guarded output", + }, + { + type: "finish" as const, + finishReason: "stop", + usage: defaultMockResponse.usage, + totalUsage: defaultMockResponse.usage, + }, + ]), + rawCall: { rawPrompt: null, rawSettings: {} }, + usage: Promise.resolve(defaultMockResponse.usage), + warnings: [], + }, + }); + + const agent = new Agent({ + name: "Parallel Guardrail Agent", + instructions: "Stream response.", + model, + inputGuardrails: [inputGuardrail], + }); + + const streamResult = await agent.streamText("hello"); + const textPromise = collectTextStream(streamResult.textStream); + await guardrailStarted; + releaseGuardrail(); + await expect(textPromise).resolves.toBe("guarded output"); + }); + + it("replaces blocked parallel input streams and skips assistant memory persistence", async () => { + let releaseGuardrail!: () => void; + let markGuardrailStarted!: () => void; + const guardrailStarted = new Promise((resolve) => { + markGuardrailStarted = resolve; + }); + const inputGuardrail = createInputGuardrail({ + name: "async-blocker", + execution: "parallel", + handler: vi.fn(async () => { + markGuardrailStarted(); + await new Promise((release) => { + releaseGuardrail = release; + }); + return { pass: false, action: "block", message: "Blocked by async input guardrail." }; + }), + }); + + const model = createMockLanguageModel({ + doStream: { + stream: convertArrayToReadableStream([ + { type: "text-start" as const, id: "text-1" }, + { + type: "text-delta" as const, + id: "text-1", + delta: "unsafe model output", + text: "unsafe model output", + }, + { + type: "finish" as const, + finishReason: "stop", + usage: defaultMockResponse.usage, + totalUsage: defaultMockResponse.usage, + }, + ]), + rawCall: { rawPrompt: null, rawSettings: {} }, + usage: Promise.resolve(defaultMockResponse.usage), + warnings: [], + }, + }); + + const memory = new Memory({ + storage: new InMemoryStorageAdapter(), + }); + const saveSpy = vi.spyOn(memory, "saveMessageWithContext"); + const agent = new Agent({ + name: "Blocking Parallel Guardrail Agent", + instructions: "Stream response.", + model, + memory, + inputGuardrails: [inputGuardrail], + }); + + const streamResult = await agent.streamText("hello", { + userId: "user-1", + conversationId: "conv-1", + }); + const textPromise = collectTextStream(streamResult.textStream); + + await guardrailStarted; + releaseGuardrail(); + + await expect(textPromise).resolves.toBe("Blocked by async input guardrail."); + await expect(streamResult.text).resolves.toBe("Blocked by async input guardrail."); + expect(saveSpy).not.toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ role: "assistant" }), + ); + const savedMessages = await memory.getMessages("user-1", "conv-1"); + expect(savedMessages.some((message) => message.role === "assistant")).toBe(false); + }); + + it("replaces blocked parallel input full and UI streams", async () => { + const inputGuardrail = createInputGuardrail({ + id: "input-policy", + name: "async-stream-blocker", + severity: "critical", + execution: "parallel", + handler: vi.fn(async () => ({ + pass: false, + action: "block", + message: "Input blocked before display.", + })), + }); + + const agent = new Agent({ + name: "Blocked Stream Surfaces Agent", + instructions: "Stream response.", + model: createStreamingModel("unsafe model output"), + inputGuardrails: [inputGuardrail], + }); + + const fullStreamResult = await agent.streamText("hello"); + const fullChunks = await collectStream>( + fullStreamResult.fullStream, + ); + const fullStreamText = fullChunks + .filter((chunk) => chunk.type === "text-delta") + .map((chunk) => chunk.delta ?? chunk.text ?? "") + .join(""); + expect(fullStreamText).toBe("Input blocked before display."); + expect(fullStreamText).not.toContain("unsafe model output"); + expect(fullChunks.some((chunk) => chunk.type === "finish")).toBe(true); + const fullFinish = fullChunks.find((chunk) => chunk.type === "finish"); + expect(fullFinish).toMatchObject({ finishReason: "error" }); + const fullBlockEvent = fullChunks.find( + (chunk) => chunk.type === "input-guardrail-blocked", + ) as any; + expect(fullBlockEvent?.data).toMatchObject({ + code: "GUARDRAIL_INPUT_BLOCKED", + reason: "input_guardrail_blocked", + message: "Input blocked before display.", + guardrailId: "input-policy", + guardrailName: "async-stream-blocker", + severity: "critical", + }); + + const uiStreamResult = await agent.streamText("hello"); + const uiChunks = await collectStream(uiStreamResult.toUIMessageStream()); + const uiStreamText = uiChunks + .filter((chunk) => chunk.type === "text-delta") + .map((chunk) => chunk.delta ?? "") + .join(""); + expect(uiStreamText).toBe("Input blocked before display."); + expect(uiStreamText).not.toContain("unsafe model output"); + expect(uiChunks.some((chunk) => chunk.type === "finish")).toBe(true); + const uiFinish = uiChunks.find((chunk) => chunk.type === "finish"); + expect(uiFinish).toMatchObject({ finishReason: "error" }); + const uiBlockEvent = uiChunks.find((chunk) => chunk.type === "data-input-guardrail-blocked"); + expect(uiBlockEvent?.data).toMatchObject({ + code: "GUARDRAIL_INPUT_BLOCKED", + reason: "input_guardrail_blocked", + message: "Input blocked before display.", + guardrailId: "input-policy", + guardrailName: "async-stream-blocker", + severity: "critical", + }); + }); + + it("keeps parallel input block messages ahead of output guardrail transforms", async () => { + let releaseGuardrail!: () => void; + let markGuardrailStarted!: () => void; + const guardrailStarted = new Promise((resolve) => { + markGuardrailStarted = resolve; + }); + const inputGuardrail = createInputGuardrail({ + name: "async-input-blocker", + execution: "parallel", + handler: vi.fn(async () => { + markGuardrailStarted(); + await new Promise((release) => { + releaseGuardrail = release; + }); + return { pass: false, action: "block", message: "Input policy blocked this request." }; + }), + }); + const outputGuardrail = createOutputGuardrail({ + name: "output-transform", + handler: vi.fn(async ({ outputText }) => ({ + pass: true, + action: "modify", + modifiedOutput: `output transformed: ${outputText}`, + })), + streamHandler: ({ part }: OutputGuardrailStreamArgs) => { + if (part.type !== "text-delta") { + return part; + } + return { + ...part, + text: "output transformed", + delta: "output transformed", + }; + }, + }); + + const model = createMockLanguageModel({ + doStream: { + stream: convertArrayToReadableStream([ + { type: "text-start" as const, id: "text-1" }, + { + type: "text-delta" as const, + id: "text-1", + delta: "model output", + text: "model output", + }, + { + type: "finish" as const, + finishReason: "stop", + usage: defaultMockResponse.usage, + totalUsage: defaultMockResponse.usage, + }, + ]), + rawCall: { rawPrompt: null, rawSettings: {} }, + usage: Promise.resolve(defaultMockResponse.usage), + warnings: [], + }, + }); + + const agent = new Agent({ + name: "Input Override Agent", + instructions: "Stream response.", + model, + inputGuardrails: [inputGuardrail], + outputGuardrails: [outputGuardrail], + }); + + const streamResult = await agent.streamText("hello"); + const textPromise = collectTextStream(streamResult.textStream); + + await guardrailStarted; + releaseGuardrail(); + + await expect(textPromise).resolves.toBe("Input policy blocked this request."); + await expect(streamResult.text).resolves.toBe("Input policy blocked this request."); + }); }); diff --git a/packages/core/src/agent/guardrail.spec.ts b/packages/core/src/agent/guardrail.spec.ts index e61ea49a7..56d3107d1 100644 --- a/packages/core/src/agent/guardrail.spec.ts +++ b/packages/core/src/agent/guardrail.spec.ts @@ -127,6 +127,25 @@ describe("guardrail helpers", () => { 2, ); expect(guardrails[0].name).toBe("Input Guardrail #3"); + expect(guardrails[0].execution).toBe("blocking"); + expect(guardrails[0].streamPolicy).toBe("holdUntilPass"); + }); + + it("normalizes parallel input guardrail settings", () => { + const guardrails = normalizeInputGuardrailList([ + createInputGuardrail({ + name: "parallel", + execution: "parallel", + streamPolicy: "holdUntilPass", + handler: vi.fn(async () => ({ pass: true })), + }), + ]); + + expect(guardrails[0]).toMatchObject({ + name: "parallel", + execution: "parallel", + streamPolicy: "holdUntilPass", + }); }); it("normalizes output guardrail list", () => { @@ -230,17 +249,48 @@ describe("guardrail helpers", () => { it("throws when guardrail blocks input", async () => { const guardrails: NormalizedInputGuardrail[] = [ { + id: "policy", name: "block", + severity: "critical", handler: vi.fn(async () => ({ pass: false, action: "block", message: "Blocked" })), }, ]; await expect( runInputGuardrails("bad", oc, guardrails, "generateText", agent), - ).rejects.toThrow(/Blocked/); + ).rejects.toMatchObject({ + message: "Blocked", + code: "GUARDRAIL_INPUT_BLOCKED", + metadata: { + guardrailId: "policy", + guardrailName: "block", + guardrailSeverity: "critical", + }, + }); expect(oc.isActive).toBe(false); expect(oc.traceContext.end).toHaveBeenCalledWith("error", expect.any(Error)); }); + + it("throws when parallel input guardrail tries to modify input", async () => { + const guardrails: NormalizedInputGuardrail[] = [ + { + name: "parallel-modify", + execution: "parallel", + handler: vi.fn(async () => ({ + pass: true, + action: "modify", + modifiedInput: "changed", + })), + }, + ]; + + await expect( + runInputGuardrails("original", oc, guardrails, "streamText", agent, { + allowModify: false, + }), + ).rejects.toThrow(/Parallel input guardrails can only allow or block/); + expect(oc.isActive).toBe(false); + }); }); describe("runOutputGuardrails", () => { @@ -390,12 +440,14 @@ describe("guardrail helpers", () => { id: "helper-input", name: "Helper Input Guardrail", severity: "warning", + execution: "parallel", handler: vi.fn(async () => ({ pass: true })), }); const [normalized] = normalizeInputGuardrailList([helperGuardrail]); expect(normalized.name).toBe("Helper Input Guardrail"); expect(normalized.severity).toBe("warning"); + expect(normalized.execution).toBe("parallel"); expect(normalized.handler).toBe(helperGuardrail.handler); }); diff --git a/packages/core/src/agent/guardrail.ts b/packages/core/src/agent/guardrail.ts index dc5c678e5..a6417e902 100644 --- a/packages/core/src/agent/guardrail.ts +++ b/packages/core/src/agent/guardrail.ts @@ -15,7 +15,10 @@ import type { GuardrailSeverity, InputGuardrail, InputGuardrailArgs, + InputGuardrailDefinition, + InputGuardrailExecution, InputGuardrailResult, + InputGuardrailStreamPolicy, OperationContext, OutputGuardrail, OutputGuardrailArgs, @@ -50,7 +53,11 @@ type CreateGuardrailDefinition< export type CreateInputGuardrailOptions = CreateGuardrailDefinition< InputGuardrailArgs, - InputGuardrailResult + InputGuardrailResult, + { + execution?: InputGuardrailExecution; + streamPolicy?: InputGuardrailStreamPolicy; + } >; export type CreateOutputGuardrailOptions = CreateGuardrailDefinition< @@ -67,6 +74,8 @@ export function createInputGuardrail(options: CreateInputGuardrailOptions): Inpu tags: options.tags, severity: options.severity, metadata: options.metadata, + execution: options.execution, + streamPolicy: options.streamPolicy, handler: options.handler, }; } @@ -91,7 +100,10 @@ export function createOutputGuardrail( export type NormalizedInputGuardrail = NormalizedGuardrail< InputGuardrailArgs, InputGuardrailResult ->; +> & { + execution?: InputGuardrailExecution; + streamPolicy?: InputGuardrailStreamPolicy; +}; export type NormalizedOutputGuardrail = NormalizedGuardrail< OutputGuardrailArgs, @@ -153,13 +165,20 @@ export function normalizeInputGuardrailList( guardrails: InputGuardrail[], startIndex = 0, ): NormalizedInputGuardrail[] { - return guardrails.map((guardrail, index) => - normalizeGuardrailDefinition( + return guardrails.map((guardrail, index) => { + const normalized = normalizeGuardrailDefinition( guardrail, "input", startIndex + index, - ), - ); + ) as NormalizedInputGuardrail; + const descriptor = + typeof guardrail === "function" ? undefined : (guardrail as InputGuardrailDefinition); + + normalized.execution = descriptor?.execution ?? "blocking"; + normalized.streamPolicy = descriptor?.streamPolicy ?? "holdUntilPass"; + + return normalized; + }); } export function normalizeOutputGuardrailList( @@ -271,6 +290,7 @@ export async function runInputGuardrails( guardrails: NormalizedInputGuardrail[], operation: AgentEvalOperationType, agent: Agent, + options: { allowModify?: boolean } = {}, ): Promise { if (!guardrails.length) { return input; @@ -342,7 +362,14 @@ export async function runInputGuardrails( if (!pass || action === "block") { const message = resolvedDecision.message ?? "Input blocked by guardrail"; - const guardrailError = createVoltAgentError(message, { code: "GUARDRAIL_INPUT_BLOCKED" }); + const guardrailError = createVoltAgentError(message, { + code: "GUARDRAIL_INPUT_BLOCKED", + metadata: { + ...(guardrail.id ? { guardrailId: guardrail.id } : {}), + guardrailName: guardrail.name, + ...(guardrail.severity ? { guardrailSeverity: guardrail.severity } : {}), + }, + }); span.setStatus({ code: SpanStatusCode.ERROR, message }); span.end(); oc.isActive = false; @@ -351,6 +378,17 @@ export async function runInputGuardrails( } if (action === "modify" && resolvedDecision.modifiedInput !== undefined) { + if (options.allowModify === false) { + const message = `Input guardrail "${guardrail.name}" returned a modified input during parallel execution. Parallel input guardrails can only allow or block.`; + const guardrailError = createVoltAgentError(message, { + code: "GUARDRAIL_INPUT_MODIFY_UNSUPPORTED", + }); + span.setStatus({ code: SpanStatusCode.ERROR, message }); + span.end(); + oc.isActive = false; + oc.traceContext.end("error", guardrailError); + throw guardrailError; + } currentInput = resolvedDecision.modifiedInput; currentInputText = await extractInputTextForGuardrail(currentInput); } diff --git a/packages/core/src/agent/streaming/input-guardrail-stream.ts b/packages/core/src/agent/streaming/input-guardrail-stream.ts new file mode 100644 index 000000000..908087c5c --- /dev/null +++ b/packages/core/src/agent/streaming/input-guardrail-stream.ts @@ -0,0 +1,389 @@ +import type { AsyncIterableStream, UIMessage, UIMessageChunk } from "ai"; +import type { Agent } from "../agent"; +import type { ConversationBuffer } from "../conversation-buffer"; +import { createVoltAgentError } from "../errors"; +import { type NormalizedInputGuardrail, runInputGuardrails } from "../guardrail"; +import type { BaseMessage } from "../providers/base/types"; +import type { InputGuardrailBlockedEventData, VoltAgentTextStreamPart } from "../subagent/types"; +import type { AgentEvalOperationType, OperationContext } from "../types"; +import { createAsyncIterableReadable } from "./guardrail-stream"; + +const DEFAULT_INPUT_GUARDRAIL_BLOCK_MESSAGE = "Input blocked by guardrail."; +export const INPUT_GUARDRAIL_BLOCKED_FULL_STREAM_PART_TYPE = "input-guardrail-blocked" as const; +export const INPUT_GUARDRAIL_BLOCKED_UI_EVENT_TYPE = "data-input-guardrail-blocked" as const; +const ZERO_USAGE = { + inputTokens: 0, + outputTokens: 0, + totalTokens: 0, +} as const; +const DEFAULT_MAX_BUFFERED_CHUNKS = 1024; + +type InputGuardrailBlockedUIStreamChunk = + | { type: "start"; messageId?: string } + | { + type: typeof INPUT_GUARDRAIL_BLOCKED_UI_EVENT_TYPE; + data: InputGuardrailBlockedEventData; + } + | { type: "text-start"; id: string } + | { type: "text-delta"; id: string; delta: string } + | { type: "text-end"; id: string } + | { type: "finish"; finishReason: "error" }; + +export type SpeculativeInputGuardrailDecision = + | { status: "passed" } + | { + status: "blocked"; + error: Error; + message: string; + data: InputGuardrailBlockedEventData; + }; + +export class SpeculativeInputGuardrailRun { + private decision: SpeculativeInputGuardrailDecision | null = null; + private blockHandled = false; + private readonly promise: Promise; + + constructor( + private readonly params: { + input: string | UIMessage[] | BaseMessage[]; + operationContext: OperationContext; + guardrails: NormalizedInputGuardrail[]; + operation: AgentEvalOperationType; + agent: Agent; + buffer: ConversationBuffer; + onBlock?: ( + decision: Extract, + ) => void; + }, + ) { + const checkpoint = params.buffer.createCheckpoint(); + + this.promise = runInputGuardrails( + params.input, + params.operationContext, + params.guardrails, + params.operation, + params.agent, + { allowModify: false }, + ) + .then(() => { + this.decision = { status: "passed" }; + return this.decision; + }) + .catch((errorValue) => { + const error = + errorValue instanceof Error + ? errorValue + : createVoltAgentError(String(errorValue), { code: "GUARDRAIL_INPUT_BLOCKED" }); + const message = error.message || DEFAULT_INPUT_GUARDRAIL_BLOCK_MESSAGE; + const decision: SpeculativeInputGuardrailDecision = { + status: "blocked", + error, + message, + data: createInputGuardrailBlockedEventData(error, message), + }; + this.decision = decision; + this.handleBlock(decision, checkpoint); + return decision; + }); + } + + wait(): Promise { + return this.promise; + } + + getDecision(): SpeculativeInputGuardrailDecision | null { + return this.decision; + } + + hasPassed(): boolean { + return this.decision?.status === "passed"; + } + + hasBlocked(): boolean { + return this.decision?.status === "blocked"; + } + + private handleBlock( + decision: Extract, + checkpoint: ReturnType, + ): void { + if (this.blockHandled) { + return; + } + + this.blockHandled = true; + this.params.buffer.restoreCheckpoint(checkpoint); + this.params.onBlock?.(decision); + + if (!this.params.operationContext.abortController.signal.aborted) { + this.params.operationContext.abortController.abort(decision.error); + } + } +} + +export function applySpeculativeInputGuardrailToFullStream(params: { + baseStream: AsyncIterable; + guardrail: SpeculativeInputGuardrailRun | null; + responseMessageId?: string; +}): AsyncIterable { + if (!params.guardrail) { + return params.baseStream; + } + return gateIterableUntilSpeculativeInputPass({ + source: params.baseStream, + guardrail: params.guardrail, + replacement: (decision) => + createInputGuardrailBlockedFullStreamParts(decision.data, params.responseMessageId), + }); +} + +export function applySpeculativeInputGuardrailToTextStream(params: { + baseStream: AsyncIterableStream; + guardrail: SpeculativeInputGuardrailRun | null; +}): AsyncIterableStream { + if (!params.guardrail) { + return params.baseStream; + } + return iterableToStream( + gateIterableUntilSpeculativeInputPass({ + source: params.baseStream, + guardrail: params.guardrail, + replacement: (decision) => [decision.message], + }), + ); +} + +export function applySpeculativeInputGuardrailToUIStream< + TStream extends AsyncIterable, +>(params: { + baseStream: TStream; + guardrail: SpeculativeInputGuardrailRun | null; + responseMessageId?: string; +}): TStream { + if (!params.guardrail) { + return params.baseStream; + } + type UIStreamChunk = TStream extends AsyncIterable ? Chunk : never; + + return iterableToStream( + gateIterableUntilSpeculativeInputPass({ + source: params.baseStream as AsyncIterable, + guardrail: params.guardrail, + replacement: (decision) => + createInputGuardrailBlockedUIStreamChunks( + decision.data, + params.responseMessageId, + ) as UIStreamChunk[], + }), + ) as unknown as TStream; +} + +export function applySpeculativeInputGuardrailToPartialOutputStream< + TStream extends AsyncIterableStream, +>(params: { + baseStream: TStream; + guardrail: SpeculativeInputGuardrailRun | null; +}): TStream { + if (!params.guardrail) { + return params.baseStream; + } + type StreamChunk = TStream extends AsyncIterable ? Chunk : never; + + return iterableToStream( + gateIterableUntilSpeculativeInputPass({ + source: params.baseStream as AsyncIterable, + guardrail: params.guardrail, + replacement: () => [], + }), + ) as unknown as TStream; +} + +export async function* gateIterableUntilSpeculativeInputPass(params: { + source: AsyncIterable; + guardrail: SpeculativeInputGuardrailRun; + replacement: (decision: Extract) => T[]; + maxBufferedChunks?: number; +}): AsyncIterable { + const immediateDecision = params.guardrail.getDecision(); + if (immediateDecision?.status === "passed") { + yield* params.source; + return; + } + if (immediateDecision?.status === "blocked") { + yield* params.replacement(immediateDecision); + return; + } + + const iterator = params.source[Symbol.asyncIterator](); + const buffered: T[] = []; + const maxBufferedChunks = params.maxBufferedChunks ?? DEFAULT_MAX_BUFFERED_CHUNKS; + let nextPromise = iterator.next(); + + while (true) { + const result = await Promise.race([ + nextPromise.then( + (value) => ({ type: "chunk" as const, value }), + (error) => ({ type: "source-error" as const, error }), + ), + params.guardrail.wait().then((decision) => ({ type: "decision" as const, decision })), + ]); + + if (result.type === "decision") { + if (result.decision.status === "blocked") { + await iterator.return?.(); + yield* params.replacement(result.decision); + return; + } + + for (const item of buffered) { + yield item; + } + yield* continueIterator(iterator, nextPromise); + return; + } + + if (result.type === "source-error") { + const decision = params.guardrail.getDecision(); + if (decision?.status === "blocked") { + yield* params.replacement(decision); + return; + } + throw result.error; + } + + if (result.value.done) { + const decision = await params.guardrail.wait(); + if (decision.status === "blocked") { + yield* params.replacement(decision); + return; + } + for (const item of buffered) { + yield item; + } + return; + } + + buffered.push(result.value.value); + if (maxBufferedChunks > 0 && buffered.length >= maxBufferedChunks) { + const decision = await params.guardrail.wait(); + if (decision.status === "blocked") { + await iterator.return?.(); + yield* params.replacement(decision); + return; + } + for (const item of buffered) { + yield item; + } + yield* continueIterator(iterator, iterator.next()); + return; + } + + nextPromise = iterator.next(); + } +} + +export function createInputGuardrailBlockedFullStreamParts( + data: InputGuardrailBlockedEventData, + responseMessageId?: string, +): VoltAgentTextStreamPart[] { + const textId = "input-guardrail-blocked"; + return [ + { + type: "start", + ...(responseMessageId ? { messageId: responseMessageId } : {}), + } as VoltAgentTextStreamPart, + { + type: INPUT_GUARDRAIL_BLOCKED_FULL_STREAM_PART_TYPE, + data, + ...(responseMessageId ? { messageId: responseMessageId } : {}), + } as VoltAgentTextStreamPart, + { type: "text-start", id: textId } as VoltAgentTextStreamPart, + { + type: "text-delta", + id: textId, + text: data.message, + } as VoltAgentTextStreamPart, + { type: "text-end", id: textId } as VoltAgentTextStreamPart, + { + type: "finish", + finishReason: "error", + rawFinishReason: "guardrail_input_blocked", + totalUsage: ZERO_USAGE, + } as VoltAgentTextStreamPart, + ]; +} + +export function createInputGuardrailBlockedUIStreamChunks( + data: InputGuardrailBlockedEventData, + responseMessageId?: string, +): InputGuardrailBlockedUIStreamChunk[] { + const textId = "input-guardrail-blocked"; + return [ + { + type: "start", + ...(responseMessageId ? { messageId: responseMessageId } : {}), + }, + { + type: INPUT_GUARDRAIL_BLOCKED_UI_EVENT_TYPE, + data, + }, + { type: "text-start", id: textId }, + { type: "text-delta", id: textId, delta: data.message }, + { type: "text-end", id: textId }, + { type: "finish", finishReason: "error" }, + ] satisfies UIMessageChunk[]; +} + +function createInputGuardrailBlockedEventData( + error: Error, + message: string, +): InputGuardrailBlockedEventData { + const metadata = + "metadata" in error && error.metadata && typeof error.metadata === "object" + ? (error.metadata as Record) + : {}; + + return { + code: "GUARDRAIL_INPUT_BLOCKED", + reason: "input_guardrail_blocked", + message, + ...stringProperty(metadata.guardrailId, "guardrailId"), + ...stringProperty(metadata.guardrailName, "guardrailName"), + ...severityProperty(metadata.guardrailSeverity), + }; +} + +function stringProperty(value: unknown, key: "guardrailId" | "guardrailName") { + return typeof value === "string" && value.length > 0 ? { [key]: value } : {}; +} + +function severityProperty( + value: unknown, +): Pick | Record { + return value === "info" || value === "warning" || value === "critical" ? { severity: value } : {}; +} + +async function* continueIterator( + iterator: AsyncIterator, + firstNextPromise: Promise>, +): AsyncIterable { + let next = await firstNextPromise; + while (!next.done) { + yield next.value; + next = await iterator.next(); + } +} + +function iterableToStream(iterable: AsyncIterable): AsyncIterableStream { + return createAsyncIterableReadable(async (controller) => { + try { + for await (const item of iterable) { + controller.enqueue(item); + } + controller.close(); + } catch (error) { + controller.error(error); + } + }); +} diff --git a/packages/core/src/agent/subagent/index.spec.ts b/packages/core/src/agent/subagent/index.spec.ts index 20b5404d7..e5a6bcc64 100644 --- a/packages/core/src/agent/subagent/index.spec.ts +++ b/packages/core/src/agent/subagent/index.spec.ts @@ -572,6 +572,14 @@ describe("SubAgentManager", () => { const mockStream = createMockStream([ mockStreamEvents.toolCall("call-1", "toolA", { foo: "bar" }), mockStreamEvents.toolResult("call-1", "toolA", { ok: true }), + { + type: "input-guardrail-blocked" as const, + data: { + code: "GUARDRAIL_INPUT_BLOCKED" as const, + reason: "input_guardrail_blocked" as const, + message: "Blocked by policy", + }, + }, ]); vi.spyOn(subAgent, "streamText").mockResolvedValue({ @@ -599,6 +607,14 @@ describe("SubAgentManager", () => { expect(toolCallPart.parentAgentId).toBe("parent-agent"); expect(toolCallPart.parentAgentName).toBe("Parent Agent"); expect(toolCallPart.agentPath).toEqual(["Parent Agent", "Sub-Agent A"]); + + const guardrailPart = forwarded.find((part) => part.type === "input-guardrail-blocked"); + expect(guardrailPart?.data).toMatchObject({ + code: "GUARDRAIL_INPUT_BLOCKED", + reason: "input_guardrail_blocked", + message: "Blocked by policy", + }); + expect(guardrailPart?.subAgentId).toBe("sub-agent-a"); }); }); diff --git a/packages/core/src/agent/subagent/index.ts b/packages/core/src/agent/subagent/index.ts index 2ed79d573..878d87653 100644 --- a/packages/core/src/agent/subagent/index.ts +++ b/packages/core/src/agent/subagent/index.ts @@ -619,7 +619,11 @@ ${task}\n\nContext: ${safeStringify(contextObj, { indentation: 2 })}`; const enrichedStream = createMetadataEnrichedStream( subagentUIStream, forwardingMetadata, - this.supervisorConfig?.fullStreamEventForwarding?.types || ["tool-call", "tool-result"], + this.supervisorConfig?.fullStreamEventForwarding?.types || [ + "tool-call", + "tool-result", + "input-guardrail-blocked", + ], ); // Use the writer to merge the enriched stream @@ -650,6 +654,7 @@ ${task}\n\nContext: ${safeStringify(contextObj, { indentation: 2 })}`; const allowedTypes = this.supervisorConfig?.fullStreamEventForwarding?.types || [ "tool-call", "tool-result", + "input-guardrail-blocked", ]; // Write subagent's fullStream events with metadata diff --git a/packages/core/src/agent/subagent/stream-metadata-enricher.ts b/packages/core/src/agent/subagent/stream-metadata-enricher.ts index 4d14bc37c..75413edc4 100644 --- a/packages/core/src/agent/subagent/stream-metadata-enricher.ts +++ b/packages/core/src/agent/subagent/stream-metadata-enricher.ts @@ -2,7 +2,7 @@ * Stream transformer that adds metadata to all parts in a UI message stream */ -import type { TextStreamPart } from "ai"; +import type { VoltAgentTextStreamPart } from "./types"; /** * Type for AI SDK's AsyncIterableStream (both AsyncIterable and ReadableStream) @@ -10,9 +10,9 @@ import type { TextStreamPart } from "ai"; export type AsyncIterableStream = AsyncIterable & ReadableStream; /** - * Stream event type from AI SDK + * Stream event type from VoltAgent's extended AI SDK stream parts */ -export type StreamEventType = TextStreamPart["type"]; +export type StreamEventType = VoltAgentTextStreamPart["type"]; /** * Metadata to be added to stream parts diff --git a/packages/core/src/agent/subagent/types.ts b/packages/core/src/agent/subagent/types.ts index b5ddbb15a..cbeeaf3b6 100644 --- a/packages/core/src/agent/subagent/types.ts +++ b/packages/core/src/agent/subagent/types.ts @@ -131,52 +131,72 @@ export function createSubagent( return config; } +export interface InputGuardrailBlockedEventData { + code: "GUARDRAIL_INPUT_BLOCKED"; + reason: "input_guardrail_blocked"; + message: string; + guardrailId?: string; + guardrailName?: string; + severity?: "info" | "warning" | "critical"; +} + +export interface InputGuardrailBlockedStreamPart { + type: "input-guardrail-blocked"; + data: InputGuardrailBlockedEventData; + messageId?: string; +} + +type VoltAgentStreamMetadata = { + /** + * Optional response message identifier (carried on start/step chunks). + */ + messageId?: string; + + /** + * Optional identifier for the subagent that generated this event + */ + subAgentId?: string; + + /** + * Optional identifier for the agent that actually executed the step + * (same as subAgentId for first-level handoffs) + */ + executingAgentId?: string; + + /** + * Optional name of the subagent that generated this event + */ + subAgentName?: string; + + /** + * Optional name of the agent that actually executed the step + * (same as subAgentName for first-level handoffs) + */ + executingAgentName?: string; + + /** + * Parent agent reference when forwarded through supervisors + */ + parentAgentId?: string; + parentAgentName?: string; + + /** + * Ordered list of agent names from supervisor -> executing agent + */ + agentPath?: string[]; +}; + /** - * Extended TextStreamPart type that includes optional subagent metadata. - * This type extends ai-sdk's TextStreamPart to support subagent event forwarding. + * Extended TextStreamPart type that includes optional VoltAgent metadata and + * custom VoltAgent stream events. * * @template TOOLS - The tool set type parameter from ai-sdk */ -export type VoltAgentTextStreamPart = Record> = - TextStreamPart & { - /** - * Optional response message identifier (carried on start/step chunks). - */ - messageId?: string; - - /** - * Optional identifier for the subagent that generated this event - */ - subAgentId?: string; - - /** - * Optional identifier for the agent that actually executed the step - * (same as subAgentId for first-level handoffs) - */ - executingAgentId?: string; - - /** - * Optional name of the subagent that generated this event - */ - subAgentName?: string; - - /** - * Optional name of the agent that actually executed the step - * (same as subAgentName for first-level handoffs) - */ - executingAgentName?: string; - - /** - * Parent agent reference when forwarded through supervisors - */ - parentAgentId?: string; - parentAgentName?: string; - - /** - * Ordered list of agent names from supervisor -> executing agent - */ - agentPath?: string[]; - }; +export type VoltAgentTextStreamPart = Record> = ( + | TextStreamPart + | InputGuardrailBlockedStreamPart +) & + VoltAgentStreamMetadata; /** * Extended StreamTextResult that uses VoltAgentTextStreamPart for fullStream. diff --git a/packages/core/src/agent/types.ts b/packages/core/src/agent/types.ts index 55a01958f..24ea5a84d 100644 --- a/packages/core/src/agent/types.ts +++ b/packages/core/src/agent/types.ts @@ -13,7 +13,7 @@ import type { } from "../agent/providers/base/types"; import type { PrepareStep, StopWhen } from "../ai-types"; -import type { LanguageModel, TextStreamPart, UIMessage } from "ai"; +import type { LanguageModel, UIMessage } from "ai"; import type { Memory } from "../memory"; import type { BaseRetriever } from "../retriever/retriever"; import type { ProviderTool, Tool, Toolkit, VercelTool } from "../tool"; @@ -317,10 +317,9 @@ export type ProviderOptions = LegacyProviderCallOptions & { * Configuration for supervisor agents that have subagents */ /** - * StreamEventType derived from AI SDK's TextStreamPart - * Includes all event types from AI SDK + * StreamEventType derived from VoltAgent's extended AI SDK stream parts. */ -export type StreamEventType = TextStreamPart["type"]; +export type StreamEventType = VoltAgentTextStreamPart["type"]; /** * Configuration for forwarding events from subagents to the parent agent's stream @@ -328,14 +327,15 @@ export type StreamEventType = TextStreamPart["type"]; export type FullStreamEventForwardingConfig = { /** * Array of event types to forward from subagents - * Uses AI SDK's TextStreamPart types: + * Uses VoltAgent's extended AI SDK stream part types: * - Text: 'text-start', 'text-end', 'text-delta' * - Reasoning: 'reasoning-start', 'reasoning-end', 'reasoning-delta' * - Tool: 'tool-input-start', 'tool-input-end', 'tool-input-delta', * 'tool-call', 'tool-result', 'tool-error' + * - Guardrails: 'input-guardrail-blocked' * - Other: 'source', 'file', 'start-step', 'finish-step', * 'start', 'finish', 'abort', 'error', 'raw' - * @default ['tool-call', 'tool-result'] + * @default ['tool-call', 'tool-result', 'input-guardrail-blocked'] * @example ['tool-call', 'tool-result', 'text-delta'] */ types?: StreamEventType[]; @@ -363,7 +363,7 @@ export type SupervisorConfig = { /** * Configuration for forwarding events from subagents to the parent agent's full stream * Controls which event types are forwarded - * @default { types: ['tool-call', 'tool-result'] } + * @default { types: ['tool-call', 'tool-result', 'input-guardrail-blocked'] } */ fullStreamEventForwarding?: FullStreamEventForwardingConfig; @@ -393,6 +393,10 @@ export type GuardrailSeverity = "info" | "warning" | "critical"; export type GuardrailAction = "allow" | "modify" | "block"; +export type InputGuardrailExecution = "blocking" | "parallel"; + +export type InputGuardrailStreamPolicy = "holdUntilPass"; + export interface GuardrailBaseResult { pass: boolean; action?: GuardrailAction; @@ -487,6 +491,23 @@ export interface InputGuardrailResult extends GuardrailBaseResult { modifiedInput?: string | UIMessage[] | BaseMessage[]; } +export interface InputGuardrailDefinition + extends GuardrailDefinition { + /** + * Controls when the input guardrail runs. + * + * - `blocking` runs before the agent starts, preserving support for modified input. + * - `parallel` starts with the agent stream and may only allow or block. + */ + execution?: InputGuardrailExecution; + /** + * Streaming policy for parallel input guardrails. + * + * `holdUntilPass` buffers model stream chunks until all parallel input guardrails pass. + */ + streamPolicy?: InputGuardrailStreamPolicy; +} + export interface OutputGuardrailArgs extends GuardrailContext { /** * The latest value after any previous guardrail modifications. @@ -522,7 +543,9 @@ export interface OutputGuardrailResult extends GuardrailBaseR modifiedOutput?: TOutput; } -export type InputGuardrail = GuardrailConfig; +export type InputGuardrail = + | GuardrailFunction + | InputGuardrailDefinition; export type OutputGuardrailFunction = GuardrailFunction< OutputGuardrailArgs, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e3a382259..b22b821ee 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -64,6 +64,8 @@ export type { GenerateTextSubAgentConfig, StreamObjectSubAgentConfig, GenerateObjectSubAgentConfig, + InputGuardrailBlockedEventData, + InputGuardrailBlockedStreamPart, VoltAgentTextStreamPart, VoltAgentStreamTextResult, } from "./agent/subagent/types"; diff --git a/packages/core/src/utils/streams/types.ts b/packages/core/src/utils/streams/types.ts index 37d7e35f7..37a73868d 100644 --- a/packages/core/src/utils/streams/types.ts +++ b/packages/core/src/utils/streams/types.ts @@ -1,16 +1,15 @@ -import type { TextStreamPart } from "ai"; +import type { VoltAgentTextStreamPart } from "../../agent/subagent/types"; /** - * StreamEventType derived from AI SDK's TextStreamPart - * This gives us all event types from AI SDK + * StreamEventType derived from VoltAgent's extended AI SDK stream parts. */ -export type StreamEventType = TextStreamPart["type"]; +export type StreamEventType = VoltAgentTextStreamPart["type"]; /** - * StreamEvent is an extended version of TextStreamPart that includes subagent metadata + * StreamEvent is an extended version of VoltAgentTextStreamPart that includes subagent metadata * for event forwarding in supervisor agents */ -export type StreamEvent = TextStreamPart & { +export type StreamEvent = VoltAgentTextStreamPart & { // Additional metadata for subagent event forwarding subAgentId?: string; subAgentName?: string; diff --git a/website/docs/guardrails/overview.md b/website/docs/guardrails/overview.md index 478c57900..c05271909 100644 --- a/website/docs/guardrails/overview.md +++ b/website/docs/guardrails/overview.md @@ -460,6 +460,131 @@ Input guardrails receive input in three possible formats: The `inputText` property contains the extracted plain text from any of these formats. +#### Execution Modes + +Input guardrails run in `blocking` mode by default. Blocking guardrails complete before the model starts and can allow, modify, or block the input. + +For `streamText`, you can opt into parallel execution for async checks that should run while the model starts: + +```ts +const policyGuardrail = createInputGuardrail({ + id: "policy-check", + name: "Policy Check", + execution: "parallel", + streamPolicy: "holdUntilPass", + handler: async ({ inputText }) => { + const allowed = await checkInputWithPolicyModel(inputText); + if (!allowed) { + return { + pass: false, + action: "block", + message: "This request cannot be answered.", + }; + } + + return { pass: true }; + }, +}); +``` + +Parallel input guardrails buffer stream output until they pass. If one blocks, VoltAgent stops the stream, returns the guardrail message instead, and prevents the generated assistant output from being persisted to conversation memory. + +Parallel input guardrails can only allow or block. Use the default blocking mode when a guardrail needs to return `action: "modify"` with `modifiedInput`. + +#### UI Handling for Parallel Input Blocks + +When you return `agent.streamText(...).toUIMessageStreamResponse()`, blocked parallel input guardrails emit a structured `data-input-guardrail-blocked` event and then send replacement assistant text. The UI does not need a separate stream error path, and `useChat` can render the message like any other assistant response. + +```ts +// app/api/chat/route.ts +export async function POST(req: Request) { + const { messages } = await req.json(); + const result = await agent.streamText(messages, { + userId: "user-123", + conversationId: "support-thread", + }); + + return result.toUIMessageStreamResponse(); +} +``` + +```tsx +import { useChat } from "@ai-sdk/react"; +import type { InputGuardrailBlockedEventData } from "@voltagent/core"; +import { DefaultChatTransport, type UIMessage } from "ai"; + +type ChatMessage = UIMessage< + unknown, + { + "input-guardrail-blocked": InputGuardrailBlockedEventData; + } +>; + +const translations = { + "errors.inputBlocked": "Your request cannot be processed.", +}; + +function messageState(message: ChatMessage) { + const blocked = message.parts?.some((part) => part.type === "data-input-guardrail-blocked"); + const text = + message.parts + ?.filter((part) => part.type === "text") + .map((part) => part.text ?? "") + .join("") ?? ""; + + return { + blocked, + text: blocked ? translations["errors.inputBlocked"] : text, + }; +} + +export function Chat() { + const { messages, sendMessage, status } = useChat({ + transport: new DefaultChatTransport({ api: "/api/chat" }), + }); + + return ( +
+ {messages.map((message) => { + const { blocked, text } = messageState(message); + + return ( +
+ {blocked ? Request blocked : null} +

{text}

+
+ ); + })} + + +
+ ); +} +``` + +The data event contains a stable `code` and `reason`, plus the fallback message and optional guardrail identifiers: + +```ts +{ + type: "data-input-guardrail-blocked", + data: { + code: "GUARDRAIL_INPUT_BLOCKED", + reason: "input_guardrail_blocked", + message: "This request cannot be answered.", + guardrailId: "policy-check", + guardrailName: "Policy Check", + severity: "critical" + } +} +``` + +For custom `fullStream` consumers, listen for the `input-guardrail-blocked` part for structured metadata and handle the replacement like normal text deltas. Blocked full streams finish with `finishReason: "error"` after emitting the guardrail message. + ### Step-by-Step Tutorial #### 1. Simple Blocking Guardrail: Content Filter @@ -606,7 +731,7 @@ const agent = new Agent({ }); ``` -Input guardrails execute in order before the input reaches the model. If any guardrail blocks the input, execution stops and an error is thrown. +Input guardrails execute in order before the input reaches the model unless a guardrail opts into `execution: "parallel"` for `streamText`. If any blocking guardrail blocks the input, execution stops and an error is thrown. ### Testing Input Guardrails @@ -655,6 +780,17 @@ interface InputGuardrailResult { } ``` +#### InputGuardrailDefinition + +Additional options supported by `createInputGuardrail()`: + +```ts +interface InputGuardrailDefinition { + execution?: "blocking" | "parallel"; // Default: "blocking" + streamPolicy?: "holdUntilPass"; // Default: "holdUntilPass" +} +``` + ## Next Steps Review the ready-made guardrail helpers in [Built-in Guardrails](./built-in.md).