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

RoleConstructor
Client, TUI, capability processConnectClient, ConnectClientRW
Daemon/serviceAcceptServiceConn, 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. 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.

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. Service handlers may opt into PrepareInbound: the reader calls its nonblocking hook in wire order, then 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() 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, 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.

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?

NeedAPI surface / authority
Connection lifecycle, readiness, hello/ack, and version validationconn.go, startup.go
Announce capabilities; send tool, plugin, macro results; report progressoperations.go
Service-to-capability calls, metadata, acknowledgements, heartbeatsservice_operations.go
Service replies, lifecycle, and eventsserver_outbound.go
Callback routing and unsupported framesdispatch.go
Public options, callbacks, and protocol aliasestypes.go
Frame definitions and validationpkg/protocol/ and protocol
Generic JSONL flushing, pause/resume, and goroutine lifecyclepkg/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.

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.