Parked gates and remote execution in H v0.4.0
In H v0.4.0, a coding session can wait hours for a human tool approval or an external webhook while holding zero worker processes, then run approved commands across an authenticated HTTP boundary that reaps stray process groups on disconnect.
- Published
- Reading time
- 17 min read
A few days after I switched from Pi to my own coding harness, I ran into the next set of boundaries. Detaching my terminal or picking up a conversation on my phone worked because the Elixir/OTP daemon owned the session state. Once I started leaving three or four sessions running across worktrees, though, a new set of questions showed up. How do I require explicit confirmation before a mutating shell command runs without tying up a worker process while my laptop lid is closed? How do I wake a parked session from an external build job without writing another sleep loop? And what happens when the model and session state live on my machine, while the tools themselves run inside a container or on another host?
H v0.4.0 answers those questions while keeping the :harness core dependency list unchanged: bandit, plug, req, and req_llm. The standalone bundles for Apple Silicon and Linux are out on hiness.dev and hiness.app, and the updated OTP engine is packaged for Hex as hiness.
Parking tasks in the coordinator
The naive way to implement human tool approval or an external webhook wait in Elixir is to block inside a Task.Supervisor worker with a long receive timeout. On the BEAM, sleeping processes are cheap in memory, so that shortcut looks harmless in a prototype. It falls apart as soon as you care about restarts and workspace locks. If the worker already acquired the workspace writer lease before asking for permission, every other branch or review save on that checkout stalls behind an unanswered prompt. Worse, if the VM restarts for an upgrade or loses power, a receive block in a dead worker leaves behind an ambiguous “running” task record.
In H, long waits belong to H.Session.Server, the single-writer GenServer that coordinates a session, rather than to an effect worker. We already proved that pattern for delegated subagents. In v0.4.0 we extended the same coordinator state machine to two new gates: owner tool approvals and external wake signals.
When a conversation sets agent.approval_policy to "mutating" or an explicit tool list such as ["bash", "write"], H.Session.Server.Tools validates the tool arguments and resolves the target directory, then stops before acquiring H.WorkspaceLease or starting a child under Task.Supervisor. Instead, the coordinator commits a task transition to status: "waiting" with wake: %{"on" => "approval"} and writes the pending request into live.approvals inside the session’s CRC32-framed write-ahead log. Zero worker processes run while the session waits. H.Catalog marks the session with needs_attention: true so it rises to the top of hi inbox and the browser inbox.
In the terminal, hi opens a focused approval picker as soon as a new approval arrives; pressing Escape dismisses the picker without denying the call so I can read the surrounding transcript first and run /approve or /deny when ready. In hiweb, the pending card renders the tool name, working directory, and arguments with Approve and Deny actions. Both clients send the idempotent approve_tool command:
{
"version": 1,
"request_id": "approve-99",
"conversation_id": "1",
"command": "approve_tool",
"args": {"task_id": 99, "decision": "allow"}
}
Allowing the call writes "approval_decision" => "allow" into the task’s durable memos, clears live.approvals, transitions the task back to "pending", and spawns the worker to acquire the workspace lease and run. Denying the call appends an error tool_result with diagnostic: "approval_denied" without touching the filesystem, then lets the model adjust its plan. We test this path by sending SIGKILL to the OS process of a running daemon while a mutating write or bash call is parked on approval. When a fresh VM opens the store, the unapproved tool stays parked in "waiting" and never executes on its own.
External wake signals follow the same rule. An authenticated caller posts to POST /api/v1/sessions/:sid/signals with a request_id, a topic, and a bounded JSON payload up to 16 KiB. H.Session.Signals stores an idempotent receipt and a FIFO queue per topic inside the {:session, "signals"} document. When a model turn calls the new read-only wait_signal tool, two orderings can happen:
- If a signal on that topic arrived earlier and is still unconsumed,
wait_signalpops it from{:session, "signals"}and completes in the same commit without parking. - If no signal is queued yet,
H.Session.Serverparks thetool_calltask in"waiting"with zero worker processes and an optional durableuntildeadline, waking it in a single atomic commit the momentPOST /api/v1/sessions/:sid/signalsarrives.
Because H.Daemon.deliver_signal/3 wakes an idle-unloaded session on arrival and writes to disk before replying 200, signals survive five-minute idle unloads and VM restarts without race conditions between the HTTP handler and the tool call.
Run budgets and task-scoped aborts
When I supervised parallel coding agents from tmux, my way to stop a runaway loop was switching panes and hitting Ctrl-C. Detached daemon sessions need explicit guardrails when nobody is watching the terminal.
Conversations now accept an optional agent.budget map (max_turns, max_cost_usd, and max_elapsed_ms), configured at session creation, through daemon defaults, or live via /budget turns=10 cost=2.50 elapsed=300s. H.Session.Server records the run’s starting timestamp and cumulative cost when a new generation starts, then checks the budget at turn boundaries. If a turn crosses the cost or elapsed-time limit after emitting tool calls, H records synthetic budget_exceeded tool results instead of launching those tools, settles the run with live.run_failure.reason = "budget_exceeded", and flags needs_attention: true in the inbox. Because every tool call in the transcript stays paired with a result, running /continue starts a fresh run budget window cleanly from the exact point where the session paused.
We also narrowed cancellation when parallel work is in flight. Omitting task_id on abort still stops the whole conversation run. Passing /abort <task_id> (or clicking Abort on one tool or subagent card in hiweb) cancels only that child tool_call task. If the model fanned out three parallel worktree subagents and one lane goes down the wrong path, task-scoped abort sends a bottom-up parent_aborted stop to that single child session while the other two subagents finish their turns uninterrupted.
Authenticated remote execution with attempt fences
When I wrote about BeyondCorp in the age of AI agents, the principle I cared about most was separating identity and policy from network location. Having the model and session store on the same filesystem as every shell command is convenient on a laptop, yet plenty of workloads belong inside an isolated container, a disposable VM, or a dedicated build machine.
Earlier versions of H had an in-VM H.RemoteAgent prototype and an Erlang distribution helper. Erlang distribution is great inside a trusted cluster, though I rarely want to expose full BEAM node distribution just to let a coding session run mix test or cargo test inside a sandbox container. In v0.4.0, h-daemon ships a standalone remote-agent mode over HTTP or a Unix domain socket:
h-daemon remote-agent \
--cwd /srv/worktree \
--id container-a \
--bind 127.0.0.1 \
--port 4300 \
--token-file /run/secrets/h-agent.token
H.RemoteAgent.HTTP runs a minimal Bandit + Plug server around H.RemoteAgent without starting H.Catalog, H.Accounts, or session supervisors. Every request on /v1/* verifies its bearer token in constant time by hashing both the provided token and the expected token with SHA-256 before calling Plug.Crypto.secure_compare/2, so neither timing nor token length leaks across the socket. H.RemoteAgent.Client wraps the token in %H.Credentials.Redacted{} so inspect/1 and crash logs never print it.
Networked command execution has two classic failure modes: duplicate retries after a dropped packet, and orphan child processes after a client crash. H handles both explicitly:
- Every
POST /v1/exec/streamcall carries a four-part{session_id, incarnation, task_id, attempt_id}fence.H.RemoteAgentchecks that fence before opening an ErlangPort. Any duplicate or older attempt receives409 Conflict("stale_fence") before an OS process can spawn. - While NDJSON base64 output chunks stream back to the session’s tool worker,
H.RemoteAgent.Clientrenews the execution lease onPOST /v1/exec/renewevery few seconds. At the same time,H.RemoteAgent.HTTPmonitors the HTTP socket withactive: :once. - If the socket drops or the lease expires without renewal,
H.RemoteAgentterminates the remote OS process group (SIGTERMfollowed bySIGKILLafter grace) so background child processes spawned by/bin/sh -ccannot linger in the container.
In our subprocess restart suite, we start h-daemon remote-agent and a separate brain daemon, kick off a mutating bash command that spawns a child sleep loop on the remote agent, and SIGKILL the brain daemon mid-run. The remote agent reaps the entire process group on disconnect and lease expiry, and when the brain daemon boots back up on the same data directory, it marks the :unsafe bash task as "interrupted" without replaying it.
Running Phoenix out of VM
Bundling hiweb inside the same BEAM VM as :harness (HWeb.Backend.InVM) keeps single-machine installs simple, which is why H.app and the standalone release tarballs use it by default. During web UI development, or when running the web frontend in a separate process from the long-lived daemon, sharing a VM is a constraint rather than a benefit.
HWeb.Backend.HTTP implements the full HWeb.Backend behaviour over <data_dir>/api.sock or loopback HTTP (H_WEB_BACKEND=http). Two supervised SSE bridge processes connect to GET /api/v1/sessions/events and GET /api/v1/sessions/:sid/conversations/:cid/events, translating initial snapshots, replay rings, commit frames, and ephemeral streaming deltas into the exact messages that InboxLive, WorkspaceLive, SessionLive, and ReviewLive consume in-VM. Account management (AccountsLive), provider catalogs (ProvidersLive), harness selection, tool approvals, and budget controls all route through HWeb.Backend, so switching between InVM and HTTP requires zero template or LiveView changes.
Startup-only extension seams and EditorHost
One architectural boundary we sharpened in v0.4.0 is how extensions load. BEAM supports hot code swapping, and it is tempting to expose an endpoint that reloads extension .beam files inside a live daemon. After reviewing what that does to reasoning about recovery, we chose the opposite rule: H extensions (H.Extension API 1) load strictly at daemon startup from operator-owned local artifacts listed in <data_dir>/extensions.json. When you upgrade an extension, you run hi daemon restart, which cooperatively drains in-flight workers and boots cleanly against the committed store.
Within that startup-loaded model, v0.4.0 adds the concrete seams needed by real packages:
GET /api/v1/harnessespublishes registeredH.Harness.descriptor/0records sohi --harness <id>,/harness, andhiwebcan select profiles without hardcoding names.H.Extension.Observer(command_committed/1andwork_settled/1) runs in a supervisedH.Extensions.ObserversGenServer with a bounded 256-event queue andtry/rescue/catchisolation. Notifications fire viaGenServer.cast/2strictly afterH.Storage.commit/2succeeds, never on idempotent deduplication hits, and never with raw prompts or credentials.H.Harnessadds optionalprepare_context/2andproject_response/2callbacks.prepare_context/2runs inside the short-lived inference worker rather than blocking the session single writer, validates that UTF-8 contributions stay within 32 KiB without escalating tools, and fails closed (context_preparation_failed) on error or timeout rather than sending an unreviewed request.H.ExecutionEnvadds optionaladmit_exec/2(a fail-closed pre-launch gate that can deny a command or tightentimeout_msand output windows) andoperation_finished/2(lossy sanitized duration and result-class telemetry).GET /api/v1/sessions/:sid/conversations/:cid/extension-statusexposes cached scalar status maps with remaining TTL (max_age_ms) and zero provider I/O on read.MultiCodexuses it to projectaccount_pooleligibility for Codex models, andhipolls it only when"extension_status": trueis enabled in<data_dir>/hi.json.
To test live external capabilities without turning SSE viewers into tool workers, we also built extensions/editor_host (EditorHost), bundled alongside MultiCodex as a disabled-by-default artifact. When two clients (hi and hiweb) watch the same conversation, a tool call must never broadcast to both viewers and hope only one answers. EditorHost pairs a single live editor process per workspace using a short-lived, single-claim 32-byte grant (verified in constant time, never reusing the daemon’s owner token) and fences invocations by a monotonic host_generation counter. Its read-only editor_buffer_summary tool requires an expected_revision argument so an unsaved buffer that changed mid-turn returns an explicit revision_mismatch instead of silently mixing revisions.
Daily terminal cutover details
Finishing the daily hi workflow rounded out the rest of the release:
hi logout [alias]andhi key remove <provider> <alias>(plus/logout,/key remove, and Remove buttons inhiweb) delete credentials cleanly from<data_dir>/credentials/and reassign or clear active aliases.- Custom JSON themes in
<data_dir>/themes/<name>.jsonextenddark,light,ansi, orplainpalettes and roll back atomically on/reloadif a file has an unknown key or invalid hex color. - Markdown prompt templates in
<data_dir>/prompts/<name>.mdexpand `` or$ARGUMENTSvia/prompt:<name>with/Tab completion. - In
--tui-mode regular,hidetects Kitty/Ghostty and iTerm2/WezTerm inline graphics protocols (HI_INLINE_IMAGES=kitty|iterm2|off), validates base64 payloads against[A-Za-z0-9+/=]so untrusted image data cannot smuggle escape sequences, and uses text captions in fullscreen mode.
Try v0.4.0 or embed :harness
If you want to run hi and hiweb on your own projects, install the signed v0.4.0 bundle from hiness.dev or grab H.app for macOS from hiness.app:
curl -fsSL https://hiness.dev/install.sh | sh -s -- --service
hi daemon status
To embed the OTP engine inside an Elixir 1.20 / Erlang/OTP 29 application without the Rust CLI or Phoenix workbench, depend on hiness on Hex:
{:harness, "~> 0.4.0", hex: :hiness}
The module documentation and behaviour specs are on HexDocs. Every claim in this post is backed by --no-start ExUnit suites, PTY harness runs, and SIGKILL recovery tests in the repository. If you build an execution environment, a harness profile, or an external signal workflow on v0.4.0, tell me how it holds up.