Native Bundle Runtime ABI v2 (crates/hya-runtime-abi)
1. Introduction
Lockstep Native ABI v2 (crates/hya-runtime-abi) is the unified Rust dynamic-library (cdylib) contract between the hya host binary and compiled native bundles (runtime: { kind: native, abi_version: 2 }).
Under Hya v2, core crates (hya-core, hya-engine, hya-server, hya-store, hya-proto) stay slim and single-agent focused while domain capabilities—hashline editing, LSP/formatters, context compaction, network fetch/search, plan mode, goal/loop drivers, multi-agent supervision, vertical channels, and workflows—live in modular native bundles under the official bundle repository.
Native ABI v2 solves two problems that limited ABI v1:
- Unified registration: A single
cdylibcan register any combination of tools, context rewriters, background services, lifecycle hooks, HTTP/gRPCBundleApihandlers, event-logProjectionReducers, custom URIUriSchemaHandlers,NativeDrivers, and declared hook points through one entry symbol (hya_native_register_v2). - Zero-linkage host mediation: Native bundles never link
hya-store,sqlx,hya-engine,hya-server,axum, ortonic. Instead, the host injects anArc<dyn HostRuntime>giving typed, mediated access to session logs, generic KV/claim persistence, turn execution, model calls, the live event bus, catalogs, and sibling extensions—verified before registration by a 32-byte lockstep SHA-256 ABI digest.
2. Usage
Declaring a Native ABI v2 bundle (bundle.yaml)
Declare schema_version: 2, runtime.kind: native, runtime.abi_version: 2, crate_dir, library, and the capability flags your native library registers:
kind: Bundleschema_version: 2identity: id: acme/metrics-pack version: 1.0.0 publisher: acmenamespace: metrics-packruntime: kind: native abi_version: 2 crate_dir: native library: native/libacme_metrics_native.so # .dylib on macOS capabilities: - tools - services - hooks - apisresources: tools: - id: record_metric path: tools/record_metric.jsonA native tool registers under its own Tool::name(), whatever the publisher. When two enabled bundles export the same name, exactly one of them must declare overrides: <other-bundle-id>, otherwise the load fails; load order never decides. To replace a standard hya-bare tool (read, write, edit, grep, or bash), declare overrides: hya/bare on the bundle and/or individual tool entries. Reserved kernel tools (todo and rewrite) can never be overridden, shadowed, or aliased by any bundle.
Zero-linkage red line & crate layout
Every native bundle crate MUST respect the zero-linkage red line (enforced in CI and crate boundaries):
- ABI boundary crates:
hya-runtime-abi,hya-proto,hya-tool, andhya-provider. - One dependency is enough:
hya-runtime-abire-exportshya_proto,hya_provider, andhya_tool(includinghya_runtime_abi::hya_tool::ToolError), and the bundle types fromhya_proto::bundle. An external bundle can depend onhya-runtime-abiand generic crates alone.bundles/examples/mini-agentsdoes exactly that: itstasktool and child session run withhya --bundles example/mini-agents(see Bundles). - Forbidden host-internal crates:
hya-store,sqlx,hya-engine,hya-server,axum,tonic.
Tip (rlib core + thin
cdylibwrapper): If a workspace test or another crate needs to import your bundle’s Rust types directly alongside other native bundles, put the domain logic in a pure library crate (crate-type = ["rlib"]) and keepexport_native_bundle_v2!inside a thincdylib-only wrapper crate so two linked crates never export colliding#[no_mangle]ABI v2 C symbols.
Worked example (native/Cargo.toml & native/src/lib.rs)
[package]name = "acme-metrics-native"version = "0.1.0"edition = "2024"
[lib]crate-type = ["cdylib"]
[dependencies]async-trait = "0.1"# Inside an extracted hya-abi-sdk workspace, use `{ workspace = true }`:hya-runtime-abi = { workspace = true }serde_json = "1"use std::sync::Arc;
use async_trait::async_trait;use hya_runtime_abi::hya_proto::{ToolName, ToolSchema};use hya_runtime_abi::hya_tool::{Tool, ToolCtx, ToolError};use hya_runtime_abi::{ ApiMethod, ApiScope, HostError, HostRuntime, NativeApiEndpoint, NativeBundleApiHandler, NativeBundleApiReply, NativeBundleApiRequest, NativePluginContext, NativeRegistrations, NativeService, ServiceHealth,};use serde_json::{Value, json};
struct RecordMetricTool { bundle_id: String, runtime: Arc<dyn HostRuntime>,}
#[async_trait]impl Tool for RecordMetricTool { fn name(&self) -> &str { "record_metric" }
fn schema(&self) -> ToolSchema { ToolSchema { name: ToolName::new("record_metric"), description: "Persist a session metric via HostBundleStorage and emit an Event::Extension.".into(), input_schema: json!({ "type": "object", "properties": { "key": { "type": "string" }, "value": { "type": "number" } }, "required": ["key", "value"] }), output_schema: None, } }
async fn execute(&self, ctx: &ToolCtx, input: Value) -> Result<Value, ToolError> { let key = input["key"] .as_str() .ok_or_else(|| ToolError::Input("missing string `key`".into()))?; let scope = ctx .session .map(|id| format!("session:{id}")) .unwrap_or_else(|| "global".to_string());
// Write scoped KV state through HostBundleStorage (no sqlx/hya-store linkage!) let entry = self .runtime .bundle_storage() .put_state(&self.bundle_id, &scope, key, input["value"].clone(), None) .await .map_err(ToolError::from)?;
// Append a durable Event::Extension if running inside a session if let Some(session) = ctx.session { self.runtime .session_store() .append_extension_event( session, &self.bundle_id, "metric_recorded", json!({ "key": key, "value": entry.value }), None, ) .await .map_err(ToolError::from)?; }
Ok(json!({ "key": entry.key, "version": entry.version })) }}
struct MetricsApi { bundle_id: String, runtime: Arc<dyn HostRuntime>, endpoints: Vec<NativeApiEndpoint>,}
#[async_trait]impl NativeBundleApiHandler for MetricsApi { fn id(&self) -> &str { "metrics-api" }
fn endpoints(&self) -> &[NativeApiEndpoint] { &self.endpoints }
async fn handle( &self, request: NativeBundleApiRequest, ) -> Result<NativeBundleApiReply, HostError> { let scope = request .session .map(|id| format!("session:{id}")) .unwrap_or_else(|| "global".to_string()); let rows = self .runtime .bundle_storage() .list_state(&self.bundle_id, &scope, None) .await?; Ok(NativeBundleApiReply { status: 200, body: json!({ "metrics": rows }), }) }}
struct MetricsService;
#[async_trait]impl NativeService for MetricsService { fn id(&self) -> &str { "metrics-service" }
async fn start(&self, _runtime: Arc<dyn HostRuntime>) -> Result<(), HostError> { Ok(()) }
async fn stop(&self) -> Result<(), HostError> { Ok(()) }
async fn health(&self) -> ServiceHealth { ServiceHealth::healthy("ready") }}
fn register(ctx: &NativePluginContext, out: &mut NativeRegistrations) { let runtime = Arc::clone(ctx.runtime()); let bundle_id = ctx.bundle_id().to_string();
out.tools.push(Arc::new(RecordMetricTool { bundle_id: bundle_id.clone(), runtime: Arc::clone(&runtime), })); out.services.push(Arc::new(MetricsService)); out.api_handlers.push(Arc::new(MetricsApi { bundle_id, runtime, endpoints: vec![NativeApiEndpoint { id: "list-metrics".into(), method: ApiMethod::Get, scope: ApiScope::Session, path: "/metrics".into(), description: "List metrics stored for this session".into(), }], }));}
// Export all four lockstep ABI v2 C symbols:hya_runtime_abi::export_native_bundle_v2!(|ctx, out| { register(ctx, out);});Building, inspecting symbols & packaging
The commands use Linux library names. On macOS, use .dylib in the manifest and staging path.
# 1. Build the cdylibcargo build --manifest-path native/Cargo.toml --release --target-dir target
# 2. Verify all four ABI v2 C symbols are exported (Linux example)nm -D --defined-only target/release/libacme_metrics_native.so | grep hya_native_
# 3. Stage the library, then validate and pack the .hyabundle archivecp target/release/libacme_metrics_native.so native/hya bundle verify --strict .hya bundle pack . acme-metrics-pack.hyabundleHost loading (crates/hya-tool-loader)
Installed native bundles load their packaged libraries through
hya-tool-loader. The loader registers tools from the bundle’s own
resources.tools descriptors and binds registration to its bundle ID.
Loading runs in four steps:
dlopen(RTLD_NOW | RTLD_LOCAL)the verified dynamic library (cached by(canonical_path, content_digest), staging fresh bytes if a path is replaced in place so stale code is never served).- Call
hya_native_abi_v2and compare its 32-byte digest againsthya_runtime_abi::abi_digest_v2()(mismatches abort immediately withAbiError::DigestMismatchbefore any Rust object crosses FFI). - Call
hya_native_share_deadline_v2to adopt the host’s process-lifetime run-deadline cell and bindhya_native_with_runtime_v2for Tokio TLS bridging across thecdylibboundary (registration, future-poll, and event-observer FFI trampolines are guarded withstd::panic::catch_unwindso a bundle panic cannot unwind acrossextern "C"). - Wrap the host
Arc<dyn HostRuntime>inScopedHostRuntime::for_bundle(bundle_id, runtime), constructNativePluginContext::new(bundle_id, scoped_runtime), and callhya_native_register_v2, returning aNativeRegistrationscontainer wrapped in runtime-bridged adapters.NativeService::startandNativeDriver::runlikewise receive aScopedHostRuntimebound to their owning bundle (enforced both byhya-tool-loader’s adapters andhya-app’sprepare_driver).
A bundle that returns providers registrations without declaring providers in runtime.capabilities fails to load with <bundle-id> registers providers but does not declare the providers capability, so a provider kind is never dropped silently.
3. Interface Definitions
3.1 Exported ABI v2 C Symbols & Export Macro
ABI_VERSION_V2: u32 = 2. Generated automatically by hya_runtime_abi::export_native_bundle_v2!:
export_native_bundle_v2!(|ctx, out| { ... });export_native_bundle_v2!(|out| { ... });
The block may return () or Result<(), E> (where E: Display, via IntoRegistrationResult).
| Constant / Symbol | C Function Signature (extern "C") |
Responsibility |
|---|---|---|
SYMBOL_ABI_V2 (hya_native_abi_v2) |
unsafe extern "C" fn(out: *mut u8) (AbiDigestFn) |
Writes the 32-byte lockstep SHA-256 digest (abi_digest_v2()). Verified before any other symbol is called. |
SYMBOL_WITH_RUNTIME_V2 (hya_native_with_runtime_v2) |
unsafe extern "C" fn(handle: *const c_void, callback: unsafe extern "C" fn(*mut c_void), state: *mut c_void) (WithRuntimeFn) |
Enters the cdylib’s Tokio runtime TLS handle while synchronously polling one future. |
SYMBOL_SHARE_DEADLINE_V2 (hya_native_share_deadline_v2) |
unsafe extern "C" fn(cell: *const c_void) (ShareDeadlineFn) |
Adopts the host’s process-lifetime deadline cell (deadline_cell_v2()) inside the bundle’s hya-tool copy. |
SYMBOL_REGISTER_V2 (hya_native_register_v2) |
unsafe extern "C" fn(ctx: *const NativePluginContext, out: *mut NativeRegistrations, error_out: *mut Option<String>) -> i32 (RegisterV2Fn) |
Populates NativeRegistrations. Returns 0 on success, -1 on null pointer, or 1 with error_out populated on registration failure. |
Lockstep digest coverage (abi_digest_v2()): The digest includes the ABI
domain separator, major version (ABI_VERSION_V2), independent contract
version (ABI_SEMVER), rustc -V, the full Cargo target triple, and the
resolved versions and features of tokio, tokio-util, serde_json,
indexmap, and uuid. It includes sizes and alignments for the ABI-crossing
types plus the normalized contract digest (abi_contract_digest_v2()), which
strips comments, formatting whitespace, and #[cfg(test)] items from the
curated ABI-crossing source files across the four boundary crates. Host-only
modules (hya-runtime-abi/src/scoped.rs, hya-tool/src/registry.rs,
hya-tool/src/permission/policy.rs, and hya-provider/src/registry.rs) are
outside the ABI boundary so edits to host implementations, comments,
formatting, or unit tests never invalidate abi_digest_v2().
tokio/parking_lot is forbidden because its process-local parking table
cannot coordinate between two copies of Tokio, and the build script enforces
exact adherence to the declared SDK_FEATURES set so unrelated workspace
crates cannot silently drift cross-boundary dependency features. The build uses
Cargo’s resolved graph in the source workspace and the SDK. Cargo’s isolated
package verification uses the packaged lockfile and the SDK feature contract.
One Tokio feature set, without parking_lot: the host and every bundle library link their own copy of tokio, and tokio objects cross the boundary (HostEventBus::subscribe receivers, subscribe_transient_state watch channels, CancellationTokens). With tokio’s parking_lot feature a thread parks in a table global to its parking_lot copy, so one copy cannot wake a thread the other parked, and a contended channel hangs. The workspace therefore enables tokio’s full set minus parking_lot (root Cargo.toml); a bundle built in the same Cargo invocation inherits that set and must not add parking_lot.
3.2 NativePluginContext & NativeRegistrations
pub struct NativePluginContext { // Methods: pub fn new(bundle_id: impl Into<String>, host_runtime: Arc<dyn HostRuntime>) -> Self; pub fn bundle_id(&self) -> &str; pub fn runtime(&self) -> &Arc<dyn HostRuntime>;}
#[derive(Default)]pub struct NativeRegistrations { pub tools: Vec<Arc<dyn Tool>>, pub rewriters: Vec<Arc<dyn Rewriter>>, pub services: Vec<Arc<dyn NativeService>>, pub hooks: Vec<Arc<dyn NativeHook>>, pub api_handlers: Vec<Arc<dyn NativeBundleApiHandler>>, pub projection_reducers: Vec<Arc<dyn ProjectionReducer>>, pub uri_schema_handlers: Vec<Arc<dyn UriSchemaHandler>>, /// Hook points this bundle declares (local names; namespaced `<bundle-id>:<name>`). pub hook_points: Vec<String>, /// Drivers that own a session run (namespaced `<bundle-id>:<name>`). pub drivers: Vec<Arc<dyn NativeDriver>>, /// Provider kinds (config `kind` labels) and their optional OAuth flows. pub providers: Vec<hya_provider::ProviderKindEntry>, /// Generic in-lock post-write file normalizers attached to `ToolCtx::extensions`. pub post_write_normalizers: Vec<Arc<dyn hya_tool::PostWriteNormalizer>>,}3.3 HostRuntime & Its Seven Sub-Traits
HostRuntime is passed as Arc<dyn HostRuntime> and exposes seven capability plane accessors plus optional driver lookups:
pub trait HostRuntime: Send + Sync { fn session_store(&self) -> &dyn HostSessionStore; fn bundle_storage(&self) -> &dyn HostBundleStorage; fn turn_runner(&self) -> &dyn HostTurnRunner; fn model_caller(&self) -> &dyn HostModelCaller; fn event_bus(&self) -> &dyn HostEventBus; fn catalog_reader(&self) -> &dyn HostCatalogReader; fn extension_registry(&self) -> &dyn HostExtensionRegistry;}| Sub-Trait | Methods & Purpose | Key DTOs |
|---|---|---|
HostSessionStore |
session_exists, read_events(session, after_seq, limit) (paged directly via SQLite replay_page), append_events(session, claim, events) (enforces claim.actor_id == session), append_extension_event(session, bundle, kind, payload, claim), read_projection(session), read_extension_state(session, bundle), session_metadata(session), list_sessions(filter), runtime_owner_id(), find_sessions_with_extension(bundle, kind), stage_extension_event(during, target, bundle, kind, payload, on_commit), append_batch(AppendBatch { fence, expect, events, acquire, release }) (validates event.session() == Some(session) on every tuple), project_changes(project, since_ms, limit, exclude), allowed_workspace_roots() |
SessionSummaryMeta, SessionListFilter, Envelope, Event, Projection, ProjectChanges |
HostBundleStorage |
Scoped KV (bundle_state table with injective (bundle, scope, key) primary key and monotonic version >= 1): get_state, put_state(bundle, scope, key, value, expected_version) (None unconditional upsert, Some(0) insert-only, Some(v) optimistic CAS returning HostError::Conflict on mismatch), delete_state, list_state(bundle, scope, prefix) (strictly within scope). Fenced leases (bundle_claim table): acquire_claim, renew_claim, release_claim, read_claim, list_claims. Transient watch state: get_transient_state, set_transient_state, subscribe_transient_state (swept on session deletion). |
BundleStateEntry, BundleClaimRequest, BundleClaimLease |
HostTurnRunner |
Session trees: spawn_session, list_child_sessions (indexed by session.parent_id). Core turns: run_turn(request, cancel), run_turn_with_admission(request, admission, cancel), stop_fenced_sidecar(claim), spawn_session_and_run, steer_turn, cancel_turn, turn_status, drain_cause, user_text. (User-issued !cmd tool calls are not exposed on HostTurnRunner; they are claimed declaratively through NativeCommandBeforeOutcome::ExecuteUserTool and executed strictly by the host engine on inbound /v2 Kind::Shell turns.) |
TurnStartRequest, TurnStart, TurnAdmission, TurnSpawnRequest, TurnOutcome, TurnStatus, TurnRouteOutcome, TurnRouteFailureClass |
HostModelCaller |
complete(request, cancel), stream(request, cancel), compact_window(model, messages), model_window(model), resolve_model_route(entries), model_catalog() |
ModelCallRequest, ModelCallResponse, ModelToolCall, ModelStreamChunk, ModelWindowInfo, ModelRouteEntry, ResolvedModelRoute, ResolvedModelRouteCandidate, ModelCatalogSnapshot, ModelCatalogEntry |
HostEventBus |
publish(envelope), subscribe() -> broadcast::Receiver<Envelope>, publish_extension(session, bundle, kind, payload) |
Envelope |
HostCatalogReader |
list_agents(session), get_agent(name, session), list_skills(session), list_bundles(), get_bundle(id), bundle_config(bundle_id), global_config(), resolve_scope_catalog(session, directory), agent_call_options(session, agent), authorize_agent_run(session, caller, agent), authorize_permission(action, resource, tool, read_only) |
AgentCallOptions, BundleCatalogSummary, ScopeCatalogSnapshot, AgentDef, PreparedAgent, SkillCatalogEntry, Bundle |
HostExtensionRegistry |
list_extensions(kind), has_bundle(bundle_id), invoke_bundle_api(call), invoke_tool(session, tool_name, input, cancel), and bundle-declared hook dispatch: has_hook(session, point) and invoke_hook(session, point, input) -> Option<Value> (first answer wins; an undeclared point is InvalidInput) |
ExtensionKind, ExtensionEntry, BundleApiInvocation, BundleApiResult |
Caller identity binding (ScopedHostRuntime)
Every native bundle receives a ScopedHostRuntime (hya_runtime_abi::ScopedHostRuntime) wrapping the host’s Arc<dyn HostRuntime> and bound to that bundle’s verified bundle_id at registration (invoke_register_v2) and service startup (NativeService::start).
- Identity-bound writes (rejected with
HostError::PermissionDeniedon namespace mismatch):HostBundleStorage:put_state,delete_state,set_transient_state,acquire_claim,renew_claim,release_claim.HostSessionStore:append_extension_event,stage_extension_event,append_events(everyEvent::Extensioninevents), andappend_batch(everyEvent::Extensionineventsunless it matches and consumes a single-use prepared-event grant returned by that exact target bundle in a 2xxinvoke_bundle_apireply, plus everyacquireandrelease).HostEventBus:publish_extension, andpublishwhenenvelope.eventisEvent::Extension.- Shared session-fence exception: Claims under
SESSION_FENCE_CLAIMS("hya/session-fence") are permitted if and only ifmetadata["holder"]equals the caller’sbundle_id, andrenew_claim,release_claim,append_batch.release, andHostTurnRunner::stop_fenced_sidecaradditionally verify the stored active claim’smetadata["holder"]matches the caller’sbundle_idso a foreign bundle cannot forge lease metadata to hijack an active fence or terminate another bundle’s fenced sidecar.
- Cross-bundle reads and observations remain open:
get_state,list_state,get_transient_state,subscribe_transient_state,read_claim,list_claims,read_extension_state,read_projection,find_sessions_with_extension, andProjectionReducer::observed_bundles()can inspect sibling bundles’ published state without spoofing their writes.
Generic bundle host primitives
Transient state lets a native bundle share per-session signals with host callbacks.
Use the bundle ID from NativePluginContext and the session ID as the scope.
Values live in the host process and disappear on restart.
| Interface | Contract | Current consumer |
|---|---|---|
bundle_storage().get_transient_state(bundle: &str, session: SessionId, key: &str) |
Returns Result<Option<Value>, HostError>. |
The state regression test. |
bundle_storage().set_transient_state(bundle: &str, session: SessionId, key: &str, value: Option<Value>) |
Returns Result<(), HostError>. Pass None to remove the key. |
The state regression test. |
bundle_storage().subscribe_transient_state(bundle: &str, session: SessionId, key: &str) |
Returns Result<watch::Receiver<Option<Value>>, HostError>. The receiver exposes the current value and coalesces updates. Equal writes do not signal a change. |
The state regression test observes a key it writes. |
The host itself writes no transient key: whether an after-hook may add a
notice to a tool result reaches the hook as NativeToolAfterInput::notices
(see Bundle-driven turns and lifecycle points).
For example, subscribe to a bundle’s "ready" key, copy the value from
borrow_and_update(), and await changed() for a later value. Release the
borrow before waiting or writing to the key.
Staged extension events
A tool.execute.after hook can stage an Event::Extension that commits in
the same store transaction as the tool result it runs for. Use it when the
event must exist only if the result does, such as an inbox acknowledgement for
mail the hook shows in that result.
| Interface | Contract | Current consumer |
|---|---|---|
session_store().stage_extension_event(during: SessionId, target: SessionId, bundle: &str, kind: &str, payload: Value, on_commit: Option<Box<dyn FnOnce() + Send>>) |
Returns Result<(), HostError>. during is the session whose tool result is in its after-hooks; target is the log that receives the event. The event commits only when the tool succeeds and no wait acknowledgement owns the result; otherwise the host drops the event and on_commit. The host runs each on_commit after the commit, in staging order, before the next tool call. Returns InvalidInput when during has no tool result in its after-hooks, and Unavailable on a host without a turn path. |
The unread-mail steer hook in hya/agent-channels stages mail_consumed for the team root and advances the host’s mail watermark in on_commit. |
For example, a hook stages ("acme/audit", "seen", json!({"call": call})) for
input.session and returns the result unchanged; the audit event is then
appended in the same batch as the tool result, or not at all.
Session trees
A bundle can bind an agent to a child session with
TurnSpawnRequest { parent: Some(lead), agent, .. }. For example, the loop
driver starts each worker iteration with spawn_session_and_run and passes
the lead session as its parent.
| Interface | Contract | Current consumer |
|---|---|---|
turn_runner().spawn_session(request: TurnSpawnRequest) and spawn_session_and_run(request, cancel) |
The first returns Result<SessionId, HostError>. The second waits for a Result<TurnOutcome, HostError>. Both record the request’s parent: Option<SessionId> and agent: AgentName. |
hya/loop creates and runs an iteration worker under its lead. |
turn_runner().list_child_sessions(parent: SessionId) |
Returns Result<Vec<SessionId>, HostError> with direct children in creation order, including archived children. A parent with no rows has an empty list. |
Turn admission
Register a native hook that lists HookPoint::TurnAdmit under the name
turn.admit. Return Steer { message: "Use the cached result".into() } to
append a system message before the first model request. The engine runs the
process hooks followed by the selected agent’s hooks while the turn holds
its lease. A refusal discards all accumulated steer messages. The engine
cancels a deferred wait when the turn is cancelled. An admission hook should
signal readiness without starting another turn on the current session.
| Interface | Contract | Current consumer |
|---|---|---|
NativeHook::turn_admit(input: NativeTurnAdmitInput) |
Input fields are session: SessionId, root: SessionId, and agent: Option<AgentName>. Returns Result<NativeTurnAdmitOutcome, HostError>. Outcomes are Admit, Defer { until: oneshot::Receiver<()> }, Refuse { reason: String }, or Steer { message: String }. A dropped readiness sender or a hook error fails admission. |
The engine’s external-turn guard refuses direct turns on registered multi-agent members. Its existing error and mail guidance remain in effect. |
The hook is available to native bundles. The JSON-RPC plugin hook list remains defined by the plugin wire contract.
Bundle-driven turns and lifecycle points
These primitives let a bundle run child sessions itself: drive their turns
under a session fence, commit multi-session updates atomically, and take part
in stop, close, restore, and headless-run decisions. For example, a team
bundle holds a fence on a child session, appends the child’s directive with
append_batch, and calls run_turn with prompt: None and
start: TurnStart::IfIdle.
| Interface | Contract |
|---|---|
turn_runner().run_turn(request: TurnStartRequest, cancel) |
TurnStartRequest adds prompt: Option<String> (None runs on the log tail), guidance: Option<String> (a system-prompt layer), route: Option<ResolvedModelRoute>, and start: TurnStart (Always queues behind an active turn; IfIdle returns HostError::Conflict without admitting the prompt when a turn is active; run_turn returns Conflict for no other reason). The host admits prompt only once it holds the session’s turn, so no other turn can answer it first (a prompt the caller appends itself before a prompt: None turn has no such guarantee: a turn that claims the session in between answers it); a cancel or a drain while an Always turn with a prompt waits for it admits nothing and returns HostError::Cancelled. With actor_claim: Some(fence), the session must have a parent (otherwise HostError::InvalidInput): the host resolves the agent, roster, and resource policy from the parent session’s binding, admits the prompt under the fence, re-validates the fence before each round and stream, fences every append, and keeps one sidecar for the session until the fence is released through release_claim or the process stops. The fence must be a claim held under SESSION_FENCE_CLAIMS ("hya/session-fence") with the session id as its key, acquired through bundle_storage().acquire_claim (metadata {root_session_id, holder}, holder naming the bundle that took the fence, so each bundle recovers and counts only its own fences); a fence held under any other bundle id fails as stale. A lost sidecar fails the turn with HostError::Unavailable("sidecar lost"). A superseded fence fails it with HostError::StaleClaim and writes nothing. The returned TurnOutcome lists in route_outcomes the attempts of route finalized during the turn, in order (step counts from 0 in each turn). |
turn_runner().run_turn_with_admission(request: TurnStartRequest, admission: Arc<dyn TurnAdmission>, cancel) |
Runs a bundle-driven turn where durable wake admission (TurnAdmission::admit(&self) -> Result<Option<MessageId>, HostError>) executes under the session’s turn lease and after any fenced sidecar reaches readiness (and claim validation succeeds). If the turn cannot acquire an IfIdle lease, or if sidecar startup fails/cancels before readiness, admission.admit() is never called, so no foreign client turn can interleave between admission and execution and a member stays Spawning/Idle with empty child history until its sidecar is ready. Returning Ok(None) from admit() skips the turn cleanly without running a model round and returns Ok(TurnOutcome) with finish_reason: None, message_id: None, and error: None; returning Ok(Some(message_id)) binds that admitted prompt to the turn. Default implementation falls back to admission.admit() followed by run_turn. |
turn_runner().stop_fenced_sidecar(claim: ActorClaim) -> Result<(), HostError> |
Cancels any in-flight fenced sidecar startup for claim (preventing orphaned sidecars if release races startup) and terminates any live kept sidecar for claim, returning a HostError::Unavailable error when shutdown fails so the caller can record a durable failure diagnostic before releasing the fence. Default implementation returns Ok(()). |
NativeCommandBeforeOutcome::ExecuteUserTool { tool: String, input: Value } |
Declarative outcome returned by a command.execute.before hook (such as hya/direct-shell) when claiming SHELL_COMMAND ("!") on an inbound /v2 Kind::Shell turn. Later command.execute.before hooks are skipped and the host engine itself executes the single user-issued tool call bound to that inbound shell turn’s lease, ShellTurn.agent, and CancellationToken (registering the message with run.admitted so CancelTurn { only_if_current: true } cancels it). The host grants PermissionPlane::approving_own_call() strictly inside this inbound shell path—no native bundle can invoke it outside an inbound user ! turn—while explicit Deny rules, tool.execute.before vetoes, and ExternalDirectory asks still apply. Synthetic user-tool rounds skip LLM-only preflight (before_round compaction/rewriters, system_prompt, offered_tools, chat.params, synthetic ViewRef), record the hook-rewritten input in ToolCallRequested, cap output in-place without spilling to .hya/tool-output/, and return exact (MessageId, FinishReason, error) directly. Returning ExecuteUserTool for a slash command (or with an empty tool name) fails with invalid_argument without mutating session state. |
turn_runner().cancel_turn(session, reason) and turn_status(session) |
cancel_turn signals the session’s active turn and returns whether one was running. reason names the recorded FinishCause on the wire (archived, leader_failed, …); other text records other, and None records user_cancel. turn_status returns Running or Idle. steer_turn stays Unavailable. drain_cause() is the FinishCause the host drains with once it began stopping (leader_failed after a failed headless lead, user_cancel on an interrupt, shutdown), None while it runs; a service’s stop reads it. user_text(session, text) returns text after the session’s message.user.before hooks (plugins, then its agent’s bundle hooks; a member binds through its parent) without appending anything, so a bundle that writes a prompt itself (a woken member’s mail) passes it through the same hooks as a user prompt. |
session_store().append_batch(AppendBatch { fence: Option<ActorClaim>, expect: Vec<(SessionId, EventSeq)>, events: Vec<(SessionId, Event)>, acquire: Vec<BundleClaimRequest>, release: Vec<BundleClaimLease> }) |
One transaction across sessions and leases. fence is a session fence, as for run_turn. It returns StaleClaim when fence no longer holds its session fence, or Conflict when a session in expect no longer ends at that sequence (0 for an empty log). acquire takes leases as acquire_claim does and release gives them up as release_claim does (a released session fence ends its kept sidecar); a lease that cannot be taken or released fails the whole batch with that call’s error. Otherwise it returns AppendedBatch { envelopes, acquired }, the envelopes in order (published after the commit, as the publication row below states) and the leases acquire took, in its order. hya/multi-agent registers members with their fences in one batch and archives a member with its fence released in the same batch. |
model_caller().model_catalog() -> ModelCatalogSnapshot |
Returns a snapshot of the live provider catalog (ModelCatalogSnapshot { default_model, providers, models: Vec<ModelCatalogEntry { provider_id, model_id, servable, reasoning_variants }>, categories: BTreeMap<String, Vec<ModelRef>> }) so bundles (such as hya/multi-agent’s spawn_policy) can resolve target models and reasoning effort levels without core spawn-policy hooks. |
catalog_reader().agent_call_options(session, agent) -> Option<AgentCallOptions { system, model, reasoning }> |
The call options of agent for a one-off model call billed to session (for example through model_caller().complete): its prepared prompt, its effective model (its configured model or category, else its eligible remembered preference; None leaves the model to the caller), and its reasoning effort label. It answers for any agent the session’s binding resolves, private agents included, as get_bundle already exposes every agent’s prompt and model policy; it neither spawns, lists, nor authorizes. Ok(None) when the binding resolves no agent. The default implementation returns HostError::Unavailable. Used by hya/session-title for hya-title. |
session_store().append_events(session, claim, events) and append_batch(batch) publication |
After the commit, each appended envelope is published once, with its committed seq and in the order the call committed them, to the live bus and to an asynchronous FIFO dispatcher for every event hook chain (native NativeHook::on_event, global and session plugin event hooks) so slow event observers never block writers after persistence. Publications of concurrent writers to one session, the engine’s included, may interleave, so a later seq can reach the bus first. append_extension_event appends through append_events. A bundle does not publish them again with event_bus().publish. |
NativeHook::model_stream_permit(NativeStreamPermitInput { session, root, depth }) -> Option<NativeStreamPermit> (model.stream.permit) |
Awaited before each model stream opens. Every hook’s guard is held together and dropped when the round’s stream is collected or before the round waits to retry. |
NativeHook::turn_stop(NativeTurnStopInput { session, cause }) -> bool (turn.stop) |
Awaited by SessionEngine::stop_user_turn before it cancels the session’s turn and its live descendants’ turns. true means the stop held back work of the bundle’s own (a member’s owed turn): the stop reports that it took effect even when no turn was active. |
NativeHook::session_close(NativeSessionCloseInput { session }) (session.close.before) |
Awaited before a session is deleted, latest hook first; the first error refuses the deletion with its message. |
NativeHook::headless_run(NativeHeadlessRunInput { session, phase: Start | TurnEnded { finish } | End }) -> Option<String> (run.headless) |
Each hook may return one pending-work line; every line is kept, in hook order (SessionEngine::headless_run_lines). |
NativeHook::session_restore(NativeSessionRestoreInput { session }) -> Option<String> (session.restore) |
When any hook implements the point, each answer is appended to the restore prompt as its own paragraph, in hook order, and the built-in interrupted-member line is not added. |
NativeHook::runtime_restored() (runtime.restored) |
Notified once the host has admitted every restore prompt at startup, and right after startup when nothing was restored. |
NativeTurnAdmitInput::actor_claim |
The fence of a bundle-driven turn; None for a client turn. |
ToolVisibilityInput::depth |
Parent links between the session and its tree root (0 for a root session). |
ProjectionReducer::observed_bundles() -> &[&str] and schema_version() -> u32 |
observed_bundles() causes the host to also pass those bundles’ events to apply, after their own reducer, with event.bundle naming the owner; the reducer may fold them only into its own state. schema_version() (default 1) is a bumpable reducer schema version included alongside (owner_id, owner_present, schema_version) and sorted (observer_id, schema_version) in durable projection_snapshot signatures so enabling an observed reducer bundle or changing reducer semantics invalidates stale snapshots. Duplicate or foreign-owned ProjectionReducer registrations are rejected at registration time. Reducers receive the committed post-increment seq and real ts_millis timestamp on every ExtensionEventContext. |
StateEdit::new(state: &mut Value) |
Edits a reducer’s object state in place: get/put/remove/contains/keys on map fields (keys kept sorted), items/item/set_item/push on array fields, set_field on single values, and raw/raw_mut/put_raw on stored JSON; finish(order) drops empty fields and orders the rest as order lists them. A fold that decodes only the entries an event touches costs the same however large the state grows; the result is what encoding the typed state would write. Edits land as they are made: a fold that returns an error partway keeps its earlier edits, and the host keeps that state, as it does for any apply that fails. hya/multi-agent and hya/agent-channels fold every team event this way. |
NativeToolAfterInput::notices: bool |
Whether the host lets this tool.execute.after hook append notices to the result. It is false for a turn-ending call and the rest of its round, a call whose tool withholds notices (Tool::notices), a paged or altered result, and a user shell command. The unread-mail steer hook in hya/agent-channels adds unread mail only when it is true. |
session_store().project_changes(project, since_ms, limit, exclude) -> ProjectChanges |
A kernel read with a default Unavailable: the sessions of a Project updated since since_ms (at most limit, without exclude) and the last FilesChanged per path. hya/coding-extras’ project_activity tool builds its output from it, from session_metadata (relation, lineage root), and from turn_status (busy or idle). |
Tool::notices(output: &Value) -> Notices |
Asked after a successful call. NotInResult: the result already shows everything pending, so its tool.execute.after hooks get notices: false for the call. NotInRound: the result shows part and leaves the rest to a later call, so no later result of the round gets a notice either. When a hook replaces a NotInResult or NotInRound result, the events staged with it are dropped and the rest of the round gets no notice. A successful turn-ending call (Tool::ends_turn) also suppresses notices for the rest of its round. |
The host records a native_service startup-trace mark, with the service
id, as each native service starts (HYA_STARTUP_TRACE_FILE).
The host also records one native_bundle mark per installed native bundle,
with detail = {bundle, hooks: [id], services: [id]}.
hya/multi-agent and hya/agent-channels drive their teams through the
generic primitives above.
3.4 Native Extension Traits
| Trait | Required Methods | Notes & Contracts |
|---|---|---|
Tool (hya_tool::Tool) |
name, schema, execute(&self, ctx: &ToolCtx, input: Value) |
Model-callable tool; uses slim v2 ToolCtx + ExtensionPlanes. |
Rewriter (hya_context::rewrite::Rewriter) |
before_round(RewriteCtx), rewrite_now(RewriteCtx): context reduction passes invoked before Kernel Rewrite at 80% window occupancy and on /summarize |
RewriteCtx carries the session, turn message, model, projection, model window, request overhead, pressure, workdir, the host’s token_accounting mode (auto | provider | estimate), and the session log, transcript, model, and compaction-hook services. A rewriter reads its own settings through HostCatalogReader::bundle_config. Used by hya/compaction (shake + remote). |
NativeService |
id, start(runtime), stop(), health() -> ServiceHealth; optional is_session_busy, cancel_session, wait_session_idle |
Host starts/stops managed background services with the runtime lifecycle. |
NativeHook |
id, hook_points() -> &[HookPoint] plus default no-op methods for all 22 HookPoint variants; declared_points() + invoke_declared(point, input) for bundle-declared points; is_healthy(), permission_identity(), and a synchronous on_event(envelope) |
Covers tool.execute.{before,after}, tool.visibility, compaction.{before,after}, session.{start,end}, command.execute.before, message.user.before, turn.admit, text.complete, chat.params, model.fallback, permission.{ask,approve}, event, model.stream.permit, turn.stop, session.close.before, run.headless, session.restore, runtime.restored. Member creation is not a core point: hya/multi-agent declares hya/multi-agent:spawn and invokes it once per created member ({parent, child}); hooks and plugins subscribe to it by that name. This is the one hook shape: the engine’s HookChain holds native bundle hooks, the JS plugin host, and core built-ins as NativeHook entries, and dispatches each point through one ordered chain. A hook is called only for the points it lists. command_execute_before(NativeCommandBeforeInput { session, command, arguments, text }) returns a NativeCommandBeforeOutcome: Continue { text } rewrites the text for later hooks and admission; ExecuteUserTool { tool, input } declaratively claims an inbound /v2 shell turn (command: SHELL_COMMAND, "!") so later hooks are skipped and the host engine executes that user-issued tool call directly (hya/direct-shell returns ExecuteUserTool { tool: "bash", input: {"command": text} }). The host refuses a ! turn when no hook claims it, and rejects ExecuteUserTool on slash commands or with an empty tool. |
NativeBundleApiHandler |
id, endpoints() -> &[NativeApiEndpoint], handle(NativeBundleApiRequest) -> Result<NativeBundleApiReply, HostError> |
Mounted uniformly on hya.v2.BundleApi (/v2/bundles/{bundle}/api/{path} and /v2/sessions/{session}/bundles/{bundle}/{path}). |
ProjectionReducer |
bundle_id, initial_state() -> Value, apply(&self, state: &mut Value, event: &ExtensionEventContext); optional schema_version(&self) -> u32 (default 1), tool_output_overrides(&self, event: &ExtensionEventContext) -> Vec<ToolOutputOverride> (default empty), and observed_bundles() -> &[&str] (default empty) |
Deterministically folds Event::Extension records into Projection::extensions[bundle_id] with post-increment seq and real ts_millis. Registration rejects foreign bundle_ids and duplicate owners. Snapshot signatures include (owner_id, owner_present, schema_version) plus observers’ (id, schema_version). After apply succeeds, the host sets each returned ToolOutputOverride { part: PartId, output: String } as that tool part’s PartProjection::Tool::eviction_notice via an indexed part map, which later requests send in place of the output; replay rebuilds the same notices only while the reducer’s bundle is enabled. Used by hya/compaction for context_evicted. |
UriSchemaHandler |
scheme, description(), writable(), read(UriResolveCtx, uri) -> Result<UriContent, HostError>, write(UriResolveCtx, uri, content) |
Plugged into HandleRouter via adapt_uri_schema_handler (UriSchemaHandleAdapter). Internal schemes (artifact, skill, local) are protected. description() is the model-facing text for the scheme’s URIs: an agent whose view has no read gets a read that serves only the registered schemes (no file paths), and its tool description lists each <scheme>:// with this text (for example channel:// from hya/agent-channels). |
NativeDriver |
name, run(runtime, DriverRequest, cancel) -> Result<DriverReport, HostError> |
A run that owns a session until it returns. The host registers it as <bundle-id>:<name> and knows nothing else about it. DriverRequest carries session, agent, model, workdir, and JSON args (for a CLI command, its parsed arguments); DriverReport carries stdout, stderr, and exit_code, which the CLI prints and exits with. DriverRunOutcome is a shared terminal-outcome type for iterating drivers. Consumers: hya/goal:goal (hya -p) and hya/loop:loop (hya loop). |
ProviderKindEntry (hya_provider, capability providers) |
protocol: Arc<dyn Protocol> (kind, description, encode, decoder, plus defaulted aliases, auth_headers, compaction, min_output_tokens, and the models_* / parse_models catalog adapter); auth_flow: Option<Arc<dyn ProviderAuthFlow>> (oauth_type, default_base_url, default_model, supports_loopback, login(OAuthLoginRequest), refresh(&OAuthCredential)) |
One model provider kind. The host keeps the HTTP+SSE transport, the catalog-discovery loop, and credential storage; the protocol is called synchronously and passed through unwrapped, while login and refresh are polled through hya_native_with_runtime_v2 like every other async method. Labels, aliases, and OAuth types must be unique across the enabled bundles. |
PostWriteNormalizer (hya_tool::post_write) |
normalize(&self, workdir: &Path, path: &Path) -> PostWriteOutcome { modified: bool, warnings: Vec<String> } |
Generic in-lock post-write file normalizer collected into PostWritePlane on ToolCtx::extensions. Invoked by file-writing tools (hya-core and hya/hashline write/edit) on regular filesystem files (never local:// or custom URI handles) while holding their per-file write lock, before reloading final bytes, recording snapshots, generating diffs, or computing LINE#HASH anchors. Tools set metadata.postWriteNormalized = true so tool.execute.after hooks do not double-normalize, and surface returned warnings directly in tool output and metadata.warnings. Used by hya/coding-extras. |
3.5 ExtensionPlaneId & ExtensionPlanes (crates/hya-tool)
Core hya_tool::ToolCtx contains only single-agent v2 core planes (workdir, roots, cancel, session, operation, permission, interaction, skills, artifacts, schemas: UriSchemaPlane, nested) plus extensions: ExtensionPlanes:
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]pub enum ExtensionPlaneId { ParentSession, AgentRoster,}
#[derive(Clone, Default)]pub struct ExtensionPlanes { planes: Option<Arc<BTreeMap<ExtensionPlaneId, StoredPlane>>>,}- Sound cross-
cdylibtyped planes withoutTypeIdor raw pointer casts: Host binaries and nativecdylibbundles built in separate Cargo invocations can assign differentstd::any::TypeIdvalues to the same Rust type, and stringtype_namepointer casts cannot guarantee layout soundness.ExtensionPlanesinstead uses a closed, sealedExtensionPlanetrait keyed byExtensionPlaneIdand backed by a strongly typedStoredPlaneenum (ParentSession(ParentSession),AgentRoster(Arc<[AgentDef]>)), with zerounsafecode. - Usage on
ToolCtx: Attach withctx.with_extension(plane)(orextensions.insert(plane)/.with(plane)) and borrow withctx.extension::<T>()(orextensions.get::<T>()/.contains::<T>()/.contains_id(id)). In--baremode,ToolCtx::extensionsis empty.
3.6 Error Contracts (HostError & AbiError)
| Enum | Variants |
|---|---|
HostError (#[serde(tag = "type", content = "detail", rename_all = "snake_case")]) |
NotFound(String), Conflict(String), StaleClaim(String), InvalidInput(String), PermissionDenied(String), Unavailable(String), Cancelled, Storage(String), Internal(String). Converts bidirectionally with hya_tool::ToolError. |
AbiError |
InvalidBundleIdentity(String), DisabledOrMissing { bundle, detail }, LoadFailed { bundle, detail }, MissingSymbol { bundle, symbol }, DigestMismatch { bundle }, RegistrationFailed { bundle, detail }, RuntimeBridge(String). |
ABI identity, independent versioning, and source SDK
The Native Runtime ABI evolves on its own SemVer track (abi_version in
versions.toml and hya_runtime_abi::ABI_SEMVER, currently 2.0.0),
decoupled from the hya host release version. The four ABI boundary crates
(hya-proto, hya-provider, hya-runtime-abi, hya-tool) declare
version-reference = "abi".
- Contract lockfile (
abi-contract.lock): Recordsabi_version,abi_semver, the pinnedrust-toolchain.tomlchannel,abi_contract_digest(the target-independent normalized digest of the ABI boundary), and the 5 cross-boundaryabi_dependencies. - CI drift gate (
xtask check-abi): Fails CI if any change alters the ABI contract surface, dependency versions/features, or Rust toolchain without an intentional bump toabi_version(versions.toml+ABI_SEMVER) and a matchingcargo run -p xtask -- update-abi-lock. Ordinaryhyahost updates that leave the ABI untouched keep the exact sameabi_digestand reuse all already-published native bundles without rebuilding. - Host version access: Native bundle registration can read the running host
release through
NativePluginContext::host_version() -> Option<&str>.
Run hya abi info for key-value lines or hya abi info --json for an object
with string fields hya_version, target, rustc, abi_semver,
abi_contract_digest, abi_digest, and abi_id, plus the integer
abi_version. The packaged abi-manifest-<target>.json and the manifest
inside hya-abi-sdk-<abi_id>-<target>.tar.gz omit hya_version so the SDK
archive is byte-identical across host releases sharing the same ABI. Both
digests are 64 lowercase hex characters; abi_id is v2- followed by the
first 16 characters of abi_digest. Use the full abi_digest for binary
compatibility checks.
hya abi info --jsoncargo run --locked -p xtask -- check-abicargo run --locked -p xtask -- update-abi-lockcargo run --locked -p xtask -- package-abi-sdk --out distThe SDK command writes hya-abi-sdk-<abi_id>.tar.gz and
abi-manifest.json. The manifest uses the same fields as the CLI. It is also
included in the archive. The release publishes the SDK as
hya-abi-sdk-<abi_id>-<target>.tar.gz and its stand-alone manifest as
abi-manifest-<target>.json. The archive contains a Cargo workspace with
hya-proto, hya-tool, hya-provider, and hya-runtime-abi. Extract the
SDK, copy Cargo.lock.abi to Cargo.lock, and add your bundle crate as a
workspace member with hya-runtime-abi = { workspace = true }
in the bundle manifest. Preserve the SDK’s
cross-boundary dependency features and use the compiler pinned in
rust-toolchain.toml and the target in the ABI manifest.
Build the library and package it with a hya reporting the same full ABI digest.