# Plan: remote printers, reached through an agent Status: **planned; nothing is built.** The owner accepted every proposed default on 2026-11-30 (Decisions), and design.md's Planned next item 3 records them. This plan builds on docs/plans/job-store.md and docs/plans/printers.md and redesigns neither. It fills the seam that printers.md leaves for remote printers (printers decision 6, and its Architecture section THE SEAM FOR REMOTE PRINTERS). Stage 1 needs nothing from those plans. Stage 2 needs printers stage 1a, for its key kind for a table of named tables. Stage 3 needs job-store stage 1c, for `beforeWrite` in `printer.Client`. Stage 4 needs printers stages 1a and 1b and job-store stage 1c. Its anycast part needs printers stage 3; whichever of the two lands second builds that part. Stage 6 waits for the owner's word and job-store phase 5. Each stage runs in its own session, briefed from its section, in the order listed. Stages 2 and 3 land on main together with stage 4 (docs/plans/releases.md decision 11): stage 2 opens a route for agents that do not exist until stage 3, and an agent prints nothing until stage 4. Until then they wait on their branch, rebased as main moves. Every check on a real printer needs the owner's OK. Whichever stage finishes last deletes this plan, its findings with it, and design.md's Planned next item 3. ## Decisions (owner, 2026-11-30) - **Printers on other networks are reached through an Überbringer agent** next to them. - **The agent dials out to the main instance over HTTPS and WebSockets, using Fiber.** No inbound port is opened at the remote site. - **Messages are MessagePack through `github.com/tinylib/msgp`,** at its latest stable release. The generator is pinned in go.mod's `tool` block and run as `go tool msgp`. - **NATS JetStream, embedded etcd and VPN tunnels are not used** for this. The owner accepted the details below on the same day. They are numbered, so the rest of the plan can refer to them. "Main" is the instance that takes jobs, queues and renders them; "the agent" is the process next to the remote printers. For stage 1: 1. **Where rendering happens.** main renders each delivery in full, with the remote printer's profile and options, as for a local printer. The agent receives the finished bytes and writes them unchanged. It never parses or renders a job, fetches no images and needs no profile for printing. - Invariant 1 then holds where it holds today: main renders the whole receipt before anything leaves for the printer. The agent adds one check: it writes only once it holds every byte, matched by length and SHA-256. - Images are fetched by main, through its SSRF guard and its `images.*` exceptions. A URL that only the remote network can reach cannot print there. - Bytes cross the link instead of the JSON job: an image costs up to 64 bytes per dot row (256,000 bytes for one 4,000-dot image), against a few KB of JSON for a URL. A slow uplink at the remote site does not matter, since bytes flow from main to the agent. - Trade-off: larger transfers, and no image only the remote site can fetch. 2. **The messages and their versioning.** - Each WebSocket binary message holds one envelope: a msgp map with the message's type, as a short string, and its body. Bodies are structs that msgp encodes as maps with short field names (`msg:"k"`). Never tuples (`//msgp:tuple`), which cannot gain a field. - Generated decoders skip map keys they do not know (findings, MSGP). So a field may be added in any release, and a reader of an older release ignores it. Renaming or removing a field, or changing what one means, takes a new protocol version. - The protocol version is the WebSocket subprotocol. The agent offers `uberbringer-agent.1` in `Sec-WebSocket-Protocol`, and main accepts the versions it speaks. A later breaking change offers `.2` beside `.1` for at least one release. An agent whose offer main does not speak is refused before the upgrade (decision 7). - `Hello` and `Welcome` carry each side's release version, for the logs. They also carry each side's capabilities as a list of names, so a feature can be added without a new version. - The message types are under Architecture, MESSAGES. - Trade-off: field names cost a few bytes per message; job bytes dominate. 3. **Sizes, chunks and limits.** - Main sends a delivery's bytes as `Data` messages of at most 64 KiB, each naming its attempt key, before it asks the agent to open the printer. The agent assembles them for that printer and acts only on the whole. Offset 0 starts a new buffer. - The agent holds at most one job per printer. Main has at most one attempt in flight per remote printer, through a slot of its own for each (Architecture, A REMOTE SEND, step 1). - `agent.max_job_bytes` caps one job: default 16 MiB, from 1 MiB to 256 MiB, announced in `Hello`. Main checks a rendered delivery against it before it sends anything. One over the cap fails like a render error: nothing sent, no retry. An anycast delivery moves on to its next printer, as after any failure before a byte was sent. - Read limits per WebSocket message: 128 KiB at the agent and 64 KiB at main, since agent messages are small. `query` asks about at most 128 keys at a time, so its reply stays far under main's limit. msgp's `//msgp:limit arrays:1024 maps:64` bounds what a decoder allocates. A message over a limit, or one that fails to decode, closes the link as a protocol error. - Main's writer sends control messages (`Open`, `Go`, `Abort`, `Status`, `Query`) before queued `Data`, so a large transfer holds back neither a status request nor a go-ahead. - No WebSocket compression (`permessage-deflate`). - A 64-KiB frame within decision 9's 30-s write deadline needs about 17 kbit/s, so a slow uplink at main's side still carries image jobs. - Trade-off: a receipt over 16 MiB (about 65 images of 4,000 rows) cannot print remotely. An agent on a small board holds up to 16 MiB per printer. For stage 2: 4. **One binary.** the agent is the same binary, run as `uberbringer agent`. One build, one release, one image and one set of licence notices, and the agent reuses `printer`, `escpos`, the config loader and the logging. - Trade-off: the agent carries the whole server, about 20 MB once Expr is linked (printers decision 10), on boards where it uses a fraction of it. 5. **The WebSocket libraries.** main serves the link with `github.com/gofiber/contrib/v3/websocket` (v1.3.1, the Fiber v3 middleware), and the agent dials with the `Dialer` of `github.com/fasthttp/websocket` (v1.5.12), the library that middleware is built on. One implementation then serves both ends, and both are pure Go. - The middleware refuses a request without an `Origin` header unless `AllowEmptyOrigin` is set. The agent sends none, so the setting is on. Main refuses a request that carries one instead (decision 7). - Trade-off: fasthttp/websocket has had no release since 2025-01-01. A fault there reaches both ends. 6. **Authenticating and authorising agents.** an agent's token is a bearer token like the others, signed with `api.secret` (HS256), with a new scope claim `agt` naming the agent. `uberbringer token --agent ` issues it, refusing `--modules` and `--raw` beside it. - A token with `agt` opens the agent route only and is refused everywhere else with `403` `token_scope`. No other token opens the agent route. `agt` joins `mod` and `raw` among the scope claims, so a malformed one (another type, `null`, another letter case) makes the token invalid (`401`). - Main lists its agents as `[agents.]` tables, named by the subscriptions' rule, from the file only. A table holds `tokens_since` and nothing else yet, and may be empty. A token whose `agt` names no configured agent answers `401` `unauthorized`, as an invalid token does. - Revoking one agent: `tokens_since` (name assumed), a time. A token of that agent issued before it answers `401`. - Rotating: issue a new token and put it on the agent host. Then set `tokens_since` to just before the new token's `iat`, and restart main. The agent reads its token file at each dial, so it needs no restart. Every other token is left alone, and changing `api.secret` still revokes everything. - Main authenticates to the agent through TLS (decision 12). An agent token grants the job bytes of its printers, so it is a secret of the same weight as `api.secret`'s tokens: a 0600 file, never argv or a log. - Trade-off: whoever holds `api.secret` can issue agent tokens, as with every token. A revoked agent is refused only after main's restart (or a reload, once printers stage 2b has one). 7. **The agent route and its refusals.** `GET /api/v1/agent`, an entry in the route table with `Auth`, so it is rate limited like the others, with its case in TestRoutesConform. The OpenAPI document gives its `101` answer and the subprotocol, not the messages, which this plan's MESSAGES table and docs/agent.md describe. - A request that is not a WebSocket upgrade, or offers no subprotocol main speaks, answers `426` with a new code, `upgrade_required`, whose `details` name the subprotocols main speaks. - A request with an `Origin` header answers `403` `token_scope`. Browsers send one, agents do not, and refusing it closes cross-site WebSocket requests even if a browser held a token. - The compress middleware skips this route, and the stage checks that the `101` and the hijack pass the request logger, the recoverer and the Sentry hub unchanged. - Trade-off: one new code and a route outside JSON request and answer. 8. **One link per agent.** an agent has at most one link. A new link for an agent that has one replaces it: the old link closes with close code 4001 and a WARN names the agent and both client addresses. A half-open old link thus never blocks a reconnect. - The attempts in flight on the old link are resolved on the new one (decision 17). - Trade-off: two agents run with one token take the link from each other in turn, which the WARN lines show. Their journals differ, so one never answers for an attempt the other took (decision 13). 9. **Keepalives and dead links.** each side sends a WebSocket ping every 20 s and drops a link that has sent nothing for 60 s: no message, ping or pong. Every write has a 30-s deadline; one that misses it drops the link. - The agent sends `Hello` within 10 s of the upgrade, or main closes the link. Close codes come from RFC 6455's private range: 4001 replaced (decision 8), 4002 protocol error, 4003 refused, 4004 shutting down. - fasthttp clears the connection's deadlines when it hands over an upgraded connection, so `webserver.read_timeout` (15 s) and `idle_timeout` (60 s) no longer apply to it; the link sets its own. - 20 s stays under nginx's default 60-s read timeout for a proxied WebSocket, for a main behind an operator's nginx, and under the idle limits common in home routers' NAT. - Trade-off: about 6 small frames a minute per agent, both ways, while idle. 10. **`/healthz` and the agents.** `/healthz` gains `agents`, one entry per configured agent, sorted by name: `name`, `connected` and `since`, the time of the last connect or disconnect. A remote printer's entry in `printers` gains `agent`. No address, version or token subject appears, since the route is public. The code still follows the default printer alone (printers decision 9). - Trade-off: the public route shows agent names, as it shows printer names. For stage 3: 11. **The agent's config, and printer names on both sides.** - The agent reads its own file, `/etc/uberbringer/agent.toml`, which holds `[agent]`, `[agent.printers.]`, `[log]` and `[sentry]` only. Any other section is an unknown key, so a main config given to the agent fails at start with a clear message. - `[agent]`: `url` (main's base URL), `name`, `token_file`, `ca_file` (empty: the system roots), `state_dir` (empty: a journal in memory, decision 13) and `max_job_bytes` (decision 3). Each scalar key also reads `UBERBRINGER_AGENT_`. - `[agent.printers.]`: `address` and `port` (9100) only, from the file only, as printers decision 2 has for named tables. The agent writes only to printers its own file lists, so a compromised main cannot use it to reach other hosts on the remote network. - A printer has one name, main's. The agent's tables use the names that main's printer tables use. `Hello` lists the names, never the addresses. A remote printer main configures that the agent does not list reads as `unreachable` with a WARN; a name the agent lists that main does not use draws a WARN and is ignored. - Timeouts stay on main (decision 16), which owns each job's time budget and sends them with each request. - Trade-off: a container agent mounts a config, since its printers come from the file. Renaming a printer means editing both files. 12. **TLS from the agent.** `url` must be `https://`, except to a loopback host, for development. The certificate is checked against the system roots, or against `ca_file` alone when it is set. There is no setting that skips verification. The dialler honours `HTTPS_PROXY` from the environment. The token goes in the `Authorization` header, never the URL. - Trade-off: a test set-up with a self-signed main needs `ca_file`. 13. **The agent's journal.** an append-only file, `/agent-journal`, one record per write, each a msgp record with its length and a CRC-32. - Before the first byte of an attempt goes to the printer, the agent appends a `writing` record for its attempt key and syncs it. After the write it appends the outcome, without a sync. - At start, a `writing` record with no outcome becomes `unknown`: the agent stopped while it wrote. One WARN line gives its `job_id` and `printer`. - So "no record" means "nothing written", in the journal that saw the attempt. That is what lets main resolve an attempt whose link was lost (decision 17). - Each journal has an ID (a TypeID, prefix `journal`), made with its file, and numbers its records. `opened` gives main the journal's ID and the number its next record will take. A `query` reply of `none` counts as "nothing written" only from that journal, while its oldest kept record is at or below that number. An emptied state directory, another host, or another agent with the same token therefore never answers for an attempt it did not see. - The newest 10,000 records are kept. Retention counts records, not days, since the agent's clock may be wrong; times in the journal serve its logs only. The file is rewritten (temporary file, sync, rename, then a sync of the directory) at start and whenever it passes 1 MiB, under the one lock that every append takes. - A bad record at the end is a torn tail and is cut. A bad record followed by good ones is damage: the file is moved aside, an ERROR is logged, and a new journal with a new ID starts, so main trusts no `none` about the old one. - With `state_dir` empty, the journal lives in memory and gets a new ID at each start. - A failed `writing` append writes nothing, answers `nothing` and stops the agent. A failed outcome append answers the outcome the agent holds in memory, then stops the agent; at its restart the record reads `unknown`. systemd restarts it either way. - Trade-off: one synced write per receipt on the agent's disk, and our own recovery code. 14. **Reconnecting.** the agent dials again after 1 s, doubling to 60 s, with ±20% jitter, and starts again at 1 s after a link that lived 60 s. A `401`, a `403` or a `426` waits 5 minutes, logged at ERROR once per change of answer, as the ntfy subscriber treats refused credentials. A `429` waits for its `Retry-After`. - The agent dials a new link only after it has closed the old one and every handler of the old link has finished, a write in hand included (Architecture, A REMOTE SEND, agent rule 5). That adds up to one write timeout to a reconnect. - Trade-off: a remote site back from an outage waits up to a minute. 15. **The agent's wait for the go-ahead.** once the agent has opened the printer's connection and said so, it waits at most 15 s for main's go-ahead. Then it closes the connection with nothing written, and a later go-ahead for that attempt is answered "nothing written". - The wait covers main's synced `sending` commit and one round trip. Job-store stage 1a measured that commit at under 10 ms on a VM's virtual disk; on an SD card it is unmeasured. - Trade-off: the printer's connection is held for that long; the printers close idle connections after 90 s (TM-T88VII, TM-m50II) or 300 s (UB-E02, UB-E03). For stage 4: 16. **A remote printer in main's config.** `agent = ""` in a printer table, `[printer]` included, makes it remote. The name must have an `[agents.]` table (decision 6). - A remote printer keeps the layout keys (`model`, `codepage`, `paper_width`, `columns`, `box_line_spacing`, `cut_feed`), the timeouts (`dial_timeout`, `write_timeout`, sent to the agent with each attempt) and the retry keys (`retries`, `retry_delay`). `address` and `port` are refused beside `agent`; they belong to the agent's file. - A remote printer's `dial_timeout` is at most 30 s and its `write_timeout` at most 60 s. The agent caps what it receives at the same values, which agentproto holds, so the agent's stop timeout can be set without main's config (decision 21). - `[printer]` may be remote, so a main on a hosted server can serve printers that are all behind agents. `printer.address` is then required only when `agent` is empty. `UBERBRINGER_PRINTER_AGENT` sets the key; `[agents.*]` comes from the file only. - The address rule of printers decision 3 applies to local printers only; main cannot see where a remote one is. The agent refuses two of its own printers at one address and port. - Trade-off: a printer's keys are split across two files. 17. **A remote send and its outcomes.** the sequence under Architecture, A REMOTE SEND. An attempt ends in one of four outcomes: - `done`: written in full. - `nothing`: no byte reached the printer. The agent says so (a refused dial, a printer not ready at the anycast check, a write that took nothing, a go-ahead it never acted on), or the go-ahead never left main's writer queue. It matches printqueue's `NothingWritten`, so retries and failover treat it as today's dial failure. - `partial`: some bytes went out before a write error. It is today's write error, and job-store decision 23's retry rule applies. - `unknown`: the go-ahead was written and no outcome came back. Main never sends that delivery again. It waits for `result` on the link that carried the go-ahead. If that link drops, it asks the agent's journal on the next link, within the delivery's 2-minute bound (decision 13 says when `none` counts). With no answer, the delivery ends `uncertain`, and one WARN line names it. - An outcome is a string. A missing, empty or unknown one reads as `unknown`, never `nothing`, and `none` is a value of its own, sent only in reply to `query`. - Main waits for `opened` up to the dial timeout plus 10 s. At main's shutdown, an attempt before its `sending` mark sends `Abort` and stays queued; one past its mark gets its `Go` and waits for `result` up to the write timeout plus 10 s, then ends `uncertain`. - This adds one path that writes `uncertain` during a run; job-store writes it only at start. A lost lazy write of it still reads `uncertain` after a restart, so it needs no sync. - Trade-off: a receipt that printed but whose answer was lost needs a person to check the paper. 18. **Deliveries while an agent is offline.** a lane whose printer's agent is offline takes nothing; its deliveries wait queued, in order, and are taken once the agent is back, however long that is, as job-store decision 6 has waiting jobs print however old. - Its printers are marked down while the agent is offline, and so is a printer the agent does not list, for as long as it does not (printers decision 24). Anycast passes over them and moves the anycast deliveries waiting on those lanes on. - The wait never holds an anycast delivery. A lane whose agent is offline counts an anycast delivery it would take as failed before any byte, so it moves on, even when every printer of its list is marked down. - `queue.size` still bounds each lane, so `Submit` answers `queue_full` once a lane is full. With the memory store, the waiting deliveries are lost at main's restart, as today. - An attempt in hand when the link drops is resolved as decision 17 says; it is not counted as a retry. - Trade-off: after a long outage the backlog prints at once, stale receipts included. 19. **Status through the agent.** on demand. Main sends `Status` with its deadline. The agent reads `DLE EOT` with its `printer.Client`, reads a not-ready answer again after 750 ms (printers decision 23's settle function), and answers with the decoded status. Main's 3-s bound for `/healthz` holds; a missed deadline is `timeout`, never a fault. - An agent that is offline, or that does not list the printer, reads `unreachable` (`503` for the default printer). Concurrent reads of one remote printer share one request. - The request carries the model, so a TM-T88VII's `GS r 1` (printers stage 4a) is read at the agent as at main. - Trade-off: each `/healthz` call costs a round trip and a printer connection at the remote site, as it costs a connection locally. Status is read one round trip later than locally. 20. **The agent's answer for a delivery already `uncertain`.** when an agent connects, main asks its journal about each of its printers' deliveries that `Load` turned `uncertain` at main's start. It asks in batches of at most 128 keys, and each key once per run of main. It logs one INFO line per answer (`done`, `nothing`, `partial`, `unknown` or no record). The status stays `uncertain`: a client may already have sent the receipt again. - Trade-off: the answer helps a person who checks the paper, and changes nothing else. For stage 5: 21. **install.sh, and Caddy.** - `install.sh --agent` installs the binary, writes `/etc/uberbringer/agent.toml` from prompts (main's URL, the agent's name, its printers), reads the token on standard input into `/etc/uberbringer/agent.token` (0600, never argv), and installs `uberbringer-agent.service`. It sets up no Caddy and opens no port. Re-runs keep the config and the token. - The unit is the daemon's, sandboxed alike, with `StateDirectory=uberbringer-agent`, so an agent and a main on one host keep separate state. Its stop timeout exceeds the 60-s cap on `write_timeout` plus 10 s (decision 16); systemd's default of 90 s does. - Main's Caddy site gains `stream_close_delay 5m` in `reverse_proxy`. Without it, a reload of Caddy closes every WebSocket at once (findings, CADDY). Caddy needs nothing else to pass the upgrade. - Trade-off: one more unit and mode in install.sh. 22. **Docker.** the same image runs the agent with the command `agent`. The agent's config and token are mounted files, and a named volume holds the journal (`UBERBRINGER_AGENT_STATE_DIR`). The image changes nothing. - docs/docker.md tells operators whose own proxy sits in front of main to pass WebSocket upgrades. nginx needs `Upgrade` and `Connection` set, and closes a proxied WebSocket quiet for 60 s, which the pings of decision 9 prevent. - Trade-off: a container agent needs a mounted config. 23. **Windows.** no Windows release, as for the daemon. `uberbringer agent` builds and runs on Windows for development, with the journal in memory unless `state_dir` is set. - Trade-off: a shop whose only machine is a Windows PC needs a small Linux board. For stage 6, later: 24. **Epson's acknowledgement at the agent** (job-store decision 21). built only with job-store phase 5, and for remote printers at the agent, which owns the connection. The agent appends `GS ( H 48 ` after the bytes, waits for the matching reply and answers `done` with `confirmed`. A capability in `Hello` says it can. Its IDs are counted per printer by the agent; they never cross the link. - Trade-off: as job-store decision 21: the printer's connection stays open until the receipt is out, and a missed reply is still `unknown`. ## Investigation findings Research on 2026-11-30: module versions and source from proxy.golang.org and the module cache, Caddy's and nginx's documentation, RFC 6455, and a map of the repository. Nothing ran against a printer, no `config.toml` was read, and nothing was built. VERSIONS (proxy.golang.org, `@latest`, 2026-11-30) | Module | Latest | Released | Note | |---|---|---|---| | github.com/tinylib/msgp | v1.6.5 | 2026-09-30 | in go.mod already, indirect | | github.com/gofiber/contrib/v3/websocket | v1.3.1 | 2026-11-25 | needs Fiber v3.7.0, the version in go.mod | | github.com/fasthttp/websocket | v1.5.12 | 2025-01-01 | what the middleware is built on | | github.com/coder/websocket | v1.8.15 | 2026-06-15 | no requirements | | github.com/gorilla/websocket | v1.5.3 | 2024-06-14 | | | github.com/lxzan/gws | v1.10.2 | 2026-09-11 | not studied further | | github.com/gofiber/fiber/v3 | v3.7.0 | 2026-11-09 | the version in go.mod | | github.com/valyala/fasthttp | v1.81.0 | 2026-11-27 | go.mod has v1.80.0, indirect | MSGP - Already a dependency: go.mod:44 lists `github.com/tinylib/msgp v1.6.5 // indirect`, and `go list -deps ./cmd/uberbringer` shows `github.com/tinylib/msgp/msgp` and `github.com/philhofer/fwd` linked today, through Fiber's limiter middleware. The runtime adds nothing to the binary, and its notice is already in THIRD-PARTY-LICENSES.md. - The generator is the module's root package (`main.go`), so `go get -tool github.com/tinylib/msgp@v1.6.5` makes it `go tool msgp`. Its go.mod needs `github.com/philhofer/fwd` and `golang.org/x/tools`, which go.mod's tool modules already pull in at newer versions. - Directives (parse/directives.go): `tuple`, `vartuple`, `ignore`, `shim`, `replace`, `compactfloats`, `clearomitted`, `newtime`, `timezone` and `limit arrays:n maps:n marshal:bool` (line 359), which caps the lengths a generated decoder accepts. - Generated decoders skip unknown map keys: gen/decode.go:316 emits `default: err = dc.Skip()`. - The runtime uses `unsafe` unless built with the `purego` tag. It uses no cgo, so `CGO_ENABLED=0` builds hold. FIBER V3 AND ITS WEBSOCKET MIDDLEWARE - `github.com/gofiber/contrib/v3/websocket` v1.3.1 wraps fasthttp/websocket's upgrader. Its `Config` (websocket.go:25-79) has `HandshakeTimeout`, `Subprotocols`, `Origins`, `AllowEmptyOrigin` (default false: a request without `Origin` is refused unless `Origins` holds `*`), buffer sizes, `EnableCompression` and `RecoverHandler`. The handler gets a `*Conn` with the route's params, query, headers and locals copied (lines 183-184, 328-345). - It sets fasthttp's `KeepHijackedConns` on the server (lines 110-118), so fasthttp leaves an upgraded connection open after the handler returns, and the handler owns it. - fasthttp clears every deadline when it hands over an upgraded connection: `c.SetDeadline(zeroTime)` before `hijackConnHandler` (fasthttp v1.80.0, server.go:3086). Fiber's read, write and idle timeouts do not apply after the upgrade. - fasthttp's `Shutdown` waits for connections to go idle and does not close keep-alive ones (server.go:2190-2214); upgraded connections are the handler's to close. Main closes the links itself at shutdown. - Fiber has no WebSocket client. fasthttp/websocket's `Dialer` (client.go) dials with `net/http` types: request headers, `Proxy`, `NetDialTLSContext`. `Conn.SetReadLimit` (conn.go:1191) caps a whole message, all fragments, and returns `ErrReadLimit`; `WriteControl` (line 442) may run beside the one writer. CADDY (https://caddyserver.com/docs/caddyfile/directives/reverse_proxy, § Streaming and § transport http) - `reverse_proxy` proxies WebSocket upgrades with no extra settings and then tunnels both ways. HTTP/2 extended CONNECT (RFC 8441) is not mentioned. - By default a config reload closes every WebSocket, sending a close message to both ends. `stream_close_delay` keeps them open for up to its duration after a reload (no default; the page suggests `5m`). `stream_timeout` closes streams after a set time (no default). - No idle or read timeout closes a quiet WebSocket by default: `transport http`'s `read_timeout` has none. `keepalive` (2 m) concerns pooled idle connections, not tunnels. - `request_body max_size` (https://caddyserver.com/docs/caddyfile/directives/request_body) is described for request bodies only; nothing says it reaches an upgraded connection. install.sh sets it to `webserver.body_limit` (install.sh:384-387). If it did reach the link, it would count what the agent sends to main over the link's whole life, and cut the link after 4 MiB of pongs and replies. This plan assumes it does not; stage 2 checks it through Caddy. - `header_up` applies to every request sent upstream; the upgrade is one, so `X-Real-IP` (install.sh:393) reaches main and the rate limit and logs see the agent's address. NGINX AND RFC 6455 - nginx (https://nginx.org/en/docs/http/websocket.html): `Upgrade` and `Connection` are hop-by-hop and must be set with `proxy_set_header`; before 1.29.7 also `proxy_http_version 1.1`. A proxied WebSocket closes if the upstream sends nothing for 60 s, unless `proxy_read_timeout` is raised or pings reset it. - RFC 6455 (https://www.rfc-editor.org/rfc/rfc6455): control frames carry at most 125 bytes and are never fragmented (§5.5), and may come between the fragments of a message (§5.4). A ping is answered with a pong; an unsolicited pong is a one-way heartbeat (§5.5.2, §5.5.3). The server picks one of the client's subprotocols or none (§4.2.2), and the client fails the connection if the server names one it did not offer (§4.1). Close codes 4000-4999 are for private use (§7.4.2). THE REPOSITORY TODAY - `printer.Client.Send(ctx, data)` (internal/pkg/printer/printer.go:60) dials, sets a write deadline and writes, and discards the count `Write` returns. `Status` (line 82) sends `DLE EOT 1-4` over the same connection slot (`connect`, lines 118-141). job-store stage 1c adds `beforeWrite`; printers stage 3 adds the count (`SendError`, `NothingWritten`) and the status check on an open connection. - `printqueue.Sender` (internal/pkg/printqueue/queue.go:90) and `server.Printer` (internal/app/uberbringer/server/server.go:36) are the interfaces a printer implements; printers.md's seam keeps them. - Tokens: `TokenClaims` (server/auth.go:19-28) has `mod` and `raw`; `scopeClaims` (line 31) lists them, so a malformed one makes the token invalid. `requireBearerToken` (line 86) accepts HS256 only. `uberbringer token` sets `sub` and `iat` (internal/app/uberbringer/cli.go:242-243), and `--ttl` an expiry. - Routes: each is a `Route` in the table (server/routes.go:26-49); `Auth` routes are rate limited per client and answer `Cache-Control: no-store`. The compress middleware runs for every route (server/server.go:175), and the limiter after it (line 179). - Error codes (server/errors.go:26-46): `unauthorized` (401) and `token_scope` (403) exist; nothing answers `426` today. - Webserver defaults: read and write timeouts 15 s, idle 60 s, body limit 4 MiB (internal/pkg/config/config.go:360-371). - serve.go runs the queue, the server and the subscribers in one errgroup (internal/app/uberbringer/serve.go:136-141). - The unit (packaging/uberbringer.service) has `StateDirectory=uberbringer` (line 36) and `RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX` (line 58), which an agent's outbound HTTPS and printer connections fit. - Release archives are built for linux amd64, armv6, armv7 and arm64 only (.goreleaser.yaml:25-33). The Dockerfile's image runs the binary as its entrypoint (Dockerfile:42), so `agent` is a command for the same image. - The config has the sections `webserver`, `api`, `printer`, `format`, `ntfy`, `queue`, `images`, `sentry` and `log` (config.go:49-59); `api.secret` and `printer.address` are required at load. WHERE THE REPORTS DISAGREE OR ARE UNSURE - Whether Caddy's `request_body max_size` reaches an upgraded connection: not stated, and assumed not; stage 2 checks it. - Whether a printer behind a UB-E02 or UB-E03 takes the connection and holds the bytes while it is offline: printers decision 23's paper check. It decides the anycast check at the agent too. - The time of a synced append on an SD card, which bounds decision 15's wait at the agent and main's own mark: not measured. Job-store stage 1a measured main's synced commit on a VM's virtual disk only (under 10 ms); the agent's journal is not measured. - The round trip to a remote site and its effect on `/healthz`'s 3-s bound: not measured. - fasthttp/websocket's long gap since its last release: no advisory was found, and none was searched for beyond the module proxy. Stage 2 runs govulncheck. - The binary's growth from the middleware and fasthttp/websocket: not measured. fasthttp is linked already; stage 2 records the size from the snapshot build. SOURCES - proxy.golang.org: `@latest`, `.mod` files and module sources for the modules in VERSIONS. - Module cache: tinylib/msgp v1.6.5 (`parse/directives.go`, `gen/decode.go`, `msgp/purego.go`, `README.md`); gofiber/contrib/v3/websocket v1.3.1 (`websocket.go`, `go.mod`); fasthttp/websocket v1.5.12 (`client.go`, `conn.go`); valyala/fasthttp v1.80.0 (`server.go`). - Caddy: https://caddyserver.com/docs/caddyfile/directives/reverse_proxy, https://caddyserver.com/docs/caddyfile/directives/request_body. - nginx: https://nginx.org/en/docs/http/websocket.html. - RFC 6455: https://www.rfc-editor.org/rfc/rfc6455. - Epson: as job-store.md's SOURCES for `GS ( H` and printers.md's for the printers' idle time-outs. ## Overview WHAT SHIPS WHEN 1. Stage 1: the wire protocol, `internal/pkg/agentproto`, generated with `go tool msgp`. A library with its tests; nothing calls it yet. 2. Stage 2: main's end of the link: `[agents.]`, agent tokens, `GET /api/v1/agent`, keepalives and `/healthz`'s `agents`. An agent can connect; nothing prints through it. 3. Stage 3: `uberbringer agent`: its config, journal, reconnects, and the printer side of a send and of a status read, tested against stage 2's end in-process. 4. Stage 4: remote printers in main: the `agent` key, the remote sender behind the seam, outcomes and their resolution, lanes that wait while an agent is offline, and status through the agent. Receipts print through an agent. 5. Stage 5: `install.sh --agent`, the agent's unit, Caddy's `stream_close_delay`, and the Docker and agent docs. 6. Stage 6, later: Epson's acknowledgement at the agent, with job-store phase 5. COMPATIBILITY - A config without `[agents]` and `agent` keys runs and prints as today. The agent route exists and refuses every token, since no agent is configured. - Tokens: an older token has no `agt` and keeps every route it had. An agent token is refused on every other route. - New: the route, the code `upgrade_required`, `/healthz`'s `agents` and a remote printer's `agent`. Job status can read `uncertain` during a run, for a remote delivery only (decision 17); its enum already has it from job-store stage 1c. - What prints does not change: a remote printer gets the bytes a local one with the same table would. TestRenderCompat and TestPaperReceipts keep passing. - Main and agent of different releases work together while they share a protocol version (decision 2); each logs the other's version at connect. - A downgrade: an older binary refuses `[agents]` and `agent` as unknown keys, and has no `agent` command. INVARIANTS 1. Nothing reaches a remote printer unless main rendered the whole receipt for it and the agent holds every byte of it, checked by length and SHA-256. 2. No byte of a job reaches a remote printer before main's `sending` mark for that attempt is committed (synced when the store is durable), and after it the agent's `writing` record is synced. 3. The agent writes an attempt at most once. It writes only on a go-ahead for an attempt key it has no record of; a go-ahead for a key it has a record of is answered from the record. 4. Main sends a remote delivery again only after an outcome of `nothing` or `partial`. An `unknown` outcome is never sent again; it ends `uncertain`. job-store's invariant 3 therefore gains no new path. 5. The agent writes only to printers its own config lists. Main never names an address. 6. The link authenticates both ends: TLS authenticates main, and the agent's token the agent. Only an agent token opens the link, and it opens nothing else. 7. Print bytes, tokens and `api.secret` never reach logs or Sentry, at either end. Remote printers' addresses never leave the agent. 8. Main and an agent never both drive one printer (printers.md's seam). 9. Main has at most one attempt in flight per remote printer, through a slot it frees once the attempt's outcome is known or its link has ended. The agent holds at most one job's bytes per printer. 10. job-store's and printers' invariants hold for each remote delivery. ## Architecture THE PICTURE ```text main lane "shop-front" ─▶ render in full ─▶ remote printer ─▶ link "shop" ◀══ Caddy ◀══ wss, dialled by the agent agent link ─▶ bytes held for "shop-front" ─▶ printer.Client ─TCP 9100─▶ printer ``` THE CONFIG ON BOTH SIDES (decisions 6, 11 and 16) Main's config: ```toml [agents.shop] # may be empty # tokens_since = 2026-12-01T10:00:00Z [printers.shop-front] # a TM-m50II at the shop agent = "shop" model = "tm-m50ii" ``` The agent's `agent.toml`: ```toml [agent] url = "https://print.example.com" name = "shop" token_file = "/etc/uberbringer/agent.token" state_dir = "/var/lib/uberbringer-agent" [agent.printers.shop-front] address = "192.0.2.50" ``` - Names and addresses here are examples. - The token is issued on main: `uberbringer token --agent shop`, then written to the agent host's token file through standard input. - `[agents.]` and `[agent.printers.]` use printers stage 1a's key kind for a table of named tables, and the subscriptions' name rule. THE LINK (stages 2 and 3) 1. The agent dials `wss:///api/v1/agent` with its token and offers `uberbringer-agent.1`. 2. Main checks the token (`agt`, `tokens_since`), the subprotocol and the absence of `Origin`, then upgrades. 3. The agent sends `Hello` within 10 s, or main closes the link. Its `name` must match the token's `agt`. 4. Main answers `Welcome`, naming the printers it routes to this agent, or closes with a close code and reason (4002 protocol, 4003 refused). 5. A link with the same agent's name replaces the old one (decision 8). Pings run both ways (decision 9). 6. Each end has one reader and one writer goroutine. Main's writer drains two queues: control first (`Welcome`, `Open`, `Go`, `Abort`, `Status`, `Query`), then `Data`. A large transfer therefore holds back a status request or a go-ahead by one `Data` frame at most. Pings go through `WriteControl`, beside the writer. 7. Main's reader hands each reply to the waiter registered for its attempt key or request number, through a channel with room for one, and never blocks. A reply nobody waits for is logged at DEBUG and dropped, except a late `result`, which resolves an attempt still in doubt. 8. The agent's reader never blocks either. It passes each message about a printer (`data`, `open`, `go`, `abort`, and `query` for that printer's keys) to that printer's goroutine, in the order they arrived. The queue holds one job's `Data` and a few control messages; an overflow is a protocol error. `status` goes to a goroutine of its own, so a status read never waits behind the wait for a go-ahead. 9. At main's shutdown, the links close only after the queue has finished its lanes (Architecture, SHUTDOWN AND RESTARTS), with close code 4004. MESSAGES (stage 1; decision 2) | Type | From | Body | |---|---|---| | `hello` | agent | protocol, version, `run` (a TypeID, prefix `agentrun`), name, printers (names), `journal` (its ID), `oldest` (the number of the oldest record kept), `max_job_bytes`, capabilities | | `welcome` | main | protocol, version, the printers main routes to this agent | | `data` | main | attempt key, printer, offset, final, bytes (at most 64 KiB) | | `open` | main | attempt key, printer, length, SHA-256, `check` (anycast), dial and write timeouts | | `opened` | agent | attempt key, journal ID, the number the next record will take | | `go` | main | attempt key | | `abort` | main | attempt key | | `result` | agent | attempt key, outcome (`done`, `nothing`, `partial`, `unknown`), bytes written, error class and text | | `status` | main | request number, printer, model, deadline | | `status_reply` | agent | request number, the decoded status, or an error class (`timeout`, `unsupported`, `unreachable`, `not_listed`) | | `query` | main | attempt keys | | `query_reply` | agent | journal ID, `oldest`; per key: an outcome, or `none` for no record | - An attempt key is the job's ID, main's printer name and the attempt number: `job_…/shop-front/3`. Main's store already holds all three, so it can ask after its own restart (decision 20). Each delivery's attempt numbers are unique, and attempt numbers go on across the printers of an anycast list (printers decision 22). - The agent sends an error's class and a text without the printer's address; its own log keeps the whole error. No message carries an address. - `Data` arrives in order on one stream. Offset 0 starts a new buffer for its printer, dropping an unfinished one. Any other offset that does not follow, or bytes past `max_job_bytes`, is a protocol error. - Outcomes are strings. A missing, empty or unknown outcome reads as `unknown`; `none` is explicit and appears only in `query_reply`. A REMOTE SEND, STEP BY STEP (stage 4; decisions 15 and 17) Main's lane worker calls the remote printer's `Send(ctx, data, beforeWrite)` (or the checked send, for anycast). The remote printer: 1. Takes its own slot, waiting on the caller's context. It frees the slot once the attempt's outcome is known or its link has ended, so an attempt given up on still holds the printer until the agent has answered. 2. Fails at once with "agent offline" if the agent has no link or does not list the printer: `nothing`, as a dial failure is. 3. Checks the length against the agent's `max_job_bytes` (decision 3). 4. Sends the bytes as `Data`, unless it sent the same bytes for this printer on this link already (the agent keeps the last job's bytes per printer until new `Data` replaces them or the link closes). 5. Sends `Open`. The agent checks length and hash, takes its printer's connection slot, dials, reads status if `check` is set, and answers `opened` with its journal's ID and next record number, or `result` `nothing` with its class. Main waits at most the dial timeout plus 10 s. 6. Calls `beforeWrite`: main's synced `sending` mark. If it fails, main sends `Abort`, and the attempt is `nothing`. 7. Sends `Go`. The agent appends its `writing` record and syncs it, writes, appends the outcome and answers `result`. Main waits for `result` on this link and never sends `query` on it. 8. Returns by the outcome: `done` succeeds; `nothing` returns an error that matches `NothingWritten`; `partial` returns a write error; `unknown` returns an error that ends the delivery `uncertain` (decision 17). If the caller's context ends while this attempt's `Data` or `Go` still waits in the writer's queue, main takes them out under the writer's lock. A `Go` the writer has already taken counts as written. Where the link drops: | Last step main completed | Outcome | Why | |---|---|---| | 1-6, or a `Go` still in the writer's queue | `nothing` | the agent never received the `Go` | | `Go` taken by the writer, link dropped before `result` | resolved by `query` on the next link, within the delivery's bound | the agent's journal says what happened | | the same, and the agent answers `none` | `nothing`, only when the reply's journal ID is the one `opened` gave and its `oldest` is at or below the number `opened` gave | that journal holds a record of every write it allowed | | the same, from another journal (an emptied state directory, another host, another agent with the same token), a journal that no longer covers the number, an `unknown` answer, or no link before the bound | `unknown` | the delivery ends `uncertain` | The agent's rules: 1. It writes only after a `Go` for a key whose `Open` it acted on in this link, and only within decision 15's wait. 2. It appends and syncs `writing` before the first byte. Only a failed `writing` append answers `nothing`. A failed outcome append answers the outcome the agent holds (decision 13). 3. A `Go` or `Open` for a key it has a record of is answered from the record and never written. 4. One goroutine per printer handles that printer's messages in the order they arrived, and holds its buffer, its open connection and its records. A `query` about a key is answered by that key's printer's goroutine, after every message that came before it. 5. When a link ends, the agent marks it stale under each printer's lock. A handler of that link that has not appended its record refuses, writing nothing; a connection waiting for its go-ahead closes. A write already under way finishes and appends its outcome. The agent dials a new link only once all of these have finished, so a `query` on the new link finds every record settled, and an answer of `none` is final. Main's rules: 1. A `Go` still in the writer's queue was never sent, and a dropped link then means `nothing`. Once the writer has taken it, it counts as sent, and its outcome comes from `result` or the agent's journal. 2. An attempt in doubt keeps its waiter across links until it is resolved or its delivery's bound ends. It is asked about only on a later link. 3. A delivery with an attempt in doubt is never sent again, never moved by anycast and never cancelled (its `sending` mark stands, as job-store phase 2b requires). 4. Retries after `nothing` are new attempts with new keys; the agent may still hold their bytes (step 4). THE AGENT'S JOURNAL (stage 3; decision 13) - The journal's ID is made with its file; records are numbered from 1 in it. - Records: `writing` (number, key, printer, time) and the outcome (number, key, outcome, bytes written, time), each msgp with its length and a CRC-32. Times serve the agent's logs only. - One lock covers every append and every rewrite. - At start: read the file. Cut a bad record at the end; move a file with a bad record before good ones aside and start a new journal (decision 13). Turn each `writing` without an outcome into `unknown`, logged at WARN. Keep the newest 10,000 records; write them to a temporary file, sync, rename and sync the directory. - While running: the same rewrite whenever the file passes 1 MiB, the directory synced before the next append. - In memory: a map from key to record, for `query` and for rule 3. - One synced append per receipt; the outcome is appended unsynced. A lost outcome reads as `unknown` after a crash, never as `none`. STATUS (stage 4; decision 19) - Main's remote printer implements `server.Printer.Status` through `status` and `status_reply`, within the caller's deadline, and concurrent callers share one request. - The agent runs `printer.Client.Status` and printers stage 3's settle function, with the profile's status capabilities for the model the request names. - `/healthz` shows a remote printer's entry like a local one's, plus `agent`, and the `agents` array (decision 10). OFFLINE AGENTS (stage 4; decision 18) - A lane whose printer is remote waits, before it takes a delivery, until its agent is connected and lists that printer. printqueue gains an optional interface on a `Sender` for that wait (`Gate`, name assumed); a local printer does not implement it, and its lane behaves as today. - The wait holds unicast and multicast deliveries only. An anycast delivery at a closed gate counts as failed before any byte and moves on (decision 18). - On a link's loss, main marks the agent's printers down for as long as it is offline, and a printer the agent does not list for as long as it does not (printers decision 24). That moves anycast deliveries on. - Deliveries keep their order. A delivery's 2-minute bound starts when it is taken, so waiting for an agent does not use it up. SHUTDOWN AND RESTARTS - Main, durable store: waiting deliveries stay queued, as job-store says. An attempt that has not reached its `sending` mark sends `Abort` and stays queued. One past its mark finishes, as job-store has for a write in hand: main sends `Go` if it has not, and waits for `result` up to the write timeout plus 10 s; with none, the delivery ends `uncertain`. Then the links close. - Main, memory store: as today; the attempt in hand finishes the same way. - Main's restart: `Load` turns remote deliveries in `sending` `uncertain`; when each agent connects, main queries them and logs the answers (decision 20). The agent keeps an unanswered `result` in its journal. - The agent, at SIGTERM: closes connections still waiting for a go-ahead, with nothing written; finishes a write in hand within its write timeout; sends its `result`; closes the link with code 4004. - The agent's restart: records left `writing` become `unknown`. Main's attempts in doubt resolve through `query` as the table above says. LOCKS AND DEADLOCKS - Main: the lane's worker blocks in `Send` on a channel the link's reader fills; the reader never waits on a lane, the queue or the store. The order inside main stays job-store's: the delivery lock, then the store. The agent's printer slot is not a lock in main, so no cycle crosses the link. - The agent: a status read waits on the printer's slot while a send holds it and fails with `timeout` at main's deadline, as a local read does today. The wait for `Go` is bounded (decision 15), so a lost main never holds a printer. - Each end's writer has a bounded queue. A full queue waits on the caller's context, and a write that misses its 30-s deadline drops the link, so a stalled peer cannot block the other end for ever. - The tests for stage 4 include a large transfer beside a status request (the status answers in time) and a peer that stops reading (the link drops within the deadline). PACKAGES - `internal/pkg/agentproto` (new): the message types, their generated code, the envelope, the subprotocol names and the limits. Imports msgp only. - `internal/pkg/agentlink` (new): main's end: the link manager, the links and the remote printer that implements `printqueue.Sender` and `server.Printer`. Imports agentproto and escpos. It reads and writes through a small interface that both fasthttp/websocket's `Conn` and the middleware's `*Conn` satisfy, so tests can pair two ends in memory. - `internal/pkg/agent` (new): the agent: its dialler, journal and printers. Imports agentproto, printer, escpos and fasthttp/websocket. - server: the route, its middleware and the scope check; it hands an upgraded connection to an interface in `Deps`, so it does not import agentlink. - internal/app: `[agents]`, the constructor per printer that chooses `printer.Client` or the remote printer (printers.md's seam), and the `agent` command. - Imports: agentlink → agentproto, escpos; agent → agentproto, printer, escpos; internal/app → agentlink, agent. printqueue and printer import none of them. LOGGING AND PRIVACY - Main logs each connect and disconnect at INFO with the agent's name, client address, release version and `run`; a replaced link at WARN (decision 8); a refused upgrade as any refusal, by its request line. - Every worker line of a remote attempt carries `printer`, `agent` and the attempt number, never bytes. - The agent logs its link, each attempt's outcome by `job_id`, `printer` and attempt number, and its printers' addresses at start, as main's start-up line does. - Sentry: each end reports its own unexpected errors once, tagged with the agent's name and printer, never content. A dropped link is not a fault and is not reported. CONFIG, PACKAGING, DOCKER - Main: `[agents.]` (stage 2) and a printer's `agent` key (stage 4), each with its default, validation, `configs/config.example.toml` entry and docs/configuration.md entry. - The agent: `configs/agent.example.toml` and docs/agent.md (stage 3), a new page that the release archives carry, README's Documentation table lists and CLAUDE.md's "Read first" names. - install.sh `--agent`, `packaging/uberbringer-agent.service`, Caddy's `stream_close_delay` and docs/docker.md: stage 5. ## Phases ### Stage 1: The wire protocol **Goal.** `internal/pkg/agentproto` defines the messages of the link and their encoding, generated by `go tool msgp`. A library with its tests; nothing calls it yet. Needs nothing from the other plans. Decisions 1-3. **Work.** - go.mod: `go get -tool github.com/tinylib/msgp@` (v1.6.5 at the time of writing). The runtime becomes a direct requirement when this stage's code imports it. govulncheck after the change. - agentproto: - messages.go: the types of the MESSAGES table, `msg` tags with short names, `//go:generate go tool msgp -tests=false` and `//msgp:limit arrays:1024 maps:64`. - messages_gen.go: generated, never edited. - envelope.go: `Encode(msg)` and `Decode(b)`, the type names, the subprotocol names (`uberbringer-agent.1`), the chunk size, the read limits and the caps on dial and write timeouts (30 s and 60 s). `Decode` refuses an unknown type with a protocol error. - The gate: CLAUDE.md's generated-files line and `.gitea/workflows/test.yml` add `internal/pkg/agentproto/messages_gen.go` to the `git diff --exit-code` check. CLAUDE.md's "Read first" says the file is generated and never edited by hand. - If gofmt or goimports flag the generated file, the `go:generate` line pipes it through them, so the gate passes unchanged. Docs - docs/development.md: the package and the generator. - No CHANGELOG entry: nothing a user sees. **Tests.** - Each message round-trips. - A body with a field this version does not know decodes, and the field is skipped; a body missing a field decodes it as zero. - An empty or unknown outcome decodes as `unknown`. - An array or map over its limit is refused; so is an unknown type. - FuzzDecode: no panic, and no allocation beyond the read limit. **Commits.** 1. Pin the msgp generator as a tool 2. Add the agent link's message types **Done when.** The full gate passes, `go generate ./...` leaves the tree unchanged, and govulncheck is clean. ### Stage 2: Main's end of the link **Goal.** Agents configured on main can connect with their tokens and stay connected. `/healthz` shows them. No printer is remote yet. Needs stage 1 and printers stage 1a. Decisions 4-10. **Work.** internal/pkg/config - `Agents map[string]AgentConfig` (`agents`) with `TokensSince`, through printers stage 1a's key kind; names by the subscriptions' rule; from the file only. internal/app/uberbringer/server - auth.go: `Agent string` (`agt`) in `TokenClaims`, in `scopeClaims`; agent tokens refused on every route but the agent route (`403` `token_scope`); `tokens_since` and the configured names checked for agent tokens (`401`). - routes.go: `GET /api/v1/agent` with `Auth`, its `101` and refusals; `upgrade_required` in errors.go. - The handler: the middleware with `AllowEmptyOrigin`, the subprotocols from agentproto, a refusal for `Origin`; it hands the connection to `Deps.Agents` (an interface). - server.go: the compress middleware skips the route. - handlers.go: `/healthz`'s `agents`. internal/pkg/agentlink - The link manager: one link per agent, the newest winning (decision 8); `Hello` within 10 s and `Welcome`; the reader and the two-queue writer; pings and the 60-s silence rule; close codes; `Close` for shutdown. internal/app/uberbringer - cli.go: `token --agent `, refusing `--modules` and `--raw` beside it and a name not in `[agents]`; its subject defaults to `agent:`. - serve.go: the manager in the errgroup; the links close after the queue has stopped. Dependencies - `github.com/gofiber/contrib/v3/websocket` at its latest stable release, which brings `github.com/fasthttp/websocket`, in the commit that first uses them. `go generate ./...` regenerates THIRD-PARTY-LICENSES.md and `licenses_embed.md` in that commit, and govulncheck runs. Docs - docs/api.md: the route, `upgrade_required` in the codes table, `token_scope` for agent tokens, `/healthz`'s `agents`. docs/swagger.json regenerated. - docs/security.md: agent tokens, rotation with `tokens_since`, what an agent token grants. - docs/cli.md: `token --agent`. - docs/configuration.md: § agents. - configs/config.example.toml: a commented `[agents.]`. - design.md: "Tokens carry their scope" gains `agt`. - docs/development.md and CLAUDE.md's Layout: `agentlink`, and the import line agentlink → agentproto, escpos. - CHANGELOG: under Added, the agent route and agent tokens. **Tests.** - server: TestRoutesConform's case; an agent token on `/api/v1/print` answers `403`; a print token on the agent route answers `403`; a malformed `agt` answers `401`; a token issued before `tokens_since`, or naming an unconfigured agent, answers `401`; a plain GET answers `426` `upgrade_required`; an `Origin` header answers `403`; the compress middleware leaves the upgrade alone; the schema test holds `agents`' fields. - agentlink, on `testing/synctest` with an in-memory pair: - `Hello` in time gives `Welcome`; none within 10 s closes the link; a name that differs from the token's closes it; - a second link for one agent replaces the first, with code 4001 and one WARN; - a peer silent for 60 s is dropped; pings keep an idle link up for a simulated day without a leaked goroutine; - a peer that stops reading drops the link within the 30-s write deadline; - a message over the read limit, or one that fails to decode, closes the link. - internal/app: a real upgrade over a socket, with fasthttp/websocket's `Dialer` and a real token; `token --agent` refusals. **Commits.** 1. Add agent tokens, scoped to the agent route 2. Add the agent route and its link 3. Show connected agents in /healthz Commit 1 also adds `[agents.]` and `tokens_since`, with their example and docs. **Done when.** - The full gate passes, the generated files included; govulncheck is clean. The snapshot build, which builds every target with `CGO_ENABLED=0`, passes, and its size is recorded in the commit that adds the dependencies. - Through Caddy on a test host, without a printer: a test agent (stage 2's test dialler) connects over `wss`, and a link quiet for 10 minutes stays up. A Caddy reload with `stream_close_delay` keeps it; without it, it drops and reconnects. Unsolicited pongs totalling more than `webserver.body_limit` cross from the test agent to main and the link stays up; if it drops, the finding is corrected before stage 5. ### Stage 3: The agent **Goal.** `uberbringer agent` reads `agent.toml`, connects to main, and handles `data`, `open`, `go`, `abort`, `status` and `query` for its printers, keeping its journal. Tested against stage 2's end in-process; main sends it nothing outside tests until stage 4. Needs stage 2 and job-store stage 1c. If printers stage 3 has not shipped, this stage brings forward its `SendError` with `NothingWritten` and its move of the settle function into `printer`, each in a commit of its own. Decisions 11-15. **Work.** internal/pkg/config - `LoadAgent`: `[agent]`, `[agent.printers.]`, `[log]` and `[sentry]`; defaults and checks (an `https` URL or a loopback one; a token file that exists; at least one printer; `max_job_bytes` from 1 MiB to 256 MiB); variables for the scalar keys. internal/pkg/agent - run.go: the dial loop and backoff (decision 14), `Hello`, the reader and writer, pings, close codes, shutdown. - printers.go: per printer a `printer.Client`, the job buffer, the lock, and the send: `Send` with a `beforeWrite` that answers `opened`, waits for `go` (decision 15), appends and syncs `writing`. The checked send when `check` is set. - journal.go: the journal and its recovery (decision 13). - status.go: `status` through `printer.Client.Status` and the settle function. internal/app/uberbringer - cli.go and agent.go: the `agent` command, its `--config`, logging and Sentry, and `--check` (name assumed), which loads and checks `agent.toml` and exits, so that install.sh can check a config before it restarts the unit. Docs - docs/agent.md (new): what the agent is, its token, its journal and what it logs. It is the reference for every key of `agent.toml` and its variables, as docs/configuration.md is for `config.toml`, which links to it. .goreleaser.yaml's archives, README's Documentation table and CLAUDE.md's "Read first" name it. - docs/development.md and CLAUDE.md's Layout: `agent`, and the import line agent → agentproto, printer, escpos. - configs/agent.example.toml (new). - docs/cli.md: `agent`. - CHANGELOG: under Added, `uberbringer agent`. **Tests.** - config: the agent's file loads; a main config given to the agent is refused by its unknown sections; `http://` to a host that is not loopback is refused. - agent, against stage 2's end in memory and a fake printer listener: - `data`, `open`, `go` print the bytes once and answer `done`; - a refused dial, a printer not ready at the check, a length or hash mismatch, and a `go` after the 15-s wait each answer `nothing`, and the printer gets no byte; - a write cut short after some bytes answers `partial` with the count; - a second `go` for a key answers from the record and writes nothing; so does an `open` for a key with a record; - a `go` read from a link marked stale writes nothing; the agent dials again only after a write in hand has finished; a `query` on the next link then answers from a settled record or `none`; - the journal: a `writing` record without an outcome becomes `unknown` at start; a torn tail is cut; a bad record before good ones starts a new journal with a new ID; only the newest 10,000 records stay; a failed `writing` append writes nothing and stops the agent; a failed outcome append answers the real outcome; an append from one printer during another's rewrite is kept; - a `query` sent right after a `go` for the same key is answered after the write; - `data` at offset 0 replaces an unfinished buffer; a status read is answered while another printer's goroutine waits for a go-ahead; - a memory journal says so in `Hello`; - backoff and the 5-minute wait after `401`, on synctest; - SIGTERM closes waiting connections with nothing written and finishes a write in hand. - TLS: `ca_file` trusts a test CA; an unknown certificate is refused. **Commits.** 1. Report how much of a job a send wrote 2. Move the settled status read into the printer package 3. Load the agent's config 4. Add the agent's journal 5. Connect the agent to main 6. Print on an agent's printers 7. Answer status requests at the agent Commits 1 and 2 only if printers stage 3 has not shipped. **Done when.** The full gate passes. No paper yet: main routes nothing to an agent until stage 4. ### Stage 4: Remote printers **Goal.** A printer table with `agent` prints through that agent. Sends follow A REMOTE SEND; lanes wait while their agent is offline; status comes through the agent. Needs stage 3, printers stages 1a and 1b, and job-store stage 1c. The anycast check needs printers stage 3. Decisions 16-20. **Work.** internal/pkg/config - `agent` in `PrinterConfig`, `[printer]` included; `address` and `port` refused beside it; the name must be in `[agents]`; `printer.address` required only without `agent`; a remote printer's `dial_timeout` at most 30 s and `write_timeout` at most 60 s. internal/pkg/agentlink - remote.go: the remote printer: `Send` with `beforeWrite`, the checked send, the outcomes and their errors (`NothingWritten`; one that ends the delivery `uncertain`), the waiters in doubt across links, `query`; `Status` with one shared request; the offline wait. internal/pkg/printqueue - The optional wait before a lane takes a delivery (`Gate`, name assumed). - A send error that says `uncertain` finishes the delivery `uncertain`, with its WARN line. internal/app/uberbringer - serve.go: the constructor per printer chooses `printer.Client` or the remote printer; links lost and regained mark printers down and up; at each connect, the query of deliveries `Load` turned `uncertain` (decision 20). - server: `/healthz`'s `agent` on remote printers. Docs - docs/configuration.md § printers: `agent`, the keys a remote printer keeps and refuses. - docs/api.md: `uncertain` during a run for remote deliveries; `/healthz` for remote printers. docs/swagger.json regenerated. - configs/config.example.toml: a commented remote printer. - docs/agent.md: the send in plain words, what `uncertain` means there, offline agents. - design.md: a decision "Remote printers are reached through an agent", with this plan's decisions; "Render, then send" for remote printers. - CLAUDE.md: "Testing on the printer": how to print through an agent. - CHANGELOG: under Added, remote printers. **Tests.** - agentlink, with a fake agent that stops at any step: - a link lost before `Go` gives `nothing`, and the retry prints once; - a link lost after `Go`: a `done` answer finishes the delivery `done`; `nothing` retries; `partial` follows today's retry rule; `none` from the journal `opened` named, covering its number, retries; `none` from another journal ID, from a journal whose `oldest` has passed the number, or no link before the bound, ends `uncertain` and never sends again; - main never sends `query` on the link that carried the `Go`; - a context that ends while `Data` or `Go` waits in the writer's queue takes them out, and nothing is written; the next attempt waits for the slot until the agent has answered; - a query for 1,000 keys goes in batches that fit the read limit; - a late `result` resolves an attempt in doubt; - a delivery in doubt is neither moved by anycast nor cancelled; - over `max_job_bytes`: failed, nothing sent; - status: a reply in time, a missed deadline (`timeout`), an offline agent (`unreachable`), two callers sharing one request; a large transfer does not delay a status reply past its deadline. - printqueue: a lane whose gate is closed takes nothing and keeps order, and moves an anycast delivery on at once, also when every printer of its list is marked down; it takes again once open; a full lane answers `queue_full`; shutdown with a delivery waiting at the gate keeps it queued (durable) or fails it (memory). - internal/app: two fake agents and a local fake printer; an anycast rule passes over an offline agent; main's restart with an `uncertain` remote delivery logs the agent's answer and keeps the status. **Commits.** 1. Add the remote printer to agentlink 2. Wait for an agent before a lane takes a delivery 3. End a delivery uncertain when a send's outcome is unknown 4. Print through an agent 5. Read a remote printer's status through its agent Commit 1 is library code with its tests; commit 4 adds the `agent` key and the wiring that makes it reachable. **Done when.** - The full gate passes. - Paper, with the owner's OK, one short receipt at a time, waiting for his report after each. Main and an agent both run on the workstation; the agent's file lists the TM-T88IV at 192.168.1.245, and main's `[printer]` has `agent` set, so main never dials the printer itself: 1. The pinned note receipt, `internal/pkg/receipt/testdata/paper/note.json`, through the agent. Look at the line breaks, the characters and the cut: as when main prints directly. 2. Stop the agent, send the same receipt, see it `queued` and `/healthz` show the agent disconnected, then start the agent. The receipt prints once. - TestPaperReceipts already pins the note's bytes, and printing through an agent does not change them, so no new pin is needed. ### Stage 5: Packaging **Goal.** `install.sh --agent` sets up an agent; main's Caddy site keeps links through a reload; docs/docker.md covers the agent and proxies in front of main. Needs stage 4. Decisions 21-23. **Work.** - install.sh: `--agent`: the binary, `agent.toml` from prompts, the token from standard input into a 0600 file, the unit; re-runs keep the config and the token; no Caddy. Main's site gains `stream_close_delay 5m`. - packaging/uberbringer-agent.service: the daemon's sandbox, `ExecStart=… agent --config /etc/uberbringer/agent.toml`, `StateDirectory=uberbringer-agent`. - .goreleaser.yaml: the archives carry the agent's unit and example config. - docs/install.md: § the agent; docs/docker.md: the agent container and proxies in front of main; docs/agent.md: links to both. - CHANGELOG: under Added, `install.sh --agent`; under Changed, the Caddy site keeps WebSockets open through a reload. **Tests.** - The snapshot build; the archive lists the new files. - install.sh's agent mode run on a scratch host or container by the owner, if he wants; the script's shellcheck, if the repository runs it. **Commits.** 1. Keep agent links open through a Caddy reload 2. Install an agent with install.sh --agent **Done when.** The full gate and the snapshot build pass; docs/install.md's steps were followed once on a test host. ### Stage 6: Epson's acknowledgement at the agent (later) Built only on the owner's word, with job-store phase 5. The agent appends the process-ID request after the bytes, waits for the reply, and answers `done` with `confirmed`; `Hello` lists the capability. Decision 24.