Core Runtime & AI API Reference
Contract reference for openhusky-core (dev.openhusky.core.*) and openhusky-ai (dev.openhusky.ai.*) at 0.3.0. For exhaustive method-level signatures, see Javadoc.
AgentRuntime & AgentRuntime.Builder
Package: dev.openhusky.core.runtime · Implements AutoCloseable (thread-safe, immutable; create once per agent profile and share across sessions).
Builder Options
| Method | Required / Default | Description |
|---|---|---|
llmClient(LlmClient) / provider(LlmProvider) | Required | Model gateway client (or raw LlmProvider wrapped in LlmClient.of(...)). |
model(ModelSpec) | Required | Default model spec (ModelCatalog.defaults().require(...) or ModelSpec.custom(...)). |
systemPrompt(String) | "" | Static system prompt prepended to every session. |
systemPromptSupplier(Function<SessionContext, String>) | null | Dynamic per-step system prompt builder receiving SessionContext(sessionId, principal, model, state). |
temperature(Double) | null (provider default) | Sampling temperature. |
maxOutputTokens(Integer) | null (model default) | Maximum completion tokens per LLM step. |
maxStepsPerTurn(int) | 32 | Maximum LLM + tool cycles allowed in one turn (> 0). |
reasoningEffort(ReasoningEffort) | ReasoningEffort.NONE | Thinking / reasoning effort (NONE, MINIMAL, LOW, MEDIUM, HIGH, XHIGH). |
cacheRetention(CacheRetention) | CacheRetention.SHORT | Prompt caching hint (NONE, SHORT, LONG). |
cacheKey(String) | null | Optional prompt cache routing key. |
toolTimeout(Duration) | Duration.ofMinutes(2) | Default per-tool timeout unless overridden by AgentTool.timeout(). |
approvalTimeout(Duration) | null (wait until resolved/aborted) | Maximum wait time for ApprovalDecision.Handler. |
maxTotalTokensPerRun(int) | 0 (unlimited) | Hard token budget across a single run (>= 0). |
maxRunDuration(Duration) | null (unlimited) | Hard wall-clock deadline for a single run. |
tool(AgentTool) / tools(...) | empty | Register programmatic AgentTool instances (MCP, Sandbox, Skills, Subagent, custom). |
toolsFrom(Object... beans) | empty | Scan plain Java objects for @Tool-annotated methods via AnnotatedToolScanner. |
removeTool(String) / clearTools() | — | Remove tools when cloning via runtime.toBuilder(). |
permissionPolicy(PermissionPolicy) | PermissionPolicy.failClosed().build() | Fail-closed tool authorization rules. |
approvalHandler(ApprovalDecision.Handler) | null | HITL callback invoked when policy evaluates to REQUIRE_APPROVAL. |
sessionStore(SessionStore) | new InMemorySessionStore() | Backing append-only tree store. |
sessionAccessPolicy(SessionAccessPolicy) | TENANT_ISOLATED | Multi-tenant access enforcement (TENANT_ISOLATED, PRINCIPAL_ISOLATED, UNRESTRICTED). |
contextPipeline(ContextPipeline) | ContextPipeline.withDefaultCompactor() | Branch projection and compaction pipeline. |
stepInterceptor(StepInterceptor) | empty | Appends a reasoning-step waterfall interceptor (e.g., DoomLoopGuardInterceptor). |
toolInterceptor(ToolInterceptor) | empty | Appends a tool execution waterfall interceptor (e.g., OutputOffloadToolInterceptor). |
eventListener(Consumer<AgentEvent>) / BiConsumer<EventContext, AgentEvent> | empty | Runtime-wide observer across all sessions (used by openhusky-otel and sidecars). |
toolExecutor(ExecutorService) | Virtual-thread-per-task | Custom executor (externally supplied executors are not closed by runtime.close()). |
Runtime Methods
| Signature | Description |
|---|---|
AgentSession openSession() | Opens a new session with a random UUID and Principal.anonymous(). |
AgentSession openSession(String sessionId, Principal principal) | Opens or rehydrates sessionId, enforcing SessionAccessPolicy if the session already exists. |
List<SessionSummary> listSessions(Principal principal) | Lists sessions visible to principal under the configured SessionAccessPolicy. |
List<SessionSummary> listSessions(Principal principal, SessionQuery query) | Scoped session query (throws SessionAccessDeniedException if query requests another tenant/principal). |
Builder toBuilder() | Clones the immutable runtime configuration into a mutable Builder. |
void close() | Shuts down the internally owned virtual-thread tool executor. |
AgentSession (Control Track)
Package: dev.openhusky.core.runtime · Single-active-run lease per sessionId.
Execution & Structured Output
| Method | Returns | Description |
|---|---|---|
prompt(String) / prompt(String, Consumer<AgentEvent>) | RunResult | Runs a user turn synchronously (designed for virtual threads), optionally streaming events to a per-run listener. |
prompt(Message.UserMessage) / prompt(Message.UserMessage, Consumer<AgentEvent>) | RunResult | Multimodal user turn (text + ImageBlock). |
promptStructured(String, Class<T>) | StructuredRunResult<T> | Generates JSON Schema from Class<T>, enforces ResponseFormat, validates & retries (StructuredOutputOptions.defaults()). |
promptStructured(String, Class<T>, StructuredOutputOptions, Consumer<AgentEvent>) | StructuredRunResult<T> | Full overload supporting custom schema name, strictness, retry count (maxValidationRetries), and event listener. |
promptStructured(String, TypeReference<T>, ...) | StructuredRunResult<T> | Generic type overload (e.g., List<Item>). |
Live Mid-Run Control, Tree Operations & Hot Switching
| Method | Description |
|---|---|
void steer(String instruction) | Enqueues a mid-run redirection drained at the next tool boundary (skips remaining queued tools cleanly). |
void followUp(String nextPrompt) | Enqueues a follow-up prompt that runs automatically once the current turn completes. |
void abort(String reason) | Cooperatively cancels the active run via linked AbortSignal. |
boolean compactNow() / compactNow(AbortSignal) | Persists a non-destructive CompactionEntry on the active branch without splitting tool call/result pairs. |
AgentSession fork(String fromEntryId, String newSessionId) | Creates an independent session sharing ancestry up to fromEntryId. |
void rewindTo(String entryId) | Moves the active leaf pointer back to entryId without deleting history. |
List<SessionEntry> history() | Returns ordered entries along the active branch from root to leaf. |
Map<String, Map<String, Object>> projectedState() | Folds StatePatchEntry nodes on the active branch into the current namespace state map. |
void setModel(ModelSpec) / setModel(ModelSpec, LlmClient) / setModel(ModelSpec, LlmClient, ReasoningEffort) | Atomically switches model/client/effort and persists a ModelChangeEntry. |
void restoreModelBinding(ModelSpec, LlmClient, ReasoningEffort) | Restores in-memory binding on cold reload without writing a phantom ModelChangeEntry. |
void setReasoningEffort(ReasoningEffort) | Updates thinking/reasoning effort and persists a ModelChangeEntry. |
void setPermissionPolicy(PermissionPolicy, String modeName) | Dynamically switches session permission policy and clears prior APPROVE_SESSION grants. |
AutoCloseable subscribe(Consumer<AgentEvent>) | Subscribes a session-scoped event listener; close handle to unsubscribe. |
RunResult, StructuredRunResult<T>, RunTerminationReason & StructuredOutputOptions
RunResult:record(String sessionId, String runId, Message.AssistantMessage finalMessage, StopReason stopReason, RunTerminationReason terminationReason, TokenUsage totalUsage, int turnsExecuted, int stepsExecuted)with helpersfinalText()andfinalMessageOptional().RunTerminationReason:COMPLETED,MAX_STEPS,TOKEN_BUDGET_EXHAUSTED,DURATION_BUDGET_EXHAUSTED,MODEL_MAX_TOKENS,ABORTED,ERROR.StructuredRunResult<T>:record(T value, RunResult runResult)with convenience accessorssessionId(),runId(),totalUsage(),stepsExecuted(),turnsExecuted(), andrawText().StructuredOutputOptions:StructuredOutputOptions.builder().schemaName(...).schemaDescription(...).strict(true).maxValidationRetries(2).build(). On exhaustion or early termination,promptStructuredthrowsStructuredOutputExceptioncontainingrawText()andrunResult().
AgentEvent (22 Sealed Event Types)
Package: dev.openhusky.core.event · Exhaustive switch pattern matching over sealed interface AgentEvent. Every event exposes sessionId() and timestamp().
| Category | Event Record | Key Fields |
|---|---|---|
| Run / Turn | RunStarted | runId |
TurnStarted | runId, turnIndex, userPrompt | |
TurnFinished | runId, turnIndex, finalMessage, usage | |
RunFinished | runId, stopReason, terminationReason, totalUsage | |
RunError | runId, message, cause | |
| LLM Steps | StepStarted | runId, stepIndex |
StepFinished | runId, stepIndex, usage | |
TextDelta | runId, delta | |
ThinkingDelta | runId, delta | |
ToolCallDelta | runId, toolCallId, toolName, argumentsDelta | |
| Tools | ToolCallStarted | runId, toolCallId, toolName, argumentsJson |
ToolCallProgress | runId, toolCallId, toolName, message | |
ToolCallFinished | runId, toolCallId, toolName, outputPreview, isError, durationMs, details | |
| HITL & Policy | ApprovalRequested | runId, approvalId, toolCallId, toolName, argumentsJson, reason |
ApprovalResolved | runId, approvalId, toolName, approved, reason | |
PermissionPolicyChanged | runId, modeName | |
| State & Control | StateDelta | runId, namespace, patch (null deletes key) |
SteeringApplied | runId, steeringText, skippedToolsCount | |
CompactionApplied | runId, messagesBefore, messagesAfter | |
ModelChanged | runId, providerId, modelId, reasoningEffort | |
| Resilience | DoomLoopDetected | runId, toolName, consecutiveCount, action |
ModelRetryScheduled | runId, attempt, maxRetries, delayMs, reason |
Tools, Permissions & Interceptors SPI
AgentTool, ToolContext & ToolResult (dev.openhusky.core.tool)
AgentTool: implementspec(),execute(ToolContext, Map<String, Object>), and optionally overrideexecutionMode()(SEQUENTIALdefault orPARALLEL_SAFE),readOnly()(falsedefault), andtimeout()(nullinherits runtime timeout).ToolContext:record(sessionId, runId, toolCallId, principal, abortSignal, progressEmitter, attributes)withemitProgress(String).ToolResultfactories:ToolResult.ok(String text)/ok(List<ContentBlock>)/ok(List<ContentBlock>, Map<String, Object> details)ToolResult.okWithDetails(String text, Map<String, Object> details)ToolResult.okWithState(String text, String namespace, Map<String, Object> stateDelta)ToolResult.error(String message)/error(String message, Map<String, Object> details)
PermissionPolicy & ApprovalDecision (dev.openhusky.core.policy)
- Evaluation precedence (fail-closed):
deny→requireApproval→allow→readOnlyDefault/writeDefault(both default toDENY). Supports exact names and prefix wildcards ("mcp__docs__*"). - Presets:
PermissionPolicy.failClosed(),readOnly(),requireApprovalForWrites(),allowAll(). ApprovalDecisionfactories:approveOnce(),approveForSession(),reject(String reason).ApprovalDecision.Handler: implementrequestApproval(Request, AbortSignal); async brokers can also overrideprepareApproval(Request)andcancelApproval(String approvalId, String reason).
Interceptors
LlmInterceptor(dev.openhusky.ai.provider):ChatResponse intercept(ChatRequest, AbortSignal, Consumer<StreamEvent>, Chain)StepInterceptor(dev.openhusky.core.interceptor):ChatResponse intercept(Context, Chain)ToolInterceptor(dev.openhusky.core.interceptor):ToolResult intercept(Invocation, Chain)
Model Gateway (openhusky-ai)
Providersfactory methods (dev.openhusky.ai.transport.Providers):openai(apiKey)/openai(apiKey, baseUrl)openaiResponses(apiKey)/openaiResponses(apiKey, baseUrl)anthropic(apiKey)/anthropic(apiKey, baseUrl)gemini(apiKey)/gemini(apiKey, baseUrl)deepseek(apiKey)/qwen(apiKey)/zhipu(apiKey)/mistral(apiKey)/openRouter(apiKey)(all have(apiKey, baseUrl)overloads)ollama()/ollama(baseUrl)litellm(baseUrl, apiKey)/litellm(baseUrl, apiKey, defaultHeaders)forConfig(ModelSpec.Protocol, ProviderConfig)
LlmClient:LlmClient.of(provider).withInterceptor(RetryInterceptor.defaults()).withInterceptor(costTracker).ModelSpec:ModelCatalog.defaults().require("gpt-4.1")orModelSpec.custom(id, contextWindow, maxOutputTokens).