docs/pkg/ezagentapi.md
pkg/ezagentapi typed protocol peers
pkg/ezagentapi performs startup handshake, typed operations, inbound dispatch,
and RPC correlation for EzAgent peers. It hides jsonlpipe.Conn. Wire fields and
examples belong to the JSONL catalog; validation
to pkg/protocol.
Connection roles and lifecycle
| Role | Constructor |
|---|---|
| Client, TUI, capability process | ConnectClient, ConnectClientRW |
| Daemon/service | AcceptServiceConn, AcceptServiceConnRW |
Start completes hello/ack before normal traffic. Build options and handlers,
construct the connection, call Start, then use typed sends or RPC(). Close
ends local work; Wait joins connection-owned callbacks. Closed signals
terminal transport/correlation earlier and is not a callback join.
Use an RW form when one stream supplies both directions. BuildAck and
OnHello own service-side acknowledgement; clients may inspect validated
HelloAck after startup.
Ordering, callbacks, and RPCs
Every outbound top-level frame receives a direction-local ordered Itr; hello
or ack consumes the first value. Itr means per-connection enqueue order. For
one leaf, service snapshot/stats capture remains ordered through enqueue. It is
not an RPC ID, global revision, cross-connection order, or loss detector.
Matching RPC replies and heartbeats route before callbacks. Callbacks serialize
per connection by default; the service enables ConcurrentRPCs so independent
RPCs and control requests use their own admission gates. Callbacks
may make blocking same-connection RPCs, and are joined by Wait. Unknown frames
reach OnUnsupportedMessage when configured.
RPC() creates request IDs and waits by response type, allowing out-of-order
replies. Late response-only frames remain responses and are discarded rather
than broadcast. Solicited and unsolicited turn_content split between RPC and
event paths; leaf_switched is response-only and a separate leaf_updated
carries current state.
Tool invocation
rpc := conn.RPC(); inv, err := rpc.InvokeTool(ctx, leafID, name, arguments)
waits for acceptance and exposes inv.InvocationID. Arguments are
json.RawMessage. done, err := inv.Wait(ctx) waits for the canonical
protocol.ToolInvokeDone; its turn may contain an ordinary tool error in
Advanced.OtherMeta, which is not a transport error. The caller can wait again
after a wait context expires. Waiting does not cancel the tool and has no
implicit lifetime timeout. To request cancellation explicitly, call
rpc.CancelToolInvocation(ctx, inv.InvocationID) and continue waiting for the
terminal result.
The acknowledgement uses the standard RPC inactivity watchdog and errors.
If an acknowledgement is lost, acceptance is unknown and the client does not
retry. Completion is correlated before serialized callbacks, including when it
arrives before the acceptance caller wakes. An explicitly configured
OnToolInvokeDone observes every decoded completion, including those resolved
by a future. Without that hook, completions matched or buffered for a future
are consumed rather than sent to OnUnsupportedMessage. Completed results
live in the caller's handle, not a replay API;
connection closure releases unfinished waits with a connection error while
preserving results already received.
Leaf snapshots and history
LeafUpdated is a complete snapshot, not a patch. Empty, zero, nil, and
PendingQuestions: [] clear older projection state. Question replies send exact
leaf, kind, revision, and answer; committed changes produce a fresh snapshot.
protocol.LeafUpdated.AccessSource and the protocol.LeafStatsResponse returned
by RPC.LeafStats expose the optional, read-only computed access source. Values
are local, openai_subscription, api_key, unknown, and unavailable.
An active run retains its captured source; an idle leaf reports its resolved
next-run configuration. An absent or unfamiliar value must clear any prior
classification and display neutrally. These additive string fields do not change
RPC signatures or callback arguments, and they never expose authentication data.
ListHistorySnapshot retains the complete envelope and canonical TipTurnID;
ListHistory returns summaries only. LeafStatsResponse also carries the exact
tip. Method signatures and inactivity thresholds live in
rpc.go.
RPC.RewindLeaf(ctx, leafID, currentTipTurnID, newTipTurnID string, replay bool)
uses "" as the explicit root boundary. Success consumes leaf_rewound;
subscribers receive leaf_updated separately. Replay returns on admission, with
ordinary lifecycle events reporting generation outcome. Correlated service
errors are parse_error, leaf_not_found, leaf_busy, turn_conflict,
invalid_rewind_target, invalid_model, and provider_error.
RPC.CreateVirtualRoot(ctx, leafID, reason, turns, metadata) accepts optional
JSON-object metadata. Nil omits it; malformed/non-object metadata and top-level
exit_message fail without commit. Numbers decode as json.Number. Storage
rules belong to service/session.
Boundaries
This package owns typed peer behavior. pkg/jsonlpipe owns
generic JSONL transport and goroutine lifetime. pkg/protocol
owns frame validation. The daemon's runtime semantics belong to
pkg/service.
Virtual-root metadata
RPC.CreateVirtualRoot(ctx, leafID, reason, turns, metadata) takes
metadata map[string]any after the pending turns. Pass nil for ordinary
history replacement. The wire field is an optional JSON object, not a
JSON-encoded string. Nil, JSON null, and empty objects add no metadata;
malformed or non-object JSON is rejected. The service rejects the top-level
exit_message key, including a null value, without committing the mutation.
Storage serializes metadata into only the boundary turn's existing
other_meta column in the same transaction as the boundary, pending turns,
and leaf-tip update. TurnContent.OtherMeta remains a JSON-encoded string.
Metadata does not propagate to pending turns or a held draft. Decoding
CreateVirtualRoot represents metadata numbers, including nested values, as
json.Number so storage preserves exact JSON numeric values rather than
rounding through float64. The public type remains map[string]any; this
decoding rule does not change other JSONL frame types. Callers needing exact
large integers should supply integer types or json.Number, not values
already rounded to float64.
Both builtin compaction modes send {"continuation":true,"pivot_turn_id":"..."}.
The flag marks continued source history. The pivot is the last source turn
summarized, not the generated summary or first retained turn. It does not
change the boundary's physical parent, which remains the old tip, or the old
sent tip before a held draft. Other than the reserved key restriction, the
daemon leaves metadata semantics to consumers. Human-readable reason text
stays unchanged. This additive field needs no API version or database schema
change, and does not change PRAGMA user_version.
Where do operations and detail live?
| Need | API surface / authority |
|---|---|
| Connection lifecycle, readiness, hello/ack, and version validation | conn.go, startup.go |
| Announce capabilities; send tool, plugin, macro results; report progress | operations.go |
| Service-to-capability calls, metadata, acknowledgements, heartbeats | service_operations.go |
| Service replies, lifecycle, and events | server_outbound.go |
| Callback routing and unsupported frames | dispatch.go |
| Public options, callbacks, and protocol aliases | types.go |
| Frame definitions and validation | pkg/protocol/ and protocol |
| Generic JSONL flushing, pause/resume, and goroutine lifecycle | pkg/jsonlpipe/ and jsonlpipe |
Send and progress helpers validate locally and only confirm local transport; daemon rejection is an asynchronous protocol error. For capability flows, use the builtin and hello examples.
Internal request receipt and transport classification
Handlers.OnRequestQueued func(RequestReceipt) func() is an optional Go-only
observation hook. It runs after response correlation, on selected request frame
receipt, before spawning the callback goroutine or acquiring the connection's
callback mutex. It must be quick and nonblocking. A non-nil returned function
runs once after mutex acquisition and before handler start. A nil hook or nil
completion is supported. It does not run for response-only frames and introduces
no JSONL fields, acknowledgement, queue ordering guarantee, or cancellation.
RequestReceipt contains Kind, LeafID, and RequestID, all strings. Kind
is one of leaf_stats, abort, prompt, or rename_leaf. The IDs are decoded
wire values and remain untrusted; logging observers must validate them and must
not inspect request payloads. Receipt projection decodes only these envelope
fields; the regular typed handler still owns full request decoding. The service
uses this hook to distinguish callback-lane wait time from handler execution.
IsTerminalTransportError(error) bool recognizes typed closed/disconnected
causes, including wrapped causes: the JSONL closed sentinel, the service RPC
connection-closed sentinel, EOF, closed pipe, closed network connection, EPIPE,
and ECONNRESET. It does not infer closure from error text. Context cancellation
or deadline, service rejection, RPC timeout, and admission ambiguity are separate
categories, not terminal transport classifications. In particular, this helper
does not say whether a request was admitted or a peer read its acknowledgement.
Background ownership RPCs
RPC.BackgroundTaskAdd(ctx, leafID, taskID) and
RPC.BackgroundTaskRemove(ctx, leafID, taskID) await correlated acknowledgements
or errors and validate the echoed leaf/task identity. Providers need no
originating tool call. Handlers.OnBackgroundTaskAdd, OnBackgroundTaskRemove
and OnBackgroundTaskKill dispatch the approved typed frames. The service's
SendBackgroundTaskKill is one-way; unknown informative reasons still require
cancellation. No kill acknowledgement or task-status RPC exists. For background
bash, status is read through buffer at meta:bash-<id>/state.
Renewable call waits
Each heartbeat travels one way, from the receiver of a request back to its caller. For a client-initiated RPC the service sends updates to the client; for a service-initiated capability call the provider sends updates to the service. There is no heartbeat reply, echo, or ping/pong exchange.
Receivers heartbeat admitted tool, plugin, macro and RPC requests until the
matching terminal is enqueued or the connection closes. A registered typed
handler may return before publishing an asynchronous result; that return does
not retire ownership. An OnUnsupportedMessage observer returning without a
reply does not retain ownership for a request with no typed handler. The library
publishes a generic terminal failure if the observer did not already publish a
terminal. Automatic failure replies do not include handler error details; the
original error reaches the local OnError callback. For decode failures,
OnError runs before the fallback so the service can preserve its existing
parse_error response. If that callback sends a terminal, the fallback sends
nothing; otherwise it retires the request with a generic failure.
tool_ack is not terminal.
Typed RPCs reuse
watchdog.Manager with a renewable five- or ten-second inactivity threshold,
without an elapsed-time cap. Explicit context deadlines and local cancellation
still retire the waiter, without sending a cancellation frame or asserting
rollback. RPC.ToolMetadata, PluginMetadata and MacroMetadata use this same
connection-local correlation. Startup handshake/readiness bounds are separate.
Disconnect is terminal for outstanding calls. New connections have fresh IDs
and carry new requests only. Already-correlated replies survive EOF; calls are
never transferred or automatically replayed. Handler contexts observe transport
closure, while Close itself does not join outstanding callbacks.