docs/pkg/service.md
pkg/service — daemon orchestration
pkg/service runs the persistent daemon: startup and readiness, Unix-socket peers,
external service processes, capability routing, and shutdown. For executable behavior,
see cmd/ez-agent-service; for configuration, see
service/config; for stored session state, see
service/session; for per-leaf model execution, see
service/agent. Other destinations are in the routing table below.
| Role | Key files |
|---|---|
| Daemon lifecycle and readiness | daemon.go, state_lock.go |
| Socket server and peer dispatch | server.go |
| Leaf runtime/state operations and coordination | leaf_operations.go, leaf_runtime_operations.go, leaf_sync.go |
list_leaves sync views | leaf_list_sync.go |
| Capability ownership and pending calls | registry.go, ipc.go |
| Child service supervision | process_pool.go, service_process.go |
| Progress/replay and logging | progress.go, logging.go |
How do list_leaves sync views work?
list_leaves with sync: true creates a view holding the request's filters,
the confirmed revision's row fingerprints, and the newest sent revision until
the client confirms it. Replies carry at most 200 rows; offset reads later
chunks of the held revision. A poll with sync_id and the last fully received
revision confirms it and returns the next revision: changed rows, plus
removed IDs on the offset: 0 chunk. Each poll re-runs the stored query and
diffs fingerprints of the whole LeafInfo, including has_pending_questions,
so the flag can change without a turn or metadata update. Polling again from
the confirmed revision re-diffs it under a new revision number.
Plain and sync lists compute the flag before sending or fingerprinting rows.
Project trust checks only existing question observations of the current
revision and reads config once per resolved workspace for the query. Tool approvals count for eligible clients
with known tool_approval version 1 support. Neither check requires the list
recipient to follow the leaf. Connections with a restricted socket origin and
daemon-managed providers always get a false flag, including when a leaf
snapshot shows them a project-trust question. Turning Workspace approvals off
does not grant question-answer authority.
Views live only in memory and are not tied to a connection. Each poll or chunk
read must match the view's question visibility, including across reconnects or
after capability discovery. A mismatch returns list_sync_unavailable so the
client can reopen the view. Eviction is least recently used under a
budget of max(32 MiB, 32 × leaf count × 48 B), roughly 32 full-size views. Each
view is charged 4 KiB plus its filter strings, 48 B per row fingerprint and any
held reply rows, so empty views still reach eviction. A view used in the last
10 minutes is never evicted, even over budget. An unknown,
evicted, unheld or out-of-range request returns list_sync_unavailable, and the
client reopens. Malformed combinations, such as filters with sync_id, return
parse_error.
When is the daemon ready?
A bound socket is not readiness. Each bound listener answers only
hello_ack{ready:false} while session maintenance runs. The same listeners then
hand off to the normal server, preserving their inodes and queued clients.
ProbeDaemonContext distinguishes an unavailable daemon from one still starting;
StartDaemonContext joins an existing starting/ready daemon, while
StopDaemonContext refuses a bootstrap daemon and verifies readiness again before
shutdown.
The ready daemon advertises future.version_info version 2 through optional
V1 extra discovery. Its version request returns this receiving daemon's
release, stability, build date and Git revision in version_result, matching
the V2 contract. It does not send an unsolicited version announcement.
Bootstrap peers do not run discovery. See the
JSONL catalog for the discovery and
backport rules.
Startup storage cleanup, interrupted-turn repair, optional vacuum, and content
reconciliation are orchestrated here but owned by
service/session. Warning failures may still permit readiness;
failed cleanup or repair suppresses automatic vacuum.
Interrupted-leaf alert recovery runs during repair, before serving clients. Unlike best-effort turn repair, failure to recover these alerts stops startup so active recovery markers are not mistaken for fresh activity.
Selected incident registrations in audit.go use fixed friendly operation
descriptions for stats reads, leaf names, prompt admission, abort, and individual
startup phases. Handler entry, panic boundary, and response sites have distinct
static file/method/index identities. The descriptions share the internal Go/Ruby
operation allowlist; they never come from request text
or exceptions. This labeling does not change service behavior or add stack-wide
instrumentation.
What does a connection own and lose on cleanup?
Server accepts Unix peers and dispatches typed operations, but JSONL frame schemas
belong to pkg/protocol and pkg/ezagentapi.
The daemon binds the trusted listener at $XDG_RUNTIME_DIR/ez-agent/ez-agent.sock
and the restricted one at $XDG_RUNTIME_DIR/ez-agent/restricted/ez-agent/ez-agent.sock.
config.RestrictedRuntimeHome() returns $XDG_RUNTIME_DIR/ez-agent/restricted.
Bubblewrap mounts only the restricted listener's socket at the normal client
path in its private runtime directory. Both listeners use the same socket
permissions and stale-socket handling. The daemon owns the listener, so
provider recovery does not recreate it. If the restricted bind fails, the
trusted listener still starts and the daemon does not expose a socket to
managed providers.
The restricted listener always assigns the restricted role. On the normal
socket on Linux, the daemon checks the peer PID from the Unix socket credentials
before reading hello. If a bounded walk through /proc finds the daemon among
the peer's ancestors, the peer is restricted. The daemon itself is not a
descendant. Clients relayed by a live daemon-launched background service, such
as an on_start Hub, keep the listener's role. Ancestry is not checked on
non-Linux platforms or when the daemon is PID 1 or a child subreaper. If the
lookup fails, the listener's role applies. The role is fixed at accept.
Restricted clients can create and run child leaves, list them, and read their results. A restricted provider can request approval for a tool call it owns. The daemon omits tool approvals from restricted peers' snapshots and always sets their leaf-list question flag to false. Restricted peers cannot answer questions. Project-trust questions can still appear in their leaf snapshots. Daemon-launched providers cannot answer on managed stdio connections either. Only trusted clients can become remembered-grant responders. Grants retain their answered-run and trusted-responder scope.
With Bubblewrap off, agent-launched clients still use the normal socket and keep their runtime directory. The ancestry check is best effort: a detached process may be treated as trusted. With Bubblewrap on, all callers use the same leaf workspace rule for starting work, whether they use a socket or provider stdio. Selecting a saved leaf at hello or later subscribes to its feed and does not require a usable cwd.
Connections have subscriptions, correlated-response routing, capability claims, and
pending IPC calls. Completion records retain their originating connection only to
route that request's terminal notification. leafOperations owns and coordinates
live leaf runtime independently of the socket; connections do not own leaves or
Agents. Cleanup removes subscriptions and transient progress, closes the peer, and
releases registry ownership. It does not cancel accepted prompt or replay work.
Those runs continue with no connected requesters and remain visible to a later
subscriber. Do not send to peers while holding Server.mu: SendToLeaf snapshots
subscribers first.
Connection cwds are optional filters and defaults, not authority for a leaf's
work. They are captured in inbound wire order before context-dependent handlers
run. With Bubblewrap on, an explicitly selected filter must be absolute, but
need not exist. update_cwd changes that default and can switch the subscription;
it does not modify a stored root. Leaf-gated switch and replay work runs outside
the wire reader. Only requests that use the connection default wait for an
unresolved cwd update; explicit-leaf and explicit-cwd work can continue.
Subscription versions stop older pending create, switch, or hello replay from
replacing a newer selection or a successful feed drop. Failed drops do not
advance the version. A new root uses the captured default only when neither cwd nor a fork
source is supplied. list_cwd returns distinct CWDs containing non-temporary
leaves with turns, including missing paths and unloaded conversations. Temporary
leaves, empty leaves and orphan roots do not contribute to the list or its
summaries. Running, aborting and background leaves count as active.
leafOperations owns the live-Agent registry, prompt-like admission reservations,
progress registry, per-leaf gates, Agent construction, and runtime/state
operation policy. It coordinates create and fork initialization, prompt and steer
admission, tool-result admission acknowledgements, abort, rewind, deletion, virtual
root creation, vacuum cleanup, leaf mutations and cache effects, snapshot and stats
capture, replay barriers, eviction, and shutdown closure. Operations also choose each
required notification and its order. The server implements a narrow routing
interface that looks up recipients and enqueues immutable frames; it has no runtime
map and leafOperations has no Server backpointer.
Provider-native thinking (Anthropic thinking/redacted blocks and OpenAI Responses
encrypted reasoning) is durable data belonging to the assistant turn that
produced it. leafOperations keeps no cache of it: Agents load it with the
provider context from SQLite and release the request-local copy when the
provider cycle ends. Forks, rewinds, restarts, and idle Agents need no native-state
bookkeeping because they follow the durable turns.
The exported Server.PublishLeafSnapshot, Server.AdvanceSentTurn, and
Server.NotifyRunCompleted methods forward directly to leaf operations for Go API
compatibility. Production Agents receive leafOperations as their event router and
run notifier, so these compatibility methods do not restore runtime ownership to
dispatch.
Direct prompt admission treats a registered closed Agent as unloaded. Under the leaf gate, it drains that generation's owned subscription resolution before conditionally removing the reference and following normal lazy loading; concurrent admissions share the replacement without requiring a stats or replay read first. A stale reference cannot remove a newer registered Agent.
Prompt failures retain their admission-stage error code and original message.
In particular, a request that passes preliminary validation but loses admission to
another prompt returns leaf_busy with agent is running. Preliminary
ensureAgent busy errors retain their existing leaf_busy: message prefix.
Storage still owns transactions and durable session mechanics. Agent still owns
model execution, queues, run lifecycle, and Agent-internal compaction. The capability
registry and IPC caller still own invocation claims, watchdogs, and process routing.
Read-only command handlers may combine those owners' snapshots, but they do not
mutate leaf runtime state.
How are leaf snapshots and stats ordered?
Leaf lifecycle notifications are selected under the same per-leaf gate used for
ownership changes and snapshot publication. on_success and on_error still
describe each model run. After execution retirement, on_background describes
model processing stopped with provider-owned tasks remaining. on_idle describes
true quiescence: no execution, queued/in-flight input, terminalization, or pending
admission reservation, and no background owner. Last-task removal and provider
loss can select idle without a new model turn. Initial leaf loading and repeated
snapshots do not deliver duplicate idle notifications.
Selection and canonical snapshot publication share the gate. External macro calls
run afterward, without a service/Agent mutex. Callbacks execute in selection order
per leaf, so background rejection cannot lose to a later idle callback. A held
callback queues later notifications without blocking their callers or model
completion frames. It cannot block completion admission or work on another leaf.
Background alone is not an editing or admission lock.
For add/remove RPCs, the tracked worker enqueues the ownership acknowledgement,
then cancels and joins the admission cancellation watcher before invoking the selected
notification. Admission is cancellable by disconnect/shutdown, without an implicit elapsed-time maximum;
a slow macro cannot turn committed ownership into an acknowledgement timeout or
disconnect the shared provider. Notification work remains tracked for cleanup.
Admission reservations project running during handoff, including before lazy
loading, and prevent both idle delivery and eviction. Idle age starts at true
quiescence rather than at the first model stop with owners remaining.
These notifications are not subscriber termination commands. Requester-directed
prompt_completed and leaf-wide agent_end remain per-run outcomes, and may arrive
after a background notification macro completes. Ownership-only retirement emits
the idle snapshot and configured idle macros, not a fabricated model terminal
event. Followers must observe the accepted leaf through background activity and
owned follow-up runs until idle or deletion.
Provider invocation and provider-setup failures terminate the model run without
retiring independently owned background tasks or cancelling unadmitted daemon
continuations. Remaining owners keep the leaf in background; a later completion
can wake the model without another user message. Failed requests and tool calls
are not replayed. Run cleanup still discards queued/in-flight input and rolls back
unsent turns. Agent/storage failures, including context-storage reads during
provider preparation, retain the ownership cleanup path, retiring an immutable
task snapshot and routing kills with reason error outside the gate.
Registration cannot race past a claimed error. Cleanup preserves that error and
never calls public abort or appends an ABORT record. Explicit abort retains its
existing outcome selection and cancels background tasks after provider failure.
Shutdown closes admission before provider teardown, retires remaining owners,
and suppresses new idle/background notifications and follow-up admission.
leaf_updated and leaf_stats_response hold the same per-leaf gate from capture
through response enqueue. Their connection-local itr values therefore preserve
capture order, even when RPC handlers or client callbacks run out of order.
leafOperations captures stats and invokes the response-enqueue callback before it
releases the gate, including when that enqueue fails. Capture failures invoke the
handler's error-translation and enqueue callback before releasing any acquired
gate. Enqueue failures return directly without a second response. Enqueue does not
wait for a socket write or remote acknowledgement. Other leaves use independent
gates.
The gate serializes snapshot assembly, not every database or runtime mutation. Durable reads and process-local snapshots still use their own subsystem locks; they are not one global transaction.
Model activation, retirement, and background-presence changes record activity
in the existing leaf metadata under Agent.mu. Background ownership mutations
and the Agent's presence mirror share that critical section, so model admission
and retirement cannot run between them. Ownership callbacks release
leafOperations.mu before activity storage writes. Closed Agents reject new
ownership; cleanup can still remove their owners without consuming recovery
markers. At the idle transition, storage consumes an armed alert_idle and
sets alert_time to the current UTC time in one transaction, before another
run can enter. Queued work and prompt-like admission reservations defer that
transition along with background ownership. Releasing the final reservation
records quiescence even when the lifecycle phase label is unchanged. Multiple
background tasks keep the leaf active until the last one finishes. Normal shutdown freezes idle conversions before disconnecting
task owners. Startup applies the same conversion to leaves left active by
either a normal stop or a crash. Snapshot reads do not drive these transitions.
The metadata conventions and one-shot behavior are described in
session storage.
Both frames project one computed access_source through
leaf_access_source.go. An active
Agent retains its captured route, using host-reported information for remote
models. Idle or unloaded leaves use known configuration, including the trusted
project overlay, or cached discovery data. Missing source information can fall
back to the remembered model_access_source label for the same resolved model.
SIWC uses the selected registration from GetOAuthCredentials and requires
UsableSubscription; legacy, missing, or incomplete authorization is
unavailable, never API-key fallback. Validated provider subscription
observations report the provider-defined indicator, such as muse_subscription
or claude_subscription. Explicit loopback compatible/Ollama routes without
API-key authentication are local. A keyless remote route is unknown, not
implicitly local or free. API-key routes are api_key.
Live observations and their timestamps remain in RAM. The last reported label
is saved in ordinary leaf properties and survives observation expiry, unload,
and restart. Omitted discovery information preserves it; an explicit unknown
replaces it. Snapshot reads do not write these properties. The label is
non-secret display data, not authorization, a current entitlement assertion,
or a price estimate. See remembered model information
for persistence and model-matching rules.
Pending questions are daemon-owned leaf state captured inside this same gate.
This includes snapshots sent for hello subscription and reconnect, switch,
autosubscribe, and ordinary live publication. The project-trust owner supplies
project_config_trust questions and resolves exact question_reply revisions;
it has no generic producer or macro route. For that kind, a reply other than
trust or reject receives parse_error before reaching the owner.
After the project-trust owner accepts a reply, the durable decision invalidates
cached project resolution. The operation enqueues the acknowledgement and replying-leaf snapshot,
then releases that gate before taking each other leaf gate individually. It fans out
a freshly captured complete snapshot to every currently loaded or followed leaf
whose physically resolved CWD/config identity and exact bytes still match. A failed
acknowledgement does not suppress fan-out; its saved error is returned afterward.
Dormant leaves derive the decision on their next snapshot/config sync. Concurrent
or duplicate replies are serialized across leaves: exactly one decides an undecided
revision and later replies receive question_not_found. If the current project
bytes changed before a reply, that error is followed by fresh snapshots carrying
the replacement question for matching loaded/followed leaves. If the config was
removed or current inspection fails, the exact previously observed revision is
used only to select matching live/followed leaves; their fresh snapshots clear
the obsolete question without persisting a decision. The owner retains one compact
path/fingerprint/revision identity per leaf—not config bytes or revision history—
and prunes leaves that are no longer loaded or followed.
Tool approvals have a separate RAM-only owner. Each
recipient gets a complete snapshot: project trust first, then the tool
approvals they can see, in creation order. If support is unknown, the daemon
sends the first snapshot without tool approvals and waits for discovery outside
the leaf gate. It refreshes the snapshot once support is known if the
subscription is still current and there is an approval to show. At resolution,
the daemon checks eligibility, advertised support, the exact revision, and the
offered choice. The responder need not follow the leaf; subscriptions only
deliver notifications. The asking provider cannot see or
answer its own question. question_reply_ack accepts the decision; only a
still-live call can claim execution. Tool decisions do not invalidate the
project-trust cache or notify other leaves.
leaf_stats_response.pending_questions is captured in the same leaf gate from
the same owners, filtered to questions the caller can answer: none for
restricted peers or managed providers, and tool approvals only for an eligible
client with tool_approval support, excluding its own. Project trust appears only
if a snapshot already observed that current, undecided revision; lookup never
records or discards an observation, so stale-reply reconciliation is unchanged.
The field is omitted when empty. Stats lookup never subscribes or starts work.
Stats and leaf lists can start SDK capability discovery for eligible clients
regardless of whether an approval is pending. Neither waits for it. Both omit
tool-approval information while support is unknown or absent. Later requests use
the SDK's cached inventory.
tool_approval_request
is bound to a live dispatch on the asking provider connection. A pending
approval suspends both tool timers without holding the leaf gate or registry
lock. Nothing runs while it waits. The daemon retains the request until an
eligible client answers or the call ends, even if no client is connected when
it asks. The TUI Inbox shows these requests for persistent leaves only.
Aborting the run, deleting the leaf, disconnecting the provider, or shutting
down the daemon clears a pending request.
The daemon sends the decision only to the asking connection. It starts fresh timers on admission after a pending grant; a call admitted by match keeps its dispatch timers. A rejected call has five seconds to return its restriction result, independent of its execution timers.
The tool approval owner keeps remembered grants in RAM. The daemon binds the
provider's match_key to its connection, the session's resolved workspace root,
and the workspace policy version. Command grants also bind to the tool. File
grants can match across file handlers on the same provider. A change to the
approval policy or combined audit instructions retires the workspace's grant
version. A failed user config reload retires all grant versions. Only calls
eligible for allow_until_client_exit can reuse a grant. A match skips the
repeat question, not the mode, path, or protected-file checks.
The answered leaf's loaded Agent holds the grant from the moment it is remembered. The hold covers the answered execution. It also covers other work on that Agent unless a connection with a restricted origin started the work. Separately, while the responder stays connected, the grant covers the answered execution and executions that connection starts in the same workspace. Only the prompt that starts an execution sets its starter. A steer does not change it, and internal activations have no client starter. Disconnect ends only the connected scope. A client with a restricted origin cannot answer the question and create a grant; the answered run can still match a grant the user approved for it.
Unloading the Agent removes its hold, including idle eviction, deletion, and replacement. Rewind keeps the hold only if it keeps the same Agent. An accepted abort removes the Agent's hold even if it only cancels queued input or background tasks on an idle leaf. It does not remove the scope of a still-connected responder. Provider disconnect removes its grants. Reconnecting does not restore connection scope, and shutdown clears all grants.
The daemon checks the grant again before enqueueing granted. A live call's
match returns none if the grant lapsed; a create that lost its match is refused.
The leaf gate orders that check and enqueue with abort and idle eviction. A
responder's transport can still close between the final check and enqueue.
A create that offers allow_until_client_exit must carry a match_key.
rewind_leaf is a leaf operation that coordinates both layers. The leaf gate
serializes it with lazy load, eviction/unload, deletion, and prompt admission; a
loaded Agent's lifecycle lock then serializes the compare-and-rewind with prompt and
run admission. Only idle or unloaded leaves qualify. Non-replay rewind leaves an
unloaded leaf unloaded. Replay lazily creates an Agent, reserves the run, and
enqueues the correlated leaf_rewound acknowledgement
followed by canonical leaf_updated, releases the gate, and only then starts normal
stream lifecycle. On failure, the operation invokes the handler's error-translation
and enqueue callback before releasing an acquired gate. Admission-reservation
rejection keeps its leaf-specific busy message; Agent busy errors keep their
original messages.
Snapshot capture takes the leaf gate, then one subsystem at a time. leafOperations.mu is
held only for short live-Agent and admission access and is released
before entering storage, Agent methods, progress, or routing. Server.mu protects
connection and subscription routing and is likewise not held while entering leaf
operations or sending frames. Snapshot capture therefore proceeds as gate, storage,
live-Agent lookup/runtime, then progress. Enqueue happens while the gate still
establishes order, but without either map lock held. Agent stream replay barriers
never acquire a leaf gate while held.
Progress mutation checks the current connection after acquiring the leaf gate and progress mutex. Cleanup removes routing before taking the progress mutex. A write therefore finishes before cleanup or is rejected. No routing lock spans a leaf-gate wait or frame enqueue.
Progress items are generic connection-owned statuses, not projections of tool invocations. The producer chooses an update ID within a leaf and supplies the current authoritative sent turn. Items have no per-leaf, per-connection, or server-wide count caps. Payload validation remains unchanged: identifiers and titles are bounded, text rejects controls, and an item has at most five optional lines. Visualizer descriptors retain their wire shape and live runtime macro ownership checks.
Progress ingestion uses the existing positive report_progress.itr as a
high-water mark for each connection owner, leaf, current sent turn, and update ID.
After validation, a positive iteration at or below that key's accepted high-water
mark is silently ignored. Other IDs, owners, leaves, and turns have independent
history; there is no connection-wide lower-iteration rejection or callback FIFO
requirement. Omitted, zero, negative, or otherwise unusable iterations keep
compatibility arrival-order behavior and do not erase positive iteration history.
Newer identical replacements and clears of absent items advance this history without publishing a snapshot. Clear records retain only the owner, update ID, and iteration, never old summary payloads. They do not reserve an inactive ID against another owner. Ordering records have no count cap or eviction policy and last only through the current sent turn and owner lifetime. Disconnect, leaf deletion, and authoritative sent-turn changes clear the corresponding records, including transitions discovered during ingestion and gate-held rewind reconciliation. Records-only cleanup does not publish an unchanged snapshot.
Identical replacements and clears of absent items skip snapshot capture and publication after turn and ownership validation. Turn transitions still publish complete affected leaf snapshots, including a transition discovered by a stale report. A status published once stays in RAM without subscribers or refreshes; leaf stats, switching, and reconnect replay recover it. Producers clear their statuses when work ends. Disconnect or provider death clears all items owned by that connection, and a new authoritative sent turn clears the leaf's old items. Queued drafts do not advance this authority, and late old-turn reports cannot restore cleared statuses.
Who may claim a capability, and how does reload preserve routing?
Tools, macros, and plugins register in a daemon-global namespace for each capability kind. Project configuration can supply an automatic loading fallback, but does not create a project-local provider scope. An existing live owner takes precedence over that fallback. Once a project-triggered provider registers, its claims participate in the same global routing as any other provider. Registration does not by itself add a capability to every leaf's enabled set.
Use distinct registered names for distinct implementations that must coexist, including generated unique macro names for workflows. Distinct service definitions that must coexist also need distinct service names, because the process pool is keyed by service name. Reusing a capability name does not create a local override.
Configured capability claims come from launch ownership, never a peer's hello name. Without Bubblewrap, only direct service definitions supply configured claims. With Bubblewrap, a socket connection from a verified managed background launch may register its declared capabilities when it announces. Runtime announces and configured placeholders are first-live-owner-wins, except that with Bubblewrap on a managed launch's declaration displaces an unmanaged live owner of the same name. When an owner disconnects or releases, runtime-only claims vanish; configured placeholders remain and become claimable again. Reload reconciles placeholders without replacing live owners (other than that Bubblewrap displacement) or in-flight calls, so each admitted request retains its configuration snapshot. Results must be claimed exactly once by their owning connection; malformed results complete synthetically rather than stranding a call.
A model tool call retains the provider connection selected when its definition was offered. Dispatch checks that connection instance and the registry's current owner together, then reserves the trusted invocation before sending. A disconnected configured direct service can recover before reservation: the daemon verifies the same launched service name and definition, requests missing tool metadata even when the replacement omits announce, waits for metadata, and checks that the offered description and parameter schema still match under the run's admitted overrides. Recovery refreshes the private caller's binding; it cannot redirect a call to an unrelated provider or a different service definition. Each dispatch attempts recovery at most once. Validation and timeout selection merge the selected provider's metadata with the explicit tool overrides from the run's admitted config. Provider disconnect completes both pre-ack and result waits, including parallel calls and calls with disabled timers. A sent call or failed send is never automatically replayed because its execution status may be unknown.
Macro dispatch also retains the admitted provider connection. Disconnect cleanup eagerly aborts visible calls, while each waiter observes that connection's closure to cover calls admitted during the cleanup sweep. Results, timeouts, and disconnects share one terminal claim. Connection release and registry shutdown preserve pending macro, tool, and plugin calls for terminal completion when the provider closes. Plugin waiters also claim a disconnect result without relying on watchdog expiry.
Inbound peers and spawned services use the same fresh c_ connection-ID allocator.
An ID identifies one connection lifetime and is never intentionally reused. Service
names remain process-pool keys; PIDs are for diagnostics and process management.
Disconnect removes routing and capability claims before cleaning up leaf state.
Managed-service replacement waits for that generation's cleanup; unrelated incoming
connections do not wait. Deferred sends retain the captured transport. Late capability
frames, subscriptions, and progress reports check that their connection is still current.
Prompt and steer accept the requester after their leaf admission reservation and before recovery or mutation. Rewind checks after acquiring its leaf gate, before changing history. The short routing liveness check is the acceptance point. Rejected work neither starts an Agent nor mutates history. Once prompt or replay work is accepted, requester cleanup does not affect it: the run survives with zero connected clients and later subscribers receive its normal snapshot and durable history. Explicit abort remains the cancellation path. Accepted steers retain their existing detached processing and append-failure behavior. No routing lock spans Agent, storage, startup, or leaf-gate calls.
How are external services kept alive or reaped?
ProcessPool is keyed by service name: concurrent direct requests share one spawn
flight and its published connection. Lazy GetOrSpawn is direct-only; background
services are started with StartService and have no JSONL connection. Failed or
immediately exited children are never published, and shutdown waits for admitted
startup records rather than relying on output EOF. Direct-service IPC closure retires
the exact managed child even if it is still alive. Replacement waits for reaping and
connection cleanup so old cleanup cannot remove a new generation's claims.
The host retirement limit is two seconds; the sandbox has its own cleanup limit. Recovery callers share a startup flight and can cancel
their own wait without cancelling startup for other leaves. Failed flights have a
250-millisecond retry cooldown. A healthy matching replacement is reused; recovery
never displaces a differently configured service instance.
Service executables do not resolve through PATH or the project working directory:
relative paths are beside the physical daemon executable, ~ is the daemon user's
home, and Ruby services use the bundled ez-agent-ruby launcher.
Spawned services inherit ordinary operation settings, including XDG, locale,
certificate, path, proxy routing, and service-specific variables. The daemon
filters every environment variable named by a user-global auth profile's
api_key_env (project config cannot redirect that auth source), common provider
API keys, token/secret/password/credential
suffixes, AWS credentials, and the caller's AGENTCLI; it then supplies an AGENTCLI resolved
beside the running daemon when available. Uppercase and lowercase HTTP, HTTPS,
and all-proxy settings remain available after URL userinfo is removed, while
NO_PROXY and no_proxy pass through unchanged. Malformed credential-bearing
proxy values are dropped. This reduces accidental credential exposure. It is not
a sandbox. With Bubblewrap off, configured subprocesses still run with the
daemon user's filesystem and process privileges.
Bubblewrap launch
With execution_safety.bubblewrap: true, the process pool wraps managed
provider launches, including configured startup, lazy direct services, and
replacements. It uses the bwrap found on the daemon's PATH when it takes
the startup snapshot of the resolved mount policy.
Use non-setuid bwrap 0.8.0 or later with --bind-fd and --ro-bind-fd support.
The effective minimum kernel is Linux 5.6. The daemon checks the version,
setuid bit, openat2, and pidfds before launching providers.
If startup config cannot be decoded, the first decoded global config sets the
policy before its managed services can launch. Restart the daemon to change it.
The daemon, model bridges, and installed non-direct AgentHub stay on the host.
All managed providers, direct and background, run in one Bubblewrap system per
daemon. They share one mount view, user, PID, IPC and UTS namespaces, /proc,
/dev/shm, and loopback.
Providers can see and signal one another's processes. In Normal mode loopback
is the host's. The keeper starts inside Bubblewrap; the daemon sends it launch
requests and stdio descriptors over a socketpair passed to the keeper above
fd 2. Bubblewrap's PID 1 and providers do not keep that control descriptor.
Each provider has separate stdio, but it is not protected from other processes
inside the sandbox, which run as the same user.
Bubblewrap's PID 1 reaps orphans. Each provider also has a supervisor that
adopts and reaps its descendants, including processes that start a new session.
Stopping or replacing the provider stops that tree and leaves other providers
and the shared filesystem intact. Work delegated to a different provider or a
host service is outside the stopped tree. Cleanup logs a warning after one
second. Recovery waits at most the greater of ten seconds and the provider's
startup_timeout for retirement. If that expires, the old generation stays
unavailable and the daemon keeps waiting for cleanup before allowing a replacement.
The keeper and supervisors discard SIGTERM, SIGINT, SIGHUP and SIGQUIT. SIGKILL of the keeper or a supervisor ends the shared system and makes every sandboxed provider unavailable until daemon restart. On supervisor death the daemon cannot confirm its descendants were reaped, so it stops the namespace. On shutdown, the daemon stops and waits for the namespace init and reaps the Bubblewrap wrapper. A daemon crash closes the control connection and triggers Bubblewrap's parent-death protection. When PID 1 exits, Linux kills the whole sandbox PID namespace, including detached processes.
Offline and private-localhost add one network namespace for all sandboxed
services in this daemon, including background services and the tunnel provider.
A short Bubblewrap bootstrap brings up loopback and exits. The pool holds
descriptors for that network namespace and its owning user namespace until
shutdown. The keeper launch uses system util-linux nsenter to join both,
verifies the joins, then closes the descriptors before starting Bubblewrap.
The shared system's user namespace cannot administer the network. In Offline
mode, there is no interface or route other than
loopback. In both modes a host process cannot dial a sandbox loopback port
directly. A user-started preview can reach
a port on that loopback through the existing tunnel. The daemon and model
bridges keep using host networking.
In private-localhost, one foreground pasta process connects the namespace
to the host's routed networks. The daemon takes a startup snapshot of host
routes and nameservers. It chooses IPv4 /24 guest subnets from
10.250.0.0/16, 172.30.0.0/16, or 192.168.0.0/16 and an IPv6 /64 from
fd7e:2d6b:d852::/48, avoiding specific host routes and the selected
nameservers. Broader routes such as VPN split defaults don't count as
collisions. The daemon enables families with a main-table default route and
waits for a usable guest address and default route for each enabled family. The
helper does not map its gateway to host loopback, forward DNS to the host stub,
or forward listening ports between the host and the sandbox. Services on
reachable non-loopback host and LAN addresses are still accessible.
The sandbox routes, guest subnets, enabled families, and nameservers are
fixed at startup. A VPN that connects later can add a route that the guest
subnet shadows inside the sandbox. Its DNS servers are not picked up, and
the saved nameservers may stop answering after a network change. If the
host gains IPv6 later, the sandbox won't gain it. Restart the daemon to
take a new snapshot. Proxy variables still pass through, but a proxy on
host loopback, such as http_proxy=http://127.0.0.1:3128, is unreachable.
The daemon reaps pasta at shutdown. Linux kills the helper if the daemon
crashes. If the helper exits while the daemon is running, the daemon stops
providers using that namespace and rejects new launches with the exit reason.
Restart the daemon to recover or to take a new snapshot of the routes and
resolver. CheckPrivateLocalhostPrerequisite checks the host tools, routes,
TUN access and upstream resolver before attempting the namespace setup.
The baseline filesystem is explicit:
- Read-only
/usrand, when present,/bin,/sbin,/lib,/lib32,/lib64, and/libx32. Merged/usraliases become symlinks inside the sandbox, not additional host mounts. - Read-only system data where available:
/etc/ld.so.cache,/etc/hosts,/etc/nsswitch.conf,/etc/resolv.conf,/etc/alternatives,/etc/ssl/certs,/etc/ssl/cert.pem,/etc/pki/tls/certs,/etc/pki/tls/cert.pem,/etc/pki/ca-trust/extracted, and/etc/ca-certificates/extracted/tls-ca-bundle.pem. The daemon reports missing optional paths and skips data links outside the baseline. For Normal networking,/etc/resolv.confcan bind a single regular resolver file from/run/systemd/resolve/(stub-resolv.conforresolv.conf),/run/NetworkManager/(resolv.conforno-stub-resolv.conf), or/run/resolvconf/resolv.conf. It never mounts the parent directory or a resolver file in a user or daemon runtime directory. Offline substitutes read-only/etc/hostswith loopback entries for localhost and the sandbox hostname,/etc/nsswitch.confwithhosts: files, and/etc/resolv.confwith no nameserver or search domain andoptions timeout:1 attempts:1for direct resolvers. It does not mount or query the host resolver.private-localhostuses the same synthetic hosts file, enables DNS innsswitch.conf, and generates a read-onlyresolv.confwith up to three non-loopback, non-link-local nameservers for the enabled address families. It prefers the upstream files from systemd-resolved, NetworkManager and resolvconf to/etc/resolv.conf. It does not mount a resolver directory or inherit the host's search domains or split-DNS rules. - Synthetic read-only
/etc/passwdand/etc/groupdescribe one sandbox user and group. The host account files are not mounted. - Fresh
/proc, a minimal/devwith shared/dev/shm, and a shared/tmpthat starts empty on each daemon run.HOMEand XDG config, cache, data, state, and runtime are shared under/.ezagent-sandbox. Home, config, cache, data, and state persist in<daemon state_dir>/bubblewrap-system/, outside EzAgent's file-cache cleanup. Runtime is fresh on daemon restart. Providers get a clean environment withPATH,TMPDIR, those home and XDG paths,EZ_AGENT_SANDBOX=bubblewrap, andEZ_AGENT_SANDBOX_NETWORKset by the launcher tonormal,offline, orprivate-localhost. Uppercase and lowercase proxy variables (HTTP_PROXY,HTTPS_PROXY,NO_PROXY,ALL_PROXY) pass through after credential filtering, as doLANG,LC_*, andTZ. - Only validated project and grant mounts, plus the regular-file entrypoints
of startup-configured providers if not already visible. A later service
definition can use an entrypoint already visible in the shared view, but
cannot add a mount. Every provider starts in the first listed
project, or
/when there are none. Tools receive the session workspace at its original absolute path. An explicittool_invokewith an unavailable workspace is rejected before admission; a workspace that disappears before an accepted tool is dispatched produces a tool error. hello_ack.state_dirkeeps its original path inside the sandbox, with only writablebuffers/,cache/, andleaf-files/available to all providers. A file saved to the EzAgent cache by one provider can be used by another.- Providers can use the installed builtin's Ruby launcher, CLI and WebFetch
siblings, bound as individual read-only executable files. Ruby's sandbox
data directory uses
bubblewrap-ruby/under the daemon state directory on disk. Providers see it only at/.ezagent-sandbox/data/ez-agent, outside the file cache and Workspace approvals cache root. The launcher extracts its payload there on demand and reuses it after provider recovery. No Ruby process runs on the host for a sandboxed tool call. - The daemon reads the builtin's Ruby worker limit once at startup. It passes
that limit and the user-config pathname for protected-edit checks, not the
builtin_plugin.yamlorconfig.yamlfiles. The builtin uses its normal stdio RPCs for the effective config, mode, audit and workspace approvals. Only the user instructions and explicitly granted skill packages enter the shared sandbox config directory from host config. They are read-only, and theirconfig/ez-agentmount cannot be renamed or replaced.
Neither the host home nor all of /etc or /var is mounted. The EzAgent
config directory, auth file, host runtime directories, trusted socket, database,
trust store, and daemon logs stay out. The one daemon socket in the sandbox is
/.ezagent-sandbox/run/ez-agent/ez-agent.sock, a read-only bind of the restricted
socket file itself. The launcher checks its identity against the one captured
at startup and gives Bubblewrap a mount-source descriptor, not a connected
socket or a runtime directory. Read-only and non-renamable mount points keep
the endpoint in place. Nested user namespaces are disabled for managed
providers so descendants cannot acquire mount privileges. Tools that require
new user namespaces, including nested Bubblewrap, rootless Podman, and the
Chromium and Electron namespace sandbox, cannot use them here. Do not grant directories
that contain sensitive data or sockets: a read-only grant does not stop clients
from connecting to a socket.
Engine settings, credentials and devices are not passed through by default. An explicit engine destination can add one read-only socket bind per engine and its client endpoint setting, without mounting the runtime directory. The socket directory is a read-only mount so providers cannot rename it or plant an endpoint there. The engine can act on the host outside Bubblewrap. TCP reachability is controlled by the network mode, not the list of engine destinations.
$AGENTCLI and the Ruby socket API use their normal lookup inside Bubblewrap.
A missing or unavailable listener returns an error without daemon autolaunch.
Managed Ruby's invoke_tool still uses the builtin's stdio connection. The
child's calls go through normal policy; its approval questions stay on the
child and in the user's Inbox. Pathname Unix sockets do not depend on the
network namespace.
At hello, the daemon ignores a restricted client's default CWD if it is not
a mounted project directory. A client starting from scratch can still connect
and read results. A macro call that selects a leaf must use a mounted leaf CWD.
There is no host retry. A missing prerequisite, invalid policy, failed setup,
or lost keeper or pasta leaves every sandboxed provider unavailable until the
daemon restarts. The installed non-direct Hub is managed but runs on the host,
so it is unaffected. A provider that fails independently can retry after the
normal 250-millisecond process retry delay, in the same shared system. If a
provider's supervisor is lost during launch or retirement before it confirms
cleanup, the daemon closes the shared system rather than risk overlapping
generations. When a provider cannot start, model runs are not offered its tools
and the daemon logs why. tool_invoke reports policy, setup, keeper or network
failures that prevent workspace validation before admission. If workspace
validation succeeds but the selected provider fails to launch, the invocation
result carries that cause. A healthy system still waiting for a provider's
announcement reports only that the capability is unavailable.
For a managed background service, the daemon uses Unix peer credentials and a
peer pidfd to check that the live process belongs to the launcher before it
reads hello. This requires Linux support for SO_PEERPIDFD, normally Linux
6.5 or later, beyond the 5.6 base minimum. On an older kernel the daemon does
not launch sandboxed background services and reports why; direct providers are
unaffected. An unverifiable
peer can still connect but cannot claim a managed capability. Peers remain
restricted, and the process pool closes their connections when that launch
exits. The daemon logs unmanaged capability announcements. An unmanaged peer cannot
take over a name reserved for a managed service, even if it uses the service's
hello name. Other unmanaged capabilities remain usable. Capability names are
daemon-global; use distinct names for providers that need to coexist. When
Bubblewrap is on and multiple services declare the same name, lookup selects
the first service in name order.
The non-direct service that resolves to ez-agent-hub beside the physical
daemon executable is a client relay, not a provider. A symlink in that slot, a
copy elsewhere, or a direct or Ruby service stays sandboxed. The Hub uses the
host network, XDG paths, and normal EzAgent socket even if the sandbox fails or
its keeper exits. Relayed clients keep the listener's role. Daemon shutdown
still stops the Hub. Other background services run inside Bubblewrap and can
reach only the restricted EzAgent socket.
What must remain true when touching lifecycle, routing, or progress?
- The state-directory lock precedes socket binding and SQLite access; interrupting startup unlinks both bound sockets and releases the lock.
Server.Stopis idempotent: leaf operations close their Agent snapshot while the server shuts down processes, listeners, connections, and registry state. The leaf owner atomically closes Agent registration and captures that snapshot. A lazy generation that loses registration is closed before recovered work can launch; new construction after the boundary also produces a closed Agent. Every Agent is canceled before any owned subscription resolution is drained, so one slow renewal cannot defer cancellation of other leaves. Ordinary close and closed-generation removal also drain credential persistence. These waits do not join tools, plugins, or whole run loops.StopDaemonContextallows up to 80 seconds for this bounded renewal/save drain, still honoring caller cancellation. Its startup probe and readiness handshake keep their short deadlines. TUI disconnect does not stop the daemon or its accepted leaf work.- Progress belongs to the authoritative sent turn. The leaf owner publishes canonical
turns before advancing and clearing progress. A visualizer macro must be live and
owned by its reporting connection; disconnect removes its progress through the leaf
owner. Operations that already hold the leaf gate can reconcile a storage-resolved
sent turn with
advanceProgressTurnLockedbefore capturing their own canonical snapshot; they must not recursively callAdvanceSentTurnwhile holding that gate. - Leaf deletion is a daemon-side decision: an in-progress prompt or prompt-like
idle user steer reserves the leaf before admission, and deletion returns
leaf_busyuntil that request has produced its acceptance or error. Clients do not preflight, retry, or participate in an additional handshake. - Timeout policy is provided by
pkg/watchdog, not duplicated here.
Where detail lives
| Need | Authority |
|---|---|
| Service definitions and reload inputs | service/config |
| Roots, leaves, turns, and maintenance | service/session |
| Per-leaf prompting and model execution | service/agent |
| Unix sockets and JSONL transport | pkg/ipcsocket, pkg/ezagentapi |
| Frame contracts | pkg/protocol, JSONL API |
| Tools, plugins, and macros | pkg/tools, cmd/ez-agent-builtin |
For behavior-level examples, start with
daemon_startup_test.go and
process_pool_test.go.
Service waits and incident timing
leafGateRegistry pins and locks a new gate before publishing it, then validates
its leaf outside the global registry mutex. Other leaves can look up and release
gates while SQLite is blocked. Same-leaf waiters share the validation and retain
one gate through capture and response enqueue. Failed validation retires the gate;
a retiring gate remains registered until its last reference drains. No competing
gate can overlap deletion or retirement.
The daemon creates one incident recorder before global
configuration loading, state locking, socket binding, or database open. The
executable calls RunDaemon(nil) to load configuration inside this timed path;
fixtures and other Go callers may still pass an already resolved configuration.
It carries that recorder into the ready
server and closes it after storage and state-lock cleanup. Healthy breadcrumbs
remain in memory and create no audit directory, file, or worker.
Fixed observation thresholds live in pkg/service/audit.go:
| Observation | Threshold | Meaning |
|---|---|---|
| Selected dispatch-lane wait, RPC, gate validation/wait, stats capture | 2 seconds | Record a timeout while work is still waiting; slow abort handling records cleanup_slow. Do not cancel it. |
| Each startup phase | 5 seconds | Record a slow config-load, state-lock, socket, DB-open, maintenance, or server-start phase before it returns. |
| Each shutdown phase | 5 seconds | Record cleanup_slow while pool, admission publication boundary, Agent, registry, transport, storage, or state-lock cleanup is still running. |
| Final audit or panic-boundary drain | 100 milliseconds | Bound the caller's wait; audit failure never gates service success. |
The API's Handlers.OnRequestQueued hook records selected decoded request IDs
before callback serialization. The dispatch timer remains active while that
connection's callback lane is blocked, then ends before the handler's own start
observation. Matching responses still bypass the lane for correlation; neither
the hook nor the timer changes dispatch ordering or cancellation semantics.
Selected handlers record receipt, start, response-enqueue decisions, and safe
unexpected boundaries for stats, prompt, abort, and rename requests. Only admitted
machine IDs and numeric observations enter audit data, never names, errors,
payloads, or panic values. Ordinary abort/rejection is a breadcrumb, not an
incident. Selected panic boundaries record a fixed category and rethrow the
original value without inspecting it. Abort evidence distinguishes the requested cancellation, process-local
aborting state and snapshot publication, abort_received enqueue, and later
prompt completion. Enqueue is not proof that a peer read an acknowledgement, and
an accepted abort is not proof that a durable ABORT turn has committed.
Operation/storage results and response delivery have separate callpoints.
Expected typed not-found, validation, busy, and cancellation outcomes remain
noncritical and end with fail or cancel, not success. Fast unexpected
storage/admission failures open an incident even when their public rejection is
successfully enqueued. Known terminal transport causes use the shared
ezagentapi.IsTerminalTransportError classifier and record cancellation rather
than an unexpected incident. This includes the distinct closed JSONL sentinel.
A failed acknowledgement does not roll back an admission or authorize a retry.
The internal leaf router returns its fanout enqueue result. An abort snapshot
records completed/fail when any subscribed enqueue fails; the missed-snapshot
connection is still closed. A closed peer alone is noncritical, so this outcome
may remain only in the breadcrumb ring until another incident opens the file.
Pool observations use duration_ms for the change in DBStats.WaitDuration,
attempt for the change in WaitCount, and pending for ending InUse. These
are process-wide counters observed around an operation, not exclusive attribution
of wait time to its request. The single SQLite connection remains intentional.
Stats and abort carry the handler context into storage where useful; selected responses use it for enqueue. The current transport does not convey a client's local RPC timeout as server cancellation. Leaf mutex waits also remain ordinary mutex waits. A local client timeout neither rolls back admitted work nor proves that its response will never arrive.
audit_test.go, audit_admission_test.go, leaf_sync_test.go, and daemon_startup_test.go cover cold
recorders, timer-triggered incidents during unfinished phases, safe error/ID
filtering, nonfatal sink failure, and a blocked real one-connection validation
without global gate contention, correlated callback-lane waiting, fast failures,
actual shutdown admission-mutex waits, and abort fanout failures. Thresholds are observation budgets, not new wire
contracts or shutdown deadlines.
Final prompt admission revalidates the supplied parent under the Agent lifecycle
lock immediately before durable append. Preliminary ensureAgent validation
is not admission authority: an intervening completed run makes an older parent
an expected turn_conflict rejection, not a storage incident. The typed
agent.ErrPromptParentConflict survives wrapping for internal audit classification.
prompt_parent_admission_test.go holds one connection after preliminary validation,
completes a prompt from another connection, then verifies stale admission leaves
history unchanged.
Connection-owned renewable waits
Tool, plugin and macro heartbeats require the exact pending kind, call ID and owner connection. Results and acknowledgements use the same owner boundary. Plugins and default macros retain five-second inactivity watchdogs without a default elapsed-time maximum; explicit metadata maxima and caller limits remain. On-demand metadata uses the Go API's shared typed RPC correlation and renewable watchdog. Startup readiness remains bounded separately.
Connection cleanup terminally retires all outstanding kinds, including acknowledged tool calls. A replacement has a fresh connection ID and serves new calls only. Existing pre-dispatch configured-provider startup/recovery remains; a dispatched call is never transferred or replayed. Local cancellation makes no rollback claim and adds no cancellation protocol. Abort/shutdown replies, tool stop/kill paths and LLM provider retry rules are unchanged.