Skip to content

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.

xml
<dependency>
    <groupId>dev.openhusky</groupId>
    <artifactId>openhusky-agui</artifactId>
    <version>0.3.0</version>
</dependency>
kotlin
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
RunStartedRUN_STARTEDFollowed by STATE_SNAPSHOT when AgUiRunner.emitInitialStateSnapshot is true and projected state is non-empty.
StepStartedSTEP_STARTED (step-<stepIndex>)Automatically closes any open reasoning, text, tool call, or prior step first.
StepFinishedSTEP_FINISHED (buffered until step boundary)Attaches metadata.contextTokens and metadata.usage.
ThinkingDeltaREASONING_START, REASONING_MESSAGE_START, REASONING_MESSAGE_CONTENTOpens reasoning brackets lazily on the first non-empty delta.
TextDeltaTEXT_MESSAGE_START, TEXT_MESSAGE_CONTENTCloses any open reasoning block; opens assistant text message lazily.
ToolCallDeltaTOOL_CALL_START, TOOL_CALL_ARGSCloses open reasoning/text; links parentMessageId to last assistant message.
ToolCallStartedTOOL_CALL_START, TOOL_CALL_ARGS, TOOL_CALL_ENDEmits START + ARGS if not already streamed, then TOOL_CALL_END.
ToolCallFinished(TOOL_CALL_END), TOOL_CALL_RESULTIncludes metadata.isError, metadata.durationMs, and metadata.details.
StateDeltaSTATE_DELTAConverts each entry in patch to RFC 6902 JsonPatchOp under /<namespace>/<key> (null value → "remove", non-null → "add").
RunErrorRUN_ERRORCloses all open blocks; sets code to exception class name.
RunFinishedRUN_FINISHEDCloses all open blocks; sets outcome (success / error / aborted), usage, metadata.terminationReason, metadata.contextTokens.
ApprovalRequestedCUSTOM (openhusky:approval_requested)value: { approvalId, toolCallId, toolName, argumentsJson, reason }.
ApprovalResolvedCUSTOM (openhusky:approval_resolved)value: { approvalId, toolName, approved, reason }.
ToolCallProgressCUSTOM (openhusky:tool_progress)value: { toolCallId, toolName, message }.
SteeringAppliedCUSTOM (openhusky:steering_applied)value: { steeringText, skippedToolsCount }.
CompactionAppliedCUSTOM (openhusky:compaction_applied)value: { messagesBefore, messagesAfter }.
ModelChangedCUSTOM (openhusky:model_changed)value: { providerId, modelId, reasoningEffort }.
PermissionPolicyChangedCUSTOM (openhusky:permission_policy_changed)value: { modeName }.
DoomLoopDetectedCUSTOM (openhusky:doom_loop_detected)value: { toolName, consecutiveCount, action }.
ModelRetryScheduledCUSTOM (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:

  1. Authentication & Session Access Verification: Resolves Principal (using the explicitly authenticated Principal passed by the HTTP layer, or Builder.principalResolver), opens the session via sessionResolver (defaults to runtime.openSession(threadId, principal)), and verifies runtime.sessionAccessPolicy().permits(...).
  2. Single-Active-Run Protection: Atomically registers threadId in activeSessions. Concurrent runs on the same threadId are rejected (IllegalStateException for the same principal, SessionAccessDeniedException across tenants).
  3. Race-Free HITL Approvals (AgUiApprovalBroker): Implements ApprovalDecision.Handler, registering pending CompletableFuture<ApprovalDecision> entries in prepareApproval(...) before openhusky:approval_requested reaches the SSE stream, and cancelling pending futures automatically on AbortSignal, timeout (default 5m), or cancelForSession(...).
  4. Control & Graceful Shutdown: Exposes steer(threadId, instruction, principal), abort(threadId, reason, principal), approve(approvalId, decision, principal) (each verifying SessionAccessPolicy), isRunning(threadId), and abortAll(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:

java
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 MethodDefaultBehavior
principalResolver(AgUiHttpPrincipalResolver)nullAuthenticates every /run, /steer, /abort, /approve request pre-stream. Returning null yields HTTP 401; throwing AgUiAuthException yields 401 or 403.
heartbeatInterval(Duration)15sEmits : keepalive\n\n SSE comments while idle (null or <= 0 disables).
disconnectPolicy(DisconnectPolicy)DETACHDETACH 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:

typescript
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.

Released under the MIT License. Built with Java 21 Virtual Threads.