Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
6a87186
test: a holder opens the tunnel socket, sends HELLO with reverse tunn…
leonardoxr Oct 31, 2026
98cfb13
feat(tunnel): a reverse tunnel answers READY and carries device conne…
leonardoxr Oct 31, 2026
21516b5
test: a holder's HELLO that cannot be met is refused whole with REFUS…
leonardoxr Oct 31, 2026
e308d56
feat(tunnel): a HELLO that cannot be met is refused whole with its co…
leonardoxr Oct 31, 2026
2084eab
test: bytes flow both ways under a 262144-byte window per direction, …
leonardoxr Oct 31, 2026
c4f93c0
feat(tunnel): data flows both ways under a per-connection window and …
leonardoxr Oct 31, 2026
42899a1
test: a bad frame is refused BAD_REQUEST and closed 4003, a frame for…
leonardoxr Oct 31, 2026
0751cc1
feat(tunnel): a bad frame is refused BAD_REQUEST with close 4003 (#1112)
leonardoxr Oct 31, 2026
7afdb40
test: the worker removes a tunnel's rules and closes its connections …
leonardoxr Oct 31, 2026
746b8d0
feat(tunnel): closing the socket, the lease's end and a drain remove …
leonardoxr Oct 31, 2026
e330b80
test: a caller reaches the tunnel route on a lone worker only when it…
leonardoxr Oct 31, 2026
45ad185
feat(tunnel): a holder or operator reaches the tunnel route on a lone…
leonardoxr Oct 31, 2026
38af91d
feat(android): the driver's reverse sets adb reverse --no-rebind to a…
leonardoxr Oct 31, 2026
cd00d68
feat(tunnel): an iOS lease is refused TUNNEL_UNSUPPORTED and a driver…
leonardoxr Oct 31, 2026
0759879
test: two tunnels, END half-closes from each side, and a device conne…
leonardoxr Oct 31, 2026
661ddab
feat(tunnel): END half-closes a connection from each side and a devic…
leonardoxr Oct 31, 2026
617b3dd
fix(ports): a peer's half-close ends a TCP stream's readable (#1112)
leonardoxr Oct 31, 2026
29c7aec
docs(tunnel): the tunnel socket on a lone worker, its capability, por…
leonardoxr Oct 31, 2026
5a8d932
test: a socket closing while hello awaits reverse leaves no rule set …
leonardoxr Oct 31, 2026
bb30a14
fix(tunnel): a rule that arrives after the socket closed is removed (…
leonardoxr Oct 31, 2026
12d19c7
feat(android): reclaim and daemon start remove stale tunnel rules, on…
leonardoxr Oct 31, 2026
bc08674
docs(android): the cleanup of stale tunnel rules at reclaim and start…
leonardoxr Oct 31, 2026
19d0ca4
chore(tunnel): Fallow findings of the tunnel cycles (#1112)
leonardoxr Oct 31, 2026
1049697
test(tunnel): the audit's missing cases, the reclaim fixtures and the…
leonardoxr Oct 31, 2026
22169a8
fix(android): hold tunnel ports until reclaim, keep a leased device's…
leonardoxr Oct 31, 2026
c19bc15
chore(tunnel): Fallow findings of the review fixes (#1112)
leonardoxr Oct 31, 2026
ef0194e
Merge origin/main into task/1112
V3RON Nov 1, 2026
22f1d60
fix(tunnel): the lease's end waits for a removal the socket's close b…
V3RON Nov 1, 2026
5ee15c2
test(tunnel): the start sweep is awaited before the daemon serves (#1…
V3RON Nov 1, 2026
09226bb
fix(android): reclaim and the start sweep never remove a rule on a ph…
V3RON Nov 1, 2026
181af2d
docs(tunnel): phones keep their rules, a tunnel's port is open to the…
V3RON Nov 1, 2026
42f31b5
fix(tunnel): on a phone an aborted lease end still removes the tunnel…
V3RON Nov 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agents/scripts/protocol-bump-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const NOT_SHAPES = new Set([
"duration.ts",
"orientation.ts",
"os-range.ts",
"tunnel-frames.ts",
"version-order.ts",
]);
const RANGE = /PROTOCOL_VERSION_RANGE[^=]*=\s*\{\s*min:\s*(\d+),\s*max:\s*(\d+)/;
Expand Down
1 change: 1 addition & 0 deletions docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘
| agent-device | Optional edge: the two agent-device daemons (simulators, phones) beside a worker, its HTTP front | [agent-device](../../src/agent-device/AGENTS.md) |
| stream | Optional edge: a running device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) |
| input | Optional edge: a lease holder's taps and keys over a WebSocket, relayed by a gateway | [input](../../src/input/AGENTS.md) |
| tunnel | Optional edge: a lease holder's reverse tunnels from its Android device over a WebSocket, on a lone worker | [tunnel](../../src/tunnel/AGENTS.md) |
| auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) |
| http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) |
| cli | Operator command surface | [cli](../../src/cli/AGENTS.md) |
Expand Down
2 changes: 2 additions & 0 deletions docs/internal/flows/startup.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ reaches its settle step, the steps after the read are skipped. Before step 16 it
removes the `.<name>.<pid>.<uuid>.tmp` files and `.<root>.<pid>.<id>.staging` directories of dead writers beside each device root and in
the data directory (`sweepWriteLeftovers`).

Before step 16, a driver with `deviceTcp` sweeps the reverse rules into 47000-47999 a stopped daemon's tunnels left, on its idle owned emulators; on a leased emulator it only reads the rules and reserves their ports, and its reclaim removes them; on a phone it only reads them and reserves their ports, which its reclaim frees once no rule points to them (Android: `AndroidDriver` manual); a failure is a `warn`.

16. Settle open requests — `leasing.settleRequests`: every `open` request fails
`INTERNAL`; `lease.rejected` with reason `daemon-restarted`.
17. Startup read — `core.readStartup`: one `listManaged` per driver, side by side,
Expand Down
3 changes: 2 additions & 1 deletion src/contract/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Imported by: daemon, gateway, simlock-client, every frontend, core, leasing, his
| `duration.ts` | `parseDurationMs`, for the CLI and HTTP |
| `orientation.ts` | `INPUT_ORIENTATIONS`, `parseOrientation` (the aliases a spelling maps to an orientation or the unknown message), `isRotatableModel`, `modelFamily`; no wire shape |
| `relay.ts` | Bounded relay ids, channel ids, headers |
| `tunnel-frames.ts` | The tunnel socket's frame codec, tags and limits (`encodeTunnelFrame`, `decodeTunnelFrame`, `TUNNEL_*`); a helper with no wire shape, listed in the protocol-bump check |
| `console-url.ts` | The console address `status.get` reports |

## Operations
Expand Down Expand Up @@ -58,7 +59,7 @@ Three identities:

## Protocol version

- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 68, max: 68 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`.
- `PROTOCOL_VERSION_RANGE` in `protocol.ts` holds it, now `{ min: 69, max: 69 }`. `DAEMON_PROTOCOL_VERSION` (`src/daemon-protocol/`) is its `max`.
- Every change to a contract shape bumps it by one in the same PR. Move `min` too, unless
a compatibility path stays side by side. `.agents/scripts/protocol-bump-check.mjs` checks
it on push and in CI; it counts every file here as a shape but tests, `index.ts` and the
Expand Down
49 changes: 49 additions & 0 deletions src/contract/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ export interface ErrorDetailsMap {
COMPONENT_IN_USE: { readonly devices: number; readonly foreignDevices: number };
COMPONENT_BUSY: Record<string, never>;
UNKNOWN_LEASE: { readonly leaseId: string };
TUNNEL_UNSUPPORTED: Record<string, never>;
TUNNEL_PORT_IN_USE: Record<string, never>;
TUNNEL_BAD_PORT: Record<string, never>;
TUNNEL_LIMIT: Record<string, never>;
TUNNEL_FAILED: Record<string, never>;
TUNNEL_UNAVAILABLE: Record<string, never>;
TUNNEL_DISCONNECTED: Record<string, never>;
TUNNEL_CALLER_PORT_IN_USE: Record<string, never>;
TUNNEL_LEASE_ENDED: Record<string, never>;
DEVICE_NOT_ENROLLABLE: {
readonly platform: Platform;
readonly id: string;
Expand Down Expand Up @@ -325,6 +334,46 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry
httpStatus: 422,
},
UNKNOWN_LEASE: { code: "UNKNOWN_LEASE", kind: "domain", cliExitCode: 1, httpStatus: 404 },
// why: a lease's tunnel socket refuses with these (ADR 0054 section 7), so every surface reports them alike.
TUNNEL_UNSUPPORTED: {
code: "TUNNEL_UNSUPPORTED",
kind: "domain",
cliExitCode: 1,
httpStatus: 422,
},
TUNNEL_PORT_IN_USE: {
code: "TUNNEL_PORT_IN_USE",
kind: "domain",
cliExitCode: 1,
httpStatus: 409,
},
TUNNEL_BAD_PORT: { code: "TUNNEL_BAD_PORT", kind: "domain", cliExitCode: 1, httpStatus: 422 },
TUNNEL_LIMIT: { code: "TUNNEL_LIMIT", kind: "domain", cliExitCode: 1, httpStatus: 409 },
TUNNEL_FAILED: { code: "TUNNEL_FAILED", kind: "domain", cliExitCode: 1, httpStatus: 502 },
TUNNEL_UNAVAILABLE: {
code: "TUNNEL_UNAVAILABLE",
kind: "domain",
cliExitCode: 1,
httpStatus: 503,
},
TUNNEL_DISCONNECTED: {
code: "TUNNEL_DISCONNECTED",
kind: "domain",
cliExitCode: 1,
httpStatus: 503,
},
TUNNEL_CALLER_PORT_IN_USE: {
code: "TUNNEL_CALLER_PORT_IN_USE",
kind: "domain",
cliExitCode: 1,
httpStatus: 409,
},
TUNNEL_LEASE_ENDED: {
code: "TUNNEL_LEASE_ENDED",
kind: "domain",
cliExitCode: 14,
httpStatus: 410,
},
// A device that cannot be enrolled is a fact about the device, as `RUNTIME_MISSING` is about
// the host: 422 and 12. A busy device passes once what holds it ends, as `NO_CAPACITY` does:
// 409 and 11. An unknown device is the "what you named does not exist" class: 404 and 12.
Expand Down
1 change: 1 addition & 0 deletions src/contract/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from "./pushes.js";
export * from "./relay.js";
export * from "./roles.js";
export * from "./schemas.js";
export * from "./tunnel-frames.js";
export * from "./events-page.js";
export * from "./inbox.js";
export * from "./usage-window.js";
Expand Down
2 changes: 1 addition & 1 deletion src/contract/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export interface ProtocolRange {
const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() });

/** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 68, max: 68 };
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 69, max: 69 };

const LEGACY_DAEMON_PROTOCOL_VERSION = 2;

Expand Down
28 changes: 28 additions & 0 deletions src/contract/tunnel-frames.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";

import { decodeTunnelFrame, encodeTunnelFrame, TUNNEL_TAG } from "./index.js";

describe("the tunnel frame codec", () => {
it("encodes [tag][conn u32 big-endian][payload], decodes it from a view that does not start at byte 0, and answers undefined for fewer than 5 bytes", () => {
expect([...encodeTunnelFrame(TUNNEL_TAG.data, 0x01020304, "hi")]).toEqual([
3, 1, 2, 3, 4, 104, 105,
]);
expect([...encodeTunnelFrame(TUNNEL_TAG.data, 1, Uint8Array.of(9, 8))]).toEqual([
3, 0, 0, 0, 1, 9, 8,
]);
expect([...encodeTunnelFrame(TUNNEL_TAG.end, 7)]).toEqual([5, 0, 0, 0, 7]);

const pooled = Uint8Array.of(0xff, 0xff, 3, 0xff, 0xff, 0xff, 0xfe, 104, 105).subarray(2);
const decoded = decodeTunnelFrame(pooled);
expect(decoded?.tag).toBe(3);
expect(decoded?.conn).toBe(0xff_ff_ff_fe);
expect([...(decoded?.payload ?? [])]).toEqual([104, 105]);

expect(decodeTunnelFrame(Uint8Array.of(5, 0, 0, 0, 7))).toEqual({
conn: 7,
payload: new Uint8Array(),
tag: 5,
});
expect(decodeTunnelFrame(Uint8Array.of(1, 0, 0, 0))).toBeUndefined();
});
});
53 changes: 53 additions & 0 deletions src/contract/tunnel-frames.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// why: the frames of a lease's tunnel socket (ADR 0054 section 3). They are not daemon-contract
// operations, but the worker's module and the CLI's `simlock tunnel` must agree on every byte, so the
// codec sits here, imported by both: one binary message is `[tag u8][conn u32 big-endian][payload]`.
export const TUNNEL_TAG = {
credit: 0x04,
data: 0x03,
end: 0x05,
hello: 0x01,
open: 0x02,
ready: 0x81,
refused: 0x82,
reset: 0x06,
} as const;

export interface TunnelFrame {
readonly tag: number;
readonly conn: number;
readonly payload: Uint8Array;
}

const HEADER_BYTES = 5;

export function encodeTunnelFrame(
tag: number,
conn: number,
payload: Uint8Array | string = new Uint8Array(),
): Uint8Array {
const body = typeof payload === "string" ? new TextEncoder().encode(payload) : payload;
const frame = new Uint8Array(HEADER_BYTES + body.length);
frame[0] = tag;
new DataView(frame.buffer).setUint32(1, conn);
frame.set(body, HEADER_BYTES);
return frame;
}

export function decodeTunnelFrame(bytes: Uint8Array): TunnelFrame | undefined {
if (bytes.length < HEADER_BYTES) return undefined;
return {
conn: new DataView(bytes.buffer, bytes.byteOffset, bytes.length).getUint32(1),
payload: bytes.subarray(HEADER_BYTES),
tag: bytes[0] ?? 0,
};
}

export const TUNNEL_MAX_TUNNELS = 8;
export const TUNNEL_MIN_DEVICE_PORT = 1024;
export const TUNNEL_MAX_DEVICE_PORT = 65_535;
export const TUNNEL_REFUSED_CLOSE = 4003;

export const TUNNEL_WINDOW_BYTES = 262_144;
export const TUNNEL_MAX_DATA_BYTES = 65_536;
export const TUNNEL_WINDOW_LIMIT = 2 ** 31;
export const TUNNEL_HELLO_MAX_BYTES = 4096;
47 changes: 47 additions & 0 deletions src/core/device-tcp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { TcpStream } from "../ports/index.js";
import type { PhysicalDriverDevice, VirtualDriverDevice } from "./driver.js";

// why: the refusals a driver or the catalog can name; the tunnel module passes the code on to the holder.
export class DeviceTcpError extends Error {
constructor(
readonly code: "TUNNEL_PORT_IN_USE" | "TUNNEL_FAILED" | "TUNNEL_UNSUPPORTED",
message: string,
) {
super(message);
this.name = "DeviceTcpError";
}
}

// why: one wording for a lease whose device cannot take a tunnel, so the catalog's refusal and the tunnel module's read the same to the holder.
export function unsupportedTunnelMessage(platform: string, physical: boolean): string {
let noun = `a ${platform} device`;
if (platform === "ios") noun = physical ? "an iPhone" : "an iOS simulator";
return `the lease is on ${noun}; tunnels need an Android emulator or phone`;
}

// why: one device port reversed to a loopback listener on the worker; every connection the device
// opens to that port arrives on `onConnection`, until `close` removes the rule and the listener.
export interface DeviceReverse {
readonly hostPort: number;
onConnection(listener: (stream: TcpStream) => void): void;
close(): Promise<void>;
}

// why: the sweep treats a leased device differently from an idle one, and only the registry knows which is which.
export interface SweptDevice {
readonly device: VirtualDriverDevice | PhysicalDriverDevice;
readonly leased: boolean;
}

// why: an optional driver member beside `input`; a platform whose device cannot reach a worker port
// leaves it out, and the tunnel module learns that from its absence rather than from a platform name.
export interface DeviceTcp {
supports(device: VirtualDriverDevice | PhysicalDriverDevice): boolean;
// why: called once at daemon start, before any lease is served: removes the rules a stopped daemon's tunnels left on idle devices proved Simlock's own; a leased device's rules stay until its reclaim, and the ports they point to are kept from new tunnels.
sweep(devices: readonly SweptDevice[]): Promise<void>;
reverse(
device: VirtualDriverDevice | PhysicalDriverDevice,
devicePort: number,
signal: AbortSignal,
): Promise<DeviceReverse>;
}
30 changes: 30 additions & 0 deletions src/core/driver-catalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
type PassthroughCommand,
type PassthroughContext,
} from "./driver.js";
import { FakeDeviceTcp } from "./fake-device-tcp.js";
import { FakeDriver } from "./fake-driver.js";
import { DriverCatalog, NoDriverError, UnknownPassthroughToolError } from "./driver-catalog.js";

Expand Down Expand Up @@ -43,7 +44,36 @@ function route(
);
}

// why: the catalog is pure routing by platform with many cases (passthrough tools, class defaults, device ports), driven through the fake drivers it routes to.
describe("DriverCatalog", () => {
it("reverses a device port through its driver's deviceTcp, and answers TUNNEL_UNSUPPORTED, naming the device, for a platform with none", async () => {
const clock = new FakeClock();
const deviceTcp = new FakeDeviceTcp();
const catalog = new DriverCatalog([
new FakeDriver({ availableOsVersions: ["14"], clock, deviceTcp, platform: "android" }),
new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }),
]);
const simulator = { address: "", deviceId: "sim", driverData: {}, physical: false } as const;
const phone = { ...simulator, enrolledApps: [], physical: true } as const;
const signal = new AbortController().signal;

expect(catalog.supportsDeviceTcp("android", simulator)).toBe(true);
expect(catalog.supportsDeviceTcp("ios", simulator)).toBe(false);
await catalog.reverseDevicePort("android", simulator, 5173, signal);
expect(deviceTcp.reversed).toEqual([5173]);
for (const [device, noun] of [
[simulator, "an iOS simulator"],
[phone, "an iPhone"],
] as const) {
await expect(catalog.reverseDevicePort("ios", device, 5173, signal)).rejects.toEqual(
expect.objectContaining({
code: "TUNNEL_UNSUPPORTED",
message: `the lease is on ${noun}; tunnels need an Android emulator or phone`,
}),
);
}
});

it("resolves a request through its registered driver", async () => {
const clock = new FakeClock();
const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" });
Expand Down
24 changes: 24 additions & 0 deletions src/core/driver-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
PhysicalDriverDevice,
VirtualDriverDevice,
} from "./driver.js";
import { DeviceTcpError, unsupportedTunnelMessage, type DeviceReverse } from "./device-tcp.js";
import type { DeviceInput, UnavailableDeviceInput } from "./input.js";
import { type ScreenFeed, ScreenNotSupportedError, type ScreenSettings } from "./screen.js";
import { stableError } from "./stable-error.js";
Expand Down Expand Up @@ -102,6 +103,29 @@ export class DriverCatalog {
return await factory.open(device, signal);
}

supportsDeviceTcp(
platform: Platform,
device: VirtualDriverDevice | PhysicalDriverDevice,
): boolean {
return this.#drivers.get(platform)?.deviceTcp?.supports(device) ?? false;
}

async reverseDevicePort(
platform: Platform,
device: VirtualDriverDevice | PhysicalDriverDevice,
devicePort: number,
signal: AbortSignal,
): Promise<DeviceReverse> {
const deviceTcp = this.#drivers.get(platform)?.deviceTcp;
if (deviceTcp === undefined) {
throw new DeviceTcpError(
"TUNNEL_UNSUPPORTED",
unsupportedTunnelMessage(platform, device.physical),
);
}
return await deviceTcp.reverse(device, devicePort, signal);
}

async screenAvailability(): Promise<readonly ScreenAvailability[]> {
return await Promise.all(
[...this.#drivers.values()].flatMap((driver) =>
Expand Down
3 changes: 3 additions & 0 deletions src/core/driver.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { EventMap } from "../bus/index.js";
import type { Filesystem, SqliteDatabase, SqliteSchemaOwner } from "../ports/index.js";
import type { RootRejectionReason } from "./device-root.js";
import type { DeviceTcp } from "./device-tcp.js";
import type { DeviceInputFactory } from "./input.js";
import type { ScreenCapture } from "./screen.js";
import type {
Expand Down Expand Up @@ -306,6 +307,8 @@ export interface Driver {
// why: optional like `screenCapture`: a platform whose device takes no input leaves it out, and a
// lease's input socket then says the device is unavailable.
readonly input?: DeviceInputFactory | undefined;
// why: optional like `input`: a platform whose device cannot reach a port on the worker leaves it out, and a tunnel is then refused as unsupported.
readonly deviceTcp?: DeviceTcp | undefined;
/** why: `device.exec` has no pseudo-terminal (ADR 0005 §19c), so a driver may refuse there what it allows locally. */
passthrough?(
tool: string,
Expand Down
Loading
Loading