Repository navigation
Description
Part of #1110.
Scope
A lease holder with its own WebSocket client opens GET /v1/leases/{id}/tunnel on a lone worker, names reverse tunnels, and its leased Android emulator's or phone's connections to those ports arrive on the socket. This adds the tunnel error codes and the frame codec to the contract (one protocol bump), the optional tunnel module (off by default) with its worker side over a lease socket, the daemon's ctx.deviceTcp (supports, reverse) implemented by the Android driver and the fake driver, a loopback TcpListener port and TcpStream.end(), and rule cleanup at socket close, reclaim and daemon start. The configuration reference, the errors reference and the remote-agents page describe tunnels on a lone worker. The relay through a gateway is #1113's, both sides.
Kept whole: the codec, the module and the device port are one behaviour (a reverse tunnel that works); a split would ship a codec nothing uses or a port nothing calls.
In short
After this PR, with capabilities.tunnel.enabled: true on a worker, a holder opens a WebSocket to /v1/leases/<lease-id>/tunnel with its token, sends HELLO {"tunnels":[{"kind":"reverse","devicePort":5173}]}, and gets READY with the same list. The device's connections to localhost:5173 then arrive as OPEN, and bytes flow under a 262144-byte window per direction. A HELLO that cannot be met gets REFUSED {code, message} and close 4003, and nothing it named stays set up. Closing the socket removes the device rule before lease end lets reclaim run. Android reclaim, and the worker's start, remove stale reverse rules on devices proved Simlock's own.
flowchart LR
C[holder's WebSocket] -->|/v1/leases/id/tunnel - new| M[tunnel module - new]
M --> P[ctx.deviceTcp.reverse - new]
P --> A[Android driver: loopback listener + adb reverse --no-rebind - new]
R[reclaim, daemon start] --> X[remove stale reverse rules, this device's forwards - new]
HELLO names |
Today | After |
|---|---|---|
| reverse 5173 on an emulator lease | no route (404) | READY |
| reverse 5173, already reversed on the device | — | REFUSED TUNNEL_PORT_IN_USE |
| reverse 80, reverse 70000 | — | REFUSED TUNNEL_BAD_PORT |
nine tunnels (one HELLO, or across sockets) |
— | REFUSED TUNNEL_LIMIT |
| any tunnel on an iOS lease | — | REFUSED TUNNEL_UNSUPPORTED |
forward (until #1115) |
— | REFUSED TUNNEL_UNSUPPORTED, forward tunnels are not available yet |
If this goes wrong, a user sees a device rule left behind after the socket closes, another lease's rule removed, or one slow connection stall the others.
Technical spec
Facts
Commit 31ff66e.
| # | Fact | Source |
|---|---|---|
| F1 | Optional modules are listed in the registry: agent-device, input, stream | src/module-registry/index.ts:6-10 |
| F2 | A capability is on only when enabled; it defaults to false unless the definition sets enabledByDefault |
src/core/config.ts:923, src/modules/AGENTS.md:18 |
| F3 | The input module is the model: a definition with http route data, a worker side, a lease route and socket |
src/input/definition.ts:12-18, src/input/AGENTS.md:1-20 |
| F4 | Lease WebSocket upgrades go to /v1/leases/{id}/<module>; the server pings every 15 s; messages up to 1 MiB |
src/ports/upgrade-router.ts:31-39 |
| F5 | Lease routes answer the lease's owner and operators, others 404; tokens skip the Sec-Fetch-Site rule |
src/http/AGENTS.md:42, src/http/app.ts:825-832 |
| F6 | Modules never import drivers; device ports reach them through WorkerContext, built in the daemon, keyed (platform, device, signal) |
src/modules/AGENTS.md:5, src/modules/types.ts:190-197, src/daemon/main.ts:519-522 |
| F7 | Lease end reaches a module through beforeDeviceReclaim, cut at the lease's end wait |
src/modules/types.ts:154, src/leasing/lease-release-coordinator.ts:380-387 |
| F8 | Emulators use the driver's configured adb server port (default 5038); phones the default server 5037, behind DefaultAdbServerGate |
src/drivers/android/AGENTS.md:126, src/drivers/android/default-adb-server.ts:3, src/drivers/android/AGENTS.md:101-102 |
| F9 | Emulator reclaim acts on a serial only after #serialIsOwn (#284); other paths shut the emulator down |
src/drivers/android/index.ts:1133-1140 |
| F10 | At start the driver reattaches running emulators in its own port range | src/drivers/android/index.ts:890-898 |
| F11 | Neither reclaim touches reverse or forward rules today | src/drivers/android/index.ts:1102-1162, src/drivers/android/physical-handler.ts:197 |
| F12 | adb reverse tcp:<d> tcp:<h> makes a device connection to 127.0.0.1:<d> reach a host listener on 127.0.0.1:<h>; reverse --remove clears it |
run 2026-10-30, adb 37.0.0, a physical phone: host listener received "reverse-ok\n"; reverse --list empty after |
| F13 | reverse --no-rebind on a port already reversed exits 1 with error: cannot rebind existing socket on stderr |
run 2026-10-31, adb 37.0.0: {"code":1,"stderr":"adb.exe: error: cannot rebind existing socket"} |
| F14 | adb forward --list prints one line per rule, <serial> <local> <remote> |
run 2026-10-31, adb 37.0.0: "RX8M80YA1JX tcp:18790 tcp:18791" |
| F15 | adb forward --remove-all removes every forward listener on the server, for every device |
adb adb.cpp killforward-all → remove_all_listeners() (#1110 round-0 check) |
| F16 | TcpStream has readable, write, close and no half-close |
src/ports/tcp-stream.ts:10-14 |
| F17 | The contract's error table holds each code's HTTP status and CLI exit; a contract helper with no wire shape is listed for the bump check | src/contract/errors.ts:289-340, .agents/scripts/protocol-bump-check.mjs:13-18 |
| F18 | Tests drive the daemon with FakeDriver from core's testing barrel |
src/core/fake-driver.ts:1, src/daemon/input-lease.e2e.test.ts:11 |
| F19 | Leases on running emulators and on phones survive a worker restart (ADR 0019); startup restores them before serving | docs/internal/adr/0019-startup-ends-every-lease-whose-device-is-not-running.md:30-36, docs/internal/flows/startup.md:63-65 |
| F20 | adb reverse --list prints one line per rule, <transport name> <device side> <host side>; the sweep reads the third field |
run 2026-10-30, adb 37.0.0, a physical phone, after adb reverse tcp:18765 tcp:18766: UsbFfs tcp:18765 tcp:18766 |
| F21 | A lease-end hook is called with an already-aborted signal, and not awaited, while the daemon stops or is in maintenance | src/leasing/lease-release-coordinator.ts:380-386 |
| F22 | #1107 adds contract error codes, a protocol bump and a WorkerContext field beside inputs |
#1107 Modules touched; src/modules/types.ts:221, src/daemon/main.ts:519-521 |
Modules touched
Searches: optionalModules, WorkerContext, openInput, reclaim( and #reattachRunningEmulators in src/drivers/android, ERROR_TABLE.
src/contract/—tunnel-frames.ts(codec, limits, tags, the reserved port range; in the bump check's helper list), the nineTUNNEL_*codes; protocol bump.src/tunnel/(new module):definition.ts,worker.ts,sessions.ts,index.ts,AGENTS.md,CLAUDE.md.src/module-registry/— registertunnelModule.src/modules/—WorkerContext.deviceTcp(ModuleDeviceTcp, by-shape type and its type test).src/daemon/— builddeviceTcpfrom the catalog; the wiring test.src/core/—DeviceTcpon the driver catalog;FakeDriver's device-tcp.src/drivers/android/—supports,reverse; reclaim and start cleanup.src/ports/—tcp-listener.ts(new, with its fake);TcpStream.end().docs/internal/ARCHITECTURE.md— the module's row.website/— configuration reference, errors reference, remote-agents page (lone worker).
flowchart LR
http[http upgrade] --> tunnel[tunnel module*]
tunnel --> codec[contract tunnel-frames*]
tunnel --> ctx[modules WorkerContext.deviceTcp*]
ctx --> daemon[daemon main*]
daemon --> catalog[core driver catalog*]
catalog --> android[android driver*]
android --> listener[ports TcpListener*]
sequenceDiagram
participant C as Holder's socket
participant M as tunnel module
participant A as Android driver
participant D as Device
C->>M: HELLO {reverse 5173}
M->>A: deviceTcp.reverse(platform, device, 5173)
A->>A: listen on a free 127.0.0.1 port h in 47000-47999
A->>D: adb reverse --no-rebind tcp:5173 tcp:h
alt cannot rebind / other adb error
A-->>M: TUNNEL_PORT_IN_USE / TUNNEL_FAILED
M-->>C: REFUSED, close 4003 (earlier tunnels removed)
else
M-->>C: READY
D->>A: connect 5173 → h
A->>M: onConnection
M-->>C: OPEN conn 1, then DATA/CREDIT/END
end
Surface and extension points
src/tunnel/index.tsexportstunnelModule, anOptionalModuleDefinition(nametunnel), assrc/input/index.tsdoes.ModuleDeviceTcp:supports(platform, device);reverse(platform, device, devicePort, signal)→{hostPort, onConnection(listener), close()}; the catalog answers{unsupported}for a platform with no implementation, asopenInputdoes.connectis simlock tunnel forward: reach a leased device's port from the caller's machine #1115's.
Contract and event changes
This PR bumps the protocol by one: nine error codes (TUNNEL_UNSUPPORTED 422, TUNNEL_PORT_IN_USE 409, TUNNEL_BAD_PORT 422, TUNNEL_LIMIT 409, TUNNEL_FAILED 502, TUNNEL_UNAVAILABLE 503, TUNNEL_DISCONNECTED 503, TUNNEL_CALLER_PORT_IN_USE 409, each CLI exit 1; TUNNEL_LEASE_ENDED 410, CLI exit 14). tunnel-frames.ts is a helper with no wire shape of the daemon contract. No event.
Wire input from the socket follows #1110's "bad frames" row: HELLO JSON at most 4 KiB, tunnels 1 to 8 entries (a 9-entry one is TUNNEL_LIMIT), kind reverse or forward, devicePort an integer.
Other code on the same state
Searches: "reverse" in src/ (0 production hits), beforeDeviceReclaim (5), --no-rebind (0), forward --list (1, a no-device check).
device.execrunningadb reverseon the same device: a rule it set first makes the tunnel's--no-rebindfail (TUNNEL_PORT_IN_USE); a rule it sets after without--no-rebindreplaces the tunnel's, and those connections stop. The docs say so.- Two sockets on one lease share the 8-tunnel count under one lock; each removes only its own rules.
- Reclaim and lease end: the module's hook removes its rules, awaited, before reclaim; reclaim then removes any left. A rule removal never runs after reclaim began.
- Daemon start: the sweep runs before any lease is served, only on emulators proved Simlock's own (The Android startup sweep attaches another Simlock instance's emulators to this instance's adb server #264's case is untouched), and removes only rules whose host side is in 47000-47999. Leases kept across a restart (F19) keep every rule their holder made; their tunnels, which died with the old daemon, lose theirs.
- Phones (decided in delivery, pending the maintainer): reclaim and the start sweep act on emulators only. On an enrolled phone Simlock removes only the
reverserules its own tunnels set, when their socket closes, through the gate's version check; a lease end with an already-aborted signal still removes a phone's tunnel rules, since a phone's reclaim removes none and so cannot race them; it never runsreverse --remove-allor removes aforwardrule on a phone (safety rule 1, ADR 0022 §3). A tunnel rule a daemon crash or a failed removal leaves on a phone stays until the phone reboots or a person removes it; the docs say so. Its port is never handed to another tunnel: at start the worker reads (never changes)reverse --liston every phone it proves enrolled and keeps each port in 47000-47999 a rule points to reserved, and a phone's reclaim reads its rules again and frees only the ports no rule points to (decided in delivery, pending the maintainer). - The loopback listener (decided in delivery, pending the maintainer): it accepts any connection that reaches the worker's loopback port, so while a tunnel is open another lease's device on the same worker (an emulator reaches the worker's loopback at 10.0.2.2, any device through an
adb reverseset withdevice.exec) or a local process can reach the holder's tunnelled port. No listener check is added; the docs say so. - A lease-end hook called with an already-aborted signal (F21) skips its removals on an emulator, whose reclaim removes the rules, so no removal runs after reclaim began; on a phone it still removes the tunnel's rules, since a phone's reclaim removes none (decided in delivery, pending the maintainer).
- device.rotate: rotate a leased iOS simulator over the contract, HTTP and the client #1107 changes the same contract table, protocol line and
WorkerContextlines (F22): this task depends on it.
Failure modes
| Call | Outcome | What happens | Limit, counted from |
|---|---|---|---|
deviceTcp.reverse |
ok | READY once every tunnel is set |
10 s per adb call, from the call |
deviceTcp.reverse |
cannot rebind existing socket |
TUNNEL_PORT_IN_USE; earlier tunnels removed |
— |
deviceTcp.reverse |
other adb error or timeout | TUNNEL_FAILED with adb's message cut to 200 characters |
10 s |
| loopback listen | every port of 47000-47999 busy | TUNNEL_FAILED no free tunnel port on the worker |
— |
deviceTcp.supports |
false | TUNNEL_UNSUPPORTED |
— |
| rule removal on close | adb error | warn; the loopback port stays reserved, connections closed at once, until reclaim |
10 s |
| reclaim or start cleanup | adb error | warn; reclaim and start go on |
10 s per call |
| loopback accept | a 257th connection | closed at once | — |
A daemon restart with tunnels open leaves reverse rules into 47000-47999; the start sweep removes them before any lease is served on idle emulators; on a leased device it removes nothing and keeps those ports from the next reverse until its reclaim (safety rule 2).
Rules in play
- ADR 0054 §1-7 (PR docs(adr): 0054 a lease holder tunnels device ports to its own machine #1111): the module, the socket, limits, reverse, the context port, cleanup, error codes.
- ADR 0049: "the module never checks ownership" — the HTTP layer does (F5).
- Modules manual: "Never imports: … drivers" —
ctx.deviceTcp(F6). - Contract manual: a new error code goes in
ErrorDetailsMapandERROR_TABLE, with a bump.
Tests
Seam: the module's worker side over a MemoryLeaseSocket with a fake deviceTcp, modelled on src/input/worker.test.ts; the wiring on src/daemon/input-lease.e2e.test.ts; the driver on src/drivers/android/index.test.ts.
- A holder opens the tunnel socket on a lone worker, sends
HELLOwith reverse tunnels and getsREADY; a device connection arrives asOPENand bytes flow both ways under credit; cases: one tunnel; two tunnels; data both ways;ENDfrom each side half-closes; a reader that grants no credit pauses only its connection; the 257th connection is reset. - A holder's
HELLOthat cannot be met is refused whole withREFUSEDand close 4003, and nothing it named stays set up; cases: iOS leaseTUNNEL_UNSUPPORTED; reversed portTUNNEL_PORT_IN_USE; port 80 and 70000TUNNEL_BAD_PORT; a ninth tunnel across two sockets and a 9-entryHELLOTUNNEL_LIMIT; adb errorTUNNEL_FAILEDafter an earlier tunnel opened (it is removed); aforwardtunnel before simlock tunnel forward: reach a leased device's port from the caller's machine #1115TUNNEL_UNSUPPORTED. - A holder that sends a bad frame is refused
BAD_REQUESTand closed 4003, while a frame for an already closed connection is ignored; cases: frame beforeHELLO; secondHELLO; unknown tag;DATApast the window; id never opened;CREDITfor a connection just closed → ignored, other connections go on. - When the socket closes, the lease ends or the daemon stops, the worker removes the tunnel's rules and listeners and closes its connections; cases: client closes; lease ends → 4001 with the reason, rules removed before the hook returns; drain → 1001; a removal that fails keeps the port reserved.
- A caller reaches the tunnel route on a lone worker only when it may; cases: capability off → 404; another holder's lease → 404; holder → upgraded; operator → upgraded.
- Android reclaim and daemon start leave no stale rule on an emulator, and never touch another lease's or a phone's; cases: reclaim, emulator; reclaim, phone removes no rule; a rule made through exec; another device's forward on the same server stays; reclaim of an emulator not proved its own removes nothing; start removes rules into 47000-47999 on idle owned emulators; start on an idle phone removes nothing and keeps the ports its rules point to from the next
reverse; a phone's reclaim frees only the ports no rule on it points to; on a leased device it removes nothing and the ports its rules point to are skipped by the nextreverse; a leased device's rule to another port stays; a removal on an already-aborted lease-end hook is skipped on an emulator (reclaim does it) and still runs on a phone. - The Android driver's
reversesetsadb reverse --no-rebindto a loopback listener and removes it on close; cases: configured emulator server port; phone port 5037 behind the gate; the listener's port is in 47000-47999, a busy one skipped, all busy →TUNNEL_FAILED;cannot rebind existing socket→TUNNEL_PORT_IN_USE; another adb failure →TUNNEL_FAILED.
Done when
- The Tests lines pass.
tunnelModuleis in the registry, off by default;simlock statusshows thetunnelcapabilityoffuntil enabled.- The configuration reference lists
capabilities.tunnel.enabled; the errors reference lists the nine codes; the configuration reference says the worker reserves loopback ports 47000-47999 for tunnels; the remote-agents page describes the tunnel socket on a lone worker, says other leases' devices on the same worker can reach a tunnelled port while it is open, and says a tunnel rule a crash leaves on a phone stays until the phone reboots; ARCHITECTURE has the module's row.
Out of scope
- The relay through a gateway (The gateway relays the tunnel socket to the lease's worker #1113),
simlock tunnel(simlock tunnel: reverse a leased device's port to the caller's machine #1114),forward(simlock tunnel forward: reach a leased device's port from the caller's machine #1115). - iOS.
Depends on
- None
Written by an agent.
Activity
test: a holder's HELLO that cannot be met is refused whole with REFUS…
feat(tunnel): a HELLO that cannot be met is refused whole with its co…
test: bytes flow both ways under a 262144-byte window per direction, …
feat(tunnel): data flows both ways under a per-connection window and …
test: a bad frame is refused BAD_REQUEST and closed 4003, a frame for…
feat(tunnel): a bad frame is refused BAD_REQUEST with close 4003 (cal…
test: the worker removes a tunnel's rules and closes its connections …
feat(tunnel): closing the socket, the lease's end and a drain remove …
test: a caller reaches the tunnel route on a lone worker only when it…
feat(tunnel): a holder or operator reaches the tunnel route on a lone…
feat(android): the driver's reverse sets adb reverse --no-rebind to a…
feat(tunnel): an iOS lease is refused TUNNEL_UNSUPPORTED and a driver…
test: two tunnels, END half-closes from each side, and a device conne…
feat(tunnel): END half-closes a connection from each side and a devic…
fix(ports): a peer's half-close ends a TCP stream's readable (callsta…
5 remaining items
chore(tunnel): Fallow findings of the tunnel cycles (callstackincubat…
test(tunnel): the audit's missing cases, the reclaim fixtures and the…
fix(android): hold tunnel ports until reclaim, keep a leased device's…
chore(tunnel): Fallow findings of the review fixes (callstackincubato…
fix(tunnel): the lease's end waits for a removal the socket's close b…
test(tunnel): the start sweep is awaited before the daemon serves (ca…
fix(android): reclaim and the start sweep never remove a rule on a ph…
docs(tunnel): phones keep their rules, a tunnel's port is open to the…
fix(tunnel): on a phone an aborted lease end still removes the tunnel…
feat(tunnel): reverse a leased Android device's port over a lease Web…
feat(tunnel): the gateway relays the tunnel socket to the lease's wor…