AG-UI v1.0 Streaming (openhusky-agui)
openhusky-agui adapts openhusky-core to the open AG-UI v1.0 Server-Sent Events (SSE) protocol using standard JDK 21 APIs—without Spring, Jakarta Servlet, Netty, or Project Reactor dependencies.
<dependency>
<groupId>dev.openhusky</groupId>
<artifactId>openhusky-agui</artifactId>
<version>0.3.0</version>
</dependency>implementation("dev.openhusky:openhusky-agui:0.3.0")AgentEvent to AgUiEvent Protocol Mapping
AgUiEventMapper (dev.openhusky.agui.AgUiEventMapper) is a stateful per-run translator guarded by ReentrantLock that enforces strict AG-UI v1.0 open/close bracketing invariants (closing open reasoning blocks before text blocks, and closing all open blocks before STEP_FINISHED, RUN_ERROR, or RUN_FINISHED):
AgentEvent (openhusky-core) | Emitted AgUiEvent (openhusky-agui) | Notes & Payload Details |
|---|---|---|
RunStarted | RUN_STARTED | Followed by STATE_SNAPSHOT when AgUiRunner.emitInitialStateSnapshot is true and projected state is non-empty. |
StepStarted | STEP_STARTED (step-<stepIndex>) | Automatically closes any open reasoning, text, tool call, or prior step first. |
StepFinished | STEP_FINISHED (buffered until step boundary) | Attaches metadata.contextTokens and metadata.usage. |
ThinkingDelta | REASONING_START, REASONING_MESSAGE_START, REASONING_MESSAGE_CONTENT | Opens reasoning brackets lazily on the first non-empty delta. |
TextDelta | TEXT_MESSAGE_START, TEXT_MESSAGE_CONTENT | Closes any open reasoning block; opens assistant text message lazily. |
ToolCallDelta | TOOL_CALL_START, TOOL_CALL_ARGS | Closes open reasoning/text; links parentMessageId to last assistant message. |
ToolCallStarted | TOOL_CALL_START, TOOL_CALL_ARGS, TOOL_CALL_END | Emits START + ARGS if not already streamed, then TOOL_CALL_END. |
ToolCallFinished | (TOOL_CALL_END), TOOL_CALL_RESULT | Includes metadata.isError, metadata.durationMs, and metadata.details. |
StateDelta | STATE_DELTA | Converts each entry in patch to RFC 6902 JsonPatchOp under /<namespace>/<key> (null value → "remove", non-null → "add"). |
RunError | RUN_ERROR | Closes all open blocks; sets code to exception class name. |
RunFinished | RUN_FINISHED | Closes all open blocks; sets outcome (success / error / aborted), usage, metadata.terminationReason, metadata.contextTokens. |
ApprovalRequested | CUSTOM (openhusky:approval_requested) | value: { approvalId, toolCallId, toolName, argumentsJson, reason }. |
ApprovalResolved | CUSTOM (openhusky:approval_resolved) | value: { approvalId, toolName, approved, reason }. |
ToolCallProgress | CUSTOM (openhusky:tool_progress) | value: { toolCallId, toolName, message }. |
SteeringApplied | CUSTOM (openhusky:steering_applied) | value: { steeringText, skippedToolsCount }. |
CompactionApplied | CUSTOM (openhusky:compaction_applied) | value: { messagesBefore, messagesAfter }. |
ModelChanged | CUSTOM (openhusky:model_changed) | value: { providerId, modelId, reasoningEffort }. |
PermissionPolicyChanged | CUSTOM (openhusky:permission_policy_changed) | value: { modeName }. |
DoomLoopDetected | CUSTOM (openhusky:doom_loop_detected) | value: { toolName, consecutiveCount, action }. |
ModelRetryScheduled | CUSTOM (openhusky:model_retry) | value: { attempt, maxRetries, delayMs, nextRetryAt, reason }. |
TurnStarted, TurnFinished | (none) | Already bracketed by RUN_*, STEP_*, and TEXT_MESSAGE_*. |
AgUiRunner & AgUiApprovalBroker Lifecycle
AgUiRunner (dev.openhusky.agui.AgUiRunner) is a container-agnostic execution bridge connecting AgUiRunInput to AgentRuntime, AgUiEventMapper, and AgUiApprovalBroker:
- Authentication & Session Access Verification: Resolves
Principal(using the explicitly authenticatedPrincipalpassed by the HTTP layer, orBuilder.principalResolver), opens the session viasessionResolver(defaults toruntime.openSession(threadId, principal)), and verifiesruntime.sessionAccessPolicy().permits(...). - Single-Active-Run Protection: Atomically registers
threadIdinactiveSessions. Concurrent runs on the samethreadIdare rejected (IllegalStateExceptionfor the same principal,SessionAccessDeniedExceptionacross tenants). - Race-Free HITL Approvals (
AgUiApprovalBroker): ImplementsApprovalDecision.Handler, registering pendingCompletableFuture<ApprovalDecision>entries inprepareApproval(...)beforeopenhusky:approval_requestedreaches the SSE stream, and cancelling pending futures automatically onAbortSignal, timeout (default5m), orcancelForSession(...). - Control & Graceful Shutdown: Exposes
steer(threadId, instruction, principal),abort(threadId, reason, principal),approve(approvalId, decision, principal)(each verifyingSessionAccessPolicy),isRunning(threadId), andabortAll(reason)for JVM shutdown hooks.
AgUiJdkHttpHandler (Standalone JDK 21 HTTP Server)
Mount AgUiJdkHttpHandler directly onto JDK 21's built-in com.sun.net.httpserver.HttpServer. Always configure a virtual-thread executor so concurrent /steer, /abort, and /approve requests never queue behind active SSE runs:
AgUiApprovalBroker broker = new AgUiApprovalBroker(Duration.ofMinutes(5));
AgentRuntime runtime = AgentRuntime.builder()
.provider(provider)
.model(model)
.sessionStore(store)
.sessionAccessPolicy(SessionAccessPolicy.TENANT_ISOLATED)
.toolsFrom(tools)
.permissionPolicy(PermissionPolicy.failClosed()
.allowReadOnlyTools()
.requireApproval("place_order")
.build())
.approvalHandler(broker)
.build();
AgUiRunner runner = AgUiRunner.builder(runtime)
.approvalBroker(broker)
.emitInitialStateSnapshot(true)
.build();
AgUiJdkHttpHandler handler = AgUiJdkHttpHandler.builder(runner)
.principalResolver(exchange -> {
String auth = exchange.getRequestHeaders().getFirst("Authorization");
if (auth == null || !auth.startsWith("Bearer ")) {
throw AgUiAuthException.unauthorized("Missing Bearer token");
}
return Principal.of("user-1", "acme-corp"); // Validate token in production
})
.heartbeatInterval(Duration.ofSeconds(15))
.disconnectPolicy(AgUiJdkHttpHandler.DisconnectPolicy.DETACH)
.maxRequestBodyBytes(AgUiJdkHttpHandler.DEFAULT_MAX_REQUEST_BODY_BYTES) // 4 MiB
.corsAllowOrigin("https://app.example.com")
.build();
HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", 8080), 0);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.createContext("/agui", handler);
server.start();Handler Configuration Reference
| Builder Method | Default | Behavior |
|---|---|---|
principalResolver(AgUiHttpPrincipalResolver) | null | Authenticates every /run, /steer, /abort, /approve request pre-stream. Returning null yields HTTP 401; throwing AgUiAuthException yields 401 or 403. |
heartbeatInterval(Duration) | 15s | Emits : keepalive\n\n SSE comments while idle (null or <= 0 disables). |
disconnectPolicy(DisconnectPolicy) | DETACH | DETACH stops SSE writes while letting the durable run finish and persist; ABORT cancels the active run immediately on client disconnect. |
maxRequestBodyBytes(int) | 4 MiB (4 * 1024 * 1024) | Caps JSON request body size; larger payloads return HTTP 413 Payload Too Large. |
corsAllowOrigin(String) / corsAllowHeaders(String) | "*" / "Content-Type, Authorization, Accept" | Configures CORS headers and OPTIONS preflight responses (204). |
AgUiSseCodec & Frontend Consumption
AgUiSseCodec provides encodeJson(AgUiEvent), encodeSseFrame(AgUiEvent), and readSseStream(InputStream, AbortSignal, Consumer<JsonNode>).
Because AG-UI runs use POST requests with JSON bodies and Authorization headers (which the browser's EventSource API does not support), consume the stream via fetch() + ReadableStream:
const response = await fetch('/agui/run', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
threadId,
messages: [{ id: crypto.randomUUID(), role: 'user', content: prompt }],
}),
})
const reader = response.body!.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const frames = buffer.split('\n\n')
buffer = frames.pop() ?? ''
for (const frame of frames) {
if (!frame.startsWith('data: ')) continue
const event = JSON.parse(frame.slice(6))
switch (event.type) {
case 'TEXT_MESSAGE_CONTENT':
appendAssistantDelta(event.delta)
break
case 'STATE_DELTA':
applyJsonPatch(storefrontState, event.delta) // RFC 6902 patch array
break
case 'CUSTOM':
if (event.name === 'openhusky:approval_requested') {
openApprovalModal(event.value) // Resolve via POST /agui/approve
} else if (event.name === 'openhusky:tool_progress') {
showToolProgress(event.value.toolName, event.value.message)
}
break
}
}
}For Spring Boot servlet applications, openhusky-spring-boot-starter includes OpenHuskyAgUiMvcController, which exposes the exact same /run, /steer, /abort, and /approve contract over Spring MVC SseEmitter. See Embedding in Spring Boot and Session SPI & AG-UI HTTP API Reference.