Turn an AI SDK agent's stream into run events, with tool approvals that continue the same run.
Vercel AI SDK
The adapter turns the parts of streamText(…).stream (or fullStream, its deprecated alias), of a ToolLoopAgent's .stream(), or of a UI message stream into run events. The first part brings in You and the agent. Each start-step … finish-step becomes a task, titled by what the step did. A tool-input-start or tool-call becomes a call to a tool actor (brand tools such as githubListPullRequests share one actor with the brand's logo). tool-result ends the call, and tool-error or tool-output-denied fails it. Usage on finish-step becomes spend when you pass a price, otherwise a token count on the agent's activity line.
With toolApproval set to "user-approval", the call ends with a tool-approval-request: the agent shows as blocked, Allow / Decline in any component decides it, and takeApprovalResponses() gives you the tool-approval-response parts for the next call's messages. When a tool's execute runs another agent, adapter.child({ toolCallId, label, model }) draws that call to the sub-agent and hangs its own calls off it.
It has no runtime import of ai: it declares the part fields it reads, so the registry item depends on Knowns core only.
Replay a recorded run
Hand-written AI SDK 7 parts (a launch agent, a research sub-agent run as a tool, GitHub, a failing Postgres call and a Slack post that needs your approval) played through the adapter into AgentGraph and two AgentMonitors. Nothing leaves the page.
Stream it from a Next.js route
// app/api/agent/route.ts: runs the agent on the server, streams Knowns events (NDJSON)
import { isStepCount, streamText, tool, ToolLoopAgent, type ModelMessage } from "ai";
import { z } from "zod";
import { createAiSdkAdapter, toReadableStream, type AiSdkAdapter } from "@/lib/knowns/adapters/ai-sdk";
import { githubListPullRequests, slackPostMessage } from "@/lib/tools";
// One adapter per conversation: the call after an approval continues the same run.
const runs = new Map<string, AiSdkAdapter>();
const researcher = new ToolLoopAgent({
model: "google/gemini-2.5-pro",
instructions: "Research the task and answer in three lines.",
tools: { /* webSearch, webFetch… */ },
});
// An agent used as a tool: its own stream goes into a child, so its calls hang off it.
const research = (adapter: AiSdkAdapter) =>
tool({
description: "Research a topic in depth.",
inputSchema: z.object({ task: z.string() }),
execute: async ({ task }, { toolCallId, abortSignal }) => {
const child = adapter.child({ label: "Researcher", model: "gemini-2.5-pro", toolCallId, description: task });
const result = await researcher.stream({ prompt: task, abortSignal });
for await (const part of result.stream) child.push(part);
child.end();
return await result.text;
},
});
export async function POST(req: Request) {
const { id, messages } = (await req.json()) as { id: string; messages: ModelMessage[] };
const adapter =
runs.get(id) ??
createAiSdkAdapter({
agent: { label: "Launcher" },
prompt: "Announce the AI SDK 7 upgrade",
pricing: { "gpt-5": { input: 1.25, output: 10, cacheRead: 0.125 } }, // USD per 1M tokens; omit for token counts
});
runs.set(id, adapter);
// Allow / Deny clicked in the UI since the last call: hand them to the model.
const decided = adapter.takeApprovalResponses();
if (decided.length) messages.push({ role: "tool", content: decided });
const result = streamText({
model: "openai/gpt-5",
instructions: "You ship launches. Ask before posting anywhere public.",
messages,
tools: { research: research(adapter), githubListPullRequests, slackPostMessage },
toolApproval: { slackPostMessage: "user-approval" },
stopWhen: isStepCount(10),
});
return new Response(toReadableStream(result.stream, { adapter }), {
headers: { "content-type": "application/x-ndjson", "cache-control": "no-store" },
});
}
// app/api/agent/[id]/decision/route.ts: Allow / Deny from the browser
export async function PUT(req: Request, { params }: { params: Promise<{ id: string }> }) {
const event = await req.json(); // { type: "approval.resolve", id, decision }
runs.get((await params).id)?.emit(event);
return new Response(null, { status: 204 });
}// components/live-agent.tsx: any Knowns UI component, fed by the stream
"use client";
import { useEffect } from "react";
import { useAgentRun } from "@/lib/knowns/run";
import { connectEventStream, forwardDecisions } from "@/lib/knowns/adapters/ai-sdk";
import { AgentGraph } from "@/components/ui/knowns/agent-graph/agent-graph";
import { AgentMonitor } from "@/components/ui/knowns/agent-monitor/agent-monitor";
export function LiveAgent({ id, messages }: { id: string; messages: unknown[] }) {
const run = useAgentRun();
useEffect(() => {
const ctl = new AbortController();
const call = () =>
connectEventStream(run, "/api/agent", {
signal: ctl.signal,
init: { method: "POST", body: JSON.stringify({ id, messages }) },
});
// Each Allow / Deny goes to the server, then the next call picks it up.
const stop = forwardDecisions(run, async (event) => {
await fetch(`/api/agent/${id}/decision`, { method: "PUT", body: JSON.stringify(event) });
call();
});
call();
return () => { ctl.abort(); stop(); };
}, [run, id, messages]);
return (
<>
<AgentGraph run={run} layout="center" />
<AgentMonitor run={run} actor="agent" />
</>
);
}// Same process (a script, a test, a server component): skip the stream
import { adaptStream, partsFromResult } from "@/lib/knowns/adapters/ai-sdk";
const result = streamText({ model, tools, stopWhen: isStepCount(5), prompt });
await adaptStream(run, result.stream, { agent: { label: "Helper" }, prompt });
// generateText / agent.generate(): replay its steps after the fact
const done = await generateText({ model, tools, prompt });
const adapter = createAiSdkAdapter({ run, prompt });
partsFromResult(done).forEach(adapter.push);Installation is part of Pro
Pro components install from a licensed registry. The live preview stays open to everyone.
- createAiSdkAdapter(opts)
{ run?, you?, youLabel?, agent?: { id?, label?, model?, description? }, prompt?, pricing?, now? }- Default
new run, "you", { id: "agent", label: "Agent" } - Returns { run, agentId, push, end, emit, onEvent, child, resolve, waitForApproval, takeApprovalResponses, pendingApprovals }.
- push(part)
stream part or UI message chunk- Feed every part. tool-call / tool-input-available, tool-result / tool-output-available, tool-error / tool-output-error are all read; unknown types are ignored.
- end(reason?)
string- The stream ended. Calls waiting on a manual approval stay open and the agent stays blocked; a reason fails what is open.
- child({ toolCallId?, id?, label, model?, description? })
AiSdkAdapter- A sub-agent inside a tool's execute. With toolCallId, that call is drawn to the sub-agent; its own stream goes into the child.
- pricing
Record<modelId, { input, output, cacheRead? }>- USD per million tokens, matched on the step's response.modelId (with or without the provider prefix). Without a price, tokens show as activity.
- resolve(approvalId, approved, reason?)
AiToolApprovalResponse- Decide on the server: emits approval.resolve and returns the response for the next call's messages.
- waitForApproval(approvalId, signal?)
Promise<AiToolApprovalResponse>- Resolves when Allow / Deny happens anywhere. Abort denies.
- takeApprovalResponses()
AiToolApprovalResponse[]- Manual decisions not yet sent to the model; taking them clears them. Push as { role: "tool", content }.
- adaptStream(run, stream, opts?)
AsyncIterable|Iterable of parts- In-process: pushes the whole stream, then end(). A thrown stream fails the run.
- partsFromResult(result)
generateText / agent.generate() result- Its steps as parts, for push.
- toEventStream / toReadableStream(parts, { adapter?, format? })
AsyncIterable → lines / bytes- Default
format "ndjson" - Server: Knowns event lines (NDJSON or SSE), children included. Same bridge as the Claude Agent SDK adapter.
- connectEventStream / forwardDecisions
-- Client: read the stream into a run; send Allow / Deny back. Re-exported from the shared stream module.
| Prop | Type | Default | Description |
|---|---|---|---|
| createAiSdkAdapter(opts) | { run?, you?, youLabel?, agent?: { id?, label?, model?, description? }, prompt?, pricing?, now? } | new run, "you", { id: "agent", label: "Agent" } | Returns { run, agentId, push, end, emit, onEvent, child, resolve, waitForApproval, takeApprovalResponses, pendingApprovals }. |
| push(part) | stream part or UI message chunk | - | Feed every part. tool-call / tool-input-available, tool-result / tool-output-available, tool-error / tool-output-error are all read; unknown types are ignored. |
| end(reason?) | string | - | The stream ended. Calls waiting on a manual approval stay open and the agent stays blocked; a reason fails what is open. |
| child({ toolCallId?, id?, label, model?, description? }) | AiSdkAdapter | - | A sub-agent inside a tool's execute. With toolCallId, that call is drawn to the sub-agent; its own stream goes into the child. |
| pricing | Record<modelId, { input, output, cacheRead? }> | - | USD per million tokens, matched on the step's response.modelId (with or without the provider prefix). Without a price, tokens show as activity. |
| resolve(approvalId, approved, reason?) | AiToolApprovalResponse | - | Decide on the server: emits approval.resolve and returns the response for the next call's messages. |
| waitForApproval(approvalId, signal?) | Promise<AiToolApprovalResponse> | - | Resolves when Allow / Deny happens anywhere. Abort denies. |
| takeApprovalResponses() | AiToolApprovalResponse[] | - | Manual decisions not yet sent to the model; taking them clears them. Push as { role: "tool", content }. |
| adaptStream(run, stream, opts?) | AsyncIterable | Iterable of parts | - | In-process: pushes the whole stream, then end(). A thrown stream fails the run. |
| partsFromResult(result) | generateText / agent.generate() result | - | Its steps as parts, for push. |
| toEventStream / toReadableStream(parts, { adapter?, format? }) | AsyncIterable → lines / bytes | format "ndjson" | Server: Knowns event lines (NDJSON or SSE), children included. Same bridge as the Claude Agent SDK adapter. |
| connectEventStream / forwardDecisions | - | - | Client: read the stream into a run; send Allow / Deny back. Re-exported from the shared stream module. |