Session Engine, Subagents & Channels
crates/hya-engine provides the single-agent SessionEngine and extension host on top of the hya-core kernel, while modular native ABI v2 bundles (hya/multi-agent, hya/agent-channels, hya/goal, hya/loop, and hya/workflow) layer multi-agent supervision, vertical channels, governed loops, and Workflow DAG execution solely through Arc<dyn HostRuntime>.
1. Turn Lifecycle & Immutable TurnBinding
When a prompt, slash command, or shell turn enters SessionEngine:
- Lease reservation: Each session allows at most one active turn at a time (
TurnGate/TurnLease). A client prompt, like a bundle’srun_turnprompt, is admitted only under the lease of the turn that answers it (SessionEngine::admit_turn, thenrun_admitted_turn), so no other turn, such as a resident wake of the lead, can answer it first. A lead wake’s own prompt is the exception: the wake appends it before it claims the turn, so a client prompt that claims in between is answered together with it, and the wake then finds the session busy and runs no turn. Concurrent requests, including one that meets a resident wake’s turn, receive409 session_busy. - Immutable
TurnBinding: At turn start, the engine resolves the session’sCatalogScope(Global,Directory, orProject) into an immutable snapshot of tools, skills, hooks, agent definitions, and guidance. Agent definitions form one roster (AgentCatalog) from the enabled bundles alone:hya-maincomes fromhya/core-agentslike any bundle agent, and the core’s compiled-inhya-barejoins the roster (as the default) only when no enabled bundle declaresdefault_agent. If a user installs a bundle or reloads skills mid-turn, the running turn finishes cleanly on its captured binding while the next turn picks up the new generation. - File snapshots &
/undo: Before mutating tools run, workspace file hashes/blobs are recorded (FilesChanged+file_blob). CallingRevertSession(/undo) hides the reverted messages in the projection and restores prior bytes on disk until/redoor the next user message commits the cut.
2. Episodic Resident Subagents (hya/multi-agent)
Hya has one unified subagent model: every child spawned via task (or a Workflow Stage) is an episodic resident actor (at most two layers below the main agent), provided by the official hya/multi-agent bundle over Lockstep Native ABI v2. The core only knows that a session may have a parent; with the bundle disabled no supervisor, governor, or spawn queue exists and task, wait, report, and archive are not registered.
stateDiagram-v2
[*] --> ActiveEpisode: task() spawns child<br/>Mints handle + #DM + bundle_claim(epoch=1)
ActiveEpisode --> Archived: Calls report() (or parent archive())<br/>Commits state Handoff + releases claim & budget
Archived --> ActiveEpisode: Parent sends mail on #DM<br/>agent_restarted(epoch+1) with system prompt + prior Handoff + DM
The task tool is one bundle’s tool, not a core path: bundles/examples/mini-agents, built only against hya-runtime-abi and @hya/tui-sdk, replaces it with a blocking task and a child session (authorize_agent_run then spawn_session_and_run) under hya --bare (Track P T2.61).
Key invariants
- Deterministic handles: Minted on the team-root log as
main/<type>-<operator>(e.g.main/hya-scout-suzuran). - Transactional epoch fencing (
bundle_claim/ActorClaim): Every durable write by a subagent checks its fenced lease in SQLite’s genericbundle_claimtable (viaHostBundleStorage). A stale or superseded worker can never commit late tool results or consume mail meant for its replacement. - Zero-cost sleep & Handoff revival: On
report, Hya checks that the subagent has no unread mail and no still-running children, summarizes its episode into a state-only Handoff (modelsummarizer ordeterministicprojection summary), refunds its concurrency/capacity lease, and archives it. Later downward mail on its#DMrevives the same handle and session withsystem prompt + handoff(n) + new DMinstead of replaying a huge stale transcript. - Concurrency & runaway budgets: Bounds concurrent streaming members (
max_concurrency), live team members (per_run_budget), total team turns (per_team_turn_budget), and total mail events (per_team_message_budget), configured in~/.config/hya/bundles/hya/multi-agent.toml.
3. Strictly Vertical Channel Plane (hya/agent-channels)
Inter-agent mail is event-sourced on the team-root session’s event_log as Event::Extension (bundle: "hya/agent-channels", kinds channel_created, channel_joined, mail_sent, mail_consumed) with strictly vertical addressing:
#DM-{8}: Private 1-on-1 pipe between a parent and one direct child, persisted across archive/revive episodes.#announce-{8}: Broadcast pipe owned by a unit leader (mainor a depth-1 parent) to all of its live direct children. Siblings cannot discover or message each other sideways.- Exactly-once cursor (
mail_consumed): Shared across in-turn[NEW MAIL]steering notices (unread-mail-steerNativeHook), mail-awarewaitwakes, andread channel://...calls (UriSchemaHandler), preventing duplicate synthesis turns (TEAM QUIESCED) when a parent already read its children’s reports during its turn. - When a notice may join a result: the
unread-mail-steerhook appends[NEW MAIL]only when itstool.execute.afterinput saysnotices: true. The engine sets itfalsefor a turn-ending call and the rest of its round, a tool that withholds notices (Tool::notices), a paged or altered result, and a user shell command; it keeps no mail state of its own. - Channel templates are bundle assets: a template is an
assets:entry atchannels/<id>.yaml.hya/agent-channelsowns the template types and validation: it parses its own templates (unit-default,parent-dm-default) when it registers and the other catalog bundles’ templates when it compiles a scope’s channel policy.hya-bundlehas no channel types, and a top-levelchannels:key is rejected.
4. Governed Execution (hya/goal, hya/loop & hya/workflow)
- Goal (
hya -p,hya/goal) & Loop (hya loop,hya/loop) drivers: Implemented as ABI v2NativeDrivers (hya/goal:goal,hya/loop:loop) in native bundles running overHostRuntimewhere stop authority belongs strictly to budgets, stall detection,--until/--whileshell exit codes, and independent evaluator/verifier sessions or hooks. - Durable Workflow executor (
hya/workflow): Compiles*.hya.mdsources (project, user, and bundleworkflows/assets) with its owncompilemodule and runs the resultingCompiledWorkflowStage DAGs on top ofHostTurnRunnerandEvent::Extension(extensions["hya/workflow"])—mapping anonymous Stages to one-shot episodes,actor:keys to persistent resident sessions woken by mail, andmode: loopStages to fresh verifier sessions, exposed viaBundleApi(/workflows,/state,/command). - Sidecar wire contract: Per-activation JavaScript sidecars and bundle processes speak newline-delimited JSON-RPC 2.0 using plugin protocol version 1 (
initializeretains existingprotocol_versionandhostfields, and the only activation-specific metadata is{ activation_id, lifecycle }).
5. Ordered Shutdown & Crash Recovery
hya_app::BuiltSessionEngine::shutdown and hya_server::ServerRuntime::drain tear down services in strict order so no SQLite writes or orphan child processes leak:
- Fence new turn/Workflow admissions and close open SSE/gRPC streams with
serverStopping { reason }. - Cancel in-flight root and subagent turns (5s
DRAIN_DEADLINE), recordingpending_resumerows on graceful server stops. - Stop the native services together (the
hya/multi-agentsupervisor ends its members, Workflow joins its runs) within the same drain deadline. - Gracefully shut down (
shutdownRPC) and reap all MCP and plugin child processes and their tracked I/O tasks. - Flush queued store writes (
EXIT_DRAIN_TIMEOUT= 30s) and release<db>.runtime-owner.lock.