docs/internal/tunnelpipe.md
Addon tunnel pipe
internal/tunnelpipe is an addon-side, per-stream state machine. It carries
opaque bytes in ordinary macro request and reply strings. It does not run I/O,
create sockets or change the service's macro protocol. Capability discovery and
INIT/START belong to the capability adapter, not this package.
Adapter contract
Create one Pipe per stream ID. A single serialized owner handles incoming
macro rows, application queue handoffs, timers and shutdown. Decode and
Frame.Encode handle the pipe rows. IDs are nonempty UTF-8, at most 128 bytes,
without NUL or newlines. ERROR text has the same restrictions with a 256-byte
limit; adapters must choose generic messages without secrets. Data is nonempty,
at most 8192 decoded bytes per row. Sequence and ACK numbers are canonical
unsigned 64-bit decimal integers; sequences start at 1, ACK 0 means none.
The codec bounds rows before decoding. It rejects malformed and noncanonical
rows. No retransmission or replay is provided.
Rows use EzAgent CSV, with standard padded base64 for payloads and a 12000-byte maximum encoded row. These are macro string contents, not new JSONL frames:
| Row | Meaning |
|---|---|
SEND,<id>,<seq>,<base64> | One payload frame |
SEND-ACK,<id>,<ackseq>,<seq>,<base64> | Payload plus cumulative consumption ACK |
ACK,<id>,<ackseq> | Cumulative consumption ACK |
ALIVE,<id> | Reply-slot readiness, not payload credit |
CLOSE,<id> | Immediate terminal close |
ERROR,<id>,<message> | Immediate terminal error |
The client invokes the capability macro; server rows are always replies to client-opened calls. The service only routes those ordinary macro calls and replies. It does not interpret IDs or keep tunnel state. Capability setup for the shipped provider is documented in ez-agent-tunnel.
The producer fragments data and calls Send for each fragment. On ErrCredit,
it retains the unsent bytes and waits for an incoming ACK. A successfully
returned frame is emitted once. Send attaches a pending consumption ACK when
possible. Incoming rows go to Receive; the adapter terminates the stream and
completes its calls on any error. Peek exposes the next contiguous frame.
Only after handing that entire frame to a bounded application sink does the
adapter call Consume. It must not wait for a blocked sink while owning the
state machine. Ack emits a standalone ACK when due. Schedule Deadline and
call Check at wakeup, then Ack if still open. Invoke these methods after
events too, since a threshold can be reached before a timer fires. Credit
and AckDue let a server check readiness before taking a reply slot. If no
slot is available, keep scheduling GapDeadline but defer the ACK deadline
until a slot arrives, rather than repeatedly waking for an overdue ACK.
Each direction allows 256 KiB unacknowledged bytes and at most 1024 outstanding
frames, whichever limit comes first. Receive buffering has the same independent
bounds. ACKs cover contiguous consumed frames and become due at 64 KiB or 200 ms
from first consumption. An unresolved sequence gap times out after 30 seconds;
new traffic does not extend its deadline. Duplicate received sequences are not
delivered twice. There is no half-close. Close and received CLOSE or ERROR
immediately discard queued pipe data. Socket adapters must explicitly coordinate
application completion and delivery before closing; a CLOSE is not proof of a
successful HTTP transaction.
The server owns a Slots queue for pending macro calls. Register each call and
return from its callback immediately. When a data or control frame is ready,
Take reserves the oldest call for an asynchronous reply. At its Deadline,
Idle returns at most one call for an ALIVE reply; reschedule after every event.
Expired closes a stream after the initial 45-second no-slot allowance or the
30-second grace after the last slot returns. At termination, Drain transfers
all remaining calls to the adapter for exactly-once terminal replies. The queue
holds at most 1024 calls. The client uses Shortfall to maintain a target of
2 to 8 idle slots, counting all outstanding calls. This is not a cap on data or
control calls. Send data immediately when byte and frame credit permit;
control calls do not use that credit. The separate call and aggregate resource
limits still apply.
ACK, ALIVE and terminal controls bypass data credit. Returning a macro reply does not acknowledge its request payload. Upload-only streams therefore return ACK-only replies at the consumption threshold or deadline, without waiting for reverse data. The shipped client uses a target of four slots and sends data immediately even when those four calls are still pending.
The stream server promptly returns surplus slots with ALIVE when processing data or ACK calls would leave more than eight held slots. One cumulative ACK can cover many SEND payloads but completes only one macro call; surplus calls must not accumulate until uploads are paced by the idle-reply timer. ALIVE does not acknowledge payload or replenish byte credit. Blocked sinks still stop consumption ACKs and stall the sender at the existing byte window. Idle ALIVE-only calls retain the abandonment timing below.
The idle interval for returning one oldest slot is
min(60 / (pending + 1), 30) seconds. Recalculate after each reply; new calls
can advance but never postpone an existing idle deadline. With no replenishment
or other replies, two abandoned slots drain at 20 and 50 seconds and expire at
80 seconds including grace. Thirty slots expire after about 211.63 seconds.
Operation heartbeats keep held macro calls healthy under the existing service
watchdog; they do not replace the pipe timers or acknowledge bytes. Macro
timeouts, malformed replies and transport failures terminate the affected
stream, with no automatic re-INIT or replay.
Both types are deliberately unsynchronized. An adapter must serialize their methods and keep application reads, writes, transport replies and blocking shutdown outside the state owner. It also owns bounded application queues, transport cancellation, aggregate stream limits and timely timer wakeups.
Local forwarding client
internal/tunnelclient.Listen(ctx, conn, sourcePort) discovers the localport
macro through the existing ezagentapi.Conn, without a leaf, and binds an
available IPv4 loopback port. Port returns that port. Each accepted connection
opens an independent stream to the approved source port; losing one stream does
not stop the listener or replay a request. The listener accepts up to 128 active
streams. Close, context cancellation, or loss of the service connection stops
it and closes active sockets. The caller retains ownership of the service
connection. HTTP paths are not part of tunnel routing.
Frontend wrappers can instead call ListenRPC(ctx, rpc, closed, sourcePort)
with their borrowed RPC and connection-closed signal. Neither entry point owns
the service connection. Done closes when the listener and its streams have
finished, and Close waits for that cleanup.
The source adapter waits for acknowledgments of its response bytes before sending CLOSE at source EOF. The client acknowledges only after writing a complete frame to its local socket, so normal HTTP response bytes reach the local socket before the immediate CLOSE. This is not a half-close protocol: a client that shuts down its write side to mark the end of a request can terminate the stream before a response arrives. Applications must use their own message framing, as HTTP does. CLOSE or ERROR received for other reasons discards outstanding pipe data.
Reusable stream adapters
internal/tunnelstream owns the client and server byte-stream loops used by
localport. Dial(ctx, caller, macro, init) returns a net.Conn after INIT/START.
The caller supplies an exact connection-bound MacroCall implementation and
application fields starting with the tunnel type. The adapter generates the
stream ID. The context owns the entire stream lifetime. The returned connection
supports read/write deadlines through a bounded net.Pipe; Close cancels and
joins its stream owner and held calls. Orderly CLOSE becomes EOF, while protocol,
transport, and ERROR failures return ErrStream. RPC errors, error-valued macro
replies and ERROR rows retain diagnostic text capped at 4096 characters. Only
ErrStream is wrapped, so peer diagnostics cannot add retry classifications.
ServeClient runs the same owner over an already accepted application socket,
as the localport listener does.
NewServer(ServerOptions) binds a server to one macro. ValidateInit checks
canonical INIT fields before admission, and Open returns the application-side
connection. Application policy stays in these callbacks. Call enqueues rows
without waiting for application I/O; Close cancels and joins all streams.
Supply a lifetime Context and call Close when retiring the server. Reply
callbacks must return promptly or be interruptible by the supplied Fail
callback. The bounded reply queue invokes Fail on exhaustion.
A shared NewBudget(128) can cap streams across several provider servers,
including streams still opening. This is separate from the existing per-server
128-stream cap. Open cancellation closes even a socket returned concurrently
with cancellation, never sending a late START. Pipe and slot state remain under
one owner; blocking reads and writes run outside that owner. EOF still waits for
consumption ACKs before CLOSE. There is no polling loop or replay.
The localport command now supplies only its IFO, INIT validation, and loopback TCP dial policy. Its macro name, rows, limits, and frontend listener API have not changed. Destination connection ownership is documented in remote destinations.
Provider-owned LLM exports use these same stream adapters
with type llmprovider. Discovery is outside the byte stream: a minimal client
uses hello, unfiltered macro inventory, validated export names and IFO/LIST.
It opens no stream until execution needs one. HTTP uses a stream per request,
Responses WebSocket retains a stream per socket, and external protocol-1 retains
one per execution. Their setup and runtime destination owners are independent.
Orderly application close allows up to two seconds for already-written bytes to receive consumption ACKs before sending the existing CLOSE row. This preserves WebSocket close replies through the raw splice. Context cancellation, destination retirement, authorization withdrawal and failed transports remain abortive. The external client's final cancel row is still best effort; child retirement and upstream closure do not depend on its receipt.