Skip to content

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 ​

MethodRequired / DefaultDescription
llmClient(LlmClient) / provider(LlmProvider)RequiredModel gateway client (or raw LlmProvider wrapped in LlmClient.of(...)).
model(ModelSpec)RequiredDefault model spec (ModelCatalog.defaults().require(...) or ModelSpec.custom(...)).
systemPrompt(String)""Static system prompt prepended to every session.
systemPromptSupplier(Function<SessionContext, String>)nullDynamic 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)32Maximum LLM + tool cycles allowed in one turn (> 0).
reasoningEffort(ReasoningEffort)ReasoningEffort.NONEThinking / reasoning effort (NONE, MINIMAL, LOW, MEDIUM, HIGH, XHIGH).
cacheRetention(CacheRetention)CacheRetention.SHORTPrompt caching hint (NONE, SHORT, LONG).
cacheKey(String)nullOptional 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(...)emptyRegister programmatic AgentTool instances (MCP, Sandbox, Skills, Subagent, custom).
toolsFrom(Object... beans)emptyScan 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)nullHITL callback invoked when policy evaluates to REQUIRE_APPROVAL.
sessionStore(SessionStore)new InMemorySessionStore()Backing append-only tree store.
sessionAccessPolicy(SessionAccessPolicy)TENANT_ISOLATEDMulti-tenant access enforcement (TENANT_ISOLATED, PRINCIPAL_ISOLATED, UNRESTRICTED).
contextPipeline(ContextPipeline)ContextPipeline.withDefaultCompactor()Branch projection and compaction pipeline.
stepInterceptor(StepInterceptor)emptyAppends a reasoning-step waterfall interceptor (e.g., DoomLoopGuardInterceptor).
toolInterceptor(ToolInterceptor)emptyAppends a tool execution waterfall interceptor (e.g., OutputOffloadToolInterceptor).
eventListener(Consumer<AgentEvent>) / BiConsumer<EventContext, AgentEvent>emptyRuntime-wide observer across all sessions (used by openhusky-otel and sidecars).
toolExecutor(ExecutorService)Virtual-thread-per-taskCustom executor (externally supplied executors are not closed by runtime.close()).

Runtime Methods ​

SignatureDescription
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 ​

MethodReturnsDescription
prompt(String) / prompt(String, Consumer<AgentEvent>)RunResultRuns a user turn synchronously (designed for virtual threads), optionally streaming events to a per-run listener.
prompt(Message.UserMessage) / prompt(Message.UserMessage, Consumer<AgentEvent>)RunResultMultimodal 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 ​

MethodDescription
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 helpers finalText() and finalMessageOptional().
  • RunTerminationReason: COMPLETED, MAX_STEPS, TOKEN_BUDGET_EXHAUSTED, DURATION_BUDGET_EXHAUSTED, MODEL_MAX_TOKENS, ABORTED, ERROR.
  • StructuredRunResult<T>: record(T value, RunResult runResult) with convenience accessors sessionId(), runId(), totalUsage(), stepsExecuted(), turnsExecuted(), and rawText().
  • StructuredOutputOptions: StructuredOutputOptions.builder().schemaName(...).schemaDescription(...).strict(true).maxValidationRetries(2).build(). On exhaustion or early termination, promptStructured throws StructuredOutputException containing rawText() and runResult().

AgentEvent (22 Sealed Event Types) ​

Package: dev.openhusky.core.event · Exhaustive switch pattern matching over sealed interface AgentEvent. Every event exposes sessionId() and timestamp().

CategoryEvent RecordKey Fields
Run / TurnRunStartedrunId
TurnStartedrunId, turnIndex, userPrompt
TurnFinishedrunId, turnIndex, finalMessage, usage
RunFinishedrunId, stopReason, terminationReason, totalUsage
RunErrorrunId, message, cause
LLM StepsStepStartedrunId, stepIndex
StepFinishedrunId, stepIndex, usage
TextDeltarunId, delta
ThinkingDeltarunId, delta
ToolCallDeltarunId, toolCallId, toolName, argumentsDelta
ToolsToolCallStartedrunId, toolCallId, toolName, argumentsJson
ToolCallProgressrunId, toolCallId, toolName, message
ToolCallFinishedrunId, toolCallId, toolName, outputPreview, isError, durationMs, details
HITL & PolicyApprovalRequestedrunId, approvalId, toolCallId, toolName, argumentsJson, reason
ApprovalResolvedrunId, approvalId, toolName, approved, reason
PermissionPolicyChangedrunId, modeName
State & ControlStateDeltarunId, namespace, patch (null deletes key)
SteeringAppliedrunId, steeringText, skippedToolsCount
CompactionAppliedrunId, messagesBefore, messagesAfter
ModelChangedrunId, providerId, modelId, reasoningEffort
ResilienceDoomLoopDetectedrunId, toolName, consecutiveCount, action
ModelRetryScheduledrunId, attempt, maxRetries, delayMs, reason

Tools, Permissions & Interceptors SPI ​

AgentTool, ToolContext & ToolResult (dev.openhusky.core.tool) ​

  • AgentTool: implement spec(), execute(ToolContext, Map<String, Object>), and optionally override executionMode() (SEQUENTIAL default or PARALLEL_SAFE), readOnly() (false default), and timeout() (null inherits runtime timeout).
  • ToolContext: record(sessionId, runId, toolCallId, principal, abortSignal, progressEmitter, attributes) with emitProgress(String).
  • ToolResult factories:
    • 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 to DENY). Supports exact names and prefix wildcards ("mcp__docs__*").
  • Presets: PermissionPolicy.failClosed(), readOnly(), requireApprovalForWrites(), allowAll().
  • ApprovalDecision factories: approveOnce(), approveForSession(), reject(String reason).
  • ApprovalDecision.Handler: implement requestApproval(Request, AbortSignal); async brokers can also override prepareApproval(Request) and cancelApproval(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) ​

  • Providers factory 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") or ModelSpec.custom(id, contextWindow, maxOutputTokens).

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