Turn a Claude Agent SDK query into run events: tool calls, subagents, permission requests and cost.
Claude Agent SDK
The adapter turns the message stream of query() into run events, so every Knowns UI component shows a real agent. It maps the system / init message to You and the lead agent. Each tool_use block becomes a tool and a call, and its tool_result ends that call (as a failure when is_error is set). An Agent (formerly Task) call becomes a subagent with its own task, and messages carrying its parent_tool_use_id or agent_id belong to it. The result message splits total_cost_usd over the agents by input tokens. A canUseTool prompt becomes an approval.
It has no runtime import of the SDK: it declares the few message fields it reads, so the registry item depends on Knowns core only.
Replay a recorded run
A hand-written message sequence (a lead, two subagents, MCP tools, one permission prompt) played through the adapter into AgentGraph, AgentMonitor and AgentLanes. Nothing leaves the page.
Stream it from a server
// app/api/agent/route.ts: runs the agent on the server, streams Knowns events (NDJSON)
import { query } from "@anthropic-ai/claude-agent-sdk";
import { createClaudeAgentAdapter, toReadableStream } from "@/lib/knowns/adapters/claude-agent-sdk";
// One adapter per run, kept so decisions from the browser can reach it.
const runs = new Map<string, ReturnType<typeof createClaudeAgentAdapter>>();
export async function POST(req: Request) {
const { id, prompt } = await req.json();
const adapter = createClaudeAgentAdapter({ prompt, leadLabel: "Claude" });
runs.set(id, adapter);
const messages = query({
prompt,
options: {
// Permission prompts become approvals in the UI; the answer comes back below.
canUseTool: (toolName, input, { signal, toolUseID, agentID }) =>
adapter.canUseTool(toolName, input, { signal, toolUseID, agentID }),
},
});
return new Response(toReadableStream(messages, { 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/claude-agent-sdk";
import { AgentGraph } from "@/components/ui/knowns/agent-graph/agent-graph";
import { AgentLanes } from "@/components/ui/knowns/agent-lanes/agent-lanes";
export function LiveAgent({ id, prompt }: { id: string; prompt: string }) {
const run = useAgentRun();
useEffect(() => {
const ctl = new AbortController();
// Allow / Deny clicked in any component goes back to the server.
const stop = forwardDecisions(run, `/api/agent/${id}/decision`);
connectEventStream(run, "/api/agent", {
signal: ctl.signal,
init: { method: "POST", body: JSON.stringify({ id, prompt }) },
});
return () => { ctl.abort(); stop(); };
}, [run, id, prompt]);
return (
<>
<AgentGraph run={run} layout="center" />
<AgentLanes run={run} />
</>
);
}// Same process (a script, Electron, a local dev server): skip the stream
const adapter = createClaudeAgentAdapter({ run, prompt });
for await (const message of query({ prompt, options: { canUseTool: adapter.canUseTool } })) {
adapter.push(message);
}Installation is part of Pro
Pro components install from a licensed registry. The live preview stays open to everyone.
- createClaudeAgentAdapter(opts)
{ run?, you?, youLabel?, leadLabel?, model?, prompt?, now? }- Default
new run, "you", "Claude" - Returns { run, push, emit, onEvent, onPermissionRequest, canUseTool, end }.
- push(message)
SDK message- Feed every message from query(). Unknown types are ignored.
- onPermissionRequest(tool, input, { toolUseID?, agentID?, signal? })
Promise<"allow" | "deny">- Emits approval.request (detail: the exact command, the file and content, or the input) and resolves on approval.resolve. Abort denies.
- canUseTool
same as the SDK's- Drop-in for query options: returns { behavior: "allow", updatedInput } or { behavior: "deny", message }.
- emit(event) / onEvent(fn)
AgentEvent- emit puts decisions from the browser into the run; onEvent sees everything the adapter sends.
- end(reason?)
string- Closes what is still open when the stream ends without a result. A reason fails the run.
- toEventStream(messages, opts)
AsyncIterable → AsyncGenerator<string>- Default
format "ndjson" - Event lines (NDJSON or SSE). Permission events stream while the SDK waits. toReadableStream wraps it for a Response.
- connectEventStream(run, source, { signal?, init? })
URL|Response|ReadableStream- Client: reads NDJSON or SSE into a run.
- forwardDecisions(run, target)
URL|(event) => void- Client: POSTs each Allow / Deny made in the browser once. Returns an unsubscribe.
- Tool labels
-- WebSearch → "Web search"; mcp__github__* → "GitHub" (brand logos via toolIcon); the call summary is the command, file name, query or URL.
| Prop | Type | Default | Description |
|---|---|---|---|
| createClaudeAgentAdapter(opts) | { run?, you?, youLabel?, leadLabel?, model?, prompt?, now? } | new run, "you", "Claude" | Returns { run, push, emit, onEvent, onPermissionRequest, canUseTool, end }. |
| push(message) | SDK message | - | Feed every message from query(). Unknown types are ignored. |
| onPermissionRequest(tool, input, { toolUseID?, agentID?, signal? }) | Promise<"allow" | "deny"> | - | Emits approval.request (detail: the exact command, the file and content, or the input) and resolves on approval.resolve. Abort denies. |
| canUseTool | same as the SDK's | - | Drop-in for query options: returns { behavior: "allow", updatedInput } or { behavior: "deny", message }. |
| emit(event) / onEvent(fn) | AgentEvent | - | emit puts decisions from the browser into the run; onEvent sees everything the adapter sends. |
| end(reason?) | string | - | Closes what is still open when the stream ends without a result. A reason fails the run. |
| toEventStream(messages, opts) | AsyncIterable → AsyncGenerator<string> | format "ndjson" | Event lines (NDJSON or SSE). Permission events stream while the SDK waits. toReadableStream wraps it for a Response. |
| connectEventStream(run, source, { signal?, init? }) | URL | Response | ReadableStream | - | Client: reads NDJSON or SSE into a run. |
| forwardDecisions(run, target) | URL | (event) => void | - | Client: POSTs each Allow / Deny made in the browser once. Returns an unsubscribe. |
| Tool labels | - | - | WebSearch → "Web search"; mcp__github__* → "GitHub" (brand logos via toolIcon); the call summary is the command, file name, query or URL. |