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.

api.hello_ack.node_id exposes the optional persistent service identity as a frozen string, or nil when omitted by an older service or during bootstrap. It is separate from server_id and connection_id, and is lookup metadata, not authentication evidence. Tool/plugin/macro callbacks can read the same accessor on their owning connection, including Connection.open over stdio; this is a local read, not an RPC.

  • close ends 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?, and to_h retain unknown fields. Keep raw frame sending and correlation private.
  • Connection-local itr is 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.

Extra discovery and daemon version

Startup performs only the hello exchange, bounded by startup_timeout. It does not send an extra request or await optional discovery. The SDK advertises extra_api_support: true; protocol 1 requires the peer's opt-in too. Not-ready and non-opted-in connections report discovery as unavailable.

api.remote_supports(name, *bounds, timeout: nil) starts or joins one correlated connection-owned discovery request and waits for its result. There is no default discovery deadline. An explicit timeout bounds only this caller's wait and raises TimeoutError; it never expires shared discovery or another waiter. Late replies remain usable. Correlated errors and invalid inventories settle as unavailable without closing the connection. Transport failure instead raises a connection error and remains available separately through terminal_error.

api.remote_supports_if_known(name, *bounds) starts or joins the same discovery but raises CapabilityUnknownError immediately if the inventory is pending. api.remote_supports_async(name, *bounds) returns a CapabilityCheck with:

  • wait(timeout: nil) returns the version or raises its error. A timeout leaves the handle pending and usable.
  • done? passively reads completion state.
  • cancel completes only this handle with CapabilityCancelledError, detaches it from discovery, and returns whether cancellation won.
  • on_complete { |version, error| ... } registers a completion, including after settlement. Exactly one argument is non-nil. Completion callbacks run off the reader and independently of event callbacks and other completions. A blocked callback does not prevent other checks or callbacks from completing. Callback failures use events.on_error; fatal exceptions also terminate the connection.

General API completion dispatch owns transient callback threads, not a permanent worker per check. close wakes pending checks without running callbacks inline. join waits for reader, control writer, providers, event dispatch and completion callbacks. User callbacks may call close. A callback's join cannot join its own callback lane and returns without waiting for callback workers; an external join is required to await their exit. Blocking callbacks must return before external join can finish. After publishing terminal state, close interrupts only the connection-owned control writer, including its writer-lock and stream waits. It does not close caller-owned streams or interrupt application writer threads or callback threads. An interrupted partial control write cannot be reused because the connection is already terminal.

The passive extra_discovery reader returns :not_requested, :requested, :received, or :unavailable. remote_extras returns a frozen name-to-version hash. Neither starts traffic. A valid empty inventory is :received, not :unavailable. Results are cached for this connection; reconnecting starts over.

Bounds are inclusive and default to signed-32-bit minimum and maximum. Supply both bounds or neither. Names must be nonempty strings; invalid bounds or names raise ArgumentError. Supported checks return the highest compatible version; known unsupported checks return EzAgent::API::EXTRA_UNSUPPORTED, or -2147483648. After a valid inventory, future.* names also infer native support up to the negotiated API protocol version, even for an empty inventory. Unavailable discovery never infers native support. The SDK release and daemon build version are irrelevant to this inference.

Migration from startup snapshots

Support checks now wait instead of reading a startup snapshot. Use an operation directly rather than checking support and retrying it:

ruby
1# No discovery deadline; the normal RPC timeout starts after admission.
2result = api.daemon.version
3# A caller-selected deadline covers both discovery and RPC execution.
4usage = api.providers.usage_list(timeout: 10)
5# Never wait for pending discovery or send an unadmitted operation.
6begin
7 usage = api.providers.usage_list(capability_wait: :if_known)
8rescue EzAgent::API::CapabilityUnknownError
9 # Continue other work. A later call reuses the same discovery request.
10end

daemon.version, providers.usage_list, providers.usage, and providers.usage_set all accept capability_wait: :wait or :if_known. Explicit numeric timeout: values bound the whole operation. With no explicit timeout, discovery waits indefinitely, then the existing renewable RPC timeout applies. Known unsupported operations raise UnsupportedExtraError, whose extra reader names the missing capability. Pending immediate calls raise CapabilityUnknownError; neither sends an operation. Timeout or caller thread cancellation before admission prevents a later discovery reply from sending the abandoned operation. Expiry or caller interruption while awaiting the writer lock also sends nothing and leaves the connection usable. After writing starts, interruption, including Thread#kill, can leave a partial frame and terminates the connection. After a send, cancellation cannot promise remote rollback. Ordinary non-extra operations remain independent of pending discovery.

Both connection constructors accept extras: [], an array of hashes such as {name: "example.feature", version: 1}. Names must be unique and nonempty; versions must be integers greater than the unsupported sentinel and no greater than 2147483647. The connection snapshots the array at construction and queues inbound discovery replies on its connection-owned control-write lane, independently of application callbacks. The reader never waits for that lane or for the writer lock, so incoming replies can settle support checks while writes are blocked. Closing discards queued control writes and interrupts the running control worker without closing its streams. future.* entries at or below the API protocol version are omitted from advertisements because native support is inferred. Other extras can use zero or negative versions. Missing or null extras inventories and entries with missing versions are invalid. Discovery does not enable extras or subscribe to events.

api.daemon.version(timeout: ...) returns an immutable VersionResult with string version, stability, build_date, and git_commit accessors. The full git_commit string may end with * for a modified checkout; no separate dirty field is used. On protocol 1 it requires future.version_info:2 and raises UnsupportedExtraError without sending a request when unavailable. It uses the protocol-2 version and version_result frames unchanged. Ruby does not serve build identity requests and does not advertise future.version_info by default; configure only extras the application implements.

The current wire client accepts only protocol 1. The shared inference helper already handles protocol 2 and later: discovery always works regardless of hello flags. For the protocol-2 merge, future.version_info:2 must be omitted because it is native; the version helper's same support check then succeeds without a backport advertisement.

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.md has typed lookup and a handler policy example.
  • embed:skills/ruby/references/capabilities.md has registration, callback context, direct stdio and socket service installation, routing, and activation.
  • embed:skills/reflection/references/modes.md covers 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.

Connection working directory

api.subscriptions.update_cwd(cwd, leaf_id: nil) updates the connection default and returns a CwdUpdate with cwd, optional leaf_id, and correlation fields. A nonempty leaf ID switches the subscription and triggers the usual snapshot and replay. api.roots.cwds returns a frozen array of distinct persisted root cwd strings. Both calls use the normal correlated RPC timeout and errors.

api.sessions.create(cwd: nil) uses the connection default for a new root. Its usual default argument remains Dir.pwd. Existing leaves retain their root cwd. See the JSONL catalog for ordering and validation.

api.sessions.list(is_active: true) requests only running or aborting leaves. It can be combined with cwd or root_id and projected metadata_keys. Older daemons can ignore this optional filter; inspect returned statuses when compatibility with them matters. The default leaves the request unfiltered.

list also accepts metadata_equals: (a string hash) and metadata_present: (a string array). Each LeafInfo exposes the read-only root cwd and has_children; older daemons omit both and ignore the filters. list_page sends one frame and returns a LeafList with leaves, removed, and the sync fields sync_id, revision, offset and total. sessions.sync_view(...) takes the same filters and returns a LeafSyncView; refresh returns [leaves, changed], opening a service sync view, fetching its chunks, polling for changes and reopening after list_sync_unavailable. Against a daemon without sync support every refresh is a full list. Keep one refresh in flight per view. Existing list calls are unchanged.

Provider account usage

api.providers.usage_list, usage(canonical_target) and usage_set(local_provider, snapshot: hash) use optional ordinary extra provider_usage:1. Results are wire hashes. Target/result revision values are opaque configuration identities; compare them before displaying results and discard retired replies. They are not timestamps, credentials or account IDs. Targets roundtrip directly, including host/provider; account data is independent of leaves and chat-local stats. Unsupported extras raise UnsupportedExtraError; correlated daemon rejections raise ServiceError with code and request_id. Posts are accepted only for a local provider whose owning mode disables automatic querying.

See the single account usage and observer reference for freshness, decimal-string money, safety rules, and a runnable Ruby push example handling automatic-query/proxy rejections.

Standalone tool invocations

Invoke an active tool on a leaf and wait for its canonical result turn:

ruby
1invocation = api.tools.invoke(leaf_id: leaf_id, name: "run-cmd",
2 arguments: {"command" => "pwd"})
3done = invocation.wait
4puts done.turn.content
5# done.status is "completed" or "aborted"; done.turn is a PendingTurn.
6# done.turn.attachment_blob and done.turn.advanced retain provider data.

invoke returns a ToolInvocation with invocation_id after the correlated acceptance, not after execution. Its timeout: uses the usual renewable RPC default; heartbeats stop extending it once the acknowledgement arrives. The handle has no implicit execution deadline. invocation.wait(timeout: 10) sets only a local wait deadline and can be called again. To request cancellation, use api.tools.cancel(invocation.invocation_id), which returns a typed acknowledgement with operation, invocation_id, and state. Cancellation does not wait for provider exit; the original handle receives the terminal result. A normal tool result marked is_error remains a result, not a service exception. Connection closure releases pending waits. The SDK does not retry an uncertain start or recover its results after reconnect.

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, unavailable, or a provider-defined <name>_subscription indicator such as muse_subscription or claude_subscription; an older daemon returns nil. Providers choose indicator names, so clients should show unfamiliar indicators generically. Other 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, including host-reported source information for remote models. Idle or unloaded leaves use known configuration or cached discovery data, falling back to the remembered model_access_source label for the same resolved model. The label is persisted and survives observation expiry, unload, and restart. Live observations and their timestamps are not persisted. Omitted discovery information preserves the remembered label; an explicit unknown replaces it. A remembered subscription label does not assert a current paid plan or entitlement.

The field is read-only and contains no credentials. Snapshot reads do not write the remembered metadata; model selection and execution own those updates. Existing constructors, operation keywords, positional arguments, and event callbacks are unchanged.

Attachment chunks

sessions.get_attachment_chunk(turn_id, attachment_index:, offset:, length:, timeout: RENEWABLE_REQUEST_TIMEOUT) reads one bounded chunk from a stored turn's attachment. sessions.attachment_chunk is an alias. The attachment index is a required zero-based integer, offset is a required nonnegative byte offset, and length is a required integer from 1 through 98,304 decoded bytes. The helper does not download a whole file or issue follow-up or batch requests.

ruby
1chunk = api.sessions.get_attachment_chunk(
2 turn_id, attachment_index: 0, offset: 0, length: 98_304
3)
4bytes = chunk.data # Frozen binary string, decoded from data_b64.
5next_offset = chunk.offset + chunk.length

The immutable AttachmentChunk exposes turn_id, attachment_index, offset, length, size, data_b64, eof, request_id, and itr. Length is the actual decoded byte count, size is the total attachment size, and data_b64 is padded standard base64. The helper requires length to equal the smaller of the requested length and size - offset. It validates the response range, encoding, EOF flag, and request selectors. Unknown response fields remain available through [] and to_h.

Use the attachment's existing FileMeta.size when available. Older metadata may omit size; the first chunk response supplies it. A request at offset equal to size returns an empty chunk with eof == true, including for an empty file. An offset greater than size raises a correlated ServiceError with code attachment_range_error.

Keep at most two requests in flight and issue the next request when a previous response arrives. Concurrent calls are correlated by request ID even when replies arrive out of order. Use each response's actual length when advancing the offset. Timed-out, duplicate, and unmatched chunk replies are dropped rather than published as events.

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.

ruby
1created = 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.

ruby
1rewound = 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

DetailAuthority
Entry point, endpoint resolution, AF_UNIX adapterapi.rb, api/client.rb
Operations, values, events, correlation, errorsapi/
Provider definitions, calls, workers, heartbeatsapi/capabilities.rb
End-to-end Ruby behaviortest_ruby_api.py; test guide
Every frame schema and exampleJSONL 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.

Leaf file registration

api.leaf_files.attach(leaf_id, key, timeout: RENEWABLE_REQUEST_TIMEOUT) returns an immutable LeafFileDescriptor with file_id, key, and path. Both arguments must be nonempty strings. The result's leaf and operation are checked against the request. The daemon returns the same descriptor for a registered key and creates no payload. The owner manages the file; its absence does not erase the registration. api.config.get(leaf_id, "leaf_files") reads the list without allocating. Whole-list config replacement remains authoritative.

The ordinary RPC timeout and disconnect rules apply: ending the local wait does not roll back a daemon commit, and the client does not retry. A later same-key attach returns a committed registration. Older services can return the existing unknown_command error. See the wire contract and storage ordering.