docs/ez-agent-ruby/lib/ez_agent/api.md
EzAgent::API typed Ruby daemon client
EzAgent::API is the typed Ruby SDK for daemon operations, events, and addon
providers. Workflow orchestration lives in Workflow; wire fields
belong to the JSONL catalog and
pkg/protocol.
Surfaces and caller rules
Use Connection.open for supplied streams and API.connect for the local AF_UNIX
socket. Typed services cover sessions, turns, config, models, discovery,
management, and run control; tools, plugins, and macros provide addons.
resolve_endpoint(env:) resolves without dialing, and no Ruby API starts a
daemon.
closeends this connection;daemon.shutdown!is daemon-wide.- Match replies by opaque
request_id, not arrival order. Register before write. - Delivery-only operations do not imply daemon completion. Rewind acknowledges the durable tip move and optional replay admission, not replay generation.
- Values are deeply frozen while
[],key?, andto_hretain unknown fields. Keep raw frame sending and correlation private. - Connection-local
itris retained but is not an RPC ID, global revision, or reorder key. Malformed transport/decode input is terminal.
api.macros.provide(name, internal: true) hides a macro from general TUI
selection and suggestions, not direct invocation or attachment. The flag is
boolean and defaults to false; names never imply internal status.
Caller-specific mode policy and provider startup
All provider calls expose daemon-supplied call_id, name, leaf_id, and
kind. Tool calls additionally expose arguments, turn_id, root_id, and
cwd. Use call.leaf_id, not a model argument or connection-global selection,
when checking the invoking leaf's configuration.
api.config.get(call.leaf_id, "builtin.mode") returns LeafConfigValue with
String leaf_id, key, and value; the mode name is value, with an empty
string meaning no mode. api.config.effective(leaf_id: call.leaf_id) returns
EffectiveConfiguration with String cwd and YAML config, Array-of-String
layers, and optional String config_error. Both retain request_id and itr.
Check config_error, parse the YAML, find the selected name in modes, then
read that entry's flags. For an empty selection, builtin checks use
defaults.flags, or an empty list if absent. Named modes do not inherit default
flags. The top-level mode_flags catalog is not its active flags. These are
separate reads, not an atomic permission transaction. The tool owns missing-mode
and lookup-failure policy; flag names have no automatic
enforcement. See configuration.
The distribution includes self-contained references readable through buffer:
embed:skills/ruby/references/mode-flags.mdhas typed lookup and a handler policy example.embed:skills/ruby/references/capabilities.mdhas registration, callback context, direct stdio and socket service installation, routing, and activation.embed:skills/reflection/references/modes.mdcovers the configurator and whole-entry mode overrides.
Direct stdio services use Connection.open(reader: $stdin, writer: $stdout).
API.connect dials a separate socket and cannot answer the daemon's stdio
hello. Connection.open's optional block runs before startup, unlike the
lifetime/cleanup block of API.connect. Both require the connection to stay
open while providing capabilities; connection cleanup never needs daemon
shutdown.
Renewable RPC waits and timeout diagnostics
Omitted timeout: arguments use renewable inactivity thresholds, normally five
seconds or ten for longer operations. A matching heartbeat with kind: rpc
and call_id equal to the outstanding request_id renews the wait on that
connection. Numeric timeout: arguments remain explicit absolute caller limits,
even while heartbeats arrive. Passing the public numeric timeout constants
explicitly also requests an absolute limit. Metadata providers reuse the
capability heartbeat scheduler until their response is published.
Disconnect fails all pending requests on that connection. Reconnect uses a fresh identity and new calls only. No requests are inherited or replayed, and local wait cancellation neither requests rollback nor requires a remote acknowledgement.
A correlated RPC TimeoutError exposes request_id, timeout, request_type,
response_types, and leaf_id when the request targets a leaf. Its message
includes those identifiers, the expected reply types, and the local wait duration.
It retains no prompt, tool arguments, or other request payload. Errors constructed
outside the RPC path may omit these optional fields.
An RPC timeout expires only that waiter. It does not close the connection or prove that the daemon failed to act. A late response cannot satisfy a newer request. The pending registry keeps at most 32 payload-free expired correlation entries for late-reply observation. Matching late replies are consumed without reviving the waiter or dispatching them as new work. SDK operations are not automatically resent. Workflow's bounded read-only reconciliation, name read-back, and durable prompt-admission guard are described in Workflow recovery.
Error classification and incident recording
API::ErrorClassification.classify(error) returns a fixed category plus separate
transient?, retry_authorized?, and admission_ambiguous? flags. API timeouts
and I/O transport failures can be transient evidence, but never authorize retry.
The independent EzAgent::WorkflowErrorClassification helper honors only the
existing explicit typed Workflow retry flag, not terminal/provider prose.
API transport, request, callback, provider, cleanup, and join-timeout boundaries
record safe incidents through one process-wide API::Incidents.recorder.
Records use fixed registered repository sites and categories. Data permits only
validated SDK-generated request IDs and elapsed/budget milliseconds, never raw
exception text, provider bodies, payloads, peer IDs, or dynamic stacks. Request
start/completion breadcrumbs stay in memory on healthy execution. Over-budget
success remains successful but emits timeout-site evidence. Clean local-close
cancellation emits no incident; later local close cannot suppress earlier remote,
fatal, or cleanup failure evidence. If clean local close wins the terminal
transition while a request is writing or flushing, the resulting I/O failure
returns the already-published ConnectionClosedError without a transport
incident. If a remote terminal transition wins before a write or flush fails,
the writer likewise receives the published ConnectionClosedError with that
original terminal cause; the secondary write failure still records an incident.
A transport failure that wins first remains a TransportError, even if the
caller closes afterward. Auditing cannot replace useful work failures.
Ordinary error routes are preserved. Fatal connection-owned reader, provider,
and event callback failures close admission and release pending work before
rethrowing the original exception, even while the peer remains open. No caller
close is required before join, and raise_on_error: false does not suppress
fatal thread failures. First terminal provenance remains immutable. Standalone
Events retain their previous behavior. Ruby's automatic thread exception printing
is disabled for connection-owned threads; join still raises failures.
Reader and writer failure transitions retain the selected primary exception even
if transport cleanup also fails fatally. Cleanup evidence is retained separately
and audited; it cannot replace the primary at the caller or join. A fatal
cleanup error still propagates when cleanup is the sole failure, such as an
explicit local close. This changes no request correlation or wire lifecycle.
Connection.open preserves the exact primary exception from construction,
pre-start configuration, or the hello exchange. Fatal transport cleanup or
owner-join failures cannot replace it. Once a connection exists, startup cleanup
attempts both provider and event joins, retains the first secondary cleanup error
internally, and records safe evidence for secondary failures.
API.connect records endpoint, dial, and startup failures separately from the
caller block. Caller exceptions, including ordinary Workflow cancellation and
Interrupt, are rethrown unchanged after local close and join. A clean block
cancellation starts no audit worker and writes no audit records. Failed cleanup
does emit incidents, but never replaces an active caller exception. Without a
caller exception, fatal cleanup still propagates; ordinary transport cleanup
failures retain their existing incident-only behavior. Close and join cleanup
have distinct fixed sites. Frame encoding reports client.rb:write_frame, while
serialized writes report client.rb:write_encoded_frame; fixed indices distinguish
its encode, transport, and unexpected catches. Startup cleanup also distinguishes
terminal transition, provider join, and callback join. Delegated writer failures
are not relabeled as encoding failures. Audit records contain only fixed
labels and validated IDs or numbers, never exception messages or class names.
See exact categories, reusable helper APIs, and provider wire limits.
Snapshots and canonical history
sessions.stats and turns.list_history expose the canonical tip_turn_id; an
empty string means no tip. HistorySnapshot retains typed summaries,
request_id, and itr and supports Enumerable. turns.canonical_history
hydrates and verifies one snapshot, including a draft tip omitted from sent and
ready summaries. Exact fields live in
api/values.rb.
LeafUpdated#access_source and LeafStatistics#access_source read the optional
daemon-computed source. Values are local, openai_subscription, api_key,
unknown, and unavailable; an older daemon returns nil. Unknown future
values remain available without a decoding error and must display neutrally,
as must absent or unavailable values. Each snapshot replaces the prior source.
Active runs retain their captured route; idle leaves report their resolved
next-run configuration. This field is read-only, contains no credentials, and is
not persisted leaf configuration. Existing constructors, operation keywords,
positional arguments, and event callbacks are unchanged.
Virtual roots
create_virtual_root(leaf_id, reason:, pending_turns: [], metadata: nil, timeout: RENEWABLE_LONG_REQUEST_TIMEOUT) returns VirtualRootCreated. Metadata
must be a JSON object; nil omits it and an empty hash sends an empty object. Ruby
rejects invalid encodings, cycles, symbols, non-finite numbers, arbitrary
objects, non-string object keys, and the service-owned top-level exit_message.
The daemon stores accepted metadata in the boundary turn's other_meta.
| 1 | created = api.turns.create_virtual_root( |
| 2 | leaf_id, |
| 3 | reason: "compact", |
| 4 | pending_turns: compacted, |
| 5 | metadata: {"continuation" => true, "pivot_turn_id" => source_tip} |
| 6 | ) |
Rewind
rewind(leaf_id, current_tip_turn_id, new_tip_turn_id, replay: false, timeout: RENEWABLE_REQUEST_TIMEOUT) uses the expected tip as compare-and-swap.
The new tip must be a retained proper ancestor or "" for the root boundary.
RewoundLeaf reports old/new tips, replay admission, request_id, and itr.
Only idle or unloaded leaves may rewind; replay acknowledgement confirms
admission, not generation success.
| 1 | rewound = api.sessions.rewind( |
| 2 | leaf_id, expected_tip, retained_ancestor, replay: true |
| 3 | ) |
The daemon reports parse_error, leaf_not_found, leaf_busy,
turn_conflict, invalid_rewind_target, invalid_model, or provider_error
through ServiceError. Ruby also uses ordinary timeout/connection errors.
Register event handlers before rewinding or read stats/history afterward.
leaf_updated is a complete projection; pending_questions: [] clears older
questions. Question replies require exact leaf, revision, kind, and answer. RPC
and callback completion are separate. Ruby-specific routing of dual-role frames
is implemented in api/client.rb
and tested by the Ruby API suite.
Generic event handlers and events.wait observe frames as delivered.
prompt_completed and success/error macros describe one model run, which may
leave background ownership or an internal follow-up run active. Provider-call
completion and transport-terminal callbacks also keep their notification
semantics; none becomes a leaf-done waiter. Workflow separately monitors leaf
quiescence without changing persistent subscriptions.
Assistant outcomes
StoredTurn#exit_message returns nil, "SUCCESS", exact "ABORT", or a stored
nonempty error string. exit_classification maps it to :continue, :success,
or :error. The marker belongs only to service-owned sent assistant turns;
malformed metadata raises DecodeError. Error turns have no assistant-only
marker. The canonical policy table is in
pkg/service/agent.
Consumer validation may reject otherwise successful content without rewriting the durable Agent outcome.
Detail authority
| Detail | Authority |
|---|---|
| Entry point, endpoint resolution, AF_UNIX adapter | api.rb, api/client.rb |
| Operations, values, events, correlation, errors | api/ |
| Provider definitions, calls, workers, heartbeats | api/capabilities.rb |
| End-to-end Ruby behavior | test_ruby_api.py; test guide |
| Every frame schema and example | JSONL API catalog |
When protocol coverage changes, check the entry require list, connection service readers and routing, known event types, and typed value projections together.
Pending user-turn timing context
API::PendingTurn.new(kind: "user", content: "...", steer: true) and
API::PendingTurn.text("...", steer: true) accept optional boolean steer.
The reader returns nil when unspecified; to_h omits nil and retains explicit
true or false. from_h validates the boolean and preserves extension fields.
Prompt/steer calls, plugin calls/results, virtual-root pending turns, and queued
messages carry this context unchanged. Plugins may set it on synthetic user
turns for downstream consumers.
The service supplies true for unspecified user input admitted during active
assistant/tool processing. Calling the steer endpoint while idle does not
classify an ordinary follow-up. This is optional context, not an admission
command or an independently stored value. The builtin mode plugin records it
as turn-type="steer" in the leading mode tag, which may also carry the active
mode. Background bash origin uses turn-type="bash" instead and existing
free-form advanced.other_meta correlation, documented in
protocol user-turn context.
Background task ownership
Providers use api.background_tasks.add(leaf_id, task_id: id) and
api.background_tasks.remove(leaf_id, task_id: id). Both accept a bounded
timeout: and return typed correlated acknowledgements with leaf_id and
task_id, preserving extension fields. Removal is idempotent when ownership is
already absent. Registration requires an existing leaf but no originating tool
call. Listen through api.events.on(:background_task_kill) for one-way
cancellation; event["task_id"] and event["reason"] describe the task and
lifecycle reason. Cancel for unfamiliar reasons too, without replying to kill.
The service admits provider-owned internal steers with boolean
advanced.other_meta.background_progress: true and preserves that provenance
on stored user-kind turns. It scrubs untrusted claims. Existing
background_bash.task_id correlation has separate ownership checks on steer
admission. Workflow's legacy Bash compatibility relies on daemon ingress
controls; a stored task ID is not independent proof of ownership. The flags
identify internal progress, not final leaf completion.