docs · guides

Run Hekma as a service#

Unreleased: after 0.11.0. hekma serve, hekma-host, the CLI's routing through a Service Host and everything on this page are on Hekma's main branch and ship in the next release; Hekma 0.11.0 does not have them.

hekma serve is the Service Host: one process that holds the engine open for as long as it runs, so every agent in a state directory is supervised all the time: crashes restart, usage is counted and budgets are enforced, with no gaps between commands. It is also what every hekma agent command that changes something talks to: when no host serves the directory, the first such command starts one in the background. Run it yourself under systemd, launchd or a container runtime, stop it with SIGTERM, and it stops each agent cleanly before it exits. This page covers what it does, how the CLI uses it, its flags, the rules it enforces, and recipes for systemd and containers.

What it does#

When it starts, hekma serve:

  1. takes a lock on the state directory, so no second host can serve it;
  2. opens the engine, which adopts every agent still running from earlier;
  3. binds its local endpoint on loopback and records it in control.json, so hekma agent commands can reach it;
  4. waits, supervising those agents and any that are started while it runs.

On SIGTERM or SIGINT (Ctrl+C) it stops accepting Control API requests, stops every running and paused agent through the normal stop sequence, prints how each one ended, and exits (shutdown has the details).

While it runs, it prints nothing on stdout. Everything goes to stderr as lines starting with [hekma] :

[hekma] host started; state root /Users/you/Library/Application Support/ktesio — supervising agents until SIGTERM/SIGINT
[hekma] local control endpoint on 127.0.0.1:49300 (loopback, for the hekma CLI; recorded in /Users/you/Library/Application Support/ktesio/control.json)
[hekma] SIGTERM received; stopping running and paused agents (graceful window 30s) ...
[hekma] control api stopped; no requests are accepted for the rest of the shutdown
[hekma] stopping ticker (graceful window 30s) ...
[hekma] ticker: stopped gracefully
[hekma] shutdown complete (SIGTERM)

This is what changes compared with 0.11.0:

Hekma 0.11.0Hekma main, with a Service Host
A plain hekma agent startStops the agent when the command exitsThe agent runs under the host and keeps running after the command and its terminal exit
Crash detection and restartsOnly while a command runsAll the time, for every agent the host started or adopted
Budget enforcementOnly while a command runsAll the time
Usage between commandsNot countedCounted
Engine-observed agentsNeed an embedding programA plain start runs them under the host, which keeps their metering proxy alive; start --detach is still refused (exit code 5)
hekma agent sendNeeds an embedding programReaches any agent the host started, whichever command started it

How the CLI uses the host#

Every hekma agent command that writes (register, remove, start, stop, pause, resume, drain, send, config set, memory attach and memory detach) is one call to the host that serves its state directory (how the CLI reaches the Service Host). The command finds the host through control.json. If no host serves the directory, the command starts one in the background, hekma serve --autostart, appends that host's output to serve.log in the state directory, and waits up to 10 seconds for it. Commands run at the same time share the one host.

Commands that only read (list, show, usage, logs, config get and governance-vectors) open the state database read-only and never start a host. On a fresh machine, hekma agent list prints the empty-fleet hint and creates nothing. A read never writes either: if it finds a running or paused agent whose process is gone, it shows it as failed with a note, and the next write records the change (troubleshooting).

A started agent belongs to the host, not to the command:

hekma agent start ticker
✓ Started Agent Instance ticker
running
• note: the agent runs under the local Service Host (pid 19757) and keeps running after this command exits; stop it with: hekma agent stop ticker

--detach goes one step further: it also unties the agent's process from the host, so the agent survives the host's own exit and the next host adopts it.

A host the CLI started#

A host started by a command behaves differently from one you run yourself:

  • It serves only the local endpoint, never --listen.
  • It ignores SIGHUP, so closing the terminal does not end it.
  • It leaves on its own. Once no agent is starting, running, paused or stopping and no command has reached it for 30 seconds, it stops through the normal shutdown and exits. It also exits when its state directory is deleted. A hekma serve you start yourself never exits for being idle.
  • It passes on the environment of the command that started it. Agents it starts see that command's environment, as they did when the CLI ran them itself, so export KEY=... followed by hekma agent start in the same shell still works. secret:NAME references resolve in the host: its environment first, then secrets.toml. A variable exported after the host started does not reach it: stop its agents and let it exit, or end its process (control.json names the pid), and the next command starts a fresh one.
  • A host from another build, for example after an upgrade, is still used, with a note naming both versions. Restart it to match.

serve.log shows the whole life of such a host:

[hekma] host started; state root /Users/you/Library/Application Support/ktesio — supervising agents until SIGTERM/SIGINT
[hekma] local control endpoint on 127.0.0.1:49586 (loopback, for the hekma CLI; recorded in /Users/you/Library/Application Support/ktesio/control.json)
[hekma] auto-started host exiting (idle: no live agent and no request); stopping running and paused agents (graceful window 30s) ...
[hekma] control api stopped; no requests are accepted for the rest of the shutdown
[hekma] no running or paused agents; nothing to stop
[hekma] shutdown complete (idle: no live agent and no request)

Messages and exit codes are the same as when the CLI ran the engine itself: the host sends back the engine's typed error and the command prints it as before. Notes the engine raises during a command, such as a start's delivery note, are printed on the command's stderr; notes the host raises on its own, such as a crash it noticed, go to the host's stderr, which is serve.log for a host the CLI started. A host that cannot be found or started fails the command with exit code 1 and names serve.log (troubleshooting).

The local endpoint#

Every hekma serve, whether you started it or a command did, binds a local endpoint: the Control API on 127.0.0.1, on a port the OS picks, over plain HTTP. It records the endpoint in control.json in the state directory:

{
  "schema_version": 1,
  "pid": 19757,
  "addr": "127.0.0.1:49300",
  "token": "<64 hex digits>",
  "hekma_version": "0.11.0",
  "autostarted": true
}
  • token is a fresh 256-bit bearer token, drawn from the OS's random source each time a host starts. It works on every route and every listener, like the --bearer-secret value.
  • The file is readable only by its owner (mode 0600 on Unix; on Windows it inherits the state directory's permissions, like secrets.toml). Whoever can read it can drive the host, so protect it as you protect secrets.toml.
  • It is written once the endpoint is bound and removed when the API stops at shutdown. A control.json left behind by a host that crashed is harmless: the next command finds the host gone and starts a new one.
  • autostarted is true for a host a command started.

--listen adds a listener for other clients beside this one; it does not replace it.

hekma serve and hekma-host#

The same host comes in two forms:

BinaryUse it for
hekma serveA subcommand of the normal CLI. Use it on a machine where hekma is installed.
hekma-hostA standalone binary that does only this, with the same flags. It ships in the static Linux archive, for container images that do not need the full CLI.

Flags#

FlagDefaultMeaning
--state-dir <DIR>HEKMA_STATE_DIR, else the platform defaultThe state directory to serve.
--stop-window <SECS>30How long each agent gets to exit on shutdown before it is killed. 1 to 86400.
--metering-listen <PORT>0 (any free port)A fixed loopback port for every engine-observed agent's metering proxy. With a fixed port, an engine-observed agent that outlives a host restart keeps a working proxy address. A port in use stops the host from starting.
--log-capture <MODE>fullWhat is kept of agents' output: full, metadata or off. See log capture.
--listen <ADDR>offAlso serve the Control API on this address, such as 127.0.0.1:8477, beside the local endpoint. Requires --bearer-secret. An address that is not loopback also requires --tls-cert and --tls-key (TLS).
--bearer-secret <NAME>noneThe name of the secret holding the API's bearer token, read from the environment variable of that name or from secrets.toml. Requires --listen.
--tls-cert <PEM>noneServe --listen over HTTPS with this PEM certificate chain. Requires --tls-key and --listen.
--tls-key <PEM>noneThe PEM private key for --tls-cert.
--otlp-endpoint, --otlp-headers, --otlp-flush-intervaloffExport metrics to an OpenTelemetry collector. See Telemetry export.

hekma serve never prints an update notice. Exit codes: 0 after a shutdown, 1 if it could not start (for example, an unresolvable bearer secret), 2 for a bad flag, a state directory another host already serves, a non-loopback --listen without TLS, or a TLS file that cannot be read.

TLS beyond loopback#

A --listen address that is not loopback, such as 0.0.0.0:8477, must come with a certificate and key. Without them, the host refuses to start with exit code 2, before it takes the lock, binds or opens anything:

$ hekma serve --listen 0.0.0.0:8477 --bearer-secret CONTROL_BEARER
✗ --listen 0.0.0.0:8477 is not a loopback address: beyond loopback the Control API requires TLS — pass --tls-cert <pem> and --tls-key <pem> (or bind 127.0.0.1)
  • --tls-cert and --tls-key go together, and both need --listen; one without the other is a usage error.
  • The PEM files are read when the host starts. A file that cannot be read, or a key that does not match the certificate, stops the start the same way, naming the path.
  • With both, the listener answers HTTPS only; a plain HTTP request fails the TLS handshake and is never served. A loopback --listen may use TLS too. The local endpoint never does.
  • The TLS code is built into the binary (rustls with ring), so no system TLS library is needed, including on scratch images.

Earlier builds of hekma serve on main served a non-loopback address over plain HTTP with a warning. That is no longer possible: add the certificate flags, or bind 127.0.0.1.

One host per state directory#

The host holds an operating-system lock on host.lock in the state directory for as long as it runs. A second host on the same directory is refused, naming the first one's process id:

$ hekma serve
✗ the state directory is already served by another host (pid 18918, lock /var/lib/hekma/host.lock) — stop that host first, or serve a different state directory

That exits with code 2. The lock belongs to the running process, not the file: if a host crashes, the next one takes the lock without any cleanup, so never delete host.lock by hand.

hekma agent commands do not compete with the host: writes go through it and reads open the database read-only, so a hekma agent list beside a running host leaves its agents alone. A command run while your own hekma serve holds the directory uses that host rather than starting another.

A program that embeds the engine on the same directory is still a second engine. An engine also leaves alone an attached agent whose supervising engine is still alive, but two long-running engines on one directory both supervise detached agents, and both count and enforce. Give an embedding program a state directory of its own; one engine per state directory explains why.

Shutdown#

On SIGTERM or SIGINT, or for a host the CLI started when it has been idle for 30 seconds, the host:

  1. stops the Control API, closing open event streams and removing control.json, so clients see the API go before any agent stops;
  2. sends every running and paused agent the stop sequence at once, each with --stop-window;
  3. looks again for agents that started during the drain and stops those too;
  4. prints one line per agent: stopped gracefully, killed after the window, already gone, or failed to stop (with the reason);
  5. exits with code 0.

A second SIGTERM during the drain is ignored with a note; the drain already running finishes. Two things to plan for:

  • Exit code 0 does not mean every agent stopped cleanly. The per-agent lines on stderr are the record. A process manager's restart-on-failure setting will not see a failed agent stop.

  • Agents that need the full window queue up. The engine runs one forced stop at a time, so in the worst case the drain takes about one window per agent, twice. Give your process manager or container runtime a stop timeout longer than that.

  • Paused agents are resumed, then stopped. A frozen process cannot receive the graceful stop signal, so the host resumes a paused agent first and then runs the same stop sequence, with a note:

    [hekma] ticker: resumed the paused process before the stop ladder — a suspended process cannot receive the graceful stop signal (it stays pending until the process continues)
    [hekma] ticker: stopped gracefully

    A resumed agent may do a little more work, and report a little more usage, before it exits. An agent that paused itself through its adapter's pause commands is not frozen, so there is nothing to resume and the stop goes ahead directly. hekma agent stop on a paused agent does the same.

If the host is killed instead (SIGKILL, out of memory, power loss), no drain runs. On Unix, agents in their own process groups keep running; the next host adopts them and carries on. Usage they reported while no host was running is not counted.

Environment of hosted agents#

Under a hekma serve you start yourself, an agent's process does not inherit the host's environment. (A host the CLI started is different: it passes on the environment of the command that started it.) It gets:

  • the variables its adapter declares: the manifest's [lifecycle.start.env] and config key mappings, and every agent.* key;
  • PATH and HOME from the host (on Windows also SystemRoot, SystemDrive, ComSpec, TEMP and TMP), so programs can still start and find other programs.

Nothing else passes: not your shell's exports, credentials or CI variables. In a test, a variable exported in the host's shell did not reach the agent, while a manifest variable and an agent.* key did. This is always on for a serve you start. Give each agent what it needs explicitly, typically an API key as agent.OPENAI_API_KEY secret:OPENAI_API_KEY (see secrets).

Put the state directory on a volume#

Everything the host needs is in the state directory: the lock, state.db, secrets.toml, and the Agent Homes and their logs. state.db holds the agents, their transitions and breaches, and the export journal with its acknowledged position; the event logs in each Agent Home (instance.log, breaches.log) are written after each change as readable copies of the database. While a host runs, the directory also holds control.json and, for a host the CLI started, serve.log. Point --state-dir or HEKMA_STATE_DIR at storage that outlives the host, and a replacement host picks up where the last one stopped, including the export position.

Upgrading is one-way. The first time a newer engine opens a state directory, it upgrades state.db and imports the older log and journal files once (outbox.jsonl and outbox-ack.json are renamed *.migrated). An older engine then refuses the directory as too new, but one that is already running, such as an older hekma serve, does not notice. Stop every older host before you upgrade.

Use a local disk, a bind mount or a block device. Network file shares such as NFS or EFS do not reliably support the file locks and SQLite needs, and two hosts could end up serving one directory.

Log capture#

--log-capture chooses, for every agent the host runs, what is kept of the agent's output:

ModeWhile the agent runsAfter a clean stopReading logsMetering
fullagent.log, agent-stderr.log and output.log as usual. Each raw file is emptied once it passes 10 MB and everything in it has been read.The files stay.Everything works.Full
metadataThe raw files exist, but output.log holds only a timestamp, stream, length and SHA-256 hash for each line, never its text.The raw files are deleted.hekma agent logs is refused.Full
offOutput goes nowhere.Nothing.Refused.Self-reported usage lines are lost; Hekma warns at start.

metadata keeps agent output off the disk once agents stop, not while they run. If the host dies before a clean stop, the raw files remain. If output is sensitive, treat the volume as sensitive, or use off and give up self-reported metering.

Run it with systemd#

A unit for a Linux server, with the state on /var/lib/hekma and the Control API on loopback. Create a user hekma first, and put the bearer token in /etc/hekma/env as CONTROL_BEARER=... (readable only by root).

[Unit]
Description=Hekma agent host
After=network-online.target
Wants=network-online.target

[Service]
User=hekma
Environment=HEKMA_STATE_DIR=/var/lib/hekma
EnvironmentFile=/etc/hekma/env
ExecStart=/usr/local/bin/hekma serve --stop-window 30 --listen 127.0.0.1:8477 --bearer-secret CONTROL_BEARER
KillSignal=SIGTERM
KillMode=mixed
TimeoutStopSec=120
Restart=on-failure
StateDirectory=hekma

[Install]
WantedBy=multi-user.target

KillMode=mixed sends SIGTERM to the host only, so the host stops the agents itself, and systemd cleans up anything left after TimeoutStopSec. Size TimeoutStopSec well past --stop-window. Restart=on-failure restarts a host that crashes; it does not react to an agent that failed to stop, because the host still exits 0. Read the host's output with journalctl -u hekma. The hekma user's PATH and HOME are what agents receive, so install agent programs where that PATH finds them.

To manage the agents from a shell on the server, run hekma agent commands as the same user with the same state directory, for example sudo -u hekma env HEKMA_STATE_DIR=/var/lib/hekma hekma agent list. They reach the running host through its local endpoint, whose control.json only that user can read.

Run it in a container#

The static Linux archive, hekma-<tag>-x86_64-unknown-linux-musl.tar.gz, contains hekma, hkm and hekma-host, linked against nothing but the kernel and carrying their own TLS root certificates. It runs on scratch or distroless images. It is x86_64 only, and the installer does not use it; download it from the release page.

This image fetches and checks the archive, then copies the three binaries into an empty image:

# syntax=docker/dockerfile:1
ARG HEKMA_VERSION=vX.Y.Z

FROM alpine:3.22 AS fetch
ARG HEKMA_VERSION
RUN apk add --no-cache curl
WORKDIR /fetch
RUN set -eux; \
    archive="hekma-${HEKMA_VERSION}-x86_64-unknown-linux-musl.tar.gz"; \
    base="https://github.com/Ktesio/hekma/releases/download/${HEKMA_VERSION}"; \
    curl -fsSLO "${base}/${archive}"; \
    curl -fsSLO "${base}/${archive}.sha256"; \
    sha256sum -c "${archive}.sha256"; \
    mkdir /out; \
    tar -xzf "${archive}" -C /out

FROM scratch
COPY --from=fetch /out/hekma /hekma
COPY --from=fetch /out/hkm /hkm
COPY --from=fetch /out/hekma-host /hekma-host
ENV HEKMA_STATE_DIR=/data
VOLUME /data
STOPSIGNAL SIGTERM
ENTRYPOINT ["/hekma-host"]
CMD ["--listen", "0.0.0.0:8477", "--bearer-secret", "CONTROL_BEARER", \
     "--tls-cert", "/certs/cert.pem", "--tls-key", "/certs/key.pem", \
     "--stop-window", "45"]

Set HEKMA_VERSION to the release you deploy, and pin the alpine image by digest if you need reproducible builds. Binding 0.0.0.0 needs TLS, so the certificate and key come from a read-only mount; never bake them into the image. Run it with a stop timeout longer than the window, the token from the environment, the certificates mounted, and the API published only on the machine's loopback:

docker build -t hekma-host .
docker run -d --name hekma \
  -v hekma-data:/data \
  -e CONTROL_BEARER="use-a-long-random-value" \
  -v "$PWD/certs:/certs:ro" \
  -p 127.0.0.1:8477:8477 \
  --stop-timeout 90 \
  hekma-host
docker stop hekma    # SIGTERM, drain, exit 0
docker logs hekma    # the per-agent stop lines

Things to know in a container:

  • Your agents must run in the image too. scratch has no libc, so it runs only static agents (Go, Rust or musl builds). For Node, Python or anything linked against glibc, use a base image with that runtime and copy the three Hekma binaries in the same way.
  • hekma-host can be PID 1. It handles SIGTERM and SIGINT itself, even during startup. It does not reap stray grandchildren of agents, so if your agents start subprocesses, run with docker run --init or tini, which also forward SIGTERM.
  • Name resolution on scratch relies on the /etc/resolv.conf and /etc/hosts that Docker and Kubernetes normally mount. Without them, hostnames in metering.upstream_base_url do not resolve.
  • The Control API answers HTTPS on 0.0.0.0. Use a certificate your clients trust, for example curl --cacert certs/cert.pem -H "Authorization: Bearer ..." https://127.0.0.1:8477/v0/version. There is still no health route: every route needs the token, so an unauthenticated health probe gets 401. The process being up, and its [hekma] lines on stderr, are the liveness signal.
  • Commands inside the container reach the host. The host also binds its local endpoint inside the container and records it in /data/control.json, so docker exec hekma /hekma agent list talks to the running host.
  • Metrics can go to an OpenTelemetry collector with --otlp-endpoint; see Telemetry export.
  • --metering-listen is not needed when hekma-host is the entrypoint: agents are children of the container and end with it, so no engine-observed agent survives a host restart.

Metering inside a container#

Engine-observed metering works in a container as it does on a machine: the agent and its metering proxy share the container's network, so the 127.0.0.1 address the agent is given reaches the proxy. An agent in another container or pod (a sidecar) cannot reach it; it either fails every model call or ignores the address and goes around the meter. Run agents in the same container as the host, or use self-reported metering for them.

A container is not a fence. The proxy counts the traffic an agent sends to it, and an agent that calls its provider directly is not counted. If you need enforcement an agent cannot bypass, route its traffic through a gateway you control and treat Hekma's ledger as the record to reconcile against. Metering agents you don't control explains the reasoning.

The wire fence: block refuses further model calls#

Unreleased: after 0.11.0. The block breach action is on Hekma's main branch and ships in the next release; Hekma 0.11.0 does not have it.

budget.breach_action = block makes the metering listener refuse an engine-observed agent's model calls once a ceiling is reached. Unlike pause and stop it changes no lifecycle state: the process keeps running, and every further model call through the listener gets a typed refusal that common SDKs do not retry. The breach is recorded like any other (the breach event carries "action": "block"), and the engine log notes that the fence is up.

hekma agent config set my-agent budget.tokens.cumulative 2000000
hekma agent config set my-agent budget.breach_action block

The rules:

  • Never a default. block applies only where you set it.
  • It needs the listener. config set refuses block on an instance that does not meter through the engine-observed listener (a self-reported one), naming its metering source. If block reaches such an instance another way — a hand-edited config file — the breach is recorded, acts as warn, and the engine log says the fence could not be raised.
  • It lifts with the Run, or with a raised ceiling. The fence lives as long as the Run. It lifts when the Run ends (stop then start), or as soon as the matching ceiling is raised above the totals on the live Run, through hekma budget set, an agent budget.* configuration write or a Policy change. It lifts reason by reason: a fence still holding another latched block reason stays up until that ceiling is raised too. A new Run is checked before its process starts: if it already sits at or over a block ceiling — usually the cumulative one — the fence is up before its first call.
  • A relaunch keeps the fence. A Restart Policy relaunch after a crash continues the same Run, so its per-run totals keep counting and a per-run block fence is up again on the relaunched listener before its first call.
  • Changing the action re-fires once. If you switch budget.breach_action to block after a ceiling has already breached in this Run, the breach fires once more as a block breach, so the fence goes up and survives a host restart.
  • Restarts and adoption keep it. A host that restarts and adopts the instance on the same --metering-listen port rebuilds the fence from the breach log before serving traffic.
  • Safe methods pass. GET, HEAD and OPTIONS requests (model listings, probes) are forwarded; they carry no billable completion.
  • It is cooperative. The fence refuses calls that go through the listener. An agent that calls the provider directly is not fenced. It also goes up only after the breaching usage has committed, so the call that crossed the ceiling and any requests already in flight still reach the provider. Your own choke point stays the enforcement of record.

The refusal (proxy-wire v1)#

A fenced call is answered without being forwarded or metered:

  • Status 402 Payment Required. The OpenAI, Anthropic and Vercel AI SDKs retry 408, 409, 429 and 5xx, but not 402. Hekma avoids 403 because agents read it as a credential failure.
  • Headers content-type: application/json and x-should-retry: false (the OpenAI and Anthropic SDKs check this header before the status). There is no retry-after.
  • Body: compact JSON that parses as both an OpenAI and an Anthropic error:
{"type":"error","error":{"type":"hekma_budget_block","code":"tokens_cumulative","message":"Hekma budget fence: this agent's cumulative token ceiling is reached, so further model calls are refused. This is not retryable; the operator raises the ceiling or starts a new Run.","param":null,"dimension":"tokens","scope":"cumulative","proxy_wire":"v1"}}

error.type is always hekma_budget_block. error.code names the ceiling — tokens_per_run, tokens_cumulative, dollars_per_run or dollars_cumulative; when more than one ceiling is fenced, the first in that order is reported. dimension and scope repeat the code in Hekma's own spelling. The body never carries a limit, a total, an instance name, or any request or response content. Key on error.type and error.code; the message text may change.

This response is the first part of proxy-wire v1, the versioned wire contract of Hekma's metering proxy; later releases keep it unchanged. The governance vectors pin the same refusal (the fence cases, from vectors 1.1.0), so a host guard can prove it answers the same way.