Skip to content

Tree Sessions & Live Control ​

Every OpenHusky session is backed by an append-only, event-sourced tree rather than a mutable flat message list. Combined with a dual-queue virtual-thread AgentLoop, callers can branch, time-travel, compact context safely, steer active runs mid-flight, and intercept every step.

Append-Only Tree Sessions (openhusky-session) ​

openhusky-session models history as immutable SessionEntry nodes linked by (id, parentId, timestamp):

  • MessageEntry — lossless openhusky-ai Message (ThinkingBlock, ImageBlock, ToolCallBlock, ToolResultBlock, TokenUsage, StopReason)
  • CompactionEntry — non-destructive summary anchor pointing to firstKeptEntryId
  • StatePatchEntry — durable domain/UI state delta (AG-UI STATE_DELTA semantics; null removes a key)
  • ModelChangeEntry — provider, model, and ReasoningEffort switch record
  • SessionInfoEntry — append-only title and metadata updates
  • CustomEntry — extension state or branch summary (modelVisible = true projects as a UserMessage)

SessionProjector.project(branch) folds the active branch in a single pass into SessionProjection(messages, state, title, activeModel).

Pluggable Storage (SessionStore SPI) ​

StoreModuleBest For
InMemorySessionStoreopenhusky-sessionUnit tests, ephemeral sessions, high-throughput stateless gateways
JsonlSessionStoreopenhusky-sessionZero-JDBC single-file <baseDir>/<sessionId>.jsonl persistence with atomic create/fork and lenientTrailingLine crash recovery
SqliteSessionStoreopenhusky-session-sqliteProduction single-node or shared DataSource persistence with SQLite WAL mode and transactional FTS5 (unicode61) search
java
try (SqliteSessionStore store = SqliteSessionStore.open(Path.of("data/sessions.db"))) {
    List<SessionSummary> hits = store.list(
            SessionQuery.builder().textQuery("running").build()
    );
}

fork, rewindTo, and Cut-Point-Safe Compaction ​

Because entries are never mutated in place, branching and time-travel are non-destructive:

java
// Branch a new independent session from a specific entry ID
AgentSession branched = session.fork(entryId, "session-branch-2");

// Move the active leaf back to an earlier entry without deleting history
session.rewindTo(entryId);

// Non-destructive context compaction (never splits ToolCall / ToolResult pairs)
boolean compacted = session.compactNow();

CompactionCutPoint, ToolPairSanitizer, and StructuredCompactor ensure compaction never orphans a ToolCallBlock without its matching ToolResultBlock, producing structured Goal / Constraints / Progress / Artifacts / Next-Steps summaries. When a provider still signals context overflow (ContextOverflowException), AgentLoop triggers emergency compaction and performs a clean single-retry recovery.

Live Mid-Run Control ​

While session.prompt(...) is running on one virtual thread, another thread (or an HTTP endpoint like AG-UI /steer and /abort) can control the active run safely:

java
// Interrupt at the next tool boundary, synthesizing skipped ToolResultBlocks cleanly
session.steer("Skip heavyweight fleece jackets and only show ultralight trail shells.");

// Queue a continuation turn to run automatically right after the current turn completes
session.followUp("Summarize the top pick in 2 bullet points.");

// Cooperatively cancel via linked AbortSignal
session.abort("User clicked stop");

// Live model & reasoning effort switching mid-session
session.setModel(ModelCatalog.defaults().require("claude-sonnet-4-5-20250929"));
session.setReasoningEffort(ReasoningEffort.HIGH);

Interceptors & Runtime Listeners ​

OpenHusky exposes three synchronous waterfall interceptor contracts plus runtime-level event listeners:

  • LlmInterceptor (openhusky-ai): RetryInterceptor, CostTrackerInterceptor, custom header/guardrail hooks.
  • StepInterceptor (openhusky-core): DoomLoopGuardInterceptor (stateless detection of repeated identical tool calls with nudgeThreshold = 3 and breakThreshold = 5).
  • ToolInterceptor (openhusky-core): OutputOffloadToolInterceptor (in-memory or disk spill for large tool outputs while preserving ImageBlocks and details).
  • Runtime eventListener(...) v0.2.0: Subscribe once on AgentRuntime.Builder to receive (EventContext, AgentEvent) across all sessions (used by openhusky-otel and sidecar memory modules):
java
AgentRuntime runtime = AgentRuntime.builder()
        .provider(provider)
        .model(model)
        .stepInterceptor(DoomLoopGuardInterceptor.defaults())
        .toolInterceptor(OutputOffloadToolInterceptor.inMemory(32_768))
        .eventListener((ctx, event) -> auditSink.record(ctx.principal(), event))
        .build();

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