Skip to content

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

java
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) ​

java
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) ​

java
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 AbortSignal Cancellation: Aborting the parent session immediately cancels active child runs.
  • Recursion Depth Guard (maxDelegationDepth): Tracks ToolContext.attributes().get("delegationDepth") (default maxDelegationDepth = 3) and returns a tool error if exceeded.
  • Automatic readOnly() Propagation: Unless overridden via .readOnly(boolean), SubagentTool.readOnly() inspects childRuntime.tools() against childRuntime.permissionPolicy() and evaluates to true when all permitted child tools are read-only—allowing PermissionPolicy.readOnly() or allowReadOnlyTools() on the parent to permit read-only subagents automatically.
  • Session Lineage & session_id Resume: Child sessions record parentSessionId and metadata sessionKind=subagent, subagentTool=<name>. A parent model can pass the returned childSessionId in the session_id argument to resume an existing child conversation; SubagentTool verifies that tenantId, principalId, and parentSessionId all match the caller before resuming.
  • Exclusion from Top-Level Lists: SubagentTool.isSubagentSession(SessionHeader) lets session list UIs filter out internal subagent sessions when desired.
java
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.

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

  1. 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), invoke entryFactory.apply(currentLeafId), insert into session_entries, update leaf_entry_id / updated_at / entry_count (plus title on SessionInfoEntry), and commit. Never split read-leaf and write-entry across separate transactions, or concurrent writes can create unintended sibling forks.
  2. Null-Preserving StatePatchEntry.patch Serialization: SessionJsonCodec.encodeEntry(entry) preserves null map values (used by SessionProjector to delete keys). Do not configure your database JSON codec or PostgreSQL jsonb_strip_nulls to drop null entries.
  3. Tenant-Safe SessionQuery Filtering: Honor tenantId, principalId, agentId, sessionKey, textQuery, includeForkedChildren (filtering parent_session_id IS NULL when false), limit, and offset so AgentRuntime.listSessions(principal, query) stays strictly isolated.
  4. Session ID & Format Version Validation: Call SessionHeader.requireSafeSessionId(id) on creation/lookup (throwing SessionCorruptionException on unsafe IDs) and throw SessionFormatException if version > 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:

java
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:

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

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