docs · embedding

Embed the engine#

The hekma command is a thin layer over a Rust library, hekma-engine, and your own program can use the same library. In Hekma 0.11.0, embedding is the way to get supervision with no gaps, and the only way to use send and ACP prompt turns, because your program holds the engine open for as long as it runs. This page covers adding the crate, a complete quickstart, the API surface, and the errors and upgrades you need to plan for.

On Hekma's main branch (Unreleased: after 0.11.0) the CLI routes every write through a Service Host that keeps running between commands, so a plain hekma agent start is supervised continuously and send reaches an agent another command started. Embedding is then for building on the engine yourself, not the only way to keep agents watched. The engine on main also gains Runs and labels, a graceful shutdown, the drain verb and the governance decision code; each is marked below.

Who this is for#

Embed the engine when the CLI's command-scoped supervision is not enough:

  • You want an agent watched around the clock, with crashes restarted and budgets enforced when they are crossed.
  • You want to send an agent input with send_input, or drive an ACP agent's prompt turns. In 0.11.0 the CLI cannot do either usefully, because a detached agent has no stdin and an attached one stops when its command exits.
  • You run engine-observed agents, whose metering proxy lives inside the process that started them.
  • You are building a dashboard, a scheduler or a hosting product, and want events instead of polling hekma agent list --json.

If you only need to start agents and check on them now and then, the CLI with --detach and a long-running hekma agent logs NAME --follow may be enough; see Supervision and detached runs.

Add the dependency#

[dependencies]
hekma-engine = "0.7"

hekma-engine 0.7.0 is the engine inside Hekma 0.11.0. It needs Rust 1.96.1 or newer and is licensed Apache-2.0. It brings its own SQLite (compiled from source, so the first build takes a while), its own TLS stack for the metering proxy, and its own tokio runtime. You do not need tokio yourself unless you want to call the async methods.

The engine is versioned separately from the CLI. Within 0.x a minor version may break the API (see upgrading), so the "0.7" requirement above keeps you on 0.7.x until you choose to move.

Hekma's main branch carries hekma-engine 0.12.0 (Unreleased: after 0.11.0), which is not on crates.io; the next release publishes it. To build against main before then, pin the repository to a full 40-character commit SHA, never a branch, so your build is reproducible and every upgrade is a deliberate change:

[dependencies]
hekma-engine = { git = "https://github.com/Ktesio/hekma", rev = "<full commit SHA>" }

Upgrade to main's 0.12.0 lists what changes.

Quickstart#

This program opens an engine on a scratch directory, registers an agent from an adapter manifest, sets a budget, subscribes to events, starts the agent, reads the fleet, and stops it. It is a trimmed copy of embedding-quickstart.rs, which uses its own binary as a stand-in agent; point exec at your agent instead.

use std::time::Duration;

use hekma_engine::broadcast::error::TryRecvError;
use hekma_engine::{AdapterRef, ConfigLayer, Engine};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Open an engine on a state directory (None = the OS default).
    let root = std::env::temp_dir().join("hekma-quickstart");
    std::fs::create_dir_all(&root)?;
    let engine = Engine::open(Some(root.clone()))?;
    let host = engine.blocking();

    // 2. Register an agent from an adapter.toml directory.
    let manifest = root.join("hello-adapter");
    std::fs::create_dir_all(&manifest)?;
    std::fs::write(
        manifest.join("adapter.toml"),
        r#"contract_version = "1.0.0"

[adapter]
kind = "quickstart"

[lifecycle.start]
exec = "/path/to/your/agent"

[capabilities.pause]
linux = "guaranteed"
macos = "guaranteed"
windows = "best-effort"

[metering]
source = "self-reported"
"#,
    )?;
    host.register_with_adapter("hello-agent", &AdapterRef::Manifest(manifest))?;

    // 3. Set a budget and read it back with its source layer.
    host.set_config("hello-agent", "budget.tokens.cumulative", "100000")?;
    let effective = host.effective_config("hello-agent", ConfigLayer::empty())?;
    assert_eq!(effective.source_label("budget.tokens.cumulative"), Some("instance"));

    // 4. Subscribe before starting, so the start's events arrive.
    let mut events = host.subscribe();

    // 5. Start: returns once the agent is running.
    host.start("hello-agent")?;

    // 6. Drain what has arrived, then read the fleet row.
    loop {
        match events.try_recv() {
            Ok(event) => println!("event: {event:?}"),
            Err(TryRecvError::Lagged(n)) => println!("missed {n} events"),
            Err(TryRecvError::Empty | TryRecvError::Closed) => break,
        }
    }
    let entry = host.fleet_entry("hello-agent")?;
    println!("fleet: {} [{}] state={}", entry.name.as_str(), entry.kind, entry.state.as_str());

    // 7. Stop, with a 5-second graceful window before the forced kill.
    host.stop("hello-agent", Some(Duration::from_secs(5)))?;
    Ok(())
}

Run the real example from a clone of the repository:

git clone https://github.com/Ktesio/hekma.git
cd hekma
cargo run -p hekma-engine --example embedding-quickstart
event: Transition(TransitionEvent { schema_version: 1, instance: "hello-agent", prior_state: Registered, new_state: Starting, cause: Command { command: "start" }, at: "2026-10-22T19:37:36Z" })
event: Transition(TransitionEvent { schema_version: 1, instance: "hello-agent", prior_state: Starting, new_state: Running, cause: AdapterReady, at: "2026-10-22T19:37:36Z" })
fleet: hello-agent [quickstart] state=running
done — the agent ran under governance and stopped cleanly.

Two things in that program are worth carrying into your own:

  • Engine::open owns everything. It creates the state directory if needed, opens state.db, adopts any agents a previous process left running, and starts the background thread that watches for crashes. All of that stops when you drop the engine.
  • blocking() is the synchronous view. Each method on it runs the matching async method to completion on the engine's own runtime. The hekma CLI uses exactly this view. If your program already runs tokio, call the async methods on Engine directly instead (see async programs).

Keep the engine open#

The quickstart stops its agent at once. A real host keeps the engine open while agents run, and that is all it takes to get continuous supervision. This program starts an agent that reads one line of input and then reports usage every second, sends it a line, and prints events until a budget breach pauses it:

use std::path::PathBuf;
use std::time::Duration;

use hekma_engine::broadcast::error::RecvError;
use hekma_engine::{AdapterRef, Engine, EngineError, EngineEvent};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let engine = Engine::open(Some(PathBuf::from("/var/lib/my-host")))?;
    let host = engine.blocking();

    host.register_with_adapter("worker", &AdapterRef::Manifest("/opt/agents/worker".into()))?;
    host.set_config("worker", "budget.tokens.cumulative", "3000")?;

    let mut events = host.subscribe();
    host.start("worker")?;

    // The engine holds the agent's stdin for as long as it stays open.
    match host.send_input("worker", "hello") {
        Ok(()) => println!("sent: hello"),
        Err(EngineError::CapabilityUnsupported { .. }) => println!("agent takes no input"),
        Err(other) => return Err(other.into()),
    }

    // Supervision runs on the engine's own threads; this loop only reports.
    loop {
        match events.recv() {
            Ok(EngineEvent::UsageUpdate(u)) => println!(
                "usage: +{} in / +{} out (run {})",
                u.event.input_tokens, u.event.output_tokens, u.event.run_id
            ),
            Ok(EngineEvent::BudgetBreach(b)) => {
                println!("breach: {} of {} tokens, action {:?}", b.observed, b.limit, b.action);
            }
            Ok(EngineEvent::Transition(t)) => {
                println!("state: {} -> {}", t.prior_state, t.new_state);
                if t.new_state.as_str() == "paused" {
                    break;
                }
            }
            Err(RecvError::Lagged(n)) => println!("missed {n} events; resync to catch up"),
            Err(RecvError::Closed) => break,
        }
    }

    host.stop("worker", Some(Duration::from_secs(5)))?;
    Ok(())
}

Built against hekma-engine 0.7.0, with an agent whose manifest declares the interaction capability:

sent: hello
state: registered -> starting
state: starting -> running
usage: +1000 in / +200 out (run run-1792698196454613000-0)
usage: +1000 in / +200 out (run run-1792698196454613000-0)
usage: +1000 in / +200 out (run run-1792698196454613000-0)
breach: 3600 of 3000 tokens, action Pause
state: running -> paused

On Hekma main (Unreleased: after 0.11.0) a run id is run_ followed by a ULID, such as run_01JZ6Q9G3S8V2X7K4M1N5P0R2T, so ids sort by creation time; ids in the older run-… form stay valid.

The agent's agent.log starts with got: hello, so the input arrived. The budget check ran on the engine's own thread at the third usage event, with nothing in the host doing the arithmetic. Events, resync and diagnostics covers the event stream in full.

The API surface#

Everything a host can call is a method on Engine (async) and on the Blocking view from engine.blocking(), with the same name and arguments. The table groups them by job.

GroupMethodsWhat they do
OpenEngine::open(base), Engine::open_with_diagnostics(base, sink), blocking(), with_diagnostics(sink)Open an engine on a state directory (None for the default), adopting agents left running. Optionally send the engine's [hekma] diagnostics to your own writer.
Registerregister(name, kind), register_with_adapter(name, &AdapterRef), remove(name, disposition, force)Register a built-in kind ("acp", "hermes", "mock") or an AdapterRef::Manifest(path). remove stops a live agent before deleting it, and keeps or deletes the Agent Home per RemoveDisposition.
Lifecyclestart, start_detached, stop(name, window), pause, resumeDrive the lifecycle. stop takes an optional graceful window (default 30 seconds). See detached starts for start_detached.
Inputsend_input(name, text)Write one line to the agent's stdin, or for an acp agent, start one session/prompt turn and return at once.
Configset_config(name, key, value), effective_config(name, overrides), reveal_secrets(name, overrides)Write one config key to the instance layer (returns warnings), read the resolved config with each value's source layer, and resolve secret:NAME values to plain text on request. Pass ConfigLayer::empty() for no overrides.
Restart policyset_restart_policy(name, RestartPolicy)Choose OnFailure (the default) or Never. This is the only way to change the restart policy.
Fleet and statusfleet(), fleet_entry(name), list(), instance_status(name), effective_capabilities(name), agent_home(&InstanceName)Read the rows behind hekma agent list and show: state, usage, budget, metering source and supervision. FleetListing::new(entries) adds the fleet totals.
Memoryattach_memory(name, MemoryBackingKind), detach_memory(name), memory_status(name)Manage the agent's memory backing while it is stopped. attach_memory returns the managed folder's path.
Logsread_agent_log(name), read_agent_log_since(name, cursor), read_raw_output_since(name, cursor)Read the attributed output.log lines, all or after a byte cursor, or the raw agent.log that a detached agent writes while no engine reads it. Each returns the lines and the next cursor.
Historytransition_events(name), budget_breach_events(name)Read the durable transition and breach records from the Agent Home.
Eventssubscribe(), resync_events(name, ResyncCursor)Receive events live, and catch up on what you missed. See Events, resync and diagnostics.

Hekma's main branch adds these (Unreleased: after 0.11.0). The engine's methods have the same async and blocking twins; the governance row lists plain functions:

GroupMethodsWhat they do
OpenEngine::open_read_only(base), Engine::open_with_options(base, EngineOptions)open_read_only opens an engine that only reads: a read-only database connection, every write refused with a typed error (never a panic), no adoption and no crash watcher, so it never touches a process another engine supervises. A missing state.db reads as an empty fleet and creates nothing; a database at an older schema answers StoreError::NeedsMigration, since only a writing engine may upgrade it. The CLI's read commands open the state this way. open_with_options takes the open-time settings hekma serve uses (a fixed metering port, the child-environment allowlist, the log capture mode, a diagnostic sink); EngineOptions::default() behaves exactly like open.
Lifecycledrain(name, timeout), shutdown(window, notes)drain runs the adapter's declared pause command, waits up to a bound for its idle signal, then stops the agent; it returns a DrainReport whose outcome.completed and outcome.waited_ms say whether the wait finished in time. Both outcomes are Ok, because the agent is stopped either way. shutdown stops every live agent gracefully in one call; see Shut down gracefully.
Runsopen_child_run(ChildRunRequest), close_run(run_id), run(run_id), instance_run(name)Open a child Run under a supervised Run for one unit of your own work (ChildRunRequest: the parent, caller labels, per-run ceilings, and an external id that makes a retried open return the same Run), close it, read any Run, or read an agent's open Run. A RunView carries the Control Depth, Run Status, Anomalies, labels, limits and subtree usage. Refusals are a typed RunError. See Runs.
Labelslabel_run(run_id, LabelChange, dry_run), select_runs(&Selector)Bind and unbind labels on one Run as the operator, returning a LabelOutcome with the labels after and before and whether they changed; resolve a Selector (key=value,…) to the open Runs that carry every term, at most MAX_SELECTED_RUNS (1000), else RunError::TooManyRuns. Each bound Label records its origin, config or label-verb. The same verb is hekma label on the CLI.
Run verbs and limitsstop_run, pause_run, resume_run, drain_run, plan_run_verb, select_run_summaries, set_run_limits, run_limits_viewThe engine side of hekma budget and the Selector verbs. The lifecycle verbs act on the Run that owns an agent's process as the agent's own, and refuse a child Run with RunError::VerbUnavailable; plan_run_verb plans a --dry-run. set_run_limits writes limits on one Run (RunLimitChange, RunLimitField, LimitActor) and returns a RunLimitsOutcome; a cumulative ceiling on a child is RunError::ScopeUnavailable, and a Caller loosening a limit is RunError::RaiseForbidden. run_limits_view reads them back as a RunLimitsView. Every method is on Engine and the blocking engine.
Run listinglist_runs(ListRunsQuery), subscribe_sequenced, event_subject_labelsThe read behind hekma ps: a RunListing document of RunSummary rows, with ListingCounts, a keyset cursor (encode_cursor, decode_cursor, malformed ones are RunError::InvalidCursor) and ended_run_cutoff. subscribe_sequenced is the event stream with each event's outbox seq, which /v0/events uses for its id: and resume.
Policiespolicies(), policy(name), create_policy, change_policy, delete_policyManage Policies as hekma policy does, with PolicyRecord, PolicyLimits, PolicyChange, PolicyOutcome, PolicyEvent and ScentCheckMode. Refusals are RunError::PolicyNotFound, PolicyExists and PolicyDefault.
Governancedecide, decide_chain, rearm, fence_refusal, run_derivation, governance_vectors_json(), governance_vectors_checksum()The pure decision code budget enforcement runs, and the governance vectors generated from it, embedded byte for byte with their checksum. A Rust Host that enforces spend at its own choke point can call these instead of re-implementing the rules.

Usage numbers come with the fleet rows: FleetEntry::usage carries cumulative and current-run tokens (and dollars when a rate is set), and FleetEntry::budget carries each limit and what remains. These are the values the CLI prints, with the field names of the list JSON document. The crate also exports the domain types those methods return, such as LifecycleState, TransitionCause, Supervision and Micros, plus render_dollars for formatting money the way the CLI does.

Async programs#

Engine is Send + Sync, so you can keep it in an Arc and call its async methods from your own tokio tasks. The work runs on the engine's runtime; your runtime only awaits it. Two rules apply:

  • Do not call blocking() methods from inside an async task. They run the engine's own runtime on the calling thread, and tokio panics with "Cannot start a runtime from within a runtime". Use the async methods there, or move the call into tokio::task::spawn_blocking.
  • Drop the engine outside async code. The engine owns a tokio runtime, and tokio panics if a runtime is dropped on an async worker thread. Drop it on a plain thread or with tokio::task::spawn_blocking(move || drop(engine)).

Several engines#

The engine keeps no global state, so one process can open several engines, each on its own state directory.

Give your host a state directory of its own. Any other engine opened on the same directory, including a single hekma agent list, adopts the agents your engine holds and kills the attached ones when it closes. One engine per state directory explains why and what to do instead.

On Hekma main (Unreleased: after 0.11.0) this no longer happens. An engine skips an attached agent whose supervising engine is still alive, the CLI's reads open the state read-only, and the CLI's writes go to the directory's Service Host, starting one in the background if none runs. Each engine you open still runs its own store writer, though: if your program opens a writing engine on a directory that a hekma serve, or a host the CLI started, also serves, the two take turns through SQLite's write lock, and each supervises only the agents it started or adopted. Keep one owner per state directory: either drive the host through its Control API, or give your engine a directory of its own.

Detached starts: the host's duty#

start_detached launches an agent that survives the engine. When the engine is dropped, the agent keeps running, and the next engine opened on the same state directory adopts it by process id and start time (see Architecture).

The cost is the gap between engines. While no engine is open there is no crash detection, no budget enforcement and no event delivery, and usage the agent reports in that time is never counted. If you offer detached starts to your own users, say so wherever you offer them, the way hekma agent start --detach does. Supervision and detached runs lists what happens in the gap.

Three more rules carry over from the CLI:

  • start_detached fails with EngineError::DetachRefused for an engine-observed agent, before anything changes, because its metering proxy lives in the engine and would die with it.
  • A detached agent's stdin is closed, so send_input cannot reach it and an ACP agent cannot run detached. Start those with start and keep the engine open.
  • When the engine is dropped, an agent you paused yourself is resumed first, so it is never left frozen with nobody watching. An agent paused by a budget breach stays paused.

A host that keeps one engine open for its whole life rarely needs start_detached. Its main use is surviving a restart of the host itself.

Runs and labels#

Unreleased: after 0.11.0. Runs as first-class records, child Runs and bound labels are on Hekma's main branch and ship in the next release; hekma-engine 0.7.0 does not have them.

On main, every supervised start creates a Run: a record with a run id, a Control Depth, a Run Status, Anomalies and labels. A Restart Policy relaunch keeps the same Run, so per-run budgets keep counting across a crash; only start opens a new one. Your program can open child Runs inside an agent's Run for its own units of work, and their usage counts on every ancestor:

use hekma_engine::{ChildRunRequest, RunParent};

let host = engine.blocking();

// A child of the agent's open Run, with a caller label and its own ceiling.
let mut request = ChildRunRequest::under(RunParent::Instance("worker".into()));
request.labels.push(("task".into(), "review".into()));
request.limits.token_per_run = Some(20_000);

let child = host.open_child_run(request)?;
let run_id = child.record.run_id.to_string();
// ... do the unit of work ...
host.close_run(&run_id)?;

RunParent::Run(id) names a parent by run id instead.

A child's own ceilings take the warn breach action; every ancestor's ceilings still apply to its usage. pause, stop and block set directly on a child are refused with RunError::ActionUnavailable. Each RunError has a stable code(), the same string the Control API puts in error.code: run-not-found, no-open-run, instance-not-found, parent-ended, nesting-too-deep (Runs nest at most MAX_RUN_NESTING, 8, levels), action-unavailable, owns-process, run-ended, label-from-config, label-not-bound, label-bound, too-many-runs, invalid-request and store. Policies, the Run listing and Run limits add policy-not-found, policy-exists, policy-default, scent-unavailable, invalid-cursor, scope-unavailable, raise-forbidden and verb-unavailable, and Run Keys add run-out-of-scope, credential-revoked, unauthorized (an unknown credential), credential-unavailable and too-many-children.

label_run binds labels the way hekma label does: a label set with it records the origin label-verb and, per key, outranks the agent's labels.<key> configuration (origin config) and any caller label. Removing one restores the configured value in the same change; removing a configured label or a caller label is refused. Every change publishes one Run event; see Event types.

Shut down gracefully#

Unreleased: after 0.11.0. Engine::shutdown is on Hekma's main branch and ships in the next release.

Dropping an Engine kills every attached agent's process group outright, with no graceful window and no stop transition. Drop cannot wait for a stop sequence, so the graceful path is yours to call: run shutdown first, and drop the engine once it returns.

use std::time::Duration;

let outcomes = engine.blocking().shutdown(Duration::from_secs(5), None);
for outcome in &outcomes {
    println!("{outcome}");
}
drop(engine); // nothing is left for the drop to kill
  • What it stops. Every running and paused agent this engine can see, adopted detached ones included, one at a time in fleet order through the normal stop sequence, with window as each one's graceful window. A paused agent is resumed first, so the graceful signal can reach it. It then looks once more for agents that started meanwhile. The worst case takes the sum of the windows.
  • What it returns. One DrainOutcome per agent, never an early error: its result is a StopResult of Graceful, Forced (the window ran out and the agent was killed), ExitedOnItsOwn, Unverified or Failed with the reason. Display prints a one-line summary.
  • Notices. Pass Some(&sink), a diagnostic sink, to get the same [hekma] progress lines hekma serve prints when it shuts down, or None for the return values only.

hekma serve does exactly this on its shutdown signal. An engine that ends without a shutdown, in a crash for example, leaves detached agents running for the next engine to adopt, as above.

What the engine promises a host#

The engine is built to live inside someone else's process without surprises:

  • It never reads your stdin, never prints a prompt, and never checks whether it is attached to a terminal.
  • It never writes to your stdout. Its only output is a small set of [hekma] diagnostic lines on stderr, which you can redirect with a diagnostic sink.
  • It never changes your process's environment variables, and installs no signal, panic or console handlers.
  • It keeps no global state, so several engines can share a process.
  • The CLI uses the same public API you do. Every async method has a blocking twin, and the CLI calls only the blocking ones.

Hekma's test suite checks each of these on every change, including a test that runs two engines side by side in one process and checks that neither sees the other's agents or events.

Errors#

Every method returns a typed Result. Nothing panics on a bad name, a wrong state or a failed launch. Three error enums cover most calls:

EnumReturned byExamples
RegistryErroropen, register, remove, fleet reads, memoryDuplicateName, NotFound, UnknownAdapterKind, ManifestInvalid, ContractIncompatible, RunningRequiresForce
EngineErrorlifecycle, input, status, events, logs, restart policyNotFound, InvalidTransition, CapabilityUnsupported, LaunchFailed, DetachRefused, NotRunning, InteractionUnavailable, StopUnconfirmed
ConfigErrorset_config, effective_config, reveal_secretsUnknownKey (with a suggestion), InvalidValue, InvalidName

Each variant's Display text is the message the CLI prints, naming the problem and the fix. The CLI maps them to exit codes; for example InvalidTransition is exit code 4 and DetachRefused is 5.

The enums are exhaustive (none is marked #[non_exhaustive]), so a new variant is a breaking change and arrives only in a new minor version of the crate. If you match every variant, a new one is a compile error you fix once; add a _ case if you would rather not. hekma-engine 0.7.0 added these variants since 0.4.0, the previous version on crates.io:

VariantWhen it happens
EngineError::AcpTurnInFlightsend_input to an acp agent while its previous prompt turn is still running. The first turn is unaffected.
EngineError::MemoryBackingChangedUnderStartA memory attach or detach in another process raced this start. Nothing launched; retry the start.
RegistryError::MemoryBackingRowCommittedDirFailedA memory attach was recorded but the folder could not be created.
TransitionCause::DetachedResumedNot an error, but a new variant of an exhaustive enum: the cause recorded when an engine resumes a detached agent you paused, as it closes.
StoreError: MemoryBackingKindConflict, MemoryBackingHotSwap, MemoryBackingChangedUnderStart, StateConflict, BusyState-store errors, seen inside EngineError::Store and RegistryError::Store. Busy means another process held the database for more than 5 seconds.

Hekma's main branch adds more (Unreleased: after 0.11.0). Each is a new arm of an exhaustive enum, so a match without a _ case needs it:

VariantWhen it happens
EngineError::PauseCommandFailedAn adapter's declared pause or resume command exited non-zero, could not start, or ran past its 30-second cap. The state is unchanged. The Control API answers it with 409.
EngineError::DrainRefused, EngineError::DrainBoundInvaliddrain on an agent that is not running, or a drain bound outside 1 to 600000 milliseconds.
RunError (a new enum)Every refusal of a Run or label call, with the stable codes listed under Runs and labels.
StoreError::NeedsMigrationA read-only engine opened a database at an older schema; a writing engine must open it first.
RegistryError::ServeOptionsOpenTimeOnlyServe options applied after the engine started its lifecycle, or twice. The shipped open paths never reach it.
TransitionCause: ReadinessTimeout, Unresponsive, RestartRequested, CleanExit, PauseCooperative, ResumeCooperative, DrainStoppedNot errors, but new causes: a readiness probe that never passed, a failed liveness check, a declared exit code class, a cooperative pause or resume, and the end of a drain.
EngineEvent::RunNot an error: the new Run event.
BreachAction::BlockNot an error: the wire fence.

The new causes and events are also new names on the wire. An older program that reads a newer engine's events or --json output, and meets readiness-timeout, unresponsive, restart-requested, clean-exit, pause-cooperative, resume-cooperative or drain-stopped, fails to deserialize it, so upgrade the readers before the engine.

On main, Busy comes after at most 1 second of waiting for the engine's store writer, and carries waited_ms: 1000. A Busy write was not applied, so retrying it is safe.

Upgrade from 0.4#

hekma-engine went from 0.4.0 straight to 0.7.0 on crates.io; 0.5 and 0.6 were never published. Change the requirement to "0.7" and work through this table:

What changedWhat to do
New error variants and the DetachedResumed cause (see errors)Add the new cases to your match, or a _ case.
New fields on FleetEntry (acp_context_usage, usage_gap, supervision), UsageView and UsageTotals (cached tokens), UsageEvent::cached_tokens, FleetTotals::total_cached_tokens and Rate::cached_micros_per_1mOnly code that builds these structs by hand needs changes. Reading them is unaffected.
SpawnRecord gained acp_session_id and run_id; SpawnSpec gained pipe_stdoutOnly if you implement your own process backend or store.
ProcessBackend gained take_stdin and take_stdout; StateStore gained set_spawn_run_id (with defaults) and six memory and spawn-record methods (without)Only if you implement these traits yourself.
New method read_raw_output_sinceOptional: use it to read what a detached agent wrote while no engine was open.
The acp built-in kindRegister ACP agents with register(name, "acp") and set acp.command.
The state database moves to schema 9 on first openAutomatic. An older Hekma refuses to open the upgraded database, so upgrade every program that shares a state directory together.

Upgrade to main's 0.12.0#

Unreleased: after 0.11.0. hekma-engine 0.12.0 is on Hekma's main branch and is published with the next release. Versions 0.8.0 to 0.11.0 of the crate were steps on main; none of them is on crates.io.

Besides the new methods and variants above, and the Run Keys surface, which Release notes lists under "For embedders" (Engine::authenticate, the Caller-acting *_as methods, the credential types, EngineEvent::Credential, and the new RunError, EngineError and Anomaly arms):

What changedWhat to do
New public fields: SpawnSpec::inherit_env (false gives the agent only its declared environment, as hekma serve does), SpawnRecord::owner (the engine process supervising the record)Only code that builds these structs field by field needs them.
ProcessBackend gained self_fingerprint and probe_aliveOnly if you implement your own process backend.
EngineOptions, new with open_with_options, has hidden test fieldsBuild it with ..Default::default().
RunId::mint returns the run_ and ULID formTreat run ids as opaque strings; the old run-… ids stay valid.
New variants on exhaustive enums: EngineEvent gains Policy and BreachDefaultUpgraded, Anomaly gains UnpricedModel, RunEventKind gains LimitsChanged, RunError gains PolicyNotFound, PolicyExists, PolicyDefault, ScentUnavailable, InvalidCursor, ScopeUnavailable, RaiseForbidden and VerbUnavailable, Case gains Rearm, CoverTag gains ReArm, and LimitSource gains CallerAdd arms (or a _ case) to any match on them.
New fields: RunLimits gains token_cumulative and dollar_cumulative_micros, RunEvent gains limits and prior_limits, FleetEntry gains breach_default_upgradedOnly code that builds these structs field by field needs them.
The default breach action is warnAn agent that relied on pause keeps it: the first open of the upgraded directory writes it into the agent's configuration. Set the action explicitly in code that depended on the default.
One store writer per engine: every write runs on one thread, each usage event commits with its rollups, breaches and outbox entries in one transactionExpect Busy after 1 second rather than 5. On a breach, events now arrive as the usage, then every breach it fired, then the pause or stop transition.
Transitions, breaches and the export outbox move into state.dbresync_events and the export read the database. instance.log and breaches.log are still written after each commit, as mirrors for people.
A breach fires once more if budget.breach_action changes during a RunThe once-per-Run rule is now kept per action, durably.
The database moves from schema 9 to schema 17 on first open, in steps: 10 records the engine process supervising each started agent; 11 records which engine re-adopted an agent whose supervisor died; 12 imports instance.log, breaches.log and the outbox files once; 13 turns recorded run ids into Runs; 14 records config as the origin of every bound label; 15 adds Policies; 16 adds three partial indexes for the Run listing; 17 adds the tokens table, the hash of every issued credentialAutomatic and one way. Stop every older engine on the directory first, including a running hekma serve: one already running does not notice the upgrade, and while its usage is still counted, its transitions, breaches and export entries after the upgrade are not. An older engine that opens the upgraded directory refuses it.