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 without sending or awaiting extra discovery. 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.
Providers use RPC().MatchToolApproval to check a remembered grant and
RPC().CreateToolApproval to create a question and wait for its decision.
Pass the leaf and runtime call IDs from tool_call. A match only applies to an
eligible command after its mandatory checks. On create, pass an empty match key
if the operation cannot be remembered. Only a granted decision authorizes
execution; errors, cancellation, and all other decisions fail closed.
Test Decision, never Reply: an aborted outcome can carry allow_once.
Cancellation stops the wait, not the daemon-owned question. Use the tool's
cancellation context and check it before starting any work. Daemons handle
OnToolApprovalRequest and send the correlated result and, for pending questions,
the terminal done frame. See the provider approval frames.
Use an RW form when one stream supplies both directions. BuildAck and
OnHello own service-side acknowledgement; clients may inspect validated
HelloAck after startup. Its optional NodeID is the persistent service
identity, separate from the connection ID and ServerID implementation label.
An empty value means unknown, including older services and bootstrap replies.
ServiceOptions.NodeID supplies it for a default acknowledgement; custom hooks
set HelloAck.NodeID. The daemon uses its existing storage identity. This is
lookup metadata, not authentication evidence. Conn.HelloAck() is a local read
available to tool/plugin/macro providers as well as ordinary clients, over
sockets or supplied stdio streams; it performs no RPC.
Optional subprotocol discovery
The SDK advertises V1 extra_api_support:true in hello/ack and handles
extra/extra_response in both directions. V1 requires mutual opt-in and a
ready peer. V2 and later ignore the V1 flags. Ready closes after hello/ack,
without waiting for an inventory.
Set ClientOptions.Extras or ServiceOptions.Extras to the subprotocols that
peer implements. Each entry has a unique nonempty name and one signed-32-bit
version, excluding the reserved minimum. Options are copied per connection.
Discovery does not activate features or subscribe to events.
After Start, Conn.RemoteSupports(ctx, "name", bounds...) (int, error) starts
or joins one connection-owned discovery request and waits for its result.
context.Background() imposes no discovery timeout. A caller cancellation or
deadline ends only that caller's wait; a late correlated response remains usable.
The shared request has no RPC watchdog and stays pending until a response,
correlated error, or transport failure. Settled results are cached until close.
This breaks the previous integer-only signature. Migrate checks as follows:
| 1 | version, err := conn.RemoteSupports(ctx, "provider_usage", 1, 1) |
| 2 | if err != nil { |
| 3 | return err |
| 4 | } |
| 5 | if version == ezagentapi.UnsupportedVersion { |
| 6 | // Known unsupported, not pending discovery. |
| 7 | } |
RemoteSupportsIfKnown(name, bounds...) starts or joins discovery but returns
*CapabilityUnknownError immediately while pending. RemoteSupportsAsync(ctx, name, bounds...) returns a buffered channel containing one ExtraResult with
Version and Err, then closes it. Cancellation detaches only that waiter.
Context errors support errors.Is; transport failures are errors, not unsupported
answers. No completion runs on the transport reader.
ExtraDiscovery() passively returns ExtraDiscoveryNotRequested,
ExtraDiscoveryRequested, ExtraDiscoveryReceived, or
ExtraDiscoveryUnavailable. RemoteExtras() passively returns a copied map,
non-nil for a valid empty inventory. Neither accessor starts discovery.
Err() and Closed() expose terminal connection failure separately.
Malformed inventories and correlated discovery errors settle as unavailable
without failing an otherwise usable connection.
Support checks return UnsupportedVersion, fixed at -2147483648, for known
unsupported names or versions, invalid bounds, and unavailable discovery.
Omitted bounds span the signed-32-bit range; two bounds are inclusive.
A received inventory, including an empty one, permits native future.*
inference using the negotiated API version. Unavailable discovery does not.
Native future advertisements are omitted at or below that API version.
Extra-dependent operations perform their own gate. Call RPC().Version(ctx),
ProviderUsageList(ctx), ProviderUsage(ctx, provider), or
ProviderUsageSet(ctx, provider, snapshot) directly rather than prechecking.
Their contexts cover discovery and execution. Discovery has no implicit deadline;
the ordinary RPC timeout starts after admission. The corresponding
VersionIfKnown, ProviderUsageListIfKnown, ProviderUsageIfKnown, and
ProviderUsageSetIfKnown methods return unknown without sending the operation
while discovery is pending. Known unsupported operations return
*UnsupportedExtraError. Cancellation before admission prevents a later send;
cancellation after sending does not imply remote rollback.
The daemon advertises future.version_info at version 2 on V1 connections.
RPC().Version(ctx) checks that support and queries the receiving daemon using
PR #37's version/version_result contract. VersionResult contains release,
stability, build date and Git commit strings. Unknown build fields use
unknown. Capability clients do not advertise this daemon operation merely
because their SDK can call it. At API 2 it is native, so its future.
advertisement disappears and the helper resolves support through the API
version instead.
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. PrepareInbound hooks must not
block and run on a separate preparation lane. Service connections call the hook
in wire order; client connections provide no wire-order guarantee. The returned
preparation runs in the connection-owned callback goroutine with a cancellable
context. Heartbeat and response correlation remain independent.
RPC.UpdateCwd changes the connection default and optionally selects a leaf;
RPC.ListCwd returns distinct CWDs containing non-temporary leaves with turns,
preserving its existing return type. RPC.ListCwdDetails returns the full CwdList, including
optional aligned CwdInfos activity summaries. Servers can send these through
SendCwdListWithInfos; SendCwdList remains compatible with older peers. See
the catalog for summary fields, validation and subscription replay.
RPC.ListLeavesFiltered accepts an active-only option while retaining the
existing leaf-list response. Older daemons may ignore the optional filter.
RPC.ListLeavesWithOptions adds the metadata_equals and metadata_present
filters, and RPC.ListLeavesRequest returns a whole leaf_list, including
sync fields. leaf_sync.go owns
LeafSyncView, which keeps a local copy of one query current. Refresh opens a
service sync view, fetches its 200-row chunks, then polls for changed rows and
removed IDs. It reopens on list_sync_unavailable
(IsLeafListSyncUnavailable) and retries the open once if its initial chunks
become unavailable. It falls back to a full list per refresh when an older
service ignores sync. Each protocol.LeafInfo has a read-only
HasPendingQuestions flag for this recipient, including when the caller isn't
following the leaf. Older services omit the flag, which decodes as false. Keep
one Refresh in flight per view. On error the previous copy and revision are
kept. Servers send sync replies with SendLeafListFrame.
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.
Clients may call LimitClientOutput before Start to cap queued outbound
frames and bytes. Flush markers count as frames; a frame already being written
is outside the queue. Zero leaves a dimension unlimited. Sends fail when the
queue is full, and the client owns the decision to close the connection.
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, unavailable, or a
provider-defined subscription indicator accepted by
protocol.IsProviderSubscriptionSource, such as muse_subscription or
claude_subscription. An active run retains its 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. That label 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.
An absent or unfamiliar wire value must clear any prior classification. Unfamiliar provider indicators display generically; other unfamiliar values display neutrally. These fields are read-only and expose no authentication data. Snapshot reads do not write the remembered metadata; model selection and execution own those updates. RPC signatures and callback arguments are unchanged.
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.
Stored attachment downloads
RPC.GetAttachmentChunk(ctx, turnID string, attachmentIndex int, offset, length int64)
returns protocol.AttachmentChunk or a correlated error. The
request and
response catalog entries define
all fields and errors; attachment.go owns
the frame types and rpc.go owns the typed helper.
Use a zero-based index into the turn's meta_files array. Each request requires
nonempty turn and request IDs, an explicit integer index >= 0, an int64 byte
offset >= 0, and an int64 length from 1 through 98304 decoded bytes. Omitted or
null numeric fields are invalid even where zero is valid. The helper supplies
the request ID and encodes index 0 and offset 0 explicitly.
The reply echoes turn, index, and offset; size is the actual total decoded
size and length is min(requested length, size - offset). Decode data_b64
as standard padded base64 for every file, including UTF-8 text. Assemble bytes
before decoding text, since a range may split a character. eof means exactly
offset + length == size. Offset equal to size succeeds with length 0, empty
data, and EOF, including an empty file at offset 0. Offset above size fails with
attachment_range_error. Invalid requests produce parse_error, a missing turn
produces turn_not_found under the same access rules as get_turn, a nonexistent
index produces attachment_not_found, and a missing or corrupt stored blob
produces internal_error.
Keep two independent requests in flight and replenish the window as each
response arrives. Replies can arrive out of order. Place bytes by the echoed
offset and track all required ranges; an EOF reply can precede earlier ranges
and does not mean the whole download is complete. FileMeta.size already
exists. For legacy metadata without size, get the actual size from the first
chunk response before scheduling subsequent ranges.
Each call owns its correlated response. attachment_chunk is requester-only,
never a frontend event or subscriber broadcast; late unmatched replies are
discarded. The helper does not introduce a batch frame or automatically download
attachments for the UI. The protocol remains version 1 with no SQLite schema or
PRAGMA user_version change.
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 the ordered preparation
lane, off the reader, 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.
Leaf file registration
RPC.AttachLeafFile(ctx, leafID, key) returns protocol.LeafFileDescriptor
with FileID, Key, and Path, or a correlated service error. It checks the
result's operation, leaf and key. The request ID and leaf ID are both present
on the wire result. The daemon atomically returns the existing registration for
the same key or registers a new storage-owned path. It does not create the
payload. Existing GetLeafConfig reads the registration list without allocating.
Manual list replacement is authoritative. See storage
for ordering and deletion. A canceled context or lost connection ends the
local wait, not necessarily the daemon operation. Calls are not retried; a later
same-key attach can recover an already committed registration. Older services
may reply with their ordinary unknown_command error.