From 0557489f265c8af27d9eda83433b571b0e863d01 Mon Sep 17 00:00:00 2001 From: Omer Date: Mon, 22 Jun 2026 18:58:01 -0700 Subject: [PATCH 1/6] feat(core): add parallel input guardrails --- .changeset/parallel-input-guardrails.md | 5 + packages/core/src/agent/agent.ts | 358 +++++++++++++++++- .../src/agent/conversation-buffer.spec.ts | 31 ++ .../core/src/agent/conversation-buffer.ts | 32 ++ .../src/agent/guardrail.integration.spec.ts | 208 +++++++++- packages/core/src/agent/guardrail.spec.ts | 42 ++ packages/core/src/agent/guardrail.ts | 43 ++- packages/core/src/agent/types.ts | 25 +- website/docs/guardrails/overview.md | 44 ++- 9 files changed, 772 insertions(+), 16 deletions(-) create mode 100644 .changeset/parallel-input-guardrails.md diff --git a/.changeset/parallel-input-guardrails.md b/.changeset/parallel-input-guardrails.md new file mode 100644 index 000000000..5c33d07b4 --- /dev/null +++ b/.changeset/parallel-input-guardrails.md @@ -0,0 +1,5 @@ +--- +"@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. diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index df3f7a64c..7186fb41e 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -218,7 +218,9 @@ const ABORT_LISTENER_ATTACHED_KEY = Symbol("abortListenerAttached"); const MIDDLEWARE_RETRY_FEEDBACK_KEY = Symbol("middlewareRetryFeedback"); const STREAM_RESPONSE_MESSAGE_ID_KEY = Symbol("streamResponseMessageId"); const STEP_RESPONSE_MESSAGE_FINGERPRINTS_KEY = Symbol("stepResponseMessageFingerprints"); +const SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY = Symbol("speculativeInputGuardrail"); const DEFAULT_FEEDBACK_KEY = "satisfaction"; +const DEFAULT_INPUT_GUARDRAIL_BLOCK_MESSAGE = "Input blocked by guardrail."; const DEFAULT_CONVERSATION_TITLE_PROMPT = [ "You generate concise titles for new conversations.", "Summarize the user's first message in a short phrase.", @@ -241,6 +243,214 @@ const DEFAULT_CONVERSATION_PERSISTENCE_OPTIONS: ResolvedConversationPersistenceO flushOnToolResult: true, }; +type SpeculativeInputGuardrailDecision = + | { status: "passed" } + | { status: "blocked"; error: Error; message: string }; + +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 = executeInputGuardrails( + 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, + }; + 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); + } + } +} + +async function* gateIterableUntilSpeculativeInputPass(params: { + source: AsyncIterable; + guardrail: SpeculativeInputGuardrailRun; + replacement: (decision: Extract) => T[]; +}): 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[] = []; + 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); + nextPromise = iterator.next(); + } +} + +async function* continueIterator( + iterator: AsyncIterator, + firstNextPromise: Promise>, +): AsyncIterable { + let next = await firstNextPromise; + while (!next.done) { + yield next.value; + next = await iterator.next(); + } +} + +function createInputGuardrailBlockedFullStreamParts( + message: string, + responseMessageId?: string, +): VoltAgentTextStreamPart[] { + const textId = "input-guardrail-blocked"; + return [ + { + type: "start", + ...(responseMessageId ? { messageId: responseMessageId } : {}), + } as VoltAgentTextStreamPart, + { type: "text-start", id: textId } as VoltAgentTextStreamPart, + { + type: "text-delta", + id: textId, + delta: message, + text: message, + } as VoltAgentTextStreamPart, + { type: "text-end", id: textId } as VoltAgentTextStreamPart, + { + type: "finish", + finishReason: "error", + } as VoltAgentTextStreamPart, + ]; +} + +function createInputGuardrailBlockedUIStreamChunks( + message: string, + responseMessageId?: string, +): any[] { + const textId = "input-guardrail-blocked"; + return [ + { + type: "start", + ...(responseMessageId ? { messageId: responseMessageId } : {}), + }, + { type: "text-start", id: textId }, + { type: "text-delta", id: textId, delta: message }, + { type: "text-end", id: textId }, + { type: "finish" }, + ]; +} + type ResolvedMessageMetadataPersistenceOptions = { usage: boolean; finishReason: boolean; @@ -1803,6 +2013,7 @@ export class Agent { resolveFeedbackDeferred(null); } let effectiveInput: typeof input = input; + let speculativeInputGuardrail: SpeculativeInputGuardrailRun | null = null; try { while (true) { try { @@ -1852,14 +2063,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); + } + // No need to initialize stream collection anymore - we'll use UIMessageStreamWriter const { messages, uiMessages, modelName, tools, maxSteps } = await this.prepareExecution( @@ -2138,6 +2371,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, @@ -2508,11 +2748,87 @@ export class Agent { } : null; + const toAsyncIterableStreamFromIterable = (iterable: AsyncIterable) => + createAsyncIterableReadable(async (controller) => { + try { + for await (const item of iterable) { + controller.enqueue(item); + } + controller.close(); + } catch (error) { + controller.error(error); + } + }); + + const applySpeculativeInputGuardrailToFullStream = ( + baseStream: AsyncIterable, + ): AsyncIterable => { + if (!speculativeInputGuardrail) { + return baseStream; + } + return gateIterableUntilSpeculativeInputPass({ + source: baseStream, + guardrail: speculativeInputGuardrail, + replacement: (decision) => + createInputGuardrailBlockedFullStreamParts( + decision.message, + responseMessageId ?? undefined, + ), + }); + }; + + const applySpeculativeInputGuardrailToTextStream = ( + baseStream: AsyncIterable, + ): AsyncIterableStream => { + if (!speculativeInputGuardrail) { + return baseStream as AsyncIterableStream; + } + return toAsyncIterableStreamFromIterable( + gateIterableUntilSpeculativeInputPass({ + source: baseStream, + guardrail: speculativeInputGuardrail, + replacement: (decision) => [decision.message], + }), + ); + }; + + const applySpeculativeInputGuardrailToUIStream = ( + baseStream: ToUIMessageStreamReturn, + ): ToUIMessageStreamReturn => { + if (!speculativeInputGuardrail) { + return baseStream; + } + return toAsyncIterableStreamFromIterable( + gateIterableUntilSpeculativeInputPass({ + source: baseStream as AsyncIterable, + guardrail: speculativeInputGuardrail, + replacement: (decision) => + createInputGuardrailBlockedUIStreamChunks( + decision.message, + responseMessageId ?? undefined, + ) as UIStreamChunk[], + }), + ) as ToUIMessageStreamReturn; + }; + const baseFullStreamForPipeline = guardrailStreamingEnabled ? createBaseFullStream() : 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 +2879,29 @@ export class Agent { const getGuardrailAwareFullStream = (): AsyncIterable => { if (guardrailPipeline) { - return guardrailPipeline.fullStream; + return applySpeculativeInputGuardrailToFullStream(guardrailPipeline.fullStream); } - return createBaseFullStream(); + return applySpeculativeInputGuardrailToFullStream(createBaseFullStream()); }; const getGuardrailAwareTextStream = (): AsyncIterableStream => { if (guardrailPipeline) { - return guardrailPipeline.textStream; + return applySpeculativeInputGuardrailToTextStream(guardrailPipeline.textStream); } - return result.textStream; + return applySpeculativeInputGuardrailToTextStream(result.textStream); }; const getGuardrailAwareUIStream = ( streamOptions?: ToUIMessageStreamOptions, ): ToUIMessageStreamReturn => { if (!guardrailPipeline) { - return result.toUIMessageStream(streamOptions); + return applySpeculativeInputGuardrailToUIStream( + result.toUIMessageStream(streamOptions), + ); } - return guardrailPipeline.createUIStream(streamOptions) as ToUIMessageStreamReturn; + return applySpeculativeInputGuardrailToUIStream( + guardrailPipeline.createUIStream(streamOptions) as ToUIMessageStreamReturn, + ); }; const createMergedUIStream = ( @@ -6456,6 +6776,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 +6837,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 +7551,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 +7581,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( @@ -7264,6 +7607,7 @@ export class Agent { if ( shouldPersistMemory && persistQueue && + (!speculativeInputGuardrail || speculativeInputGuardrail.hasPassed()) && conversationPersistence.mode === "step" && (hasResponseMessages || shouldFlushStepPersistence) ) { 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..bab483402 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, @@ -157,4 +159,208 @@ 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("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..1a8042016 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", () => { @@ -241,6 +260,27 @@ describe("guardrail helpers", () => { 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 +430,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..7585c0c55 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; @@ -351,6 +371,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/types.ts b/packages/core/src/agent/types.ts index 55a01958f..a9fd736b6 100644 --- a/packages/core/src/agent/types.ts +++ b/packages/core/src/agent/types.ts @@ -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/website/docs/guardrails/overview.md b/website/docs/guardrails/overview.md index 478c57900..b3ea405fb 100644 --- a/website/docs/guardrails/overview.md +++ b/website/docs/guardrails/overview.md @@ -460,6 +460,37 @@ 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`. + ### Step-by-Step Tutorial #### 1. Simple Blocking Guardrail: Content Filter @@ -606,7 +637,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 +686,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). From 4ff390006b60fffebd7669363f15b1cca3718cba Mon Sep 17 00:00:00 2001 From: Omer Date: Mon, 22 Jun 2026 19:41:00 -0700 Subject: [PATCH 2/6] refactor(core): harden parallel input guardrails --- .changeset/parallel-input-guardrails.md | 10 + packages/core/src/agent/agent.spec.ts | 82 +++++ packages/core/src/agent/agent.ts | 318 ++---------------- packages/core/src/agent/context-keys.ts | 1 + .../src/agent/guardrail.integration.spec.ts | 65 ++++ .../agent/streaming/input-guardrail-stream.ts | 289 ++++++++++++++++ website/docs/guardrails/overview.md | 64 ++++ 7 files changed, 546 insertions(+), 283 deletions(-) create mode 100644 packages/core/src/agent/streaming/input-guardrail-stream.ts diff --git a/.changeset/parallel-input-guardrails.md b/.changeset/parallel-input-guardrails.md index 5c33d07b4..161e736af 100644 --- a/.changeset/parallel-input-guardrails.md +++ b/.changeset/parallel-input-guardrails.md @@ -3,3 +3,13 @@ --- 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); +``` 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 7186fb41e..ef9e04897 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,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"; @@ -218,9 +225,7 @@ const ABORT_LISTENER_ATTACHED_KEY = Symbol("abortListenerAttached"); const MIDDLEWARE_RETRY_FEEDBACK_KEY = Symbol("middlewareRetryFeedback"); const STREAM_RESPONSE_MESSAGE_ID_KEY = Symbol("streamResponseMessageId"); const STEP_RESPONSE_MESSAGE_FINGERPRINTS_KEY = Symbol("stepResponseMessageFingerprints"); -const SPECULATIVE_INPUT_GUARDRAIL_CONTEXT_KEY = Symbol("speculativeInputGuardrail"); const DEFAULT_FEEDBACK_KEY = "satisfaction"; -const DEFAULT_INPUT_GUARDRAIL_BLOCK_MESSAGE = "Input blocked by guardrail."; const DEFAULT_CONVERSATION_TITLE_PROMPT = [ "You generate concise titles for new conversations.", "Summarize the user's first message in a short phrase.", @@ -243,214 +248,6 @@ const DEFAULT_CONVERSATION_PERSISTENCE_OPTIONS: ResolvedConversationPersistenceO flushOnToolResult: true, }; -type SpeculativeInputGuardrailDecision = - | { status: "passed" } - | { status: "blocked"; error: Error; message: string }; - -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 = executeInputGuardrails( - 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, - }; - 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); - } - } -} - -async function* gateIterableUntilSpeculativeInputPass(params: { - source: AsyncIterable; - guardrail: SpeculativeInputGuardrailRun; - replacement: (decision: Extract) => T[]; -}): 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[] = []; - 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); - nextPromise = iterator.next(); - } -} - -async function* continueIterator( - iterator: AsyncIterator, - firstNextPromise: Promise>, -): AsyncIterable { - let next = await firstNextPromise; - while (!next.done) { - yield next.value; - next = await iterator.next(); - } -} - -function createInputGuardrailBlockedFullStreamParts( - message: string, - responseMessageId?: string, -): VoltAgentTextStreamPart[] { - const textId = "input-guardrail-blocked"; - return [ - { - type: "start", - ...(responseMessageId ? { messageId: responseMessageId } : {}), - } as VoltAgentTextStreamPart, - { type: "text-start", id: textId } as VoltAgentTextStreamPart, - { - type: "text-delta", - id: textId, - delta: message, - text: message, - } as VoltAgentTextStreamPart, - { type: "text-end", id: textId } as VoltAgentTextStreamPart, - { - type: "finish", - finishReason: "error", - } as VoltAgentTextStreamPart, - ]; -} - -function createInputGuardrailBlockedUIStreamChunks( - message: string, - responseMessageId?: string, -): any[] { - const textId = "input-guardrail-blocked"; - return [ - { - type: "start", - ...(responseMessageId ? { messageId: responseMessageId } : {}), - }, - { type: "text-start", id: textId }, - { type: "text-delta", id: textId, delta: message }, - { type: "text-end", id: textId }, - { type: "finish" }, - ]; -} - type ResolvedMessageMetadataPersistenceOptions = { usage: boolean; finishReason: boolean; @@ -2748,69 +2545,6 @@ export class Agent { } : null; - const toAsyncIterableStreamFromIterable = (iterable: AsyncIterable) => - createAsyncIterableReadable(async (controller) => { - try { - for await (const item of iterable) { - controller.enqueue(item); - } - controller.close(); - } catch (error) { - controller.error(error); - } - }); - - const applySpeculativeInputGuardrailToFullStream = ( - baseStream: AsyncIterable, - ): AsyncIterable => { - if (!speculativeInputGuardrail) { - return baseStream; - } - return gateIterableUntilSpeculativeInputPass({ - source: baseStream, - guardrail: speculativeInputGuardrail, - replacement: (decision) => - createInputGuardrailBlockedFullStreamParts( - decision.message, - responseMessageId ?? undefined, - ), - }); - }; - - const applySpeculativeInputGuardrailToTextStream = ( - baseStream: AsyncIterable, - ): AsyncIterableStream => { - if (!speculativeInputGuardrail) { - return baseStream as AsyncIterableStream; - } - return toAsyncIterableStreamFromIterable( - gateIterableUntilSpeculativeInputPass({ - source: baseStream, - guardrail: speculativeInputGuardrail, - replacement: (decision) => [decision.message], - }), - ); - }; - - const applySpeculativeInputGuardrailToUIStream = ( - baseStream: ToUIMessageStreamReturn, - ): ToUIMessageStreamReturn => { - if (!speculativeInputGuardrail) { - return baseStream; - } - return toAsyncIterableStreamFromIterable( - gateIterableUntilSpeculativeInputPass({ - source: baseStream as AsyncIterable, - guardrail: speculativeInputGuardrail, - replacement: (decision) => - createInputGuardrailBlockedUIStreamChunks( - decision.message, - responseMessageId ?? undefined, - ) as UIStreamChunk[], - }), - ) as ToUIMessageStreamReturn; - }; - const baseFullStreamForPipeline = guardrailStreamingEnabled ? createBaseFullStream() : undefined; @@ -2879,29 +2613,47 @@ export class Agent { const getGuardrailAwareFullStream = (): AsyncIterable => { if (guardrailPipeline) { - return applySpeculativeInputGuardrailToFullStream(guardrailPipeline.fullStream); + return applySpeculativeInputGuardrailToFullStream({ + baseStream: guardrailPipeline.fullStream, + guardrail: speculativeInputGuardrail, + responseMessageId: responseMessageId ?? undefined, + }); } - return applySpeculativeInputGuardrailToFullStream(createBaseFullStream()); + return applySpeculativeInputGuardrailToFullStream({ + baseStream: createBaseFullStream(), + guardrail: speculativeInputGuardrail, + responseMessageId: responseMessageId ?? undefined, + }); }; const getGuardrailAwareTextStream = (): AsyncIterableStream => { if (guardrailPipeline) { - return applySpeculativeInputGuardrailToTextStream(guardrailPipeline.textStream); + return applySpeculativeInputGuardrailToTextStream({ + baseStream: guardrailPipeline.textStream, + guardrail: speculativeInputGuardrail, + }); } - return applySpeculativeInputGuardrailToTextStream(result.textStream); + return applySpeculativeInputGuardrailToTextStream({ + baseStream: result.textStream, + guardrail: speculativeInputGuardrail, + }); }; const getGuardrailAwareUIStream = ( streamOptions?: ToUIMessageStreamOptions, ): ToUIMessageStreamReturn => { if (!guardrailPipeline) { - return applySpeculativeInputGuardrailToUIStream( - result.toUIMessageStream(streamOptions), - ); + return applySpeculativeInputGuardrailToUIStream({ + baseStream: result.toUIMessageStream(streamOptions), + guardrail: speculativeInputGuardrail, + responseMessageId: responseMessageId ?? undefined, + }); } - return applySpeculativeInputGuardrailToUIStream( - guardrailPipeline.createUIStream(streamOptions) as ToUIMessageStreamReturn, - ); + return applySpeculativeInputGuardrailToUIStream({ + baseStream: guardrailPipeline.createUIStream(streamOptions) as ToUIMessageStreamReturn, + guardrail: speculativeInputGuardrail, + responseMessageId: responseMessageId ?? undefined, + }); }; const createMergedUIStream = ( 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/guardrail.integration.spec.ts b/packages/core/src/agent/guardrail.integration.spec.ts index bab483402..f90d6893f 100644 --- a/packages/core/src/agent/guardrail.integration.spec.ts +++ b/packages/core/src/agent/guardrail.integration.spec.ts @@ -15,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", @@ -287,6 +311,47 @@ describe("Agent guardrail integration", () => { expect(savedMessages.some((message) => message.role === "assistant")).toBe(false); }); + it("replaces blocked parallel input full and UI streams", async () => { + const inputGuardrail = createInputGuardrail({ + name: "async-stream-blocker", + 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 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); + }); + it("keeps parallel input block messages ahead of output guardrail transforms", async () => { let releaseGuardrail!: () => void; let markGuardrailStarted!: () => void; 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..e85a60a5b --- /dev/null +++ b/packages/core/src/agent/streaming/input-guardrail-stream.ts @@ -0,0 +1,289 @@ +import type { AsyncIterableStream, UIMessage } 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 { 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 type SpeculativeInputGuardrailDecision = + | { status: "passed" } + | { status: "blocked"; error: Error; message: string }; + +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, + }; + 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.message, params.responseMessageId), + }); +} + +export function applySpeculativeInputGuardrailToTextStream(params: { + baseStream: AsyncIterable; + guardrail: SpeculativeInputGuardrailRun | null; +}): AsyncIterableStream { + if (!params.guardrail) { + return params.baseStream as AsyncIterableStream; + } + 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.message, + params.responseMessageId, + ) as UIStreamChunk[], + }), + ) as unknown as TStream; +} + +export async function* gateIterableUntilSpeculativeInputPass(params: { + source: AsyncIterable; + guardrail: SpeculativeInputGuardrailRun; + replacement: (decision: Extract) => T[]; +}): 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[] = []; + 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); + nextPromise = iterator.next(); + } +} + +export function createInputGuardrailBlockedFullStreamParts( + message: string, + responseMessageId?: string, +): VoltAgentTextStreamPart[] { + const textId = "input-guardrail-blocked"; + return [ + { + type: "start", + ...(responseMessageId ? { messageId: responseMessageId } : {}), + } as VoltAgentTextStreamPart, + { type: "text-start", id: textId } as VoltAgentTextStreamPart, + { + type: "text-delta", + id: textId, + delta: message, + text: message, + } as VoltAgentTextStreamPart, + { type: "text-end", id: textId } as VoltAgentTextStreamPart, + { + type: "finish", + finishReason: "error", + } as VoltAgentTextStreamPart, + ]; +} + +export function createInputGuardrailBlockedUIStreamChunks( + message: string, + responseMessageId?: string, +): any[] { + const textId = "input-guardrail-blocked"; + return [ + { + type: "start", + ...(responseMessageId ? { messageId: responseMessageId } : {}), + }, + { type: "text-start", id: textId }, + { type: "text-delta", id: textId, delta: message }, + { type: "text-end", id: textId }, + { type: "finish" }, + ]; +} + +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/website/docs/guardrails/overview.md b/website/docs/guardrails/overview.md index b3ea405fb..80e92013b 100644 --- a/website/docs/guardrails/overview.md +++ b/website/docs/guardrails/overview.md @@ -491,6 +491,70 @@ Parallel input guardrails buffer stream output until they pass. If one blocks, V 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 are delivered as 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 { DefaultChatTransport } from "ai"; + +const INPUT_BLOCKED_MESSAGE = "This request cannot be answered."; + +function messageText(message: { parts?: Array<{ type: string; text?: string }> }) { + return ( + message.parts + ?.filter((part) => part.type === "text") + .map((part) => part.text ?? "") + .join("") ?? "" + ); +} + +export function Chat() { + const { messages, sendMessage, status } = useChat({ + transport: new DefaultChatTransport({ api: "/api/chat" }), + }); + + return ( +
+ {messages.map((message) => { + const text = messageText(message); + const blocked = message.role === "assistant" && text === INPUT_BLOCKED_MESSAGE; + + return ( +
+ {blocked ? Request blocked : null} +

{text}

+
+ ); + })} + + +
+ ); +} +``` + +For custom `fullStream` consumers, 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 From 6eb7ee48639be5cb3da1cbe03d77acea3f4d72a7 Mon Sep 17 00:00:00 2001 From: Omer Date: Mon, 22 Jun 2026 19:54:56 -0700 Subject: [PATCH 3/6] feat(core): emit input guardrail block events --- .changeset/parallel-input-guardrails.md | 6 +- .../src/agent/guardrail.integration.spec.ts | 22 ++++ packages/core/src/agent/guardrail.spec.ts | 12 +- packages/core/src/agent/guardrail.ts | 9 +- .../agent/streaming/input-guardrail-stream.ts | 64 +++++++++-- packages/core/src/agent/subagent/types.ts | 104 +++++++++++------- packages/core/src/index.ts | 2 + website/docs/guardrails/overview.md | 40 +++++-- 8 files changed, 193 insertions(+), 66 deletions(-) diff --git a/.changeset/parallel-input-guardrails.md b/.changeset/parallel-input-guardrails.md index 161e736af..e485b0117 100644 --- a/.changeset/parallel-input-guardrails.md +++ b/.changeset/parallel-input-guardrails.md @@ -4,12 +4,10 @@ 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: +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 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); + message.parts?.some((part) => part.type === "data-input-guardrail-blocked"); ``` diff --git a/packages/core/src/agent/guardrail.integration.spec.ts b/packages/core/src/agent/guardrail.integration.spec.ts index f90d6893f..41818611d 100644 --- a/packages/core/src/agent/guardrail.integration.spec.ts +++ b/packages/core/src/agent/guardrail.integration.spec.ts @@ -313,7 +313,9 @@ describe("Agent guardrail integration", () => { 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, @@ -340,6 +342,17 @@ describe("Agent guardrail integration", () => { expect(fullStreamText).toBe("Input blocked before display."); expect(fullStreamText).not.toContain("unsafe model output"); expect(fullChunks.some((chunk) => chunk.type === "finish")).toBe(true); + 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()); @@ -350,6 +363,15 @@ describe("Agent guardrail integration", () => { expect(uiStreamText).toBe("Input blocked before display."); expect(uiStreamText).not.toContain("unsafe model output"); expect(uiChunks.some((chunk) => chunk.type === "finish")).toBe(true); + 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 () => { diff --git a/packages/core/src/agent/guardrail.spec.ts b/packages/core/src/agent/guardrail.spec.ts index 1a8042016..56d3107d1 100644 --- a/packages/core/src/agent/guardrail.spec.ts +++ b/packages/core/src/agent/guardrail.spec.ts @@ -249,14 +249,24 @@ 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)); }); diff --git a/packages/core/src/agent/guardrail.ts b/packages/core/src/agent/guardrail.ts index 7585c0c55..a6417e902 100644 --- a/packages/core/src/agent/guardrail.ts +++ b/packages/core/src/agent/guardrail.ts @@ -362,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; diff --git a/packages/core/src/agent/streaming/input-guardrail-stream.ts b/packages/core/src/agent/streaming/input-guardrail-stream.ts index e85a60a5b..33fb7a9c9 100644 --- a/packages/core/src/agent/streaming/input-guardrail-stream.ts +++ b/packages/core/src/agent/streaming/input-guardrail-stream.ts @@ -4,15 +4,22 @@ 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 { VoltAgentTextStreamPart } from "../subagent/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; export type SpeculativeInputGuardrailDecision = | { status: "passed" } - | { status: "blocked"; error: Error; message: string }; + | { + status: "blocked"; + error: Error; + message: string; + data: InputGuardrailBlockedEventData; + }; export class SpeculativeInputGuardrailRun { private decision: SpeculativeInputGuardrailDecision | null = null; @@ -56,6 +63,7 @@ export class SpeculativeInputGuardrailRun { status: "blocked", error, message, + data: createInputGuardrailBlockedEventData(error, message), }; this.decision = decision; this.handleBlock(decision, checkpoint); @@ -109,7 +117,7 @@ export function applySpeculativeInputGuardrailToFullStream(params: { source: params.baseStream, guardrail: params.guardrail, replacement: (decision) => - createInputGuardrailBlockedFullStreamParts(decision.message, params.responseMessageId), + createInputGuardrailBlockedFullStreamParts(decision.data, params.responseMessageId), }); } @@ -147,7 +155,7 @@ export function applySpeculativeInputGuardrailToUIStream< guardrail: params.guardrail, replacement: (decision) => createInputGuardrailBlockedUIStreamChunks( - decision.message, + decision.data, params.responseMessageId, ) as UIStreamChunk[], }), @@ -223,7 +231,7 @@ export async function* gateIterableUntilSpeculativeInputPass(params: { } export function createInputGuardrailBlockedFullStreamParts( - message: string, + data: InputGuardrailBlockedEventData, responseMessageId?: string, ): VoltAgentTextStreamPart[] { const textId = "input-guardrail-blocked"; @@ -232,12 +240,17 @@ export function createInputGuardrailBlockedFullStreamParts( 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, - delta: message, - text: message, + delta: data.message, + text: data.message, } as VoltAgentTextStreamPart, { type: "text-end", id: textId } as VoltAgentTextStreamPart, { @@ -248,7 +261,7 @@ export function createInputGuardrailBlockedFullStreamParts( } export function createInputGuardrailBlockedUIStreamChunks( - message: string, + data: InputGuardrailBlockedEventData, responseMessageId?: string, ): any[] { const textId = "input-guardrail-blocked"; @@ -257,13 +270,46 @@ export function createInputGuardrailBlockedUIStreamChunks( type: "start", ...(responseMessageId ? { messageId: responseMessageId } : {}), }, + { + type: INPUT_GUARDRAIL_BLOCKED_UI_EVENT_TYPE, + data, + }, { type: "text-start", id: textId }, - { type: "text-delta", id: textId, delta: message }, + { type: "text-delta", id: textId, delta: data.message }, { type: "text-end", id: textId }, { type: "finish" }, ]; } +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>, 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/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/website/docs/guardrails/overview.md b/website/docs/guardrails/overview.md index 80e92013b..ee6587758 100644 --- a/website/docs/guardrails/overview.md +++ b/website/docs/guardrails/overview.md @@ -493,7 +493,7 @@ Parallel input guardrails can only allow or block. Use the default blocking mode #### UI Handling for Parallel Input Blocks -When you return `agent.streamText(...).toUIMessageStreamResponse()`, blocked parallel input guardrails are delivered as replacement assistant text. The UI does not need a separate stream error path, and `useChat` can render the message like any other assistant response. +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 @@ -512,15 +512,22 @@ export async function POST(req: Request) { import { useChat } from "@ai-sdk/react"; import { DefaultChatTransport } from "ai"; -const INPUT_BLOCKED_MESSAGE = "This request cannot be answered."; +const translations = { + "errors.inputBlocked": "Your request cannot be processed.", +}; -function messageText(message: { parts?: Array<{ type: string; text?: string }> }) { - return ( +function messageState(message: { parts?: Array<{ type: string; text?: string; data?: any }> }) { + 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("") ?? "" - ); + .join("") ?? ""; + + return { + blocked, + text: blocked ? translations["errors.inputBlocked"] : text, + }; } export function Chat() { @@ -531,8 +538,7 @@ export function Chat() { return (
{messages.map((message) => { - const text = messageText(message); - const blocked = message.role === "assistant" && text === INPUT_BLOCKED_MESSAGE; + const { blocked, text } = messageState(message); return (
@@ -553,7 +559,23 @@ export function Chat() { } ``` -For custom `fullStream` consumers, handle the replacement like normal text deltas. Blocked full streams finish with `finishReason: "error"` after emitting the guardrail message. +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 From c10afd96b2720858d2895918e055449fd77c5693 Mon Sep 17 00:00:00 2001 From: Omer Date: Mon, 22 Jun 2026 20:24:52 -0700 Subject: [PATCH 4/6] docs(core): align guardrail UI events with AI SDK --- .../core/src/agent/guardrail.integration.spec.ts | 4 ++++ .../src/agent/streaming/input-guardrail-stream.ts | 6 +++--- website/docs/guardrails/overview.md | 14 +++++++++++--- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/core/src/agent/guardrail.integration.spec.ts b/packages/core/src/agent/guardrail.integration.spec.ts index 41818611d..f1698a960 100644 --- a/packages/core/src/agent/guardrail.integration.spec.ts +++ b/packages/core/src/agent/guardrail.integration.spec.ts @@ -342,6 +342,8 @@ describe("Agent guardrail integration", () => { 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; @@ -363,6 +365,8 @@ describe("Agent guardrail integration", () => { 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", diff --git a/packages/core/src/agent/streaming/input-guardrail-stream.ts b/packages/core/src/agent/streaming/input-guardrail-stream.ts index 33fb7a9c9..2882745ea 100644 --- a/packages/core/src/agent/streaming/input-guardrail-stream.ts +++ b/packages/core/src/agent/streaming/input-guardrail-stream.ts @@ -1,4 +1,4 @@ -import type { AsyncIterableStream, UIMessage } from "ai"; +import type { AsyncIterableStream, UIMessage, UIMessageChunk } from "ai"; import type { Agent } from "../agent"; import type { ConversationBuffer } from "../conversation-buffer"; import { createVoltAgentError } from "../errors"; @@ -263,7 +263,7 @@ export function createInputGuardrailBlockedFullStreamParts( export function createInputGuardrailBlockedUIStreamChunks( data: InputGuardrailBlockedEventData, responseMessageId?: string, -): any[] { +): UIMessageChunk[] { const textId = "input-guardrail-blocked"; return [ { @@ -277,7 +277,7 @@ export function createInputGuardrailBlockedUIStreamChunks( { type: "text-start", id: textId }, { type: "text-delta", id: textId, delta: data.message }, { type: "text-end", id: textId }, - { type: "finish" }, + { type: "finish", finishReason: "error" }, ]; } diff --git a/website/docs/guardrails/overview.md b/website/docs/guardrails/overview.md index ee6587758..c05271909 100644 --- a/website/docs/guardrails/overview.md +++ b/website/docs/guardrails/overview.md @@ -510,13 +510,21 @@ export async function POST(req: Request) { ```tsx import { useChat } from "@ai-sdk/react"; -import { DefaultChatTransport } from "ai"; +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: { parts?: Array<{ type: string; text?: string; data?: any }> }) { +function messageState(message: ChatMessage) { const blocked = message.parts?.some((part) => part.type === "data-input-guardrail-blocked"); const text = message.parts @@ -531,7 +539,7 @@ function messageState(message: { parts?: Array<{ type: string; text?: string; da } export function Chat() { - const { messages, sendMessage, status } = useChat({ + const { messages, sendMessage, status } = useChat({ transport: new DefaultChatTransport({ api: "/api/chat" }), }); From 2c5844a2aebc8ed36b725542d2019d9e0159e2a7 Mon Sep 17 00:00:00 2001 From: Omer Date: Mon, 22 Jun 2026 20:30:29 -0700 Subject: [PATCH 5/6] fix(core): align guardrail stream forwarding --- .../agent/streaming/input-guardrail-stream.ts | 23 ++++++++++++++++--- .../core/src/agent/subagent/index.spec.ts | 16 +++++++++++++ packages/core/src/agent/subagent/index.ts | 7 +++++- .../subagent/stream-metadata-enricher.ts | 6 ++--- packages/core/src/agent/types.ts | 14 +++++------ packages/core/src/utils/streams/types.ts | 11 ++++----- 6 files changed, 57 insertions(+), 20 deletions(-) diff --git a/packages/core/src/agent/streaming/input-guardrail-stream.ts b/packages/core/src/agent/streaming/input-guardrail-stream.ts index 2882745ea..b1498745f 100644 --- a/packages/core/src/agent/streaming/input-guardrail-stream.ts +++ b/packages/core/src/agent/streaming/input-guardrail-stream.ts @@ -11,6 +11,22 @@ 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; + +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" } @@ -249,13 +265,14 @@ export function createInputGuardrailBlockedFullStreamParts( { type: "text-delta", id: textId, - delta: data.message, 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, ]; } @@ -263,7 +280,7 @@ export function createInputGuardrailBlockedFullStreamParts( export function createInputGuardrailBlockedUIStreamChunks( data: InputGuardrailBlockedEventData, responseMessageId?: string, -): UIMessageChunk[] { +): InputGuardrailBlockedUIStreamChunk[] { const textId = "input-guardrail-blocked"; return [ { @@ -278,7 +295,7 @@ export function createInputGuardrailBlockedUIStreamChunks( { type: "text-delta", id: textId, delta: data.message }, { type: "text-end", id: textId }, { type: "finish", finishReason: "error" }, - ]; + ] satisfies UIMessageChunk[]; } function createInputGuardrailBlockedEventData( 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/types.ts b/packages/core/src/agent/types.ts index a9fd736b6..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; 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; From e47be1e9f87eea3d8f050ecd89de183bcb5129bc Mon Sep 17 00:00:00 2001 From: Omer Date: Mon, 22 Jun 2026 20:37:48 -0700 Subject: [PATCH 6/6] fix(core): gate speculative guardrail side streams --- packages/core/src/agent/agent.ts | 72 +++++++++++++++++-- .../src/agent/guardrail.integration.spec.ts | 2 +- .../agent/streaming/input-guardrail-stream.ts | 41 ++++++++++- 3 files changed, 108 insertions(+), 7 deletions(-) diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index ef9e04897..c7fd9bb49 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -178,6 +178,7 @@ import { import { SpeculativeInputGuardrailRun, applySpeculativeInputGuardrailToFullStream, + applySpeculativeInputGuardrailToPartialOutputStream, applySpeculativeInputGuardrailToTextStream, applySpeculativeInputGuardrailToUIStream, } from "./streaming/input-guardrail-stream"; @@ -1743,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) { @@ -1789,6 +1791,10 @@ export class Agent { if (feedbackPromise) { feedbackPromise .then((metadata) => { + if (feedbackCancelled) { + resolveFeedbackDeferred(null); + return; + } feedbackMetadataValue = metadata; feedbackValue = metadata ? createFeedbackHandleHelper({ @@ -1884,6 +1890,9 @@ export class Agent { agent: this, buffer, onBlock: () => { + feedbackCancelled = true; + feedbackMetadataValue = null; + feedbackValue = null; resolveFeedbackDeferred(null); }, }); @@ -2656,6 +2665,17 @@ export class Agent { }); }; + 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 = ( streamOptions?: ToUIMessageStreamOptions, ): ToUIMessageStreamReturn => { @@ -2778,7 +2798,7 @@ export class Agent { return result.finishReason; }, get partialOutputStream() { - return result.partialOutputStream; + return getGuardrailAwarePartialOutputStream(); }, toUIMessageStream: toUIMessageStreamSanitized as typeof result.toUIMessageStream, toUIMessageStreamResponse: @@ -4958,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) @@ -5037,7 +5060,7 @@ export class Agent { oc.userId, oc.conversationId, resolvedMemory.contextLimit, - { persistInput: shouldPersistMemory }, + { persistInput: shouldPersistInputImmediately }, ); // Update conversation ID @@ -5048,6 +5071,18 @@ export class Agent { buffer.ingestUIMessages(result.messages, true); + if ( + shouldPersistMemory && + speculativeInputGuardrail && + !shouldPersistInputImmediately + ) { + this.queueSaveInputWhenSpeculativeInputGuardrailPasses( + speculativeInputGuardrail, + oc, + inputForMemory, + ); + } + return result.messages; }); @@ -5080,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 } @@ -5231,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 */ @@ -7350,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, }); diff --git a/packages/core/src/agent/guardrail.integration.spec.ts b/packages/core/src/agent/guardrail.integration.spec.ts index f1698a960..0bc47265f 100644 --- a/packages/core/src/agent/guardrail.integration.spec.ts +++ b/packages/core/src/agent/guardrail.integration.spec.ts @@ -357,7 +357,7 @@ describe("Agent guardrail integration", () => { }); const uiStreamResult = await agent.streamText("hello"); - const uiChunks = await collectStream(uiStreamResult.toUIMessageStream()); + const uiChunks = await collectStream(uiStreamResult.toUIMessageStream()); const uiStreamText = uiChunks .filter((chunk) => chunk.type === "text-delta") .map((chunk) => chunk.delta ?? "") diff --git a/packages/core/src/agent/streaming/input-guardrail-stream.ts b/packages/core/src/agent/streaming/input-guardrail-stream.ts index b1498745f..908087c5c 100644 --- a/packages/core/src/agent/streaming/input-guardrail-stream.ts +++ b/packages/core/src/agent/streaming/input-guardrail-stream.ts @@ -16,6 +16,7 @@ const ZERO_USAGE = { outputTokens: 0, totalTokens: 0, } as const; +const DEFAULT_MAX_BUFFERED_CHUNKS = 1024; type InputGuardrailBlockedUIStreamChunk = | { type: "start"; messageId?: string } @@ -138,11 +139,11 @@ export function applySpeculativeInputGuardrailToFullStream(params: { } export function applySpeculativeInputGuardrailToTextStream(params: { - baseStream: AsyncIterable; + baseStream: AsyncIterableStream; guardrail: SpeculativeInputGuardrailRun | null; }): AsyncIterableStream { if (!params.guardrail) { - return params.baseStream as AsyncIterableStream; + return params.baseStream; } return iterableToStream( gateIterableUntilSpeculativeInputPass({ @@ -178,10 +179,31 @@ export function applySpeculativeInputGuardrailToUIStream< ) 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") { @@ -195,6 +217,7 @@ export async function* gateIterableUntilSpeculativeInputPass(params: { const iterator = params.source[Symbol.asyncIterator](); const buffered: T[] = []; + const maxBufferedChunks = params.maxBufferedChunks ?? DEFAULT_MAX_BUFFERED_CHUNKS; let nextPromise = iterator.next(); while (true) { @@ -242,6 +265,20 @@ export async function* gateIterableUntilSpeculativeInputPass(params: { } 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(); } }