ez-agent-lib/README.md
ez-agent-lib (Java client only)
Java 17, Android minSDK 26-compatible client API for an existing EzAgent
protocol-1 JSONL connection. The primary model is
ez-agent-ruby/lib/ez_agent/api,
with request/reply contracts from pkg/protocol and pkg/ezagentapi in that
checkout. This library consumes the API; it is not the EzAgent service.
There is no Go, Android import, SSH implementation, remote socket dialing, file
access, or UI dependency in production sources. The optional tunnel adapter
binds a local IPv4 loopback TCP listener over a borrowed JSONL connection.
Android use
The app depends on implementation project(':ez-agent-lib'). The library uses
compileOnly 'org.json:json:20240303'; Android provides org.json at runtime.
The desktop JSON implementation and Android-compatible JSON test runtime are
test-only, never transitive APK dependencies. A standalone JVM consumer must
supply a compatible org.json implementation itself.
Create the facade over exclusively reserved, already-connected streams:
| 1 | // Run this entire startup exchange on a background executor, not the UI thread. |
| 2 | EzAgentClient client = new EzAgentClient(input, output); |
| 3 | try { |
| 4 | HelloAck hello = client.handshake("My Android client", remoteCwd); |
| 5 | if (!hello.ready()) { |
| 6 | // Present configuration/readiness state according to caller policy. |
| 7 | client.close(); |
| 8 | return; |
| 9 | } |
| 10 | client.start(new JsonlClient.Listener() { |
| 11 | public void onEvent(ProtocolEvent event) { |
| 12 | // Immutable open snapshot. Dispatch UI updates to the main thread. |
| 13 | } |
| 14 | public void onClosed(Throwable cause) { |
| 15 | // Null means explicit local close; otherwise inspect the failure. |
| 16 | } |
| 17 | }); |
| 18 | client.sessions().list(new JSONObject().put("cwd", remoteCwd)) |
| 19 | .whenCompleteAsync((frame, error) -> { |
| 20 | // frame is the full leaf_list reply, not a filtered array. |
| 21 | }, uiExecutor); |
| 22 | } catch (RuntimeException | org.json.JSONException error) { |
| 23 | client.close(); |
| 24 | // Report startup/input failure; never log raw frames or credentials. |
| 25 | } |
Imports for the example are name.devnull.ezagent.lib.*,
name.devnull.ezagent.lib.event.ProtocolEvent, and org.json.JSONObject.
On JVM implementations where JSONException is unchecked, the startup catch may
simply catch RuntimeException instead. Null optional values are omitted; empty
strings/arrays, false and zero remain significant. Do not mutate JSON objects
concurrently with an API call: the transport snapshots them during submission.
The overload handshake(name, remoteCwd, leafId) can explicitly select an
initial remote leaf through hello.leaf_id; null omits it. The two-argument
version makes no initial leaf selection and is what the app currently uses.
helloAck() retains the immutable successful acknowledgement after startup or
close. Explicit ready:false is preserved for caller policy; it is not silently
converted into readiness. The Android app rejects unready startup as before.
helloAck().nodeId() is the optional opaque service conversation-database
identity, null when absent or null on the wire (an empty string remains empty).
It is lookup metadata, not authentication or host trust, and is distinct from
the implementation's serverId() and per-connection connectionId().
Service groups and wire coverage
The facade exposes client service groups over one connection. Session and catalog
services can also be used independently with an RpcTransport; standalone tool
invocation requires the connection-owned registry exposed by the facade. Methods
are camelCase; option member names remain snake_case wire names. Open RPC
responses are JSONObjects, not claims of exhaustive typed DTO coverage.
| Facade group | Client operations / request categories |
|---|---|
roots() | list_roots |
sessions() | create_leaf (create/fork), list_leaves, rename_leaf, delete_leaf, rewind_leaf, list_queued, leaf_stats; prompt/steer/abort aliases |
metadata() | update_leaf_meta |
leafConfig() | get_leaf_config, set_leaf_config, delete_leaf_config, list_leaf_config, effective_config |
leafFiles() | leaf_files stable-key remote path registration |
turns() | list_history, get_turn, get_attachment_chunk, list_turn_tree, create_virtual_root; async canonical-history hydration with cut/summary checks |
questions() | question_reply for exact project-config trust revisions |
runControl() | prompt, steer, abort; acknowledgement is not run completion |
subscriptions() | switch_leaf, drop_feed, update_cwd, list_cwd |
tools() | list_tools, get_tool_info, add_tool, remove_tool |
toolInvocations() | standalone tool_invoke start, terminal observation and known-ID cancellation |
plugins() | list_plugins; plugin selection uses leaf configuration, not an invented add/remove RPC |
providers() | list_providers (discovery, not registration/hosting) |
connections() | list_connections |
filetypes() | get_supported_filetypes |
models() | list_models, resolve_models, set_model, set_thinking_level |
macros() | list_macros, macro_call invocation |
maintenance() | vacuum, safe dry-run default; explicit non-dry-run may permanently prune shared data |
notifications() | notify_leaf (one-way) |
progress() | report_progress (one-way), including clear |
backgroundTasks() | background_task_add, background_task_remove acknowledgements; no local task execution |
daemon() | explicit one-way shutdown; never called automatically |
Detailed option semantics and aliases are documented in
session/package-info.java
and catalog/package-info.java.
Typed immutable values (HelloAck, LeafInfo, PendingTurn, AttachmentBlob)
coexist with full open replies. The library does not filter temporary leaves or
sort results. The app's protocol.Leaf is a UI-only adapter which retains its
previous temporary-leaf filtering, date tolerance and newest-first sorting.
Open model and working-directory metadata
Model discovery returns open JSON, including model ref, flags,
thinking_levels, max_context, max_tokens and optional zdr_supported
when supplied by the service. References can be source-qualified
(source/provider/model); preserve the complete reference instead of stripping
its source. The unavailable flag indicates destination discovery failed;
not-found means the destination was reached but the model was not found.
Preserve unknown flags. max_context is the context-token limit and max_tokens
the output-token limit; omitted or zero values do not establish a limit.
Optional access-source metadata is informational, not a credential or an
entitlement assertion. Absence and unfamiliar values must remain neutral.
The existing leaf configuration keys model_info_ref and model_info_model
identify the selected reference and resolved model for remembered information;
model_max_context is a decimal token count (zero means unknown), and
model_access_source is the last reported access source. These are configuration
keys, not additional protocol frames. Do not assume remembered information
applies to a different selection or route.
subscriptions().listCwd() returns the open cwd_list reply, including
cwds and, when supplied, cwd_infos. Each summary includes cwd,
leaf_count, active_leaf_count and optional last_activity_at. Counts cover
non-temporary leaves with turns; running, aborting and background leaves count
as active. Paths belong to the remote service, not Android's filesystem.
Standalone tool invocation
| 1 | client.toolInvocations().start(leafId, "buffer", arguments) |
| 2 | .thenAccept(handle -> { |
| 3 | // This acknowledgement only establishes an invocation ID. |
| 4 | handle.result().whenCompleteAsync((done, error) -> { |
| 5 | if (error == null) { |
| 6 | JSONObject toolTurn = done.turn(); // defensive copy, including error results |
| 7 | // Inspect done.status() and toolTurn; this is not model history. |
| 8 | } |
| 9 | }, worker); |
| 10 | // If the caller explicitly decides to cancel, use the known ID: |
| 11 | // client.toolInvocations().cancel(handle.invocationId()); |
| 12 | }); |
result() returns a fresh observation future every time. Cancelling an
observation, or the start future, is local and does not request remote
cancellation. A cancel acknowledgement is not provider exit; continue observing
the original handle. A service not_found cancellation is an RPC error, not a
terminal result. Tool/provider/execution errors are represented in the terminal
turn; a rejected start is instead an RPC error. A start failure after sending
can leave acceptance unknown and is never retried automatically. Local closure
settles pending observations but does not generally cancel remote work. Matched
terminal frames are consumed by the registry; unmatched ones reach the event
listener, as do duplicates after the invocation is no longer owned. Early
frames can be retained while a start is pending. Generic standalone bash and
run-cmd with background:true are rejected by the service; no background
runner is synthesized.
The start future owns the local acceptance correlation until ACK delivery or
local terminal completion. Cancelling, explicitly completing, or using
orTimeout / completeOnTimeout on it abandons that correlation; no remote
cancel or retry is sent. completeAsync follows the same rule. Obtrusion is
unsupported because it could replace an already delivered handle. In contrast,
start.get(timeout, unit) only times out that blocking wait and leaves the
start pending. Likewise, timing out one result() observation does not settle
or unregister the invocation; another observation can still see the result.
Ownership cleanup precedes public completion, but a competing terminal mutation
can help publish the already prepared winning outcome. A losing complete or
completeExceptionally therefore returns false only after the future is done;
it does not wait for the winning caller's continuations to return. Publication
and public continuations run outside the ownership lock.
An owner that needs cleanup after an independent execution cancellation can
retain the start future under its own bounded acceptance/cleanup policy, wait
for a late ACK if possible, and explicitly call cancel(handle.invocationId())
when it has an ID. A missing ACK or unconfirmed cancellation leaves the remote
outcome uncertain. The library imposes no execution or cleanup deadline.
Local TCP/HTTP forwarding
TunnelLink.parse("ez-agent://tunnel/localport/8080/dashboard") validates a
custom link without I/O. sourcePort(), path() and localUrl(assignedPort)
retain the source port and escaped path separately; the path is not a traffic
restriction. Queries, fragments, ambiguous browser-normalized paths and
noncanonical ports are rejected.
On a background worker, client.openTunnel(sourcePort) discovers the existing
tunnel.localport macro and binds an available IPv4 loopback port. The returned
TunnelForward.port() is distinct from the source port. Each accepted local
connection opens a fresh macro stream; a failed stream is not replayed and does
not close the listener. Setup alone does not contact the source TCP service.
Consumers with an RpcTransport can instead use TunnelForward.open(rpc, port).
Both setup and close() are blocking and must stay off UI/completion lanes.
The facade automatically cancels its forwards on explicit close or connection
loss, including forwards created through controlled views. For the lower-level
TunnelForward.open(rpc, port) entry point, the caller must tie cancellation to
the borrowed transport's lifetime. The adapter never closes the RPC transport.
Interrupted setup cancels its own discovery request. cancel() promptly revokes
admission and requests shutdown without joining; close() also joins workers.
closed() completes after all owned workers have finished. isClosed() and the
generic lastFailure() support diagnostics without retaining peer error text.
The adapter implements the existing EzAgent CSV pipe rows inside ordinary
macro_call/macro_result strings, including consumption ACKs, byte/frame
credit, reply-slot replenishment and independent socket I/O. It adds no JSONL
frame kinds. See Android HTTP tunnels for UI lifecycle,
local-app access and half-close limitations.
Attachment ranges and connection cwd
These methods return asynchronous CompletableFuture<JSONObject> replies and
use normal request-ID correlation, including correlated error failures:
| 1 | client.turns().attachmentChunk(turnId, attachmentIndex, offset, length); |
| 2 | client.subscriptions().updateCwd(newCwd, leafId); |
| 3 | client.subscriptions().listCwd(); |
attachmentChunk is one range RPC, not a downloader. The turn ID must be a
nonempty opaque string (never trimmed), attachment index and decoded-byte offset
must be nonnegative, and length must be 1..98304 inclusive. Invalid arguments
throw IllegalArgumentException before transport submission. Zero index/offset
are explicitly encoded, and offsets retain Java long precision. The server
validates attachment existence and offset against actual size: offset equal to
size returns an empty EOF chunk; offset above size is attachment_range_error.
The open reply retains turn_id, attachment_index, offset, length, size,
data_b64, eof, and extension fields. All data is standard padded base64,
including UTF-8 files; callers decode bytes and validate/assemble their ranges.
Replies can arrive out of order, and EOF does not complete other pending ranges.
The library neither decodes chunks nor schedules further requests.
updateCwd accepts exact nonnull cwd strings, including empty and relative
values. Null or empty leafId is omitted and leaves the subscription unchanged;
a nonempty leaf requests a subscription switch as well. An invalid leaf fails
atomically on the server, changing neither cwd nor subscription. This updates
the connection default, not a persisted root cwd. cwd_updated is the sole
acknowledgement (not leaf_switched); a subscription switch may also replay
leaf_updated. Default capture follows client send order without requiring an
acknowledgement barrier, but execution/completion can overlap. Other dependent
operations should await their correlated acknowledgement as usual.
listCwd returns cwd_list with exact sorted, deduplicated persisted root cwd
strings in cwds (empty results are []), including missing filesystem paths
and roots without loaded leaves; unused connection defaults are excluded. Optional
cwd_infos summaries and model flags and limits remain accessible in raw JSON.
sessions().list(options) accepts Boolean is_active: true requests only running
or aborting leaves; false, omission, or null does not filter. This differs from
cwd summaries, which also count background work. Other options and response
extension fields remain open.
attachment_chunk, cwd_updated, cwd_list, tool_invoke_result, and
leaf_files_result are reply-only: matched frames
complete the RPC, and late/unmatched frames never enter listener callbacks.
tool_invoke_done is a distinct event. Decoder recognition alone does not own
lifecycles; the facade's toolInvocations() and leafFiles() services provide
invocation ownership and leaf-file registration respectively.
Existing async callback and history APIs are unchanged; callers can attach
whenCompleteAsync with their chosen executor as with other RPC futures.
Events and JSON preservation
EventDecoder and ProtocolEvent live in name.devnull.ezagent.lib.event. They cover
chat/message streaming and turn content, leaf lifecycle and full snapshots,
prompt/agent/turn lifecycle, informational messages, errors, background-task
notifications, all client RPC reply categories and capability wire frames.
Unknown types are retained as UNKNOWN with their original type and fields.
Most categories deliberately use one generic open wrapper. LeafUpdated,
progress and pending questions have richer projections. Unknown pending-question
kinds are rejected like Ruby; unknown fields of recognized kinds survive.
See event/package-info.java.
Snapshots recursively copy nested JSON objects/arrays and preserve explicit
null, zero, false, empty values and unknown members. toJson() returns a fresh
mutable copy, not a reference to internal state. The transport parses strict
JSON itself, retaining integral values as Long/BigInteger and fractional or
exponent values as BigDecimal; it also encodes outbound numbers without
Android's double/long normalization. Existing objects and saved RPC errors are
copied recursively, never serialized/reparsed for snapshots. Read exact number
objects via get/opt: Android's coercing getDouble and its own toString()
can still normalize them. Values already rounded by a caller's parser cannot
be recovered. Android org.json rejects numeric magnitudes whose double value
is nonfinite; these are not supported wire values on that runtime.
Transport correlation precedes event callbacks. Response-only frames (including
effective_config, despite its shared request/reply type) never enter the event
lane. Dual-role acknowledgements such as leaf_created, prompt_accepted,
steer_accepted, leaf_deleted and abort_received can both complete a request
and notify the listener. Unknown reply types have bounded late-reply tombstones
(32 entries), not unbounded replay history; after eviction an unknown late frame
can be delivered as an unknown event. This does not apply to known response-only
types. Event kind is descriptive, not service dispatch or routing authority.
Threads, ownership and lifecycle
- Construction does no I/O. Call blocking
handshake(name, cwd)off the Android main thread, thenstart(listener)exactly once. Startup has no deadline; close the client or interrupt the handshake owner to cancel it. - All ordinary operations return
CompletableFuture; none waits for a reply on the caller/UI thread. Snapshotting, validation and attachment encoding can be substantial for large payloads: prepare/submit images off the UI thread. - Writes use one serialized worker. Ordered events use a separate callback worker. Future completions use separate completion workers; slow continuations should use their own executor. UI callbacks must explicitly dispatch to main. There is no bounded event-consumer backpressure: consume events promptly.
- The client owns both supplied streams and closes them on close, EOF, malformed input, terminal transport failure or listener failure. Stream adapters must unblock reads/writes when closed for full worker reclamation. Cleanup is attempted asynchronously; Java cannot forcibly stop broken I/O.
close()is idempotent and releases pending futures.onClosed(null)means explicit local close; other causes are terminal errors.terminalCause()andcleanupFailure()retain callback/cleanup diagnostics. Throwing from an event listener closes the connection; throwing fromonClosedremains observable.- Close never sends shutdown, abort, unsubscribe, or any other remote mutation. Neither startup nor failure triggers reconnect, replay, retries or daemon autostart. Callers must decide whether and how to establish another connection.
Errors, bounds and cancellation
There is one no-deadline RPC contract:
request(String type, JSONObject fields, String expectedReplyType).
All session/catalog methods use it; there are no timeout overloads, policy
sentinels or timeout exceptions. A still-connected slow RPC stays pending until
a matching response/error, real transport/protocol failure, explicit close, or
future cancellation. This also applies to each canonical-history hydration RPC.
Startup, queued writes and in-progress writes have no elapsed-time watchdog.
Heartbeats are informational traffic consumed internally, never delivered as events, acknowledged or echoed. Their presence, contents and absence cannot complete, expire, renew or revive a request. Silence alone is not evidence of failure. No wire frames or fields are added.
Reply/error, cancellation and closure retire the waiter exactly once. Disconnect fails outstanding requests without replay; a reply already correlated before EOF remains completed. UI owners should keep pending indicators while they still own the operation, and explicitly release ownership on cancellation or navigation rather than treating elapsed time as proof of remote failure. Cancellation does not clear uncertainty about remote mutations or authorize replay.
canonicalHistoryCut/canonicalHistory deliberately hydrate the full cut.
For bounded display, historyIndex validates the full summary envelope without
body reads; historyWindow(leaf, 20, previous) hydrates the newest twenty turns
and retains compatible already-loaded pages. Head body acquisition prioritizes
newest non-system summaries with at most four outstanding reads per operation,
then reconstructs chronological output regardless of reply order. A hidden tip
is preserved exactly, not fetched as an invented visible member. The overload
historyWindow(leaf, count, previous, read, executor, progress) publishes an
index-only notification followed by individual validated HistoryProgress
bodies on a serialized background executor. These are provisional, not
complete canonical/action authority. Its future still returns only a complete,
validated HistoryWindow; full-cut callers retain atomic full-hydration semantics.
No full-index/body-window copies are made per progress notification. Owners must
check their visit/demand again on UI delivery and preserve live revisions.
HistoryRead is an atomic per-operation local cancellation signal; canceling
it or the returned future stops queued admissions and ignores later progress.
Already-admitted network reads are not aborted or subtracted from the concurrency
bound. Executor serialization uses a trampoline, including synchronous futures.
Failure stops new scheduling without automatic retry. The no-callback overload
uses the same head acquisition implementation, not a separate chat path.
olderHistory(window, 10) reads ten missing members of the captured index without
another list RPC; pages remain atomic and sequential. Its signal/executor overload
also stops queued obsolete page reads. Bodies are validated against exact
ID/kind/state/sequence and leaf/root (and parent when supplied by the summary).
Compatible refreshes always re-fetch the recent twenty even when summary
metadata is unchanged; only older validated cached bodies are reused. A large
forward gap stays unloaded until intentional paging.
The server still transfers the entire summary index: there is no new wire
limit/cursor API. Owners must scope previous windows to one connection/visit and
reject stale async results. Window getters are defensive and never trigger I/O.
JsonlClient(input, output) uses the default frame bound;
JsonlClient(input, output, maxFrameBytes) supplies a custom bound. Neither
constructor accepts startup or write deadlines.
The default UTF-8 JSONL frame budget is 48 MiB, allowing the protocol's
32 MiB aggregate binary attachments after Base64 expansion plus an envelope.
It is not an unlimited prompt/text budget, and peer limits may differ. Invalid
UTF-8, malformed JSON, invalid signed-64 itr, or oversized inbound frames are
terminal. An outbound frame rejected before writing any bytes fails only
that operation with FrameRejectedException; sequence numbers are not consumed,
the connection remains usable, and unrelated pending RPCs are untouched.
Invalid method arguments fail synchronously with IllegalArgumentException.
Correlated service errors fail the future with RpcException, retaining code,
message, request ID and an open defensive frame. Startup uses HandshakeException; framing uses
ProtocolException; I/O, local closure and callback failures have separate
exception classes. Adapter error messages are sanitized; raw RPC payloads and
service messages can contain sensitive content and must not be blindly logged.
Cancelling a future clears its
waiter and suppresses a queued write when possible; it is not a remote abort.
Cancellation cannot undo a write already started. A stalled write remains pending;
an actual failed write terminates the connection with ambiguous delivery. Never automatically retry a
mutation. One-way completion confirms writing, not acknowledgement/execution.
Cancelling a derived future (for example listInfo or canonical-history helpers)
does not promise cancellation propagation to constituent RPCs.
Image / remote-path boundary
AttachmentBlob and PendingTurn.withAttachments use the existing inline
attachment_blob contract: matching file_array and meta_files, filenames,
MIME types, decoded byte sizes, and b64/utf8 payloads. Filenames are metadata,
not paths to open. Binary data is limited to 32 MiB aggregate, not 32 MiB per
file without an aggregate bound. The helper and transport allocate in memory;
Android callers must budget memory and perform image work off main.
An Android content:// URI or local filename is not accessible to a remote
agent. Android URI permissions, picking/pasting/sharing, lifetime, preview,
scaling and any separate SSH transfer/staging policy belong outside this
library. It does not open files, invent a path-upload encoding, or treat local
paths as remote references. cwd and other server-side paths refer to the
already-remote filesystem; no Android working directory is substituted.
Deliberate exclusions and integration status
Standalone tool invocation is a client operation, not provider hosting. Other limitations include:
- No capability-provider registration/announcement, heartbeat, tool/plugin/macro handlers, service-side IPC replies, or local background-task execution. Those are hosting/server roles, deliberately outside the Android client scope.
- No Ruby Workflow policy, local endpoint discovery, remote dialing, SSH, credential storage, Hub, graphical viewing, daemon autostart/shutdown automation, retries/replay/reconnect, or on-device sandbox/agent execution.
- No class-per-message exhaustive schema, UI state model or remote attachment download/upload abstraction. Open raw responses are intentional.
- The Android app now consumes the library for native history/subscriptions, prompts/steers/abort, configuration, session/turn/Inbox actions, inline image posting and workflow views. UI, SSH, connection lifecycle, URI grants and attachment memory ownership remain outside this Android-free library.
- Historical image bytes and retained remote capture output have no retrieval operation in the inspected API; open raw responses do not bridge those gaps.
- JVM tests include an Android-compatible org.json runtime, but do not replace device/emulator testing or a real SSH integration test. Bounded Android/SSH checkpoints and their limits are recorded in ../docs/PORT_VALIDATION.md, separately from these fake-transport library tests.
Validation
| 1 | scripts/build :ez-agent-lib:test :app:testDebugUnitTest :app:assembleDebug :app:lintDebug |
:ez-agent-lib:test also runs androidJsonTest, a test-only alternate runtime
for core/facade tests. Tests use in-memory peers and recording transports, not
live hosts. Focused regressions cover a 6 MiB binary image under the default
budget; pre-write rejection while another RPC is pending; nested exact numbers
through outbound frames, inbound events, RPC results and error snapshots; and
stale/duplicate effective-config replies after tombstone eviction. Transport tests
also cover delayed startup, writes and replies past all former deadlines without
heartbeats, informational heartbeat handling, queued/in-flight cancellation,
interrupt/close during startup and real I/O failure. Facade tests
cover all 20 groups sharing one transport, startup, discovery, event access and
close without daemon administration. App tests additionally cover native
controllers, projection/rendering, integration seams, images, commands/settings
and lifecycle/ownership guards. See generated JUnit XML and lint reports under
each module's build folder for current counts/results and the port validation
record for the captured integrated gate and device-test boundaries.
Stable-key leaf file registration
| 1 | client.leafFiles().attach(leafId, "state.ruby").thenAccept(file -> { |
| 2 | String remotePath = file.path(); // owned by the remote service |
| 3 | // Schedule dependent remote work here, after registration succeeds. |
| 4 | }); |
Registration creates no file payload and performs no upload or local read.
Repeating the same key for a leaf returns its existing descriptor. The descriptor
is immutable and toJson() copies unknown descriptor fields. Await the reply
before dependent operations. Errors propagate; the client does not retry, and
failure or cancellation does not promise rollback of a request already sent.