Production Cookbook
Implementation patterns for extending, delegating, persisting, budgeting, and operating OpenHusky agents in production services.
1. Custom LlmInterceptor, StepInterceptor & ToolInterceptor
All three Extension Track SPIs implement an OkHttp-style synchronous waterfall chain—ideal for rate limiting, audit logging, PII redaction, and policy guardrails:
ToolInterceptor (Tool Audit & Payload Redaction)
import dev.openhusky.core.interceptor.ToolInterceptor;
import dev.openhusky.core.tool.ToolResult;
ToolInterceptor auditAndRedact = (invocation, next) -> {
long startNs = System.nanoTime();
String toolName = invocation.tool().spec().name();
String tenantId = invocation.context().principal().tenantId();
ToolResult result = next.proceed(invocation);
long elapsedMs = (System.nanoTime() - startNs) / 1_000_000L;
auditLog.info("tenant={} tool={} error={} durationMs={}",
tenantId, toolName, result.isError(), elapsedMs);
return result;
};StepInterceptor (Per-Step Tenant Budget or Dynamic Model Policy)
import dev.openhusky.core.interceptor.StepInterceptor;
StepInterceptor stepAudit = (ctx, next) -> {
var response = next.proceed(ctx);
metrics.recordStepTokens(ctx.sessionId(), ctx.stepIndex(), response.usage().totalTokens());
return response;
};LlmInterceptor (Gateway Telemetry & Header Injection)
import dev.openhusky.ai.provider.LlmInterceptor;
LlmInterceptor correlationHeader = (request, signal, onEvent, next) -> {
long start = System.nanoTime();
try {
return next.proceed(request, signal, onEvent);
} finally {
long latencyMs = (System.nanoTime() - start) / 1_000_000L;
log.debug("model={} latencyMs={}", request.model().id(), latencyMs);
}
};Register LlmInterceptors on LlmClient.of(provider).withInterceptor(...), and StepInterceptor / ToolInterceptor on AgentRuntime.builder(). Interceptors execute in registration order.
2. Hierarchical Multi-Agent Delegation (SubagentTool)
Wrap any specialized AgentRuntime inside a SubagentTool (dev.openhusky.core.subagent.SubagentTool) so a parent agent can delegate bounded subtasks:
- Linked
AbortSignalCancellation: Aborting the parent session immediately cancels active child runs. - Recursion Depth Guard (
maxDelegationDepth): TracksToolContext.attributes().get("delegationDepth")(defaultmaxDelegationDepth = 3) and returns a tool error if exceeded. - Automatic
readOnly()Propagation: Unless overridden via.readOnly(boolean),SubagentTool.readOnly()inspectschildRuntime.tools()againstchildRuntime.permissionPolicy()and evaluates totruewhen all permitted child tools are read-only—allowingPermissionPolicy.readOnly()orallowReadOnlyTools()on the parent to permit read-only subagents automatically. - Session Lineage &
session_idResume: Child sessions recordparentSessionIdand metadatasessionKind=subagent,subagentTool=<name>. A parent model can pass the returnedchildSessionIdin thesession_idargument to resume an existing child conversation;SubagentToolverifies thattenantId,principalId, andparentSessionIdall match the caller before resuming. - Exclusion from Top-Level Lists:
SubagentTool.isSubagentSession(SessionHeader)lets session list UIs filter out internal subagent sessions when desired.
import dev.openhusky.core.policy.PermissionPolicy;
import dev.openhusky.core.runtime.AgentRuntime;
import dev.openhusky.core.subagent.SubagentTool;
import java.time.Duration;
AgentRuntime researchRuntime = AgentRuntime.builder()
.llmClient(llmClient)
.model(fastModel)
.systemPrompt("You are a read-only research specialist. Return concise factual findings.")
.sessionStore(sharedStore)
.tools(readOnlyTools)
.permissionPolicy(PermissionPolicy.readOnly())
.maxStepsPerTurn(12)
.build();
SubagentTool researchSubagent = SubagentTool.builder(
"research_subagent",
"Delegate deep read-only investigation tasks to a specialist subagent.",
researchRuntime)
.inheritHistory(false)
.maxDelegationDepth(2)
.timeout(Duration.ofMinutes(3))
.build();
AgentRuntime parentRuntime = AgentRuntime.builder()
.llmClient(llmClient)
.model(primaryModel)
.sessionStore(sharedStore)
.tool(researchSubagent)
.permissionPolicy(PermissionPolicy.failClosed()
.allowReadOnlyTools() // Permits research_subagent automatically
.build())
.build();3. Implementing a Custom SessionStore SPI (PostgreSQL / MySQL)
For horizontally scaled multi-replica deployments behind a load balancer, implement dev.openhusky.session.SessionStore over your shared relational database.
Recommended Relational Schema (Modeled on SqliteSessionStore)
CREATE TABLE sessions (
id VARCHAR(128) PRIMARY KEY,
version INT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
tenant_id VARCHAR(128) NOT NULL,
principal_id VARCHAR(128) NOT NULL,
agent_id VARCHAR(128),
session_key VARCHAR(256),
parent_session_id VARCHAR(128),
parent_entry_id VARCHAR(128),
metadata_json TEXT NOT NULL,
title TEXT,
leaf_entry_id VARCHAR(128),
entry_count INT NOT NULL DEFAULT 0
);
CREATE TABLE session_entries (
seq BIGSERIAL PRIMARY KEY,
session_id VARCHAR(128) NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
entry_id VARCHAR(128) NOT NULL UNIQUE,
parent_id VARCHAR(128),
entry_type VARCHAR(32) NOT NULL,
timestamp TIMESTAMPTZ NOT NULL,
payload_json TEXT NOT NULL
);
CREATE INDEX idx_sessions_tenant_updated ON sessions (tenant_id, updated_at DESC);
CREATE INDEX idx_entries_session_seq ON session_entries (session_id, seq);Critical SPI Invariants
- Transactional
appendToLeaf(sessionId, entryFactory): Lock the session row inside a single database transaction (SELECT leaf_entry_id, entry_count FROM sessions WHERE id = ? FOR UPDATE), invokeentryFactory.apply(currentLeafId), insert intosession_entries, updateleaf_entry_id/updated_at/entry_count(plustitleonSessionInfoEntry), and commit. Never split read-leaf and write-entry across separate transactions, or concurrent writes can create unintended sibling forks. - Null-Preserving
StatePatchEntry.patchSerialization:SessionJsonCodec.encodeEntry(entry)preservesnullmap values (used bySessionProjectorto delete keys). Do not configure your database JSON codec or PostgreSQLjsonb_strip_nullsto dropnullentries. - Tenant-Safe
SessionQueryFiltering: HonortenantId,principalId,agentId,sessionKey,textQuery,includeForkedChildren(filteringparent_session_id IS NULLwhenfalse),limit, andoffsetsoAgentRuntime.listSessions(principal, query)stays strictly isolated. - Session ID & Format Version Validation: Call
SessionHeader.requireSafeSessionId(id)on creation/lookup (throwingSessionCorruptionExceptionon unsafe IDs) and throwSessionFormatExceptionifversion > SessionHeader.CURRENT_FORMAT_VERSION.
4. Budgets, Timeouts & Graceful Shutdown
Configure explicit safety bounds on every production AgentRuntime so runaway tool loops or stalled upstream models cannot exhaust token spend or virtual threads:
AgentRuntime runtime = AgentRuntime.builder()
.llmClient(llmClient)
.model(model)
.maxStepsPerTurn(20) // Default: 32
.maxTotalTokensPerRun(200_000) // Default: 0 (unlimited)
.maxRunDuration(Duration.ofMinutes(5)) // Default: null (unlimited)
.toolTimeout(Duration.ofSeconds(45)) // Default: 2m
.approvalTimeout(Duration.ofMinutes(5)) // Default: null
.stepInterceptor(DoomLoopGuardInterceptor.defaults())
.toolInterceptor(OutputOffloadToolInterceptor.inMemory(32_768))
.build();On JVM shutdown, abort active AG-UI runs and pending approvals first, then close AgentRuntime, external toolkits (McpToolkit), sandboxes (AgentSandbox), and SessionStore:
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
agUiRunner.abortAll("JVM shutting down");
runtime.close();
mcpToolkit.close();
sandbox.close();
sessionStore.close();
}, "openhusky-shutdown"));For deterministic offline unit tests, Spring Boot testing (ApplicationContextRunner / MockMvc), complete exception diagnostics, and troubleshooting, continue to Testing, Errors & Troubleshooting.