Skip to content

Session SPI & AG-UI HTTP API Reference ​

Contract reference for openhusky-session (dev.openhusky.session.*) and openhusky-agui (dev.openhusky.agui.*) at 0.3.0.


SessionStore SPI (dev.openhusky.session) ​

Implement SessionStore to persist OpenHusky's append-only tree sessions in any database or storage engine:

MethodSemantics
SessionHeader create(SessionHeader header)Creates a new session header; fails if header.id() already exists.
Optional<SessionHeader> getHeader(String sessionId)Looks up session metadata (tenantId, principalId, parentSessionId, metadata).
SessionEntry append(String sessionId, SessionEntry entry)Appends an entry and advances the active leaf; initializes with defaults if missing.
SessionEntry appendToLeaf(String sessionId, Function<String, SessionEntry> entryFactory)Atomic read-leaf → construct-entry → persist → advance-leaf operation preventing accidental sibling forks under concurrent writes.
Optional<String> currentLeafId(String sessionId)Returns the active leaf entry ID if any entries exist.
void setLeaf(String sessionId, String leafEntryId)Moves the active leaf pointer to an existing entry (non-destructive rewindTo).
List<SessionEntry> getBranch(String sessionId, String leafEntryId)Returns root-to-leaf entries (leafEntryId == null uses active leaf; shorthand getActiveBranch(sessionId)).
List<SessionEntry> getAllEntries(String sessionId)Returns every entry in the tree in append order (for tree UIs, export, and audit).
String fork(String sourceSessionId, String fromEntryId, String targetSessionId)Forks ancestry up to fromEntryId into a new session (also supports custom SessionHeader overload).
List<SessionSummary> list(SessionQuery query)Lists matching sessions filtered by tenantId, principalId, agentId, sessionKey, textQuery, includeForkedChildren, limit, offset.
boolean delete(String sessionId)Deletes a session and its entries.

SessionEntry Sealed Types ​

  1. MessageEntry — lossless openhusky-ai Message (UserMessage, AssistantMessage, ToolMessage)
  2. CompactionEntry — summary + firstKeptEntryId anchor + messagesBefore
  3. StatePatchEntry — namespace + null-preserving state patch (null value deletes a key)
  4. ModelChangeEntry — providerId, modelId, reasoningEffort
  5. SessionInfoEntry — append-only session title / metadata update
  6. CustomEntry — extension payload (modelVisible = true projects as a UserMessage)

AgUiRunner, AgUiApprovalBroker & AgUiSseCodec ​

Package: dev.openhusky.agui · Container-agnostic bridge between AgentRuntime and any HTTP/WebSocket server.

AgUiRunner ​

MethodDescription
AgUiRunner.builder(AgentRuntime)Options: .approvalBroker(AgUiApprovalBroker), .emitInitialStateSnapshot(boolean), .principalResolver(Function<AgUiRunInput, Principal>), .sessionResolver(BiFunction<AgUiRunInput, Principal, AgentSession>).
RunResult run(AgUiRunInput input, Principal authenticatedPrincipal, AbortSignal signal, Consumer<AgUiEvent> sink)Executes one AG-UI run synchronously, streaming mapped AgUiEvents to sink. Enforces SessionAccessPolicy and single-active-run per threadId.
boolean steer(String threadId, String instruction, Principal principal)Sends mid-run steering to an active threadId after access verification.
boolean abort(String threadId, String reason, Principal principal)Cancels an active threadId and any pending approvals for that session.
boolean approve(String approvalId, ApprovalDecision decision, Principal principal)Resolves a pending HITL approval after verifying caller access to the owning session.
boolean isRunning(String threadId)Returns true when threadId currently has an active run.
int abortAll(String reason)Aborts all active runs and cancels all pending approvals (for graceful shutdown).

AgUiSseCodec ​

  • AgUiSseCodec.encodeJson(AgUiEvent) — single-line JSON string with top-level "type" field (NON_NULL serialization).
  • AgUiSseCodec.encodeSseFrame(AgUiEvent) — formatted SSE frame (data: <json>\n\n).
  • AgUiSseCodec.readSseStream(InputStream, AbortSignal, Consumer<JsonNode>) — client-side SSE stream reader.

AgUiJdkHttpHandler HTTP Protocol Specification ​

When mounted on com.sun.net.httpserver.HttpServer (e.g., server.createContext("/agui", handler) with Executors.newVirtualThreadPerTaskExecutor()), AgUiJdkHttpHandler serves 4 POST routes (plus OPTIONS CORS preflight):

Builder Options ​

MethodDefaultDescription
principalResolver(AgUiHttpPrincipalResolver)nullAuthenticates every HTTP request before invoking AgUiRunner. Returning null yields 401; throwing AgUiAuthException yields 401 or 403.
heartbeatInterval(Duration)15sPeriodic : keepalive\n\n SSE comment interval (null or <= 0 disables).
disconnectPolicy(DisconnectPolicy)DETACHDETACH lets the durable run finish & persist on client disconnect; ABORT cancels the run immediately.
maxRequestBodyBytes(int)4 MiBHard cap on request body size; larger payloads return 413 Payload Too Large.
corsAllowOrigin(String) / corsAllowHeaders(String)"*" / "Content-Type, Authorization, Accept"CORS response headers.

1. POST /run (or / on mount path) — Stream an Agent Run ​

Request (application/json — AG-UI RunAgentInput):

json
{
  "threadId": "order-1042",
  "runId": "run-001",
  "messages": [
    { "id": "m1", "role": "user", "content": "Check order #1042 and highlight matching items." }
  ]
}

(Multimodal content arrays with {"type":"text","text":"..."} and {"type":"image","url":"..."} / base64 data are also supported.)

Response (200 OK, Content-Type: text/event-stream; charset=utf-8):

text
data: {"type":"RUN_STARTED","threadId":"order-1042","runId":"run-001","timestamp":1764480000000}

data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"...","delta":"Order #1042 is in transit."}

data: {"type":"STATE_DELTA","delta":[{"op":"add","path":"/storefront/cart","value":{...}}]}

data: {"type":"RUN_FINISHED","threadId":"order-1042","runId":"run-001","outcome":"success","timestamp":1764480002400}

2. POST /steer — Mid-Run Steering ​

json
// Request
{ "threadId": "order-1042", "instruction": "Focus only on waterproof models under $200." }

// Response (200 OK)
{ "accepted": true }

3. POST /abort — Cancel Active Run ​

json
// Request
{ "threadId": "order-1042", "reason": "User clicked stop" }

// Response (200 OK)
{ "aborted": true }

4. POST /approve — Resolve Pending HITL Approval ​

json
// Request (decision: "APPROVE_ONCE" | "APPROVE_SESSION" | "REJECT")
{ "approvalId": "appr-7f2a", "decision": "APPROVE_ONCE", "reason": "Confirmed by buyer" }

// Response (200 OK)
{ "resolved": true }

Error Status Codes (JSON {"error": "..."}) ​

HTTP StatusCondition
400 Bad RequestBlank/invalid JSON, missing required fields, or missing user message.
401 UnauthorizedAgUiHttpPrincipalResolver returned null or threw AgUiAuthException.unauthorized(...).
403 ForbiddenAgUiAuthException.forbidden(...) or cross-tenant SessionAccessDeniedException.
404 Not FoundUnknown route under the handler context path.
405 Method Not AllowedHTTP method other than POST / OPTIONS.
413 Payload Too LargeRequest body exceeded maxRequestBodyBytes.

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