docs/internal/agenthub-gateway.md
AgentHub gateway v1
The gateway owns the current client-entry frame, endpoint listing and selection, invitation carrier, authorization barrier, and opaque application tunnel. It does not own invitation cryptography/state or choose between invitation engines. The direct-handshake review owns the ceremony.
Frame and controls
Each outer frame is U32BE body length, one kind byte, then payload. Kind 1 is
bounded version-1 JSON control; kind 2 is opaque tunnel data. The maximum body
is 1 MiB. Decoders check size before allocation and become terminal after
truncation or protocol error.
| 1 | u32be body_length |
| 2 | u8 kind # 1 = JSON control, 2 = tunnel bytes |
| 3 | byte payload[body_length - 1] |
Controls cover hello, chunked endpoint listing, target selection, cancellation,
invitation exchange, status/error, and tunnel handoff. Invitation controls carry
one current encoded invitation payload; gateway validates only the closed
bounded envelope and direction. Exact fields, limits, negatives, and status
values are frozen in gateway.json,
gateway-list.txt,
gateway-state.json, and check-gateway.rb. The independent Ruby checker
verifies both literal list variants. Normal endpoint rows have exactly
endpoint_id (64 lowercase hex), endpoint_spki (canonical unpadded base64url
PKIX DER matching the ID), published and available (booleans),
access_revision (positive U64), and revocation_tags (zero to 1,024 sorted
unique lowercase 64-hex tags). available implies published. A conflict row
instead has exactly endpoint_id, conflict:true, binding_generation
(positive U64), and one or two sorted distinct authority fingerprint IDs in
origins. No conflict row carries a selectable SPKI or tags. The client derives
origin KEY CHECK words and check bytes locally for display. These are public
facts, not route hints or authorization data. The gateway never sends aliases,
profiles, client identities, ACLs, sockets, paths, peer addresses, raw conflict
frames, or private descriptors.
The list count is the total number of distinct endpoint IDs, at most 1,024.
Chunks have sequential zero-based U8 indices, one to 128 strictly increasing
rows, a maximum encoded body of 1 MiB and at most 128 chunks; list_end.chunks
exactly matches the number received. The sender packs rows until the next row
would exceed the entry or encoded-byte cap, rather than truncating a current
tag window. The client rejects early end, missing, duplicate or reordered rows,
wrong counts or indices, and extra chunks. List ownership covers independently
copied rows and one encoded write. Gateway reserves the worst-case list working
space before querying the store or learned owner; the client reserves its
result capacity before copying. A single 10-second read deadline covers the
complete reply. Saturation fails the list rather than silently omitting rows.
Decoded invitation buffers have explicit ownership and clearing. Scanner and encoder mechanics belong to gateway code and tests, not this boundary page.
Connection lifecycle
Production authenticated gateway admission belongs to the service's
ResourceGatewayConnection, staging transfer and NetworkAccounting owners.
They key the 1,024 lifetime ceiling and eight-per-client limit by the
TLS-authenticated stable authority SPKI. The old 64-global/four-per-source
ordinary gate is removed. PreTLSAdmission owns only generic pending/source
capacity, deadlines and TLS worker pacing. A source IP cannot limit an already
authenticated client's gateway allowance. Physical and gateway capacity remain
charged until descriptor closure and serving-owner join. See the
capacity ownership map.
An authenticated client hello establishes admission state and one permitted
operation. An admitted client may list the bounded combined projection, choose endpoint
access or application open, and receive ready only after the selected direct
path and capacity are reserved. Published local endpoints remain available even
when their AF_UNIX socket is missing; that failure is checked at open time.
Verified learned endpoints, signed current notices and conflicts appear in the
same list. A withdrawn row can remain for its notification window, but cannot
be selected. A learned remote row is available only under the routed-readiness
conditions below, including one learned from a directly connected Peer. The
server refuses selection of an unavailable row before opening a tunnel and never
substitutes a local path. Endpoint TLS and the
origin's exact ACL remain mandatory for direct and routed application rows.
Admission and endpoint authorization use the shared current invitation session through gateway carriers. Malformed input, unavailable work, terminal state, and invalid proof use one bounded generic failure path followed by close. A blocked write retains its connection and reservation until its owner joins.
Application control stays separate from invitation control. After exact endpoint
authorization, inner endpoint TLS and the application codec perform
open/open_ok. Tunnel bytes are opaque to gateway JSON parsing, and the resulting
application stream carries ordinary ez-agent-jsonl/v1.
Capacity, authorization, and TLS
The public accept owner reserves generic global/per-source capacity before TLS. Only authenticated TLS plus valid state selection transfers ownership into a finite role budget. Invitation proof pressure cannot consume ordinary application capacity. Cancellation and every terminal path release exactly once.
Public TLS shares eight active workers and 32 rolling starts per second. Each observed source IP may hold two workers and consume eight starts in that window. Excess work waits within the original absolute five-second entry deadline, with no privileged allowance for an unverified role. Worker release and rolling expiry wake pool waiters without millisecond polling. Pending lease closure wakes only that lease's acquisitions, not unrelated TLS waiters. A single pool timer retires idle start events; the queue holds at most 32 events, and the worker-source map holds at most eight keys. Closing a pending lease or cancelling a waiter never returns a still-running worker's charge. Its actual handshake return releases that charge exactly once.
This leaves capacity for other sources during one-source partial or rapidly failing TLS traffic, not at arbitrary aggregate saturation. NAT clients share the same cold-start allowance and may time out. See the configuration policy and limitations.
Authorization changes serialize through the service registry. Completed leases are tied to exact epochs so a delayed close cannot retire a replacement.
hoptls owns closed TLS roles and exporters. Gateway receives authenticated
identity and binding. Claimed and approval content supplies no replacement host
or port. The same public accept owner may dispatch pairing ALPN into its distinct
authenticated budget, but the pairing handshake still owns pairing messages and activation;
pairing never enters client gateway control.
Authority
- Invitation bytes/session/store policy:
invitationwire,invitation,store. - Composition and capacity:
gateway,service, and their tests. - Literal frame authority: fixtures.
- Client merge and Add agent:
clienttransport,frontend,store. - Directory sync lists verified learned state; routing and remote opening are separate owners. Pairing uses its own closed TLS role.
Routed readiness and status
Keep the exact codec, list rows and control fields in gateway/codec.go. No
OriginRoot, route, attempt, episode, private error or new API field goes on this
wire. Service supplies a private full selection/prepared-owner snapshot and
validation hook while keeping PrepareEndpoint's current signature. Remote
availability is verified current publication AND unique usable endpoint binding
AND a current selectable route to its verified OriginRoot AND installed local
production carrier support. ProjectEndpoints currently marks remote rows
Unavailable; its later service-supplied availability callback must use those
conditions. Local published endpoints keep their direct availability rule,
including missing-socket handling at open. A list row is never an open lease.
Selection, after prepare, before ready, and again before tunnel_ok must recheck exact ID/SPKI, OriginRoot, binding generation, publication/conflict token, selected complete route/token and immutable admitted attempt ownership. Service owns those private rechecks as specified in production composition. A newly selected route is not equality with the captured attempt. No local PrepareDirect fallback, inferred authority trust or second endpoint socket. ready promises reserved handler/carrier capacity, not endpoint authorization or successful service dial. Inner endpoint TLS and application open remain next.
The current pumpTunnelIn admits only KindTunnel after tunnel_ok, and the
current output pump writes directly through Encoder. Production composition
must replace concurrent encoder use with one reserved, joined writer. The
existing Encoder has no general concurrent-frame serialization guarantee.
One fixed 32 KiB pending tunnel buffer, one fixed status slot and one terminal
slot live within the prepared gateway owner. Do not launch a goroutine or retain
a buffer per notification. Finish the currently admitted complete frame before
a status; never interleave a JSON status with bytes of a KindTunnel frame.
Select terminal ahead of unsent tunnel/status, then current lifecycle status,
then tunnel. A blocked physical write has a fixed two-second
production output delivery deadline and caller cancellation; failure aborts and joins,
not a second writer on the same TLS conn. Apply the bounded deadline to the
whole admitted output frame so a blocked tunnel frame cannot hide terminal
state forever. This is local carrier failure, not a remote application timeout.
Status uses ONLY these existing Message projections:
| Event | Existing fields |
|---|---|
| Declared attachment failure while Session retained | TypeStatus, StatusRecovering, RemainingMS |
| Authenticated replay/live completion | TypeStatus, StatusRecovered |
| TerminalFailed after tunnel_ok | TypeStatus, StatusTerminal, CodeCircuitFailed |
| Causal TerminalResourcePressure after tunnel_ok | TypeStatus, StatusTerminal, CodeResourceLimit, explicitly approved Hub-to-client exit feedback |
| TerminalJoining or TerminalClean | No failure status; join pending or ordinary clean close |
| TerminalCallerLost | Joined cleanup; any failure delivery is best effort only |
remaining_ms is ceil(max(0, fixed_grace_deadline - now) / 1ms), capped at
65000, sampled when the writer admits the frame. It is not a fresh timeout.
If the Session is still recovering at equality, publish terminal, not more time. One
recovering notification per episode suffices; there is no periodic network
countdown or request protocol. Coalesce repeated observations of the same
phase/episode. Preserve the causal pair if an episode recovers before the
writer runs: the fixed slot contains a phase/generation snapshot plus a pending
recovered bit, so recovering precedes recovered for that episode. A completed
but unsent pair retains its original deadline for remaining_ms calculation,
using zero when it has passed; it cannot resurrect recovery or cause terminal
expiry of an already-live Session. A later
failure may replace an unsent earlier pair with the newer recovering snapshot;
never emit a lone old recovered against a newer failed attempt. TerminalFailed
clears unsent nonterminal status and is attempted exactly once before failed
close. TerminalCallerLost joins with best-effort delivery only. TerminalClean
clears unsent lifecycle work and closes normally without a failure frame.
TerminalJoining leaves the writer waiting for final classification or an actual
caller/output failure; it is not circuit_failed. This finite status policy
carries no replay history.
The Session observation API supplies local phase/terminal class/joined flag, episode/deadline and one atomic Changed pulse under its mutex. Gateway samples one exact retained owner. SessionTerminal or attachment Done alone cannot emit circuit_failed, and an old attempt completion cannot emit recovered. The Consumer owns Wait and the final classification pulse; the sole writer must not block on that join to classify a close. Observation can begin during prepare, but statuses are enabled only after tunnel_ok because current clienttransport recognizes them in the tunnel loop. Failure before ready uses existing selection error codes. Carrier failure after ready but before tunnel_ok uses TypeError/CodeCircuitFailed and close, not out-of-state status. At the tunnel barrier, classify the captured prepared owner before returning ordinary projection unavailability. Losing the sole route after ready must not hide known carrier loss as endpoint_unavailable. Publication or candidate invalidation without known carrier loss still returns endpoint_unavailable. Recheck the owner again after reprojection before sending tunnel_ok. A pending carrier that failed before tunnel cannot pass the tunnel recheck, even if it recovered in the meantime. It requires a fresh user selection rather than silently opening. This keeps the current client state machine unchanged.
After tunnel_ok, input still accepts only KindTunnel. Status does not reopen selection, invitation control or the outer parser. The client may continue reading queued inner bytes while its existing tunnel decoder reports status; no status is injected inside endpoint TLS or application JSONL. The writer, observer, tunnel pumps, prepared handler and caller bridge all join before the prepared owner releases reservations. Status delivery is best effort when the outer client is gone. It cannot delay Session terminal cleanup indefinitely.
Prepared-owner integration
The service dispatcher now installs production remote preparation independently of remote availability. Ready and tunnel boundaries call the captured owner's PreparedValidator. The gateway reserves tunnel working space before invoking preparation. Production reservations also expose the same retained Session observation/clock and nonwaiting reason-aware Abort. One output writer emits existing status and tunnel frames, with one bounded pending chunk and status slot and a two-second whole-frame write deadline. It samples Changed directly; there is no observer worker. Clean joined completion emits no circuit_failed.
The local unbuffered pipe and client Tunnel now distinguish directional output seal from Abort. Reverse EOF cannot seal the client sender before reciprocal inner TLS close_notify. Normal output drains while the terminal parent remains live, within the first 30-second close bound; malformed frames, pressure, cancellation and failure abort then join. No new JSONL fields are introduced.
Successful endpoint invitations seal inner TLS output without sealing the raw carrier. The server retains reverse input through reciprocal authenticated EOF, retires the challenge, then closes the carrier. This prevents reciprocal close_notify from hitting a closed endpoint pipe or raw EOF from exposing an unretired challenge slot. The existing invitation read bound and caller deadline cover this join; bare EOF, extra frames and cancellation remain failures.
Ordinary service construction installs the production Server.RemoteAvailable
composition; there is no fixed-path fixture override.
Directional Session EOF may precede reciprocal FIN and native settlement. The writer withholds outer TLS EOF until the same observation reports joined completion. It can then close cleanly or deliver the existing terminal failure. Production Session observation retains the most recent episode's original grace deadline after resumption. The gateway also preserves a sampled recovering deadline defensively for another PreparedObserver that omits it after transitioning live, until the causal pair is delivered. A writer that misses the whole recovery exchange while writing a frame still emits that episode's recovering/recovered pair in order. No new timer, notification worker or history queue is introduced.
Selection evidence
The optional production availability callback receives the projected endpoint
and returns its current complete route candidate only when the production
carrier is installed. ProjectEndpoints alone still leaves learned remote rows
unavailable. Server.ProjectedEndpoints adds service capability and route
reachability and returns a release for its bounded projection storage.
Private row fields retain the directory admission token and route candidate. The explicit codec emits neither. TypeSelect copies the full row, including its canonical SPKI and exact selection evidence, into PrepareEndpoint. A new list or select samples current state; neither silently retargets an existing owner. The prepared validator checks the captured evidence before ready and tunnel_ok, not just endpoint ID/SPKI or the newest route. Remote failures remain bounded unavailable/circuit errors with no direct preparation fallback. Signed conflict, withdrawal and replacement state, unavailable rows, and client-private approved descriptors retain their existing meanings. An available unapproved opaque row is still not a normal selectable agent in the client.
See the service checkpoint for exact barriers and scope limits.
Production recovery evidence
The production checkpoint records actual gateway frames through a bounded forwarding TLS/framing fixture, not a scripted status source. Two path-recovery episodes yield recovering/recovered causal pairs; fixed grace equality yields one terminal/circuit_failed frame. Clienttransport consumes these outside inner endpoint TLS and exposes the latest values through a local observer on its application handle. Exact application JSONL continues without status injection, second selection or hello. The observer adds no wire fields; its local meaning distinguishes received status, local failure and joined transport closure.
A sole-writer regression holds one admitted physical frame across a complete recovery episode. That frame remains intact, followed by recovering then recovered, or terminal in place of the unsent pair. Existing two-second whole frame delivery, grace equality, EOF join and bounded status-slot tests remain. The production pressure checkpoint proves recovering status progresses while origin DATA is paused and recovery controls complete before queued output drains. No path, attempt, detector, private error or application context enters a status. Caller loss and admission revocation can remove the outer TLS connection, so status delivery remains best effort while local joined cleanup is mandatory.
Approved client-entry pressure terminal
The user explicitly approved Hub-to-client exit feedback, for a local or remote
Hub. This permission is separate from private configuration JSONL approval.
This section and the independent internal/agenthub/testdata/trust/gateway.json
literals define the following gateway-v1 addition:
| 1 | {"v":1,"type":"status","state":"terminal","code":"resource_limit"} |
The active client-entry gateway terminal is a closed union of circuit_failed
and resource_limit. It has exactly v, type, state and code, no
remaining_ms, subtype, text, path or additional field. Duplicate fields,
unknown codes, null values and other status/code combinations are rejected.
Framing is unchanged: a four-byte big-endian body length, JSON kind byte 01,
then the JSON object. Version remains 1.
The sole gateway output writer emits resource_limit only when a local entry
owner detects pressure and publishes TerminalResourcePressure. A received
circuit RESET is a generic terminal failure, not entry-local pressure evidence.
A hop RESET follows ordinary attachment recovery with the existing fixed grace.
Origin failures, expired grace and unknown causes remain circuit_failed or
generic transport failure.
The status attempt is best effort under the existing finite whole-frame write
deadline. There is no delivery guarantee, ACK, replay or retry.
Clienttransport consumes an accepted pressure terminal outside endpoint TLS,
retains it in its local observer, and propagates ErrResourcePressure through
native application-handle Wait/Close and frontend errors. Failed endpoint TLS,
application open and EzAgent hello startup inspect their joined transport result
before redaction, even before a ready frontend client exists. Missing or truncated
notices stay generic failed, never successful application EOF. The private
entry session's emitted sample accepts the same closed union, records only a
completed local encoder write and makes no client-receipt claim.
Application JSONL bytes, the EzAgent RPC/service protocol and all inter-Hub fields remain unchanged. The service sees application socket closure only. Backpressure, required-output drain, fixed write deadlines, joined teardown, once-owned release and sibling isolation retain their existing owners.
Projection admission at gateway capacity
Chooser projection admission is derived from the retained local/directory rows,
not a fixed maximum-list prepayment. Both owners reserve under the lock used to
copy their rows. Local record canonicalization and learned conflict-selection
scratch are admitted before parsing. The combined projection reservation covers
local/learned row copies and candidate-container growth and remains held through
list encoding. Learned allocation grows the projection's byte charge without
adding another owner count beside its encoder or prepared tunnel. Slow TLS output cannot release the projection early.
MaxEndpoints, MaxListTags, chunk/frame maxima and parser limits are unchanged.
See service ownership
and service projection tests.