diff --git a/CHANGELOG.md b/CHANGELOG.md index 064f1ba4e..b6636379f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,28 @@ describe the decided end state, and they land with the PRs that implement it (the client's renew timers, and the daemon's heartbeat removal, config rename, and protocol bump). +ADR 0005 (`docs/adr/0005-gateway-and-worker-modes.md`): a simlock daemon now +runs in one of two modes. A **worker** is what every daemon is today — it +owns the devices on one machine — and a **gateway** owns none, fronting the +workers that dial out to it over a single WebSocket **uplink**. A gateway +keeps one fleet-wide queue, dispatches each request to the worker best placed +to serve it, proxies device commands to the worker that owns the device, and +implements the same typed contract towards its own clients, so every existing +frontend works against it unchanged. Nothing here is removed or repurposed +and a daemon left in the default `mode: "worker"` behaves exactly as it does +today, so every one of the entries below is additive **except the protocol +bump** — `device.exec` and its `output` pushes take the socket wire to +protocol 5, which means a client and a daemon still have to be upgraded +together. That one is listed under BREAKING CHANGES above, with ADR 0004's +own bump, since it is the same wire and the same upgrade. + +ADR 0005 is **Accepted — not yet implemented** as well: the entries under +"ADR 0005" below describe the decided end state, and they land with the PRs +that implement it (`device.exec` on the worker, then the gateway skeleton and +worker views, the fleet queue and forwarding, drain and reconnect). The +documentation is the exception to that order: it lands first, as the +specification those changes are written against. + ### ⚠ BREAKING CHANGES - **Contract:** `lease.heartbeat` is removed as an operation, and `heartbeat` @@ -43,8 +65,12 @@ rename, and protocol bump). so the daemon now writes `lastRenewedAt` onto the lease record at grant and on every renew, and `simlock status` renders it as "last renewed". A consumer reading `lastHeartbeatAt` gets `undefined`. -- **Socket protocol:** moves to protocol 4 with no compatibility shim; the - range a daemon and client advertise is `{min: 4, max: 4}`. A +- **Socket protocol:** moves twice in this release, once per ADR, each time + with no compatibility shim. ADR 0004 removes `lease.heartbeat` and `mode`, + taking the wire to protocol 4; ADR 0005 adds `device.exec` and its `output` + push family, taking it to 5. **What ships advertises `{min: 5, max: 5}`** — + 4 is a step along the way, not a range anything releases with, since a + range widens only where a compatibility path is kept (ADR 0003 §6). A version-mismatched client fails `hello` with `PROTOCOL_VERSION_UNSUPPORTED` and never restarts the daemon — run `simlock daemon stop` once it's idle. `daemon.stop` remains a frozen exception, accepted at any protocol version @@ -67,7 +93,7 @@ rename, and protocol bump). persisted in held mode survives the upgrade with its persisted deadline intact — up to the old one-hour `lease.heldTtlBackstopMs`. Nothing can renew it: its holder speaks protocol 3 and the new daemon speaks - `{min: 4, max: 4}`, so its `hello` fails. The lease simply expires on that + `{min: 5, max: 5}`, so its `hello` fails. The lease simply expires on that deadline and its device is reclaimed, or `simlock release ` ends it sooner. Stopping the old daemon while it is idle, as the protocol- mismatch error already advises, avoids the situation entirely. @@ -134,6 +160,120 @@ those changes add, alongside the breaking changes above. - **config:** `lease.maxTtlMs` bounds what any caller may ask for, so one client cannot pin a device for a day by naming a large `ttlMs`. +### ADR 0005: gateway and worker modes + +These ship with the PRs that implement ADR 0005, and every one of them is +additive: `mode` defaults to `worker`, so a daemon that ignores all of this +is the daemon that exists today. + +- **contract:** `device.exec` (role `agent`) runs one `simctl`/`adb` command + against a leased device on the machine that owns it — + `{ leaseId, tool, args, stdin?, requesterId? }` in, `{ exitCode }` out, + with output streamed as request-scoped `output` pushes + (`stream: "stdout" | "stderr"` plus a chunk, keyed by frame id like + `progress`). It works on the unix socket, over HTTP, and over the uplink, + so a remote HTTP agent can drive its device against a lone worker with no + gateway involved at all. `stdin` is one string sent with the request and + then closed; there is no pseudo-terminal, and a bare `adb shell` with no + command is refused (`PASSTHROUGH_REFUSED`) rather than left to stall until + the timeout. A non-admin caller is gated the ordinary way, its principal + against the lease's `ownerId`; `requesterId` exists for the one session + that would otherwise bypass that check, the gateway's admin session on a + worker, and **`admin` does not bypass on this one operation** — the worker + compares the supplied `requesterId` to the lease's own. +- **contract:** `worker.list|drain|undrain|remove` (admin) manage the workers + connected to a gateway; `mode` joins `status.get`'s daemon block; `workers` + joins its output; `workerId` joins every device and lease in a gateway's + aggregate; `worker: { id, label }` joins the lease object; and `worker` + joins the token roles. All additive. +- **daemon:** `config.mode` selects `worker` (default) or `gateway`. A + gateway starts no drivers, validates no device roots, and runs no reaper, + health monitor, or capacity strategy; `src/gateway/` implements the + contract's handlers over worker views and uplinks, importing nothing from + `drivers` and, from `core`, only the platform-agnostic queue and bus. A + gateway's one piece of persisted state is its **worker registry** — which + workers it knows and which an operator has drained — kept under its + `SIMLOCK_HOME` with owner-only permissions, so a drain survives both a + worker reconnect and a gateway restart. Worker _views_ are rebuilt on every + connect and never persisted. +- **Socket protocol:** the wire's second move this release, to protocol 5, + with no compatibility shim — see BREAKING CHANGES above, where it is + listed with ADR 0004's. `device.exec` and its `output` push family are new + frames and no compatibility path is kept for them, so under ADR 0003 §6's + honesty rule the range does not widen. Over the uplink this is ordinary + version negotiation: a worker older than ADR 0005 does not overlap a + gateway's range, is marked `incompatible` with both ranges shown, is never + dispatched to, and keeps serving its own local clients until it is + upgraded. +- **daemon:** one fleet queue on the gateway, dispatched to workers with + `noWait: true`, so a gateway request never sits in a worker's queue and can + be granted by whichever worker frees first. A request becomes `dispatched` + on a grant or on the first `progress` push from that worker; only an + immediate `NO_CAPACITY` (a stale view) leaves it queued. Routing is a pure + function over the worker views behind `gateway.routing`; the v1 policy is a + warm hit first, then the most free running capacity for the platform. Each + view carries the worker's effective `downloads.policy`, read once with + `config.get` on connect, so routing can tell whether a machine may install + a missing runtime at all — the worker still clamps `allowDownload` through + that same policy, as always. +- **daemon:** `lease.renew`/`release`/reads forward to the owning worker + (the lease id names it), the one-lease-per-requester rule becomes + fleet-wide, and the requester a gateway forwards is namespaced + `gw::` so local and fleet agents cannot + collide on a worker. `lease.release-all` on a gateway releases only the + leases that gateway issued, across every connected worker, and never a + worker's own local leases; a worker it cannot reach is reported as + `WORKER_UNREACHABLE` naming that worker while the rest still complete. +- **config:** new keys. Worker side: `gateway.url`, `gateway.token` (a join + token), `gateway.label`, and `exec.timeoutMs` (10 minutes, and the + authoritative one — that side owns the process). Gateway side: + `gateway.routing` (`warm-then-free`), `gateway.disconnectedRetentionMs` + (24 hours) and `gateway.execTimeoutMs` (11 minutes, a backstop for a worker + that never answers, deliberately longer than the worker's own). Plus `mode` + itself. + Worker-only keys in a gateway's config are ignored with a warning, as + unknown keys already are. Two pairs are rejected at load instead, and the + daemon does not start: `mode: "gateway"` with `http.enabled: false`, since + a gateway with no listener cannot be reached by anyone; and, in + `mode: "worker"`, `gateway.url` without `gateway.token` or the reverse, + since a half-configured uplink would otherwise come up looking like an + ordinary standalone worker. +- **http:** new routes. `GET /v1/uplink` (WebSocket upgrade, join-token + bearer, role `worker`) is the one inbound connection in a fleet; + `POST /v1/leases/{id}/exec` streams a command's output as Server-Sent + Events, the same shape `/events` already uses; `GET /v1/workers`, + `POST /v1/workers/{id}/drain`, `DELETE /v1/workers/{id}/drain`, and + `DELETE /v1/workers/{id}` (all `operator`) are what the console (#88) + renders. "Multi-host brokering" leaves `docs/HTTP-API.md`'s "Not + implemented" list, since this is it. +- **events:** `worker.connected`, `worker.disconnected`, `worker.rejected`, + `worker.removed`, `worker.drain-started`, `worker.drain-ended`, and + `request.dispatched` are emitted by a gateway, and every worker's own + business events are republished on the gateway's bus with `workerId` added + to the payload — an additive change, so no exception to events rule 6 is + needed this time. `worker.rejected` reports an uplink refused at the door, + which nothing else records — it is what answers "why did that machine never + appear". See `docs/EVENTS.md`. +- **contract:** five new error codes. `WORKER_UNREACHABLE` (`kind: +"transport"`, CLI exit 1, HTTP 503 — where every other `transport`-kind + code already sits) when a worker's uplink is down; `WORKER_CONNECTED` + (exit 2, HTTP 409) refusing `worker remove` on a connected worker; + `UNKNOWN_WORKER` (exit 12, HTTP 404) for `worker drain`/`undrain` naming a + worker the gateway does not know — `remove` instead answers + `{"removed": false}`, since forgetting an already-forgotten worker is not a + failure; `UNSUPPORTED_IN_GATEWAY_MODE` (exit 2, HTTP 501, permanently + rather than pending some later fan-out) for + `nuke`/`cleanup`/`doctor`/`driver.passthrough` asked of a gateway; and + `EXEC_TIMEOUT` (exit 10, HTTP 504) when a command outlives + `exec.timeoutMs`. `device.exec`'s refusals are **not** new codes: a refused + verb is the existing `PASSTHROUGH_REFUSED` and an unwrapped tool the + existing `UNKNOWN_PASSTHROUGH_TOOL`, both already exit 2 / HTTP 422. +- **deps:** `ws` is added as a runtime dependency — Node ships a WebSocket + _client_ but no server, and the uplink needs both ends. It sits behind the + `UplinkListenerFactory`/`UplinkConnector` ports as their one real adapter, + so nothing above the port imports it and tests script a fleet in memory + without it. + ### Documentation - record ADR 0004 as **Accepted — not yet implemented** @@ -146,6 +286,32 @@ those changes add, alongside the breaking changes above. `docs/EVENTS.md`, `docs/ABOUT.md`, and `README.md`; record the SIGKILLed holder and re-frame the reparented-holder fix around renew timers in `docs/known-pitfalls.md`. +- record ADR 0005 as **Accepted — not yet implemented** + (`docs/adr/0005-gateway-and-worker-modes.md` and `docs/adr/README.md`). +- describe gateways and workers across the user manual: a "Gateway and worker + modes" section in `docs/ARCHITECTURE.md` (topology, uplink, worker views, + the fleet queue, routing, lease forwarding, `device.exec`, failure + behaviour, the safety argument, and `src/gateway/`'s boundaries), "Against + a gateway" and `simlock worker` in `docs/CLI.md`, the uplink/worker/exec + routes in `docs/HTTP-API.md`, `exec` and `mode` in `docs/CLIENT.md`, + the new keys and a "Modes" section in `docs/CONFIGURATION.md`, the fleet + events in `docs/EVENTS.md`, and a paragraph each in `docs/ABOUT.md` and + `README.md`. +- `docs/IDEAS.md` drops "Cross-machine coordination" — ADR 0005 designs it — + and gains the items that record deferred: gateway-side file upload for + `device.exec`, reserved capacity slices, fan-out `doctor`/`cleanup`, richer + routing (label selectors, requester affinity), and a byte-heavy data plane. +- `docs/known-pitfalls.md` records five accepted fleet gaps: no file transfer + for `device.exec`, no pseudo-terminal, a dispatched request whose uplink + drops, a lease that survives a gateway restart it cannot be renewed + through, and local agents sharing a worker's capacity with the fleet. +- reserve "gateway" for ADR 0005's meaning: the `src/http` frontend is called + the **HTTP frontend** throughout `docs/ARCHITECTURE.md`, + `docs/HTTP-API.md`, and `docs/known-pitfalls.md`, where it used to be "the + HTTP gateway". No behaviour changes; one word now means one thing. ADRs + 0003 and 0004 keep the old wording deliberately — an accepted record says + what it said when it was accepted, and is never edited to match a later + vocabulary. ## [0.3.0](https://github.com/callstackincubator/simlock/compare/v0.2.0...v0.3.0) (2026-09-03) diff --git a/README.md b/README.md index 567f11931..4454c7888 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,9 @@ ### A control plane so parallel coding agents stop fighting over the same simulator Simlock is a CLI-first control plane for iOS simulators and Android -emulators, built for environments where multiple coding agents run on one -machine at the same time. Agents don't touch `simctl` or `avdmanager` +emulators, built for environments where multiple coding agents run at the +same time — on one machine, or across a fleet of them behind a single +address. Agents don't touch `simctl` or `avdmanager` directly — they ask Simlock for a device and get one back, booted and health-checked, that no other agent will touch until they're done with it. @@ -30,6 +31,23 @@ same lease, and tells the holder — it can't restore whatever was running inside the device when it died, but the lease and its device don't just vanish. +**One machine is a starting point, not a limit.** A simlock daemon runs +either as a **worker** — what every daemon is today, owning the devices on +its own machine — or as a **gateway**, which owns no devices and fronts the +workers that have joined it ([ADR +0005](docs/adr/0005-gateway-and-worker-modes.md)). Workers dial _out_ to the +gateway over a single WebSocket uplink, so a Mac behind NAT joins a fleet +with a URL and a join token and never needs an inbound port; the gateway +keeps one fleet-wide queue and sends each request to the worker best placed +to serve it — a warm device if one is free, otherwise the machine with the +most free capacity. Agents and the console point at **one URL** and stop +caring which machine a device lives on, because a gateway speaks the same +contract a worker does: the same `lease`, `renew`, `release`, and `status`, +with `simlock simctl` / `simlock adb` proxied through to the worker that owns +the device. The gateway never touches a device itself — capacity, the +registry, and every safety rule stay on the worker, which also keeps serving +its own local agents as before. + **It's advisory, not a sandbox.** Simlock doesn't wrap or intercept `simctl` / `avdmanager` — it works because agents are instructed to only use devices handed to them by a lease. What it _does_ enforce is its own blast diff --git a/docs/ABOUT.md b/docs/ABOUT.md index ce1e5d260..28240345e 100644 --- a/docs/ABOUT.md +++ b/docs/ABOUT.md @@ -1,7 +1,8 @@ # Simlock Simlock is a control plane for iOS simulators and Android emulators, built for -environments where multiple coding agents run in parallel on one machine. +environments where multiple coding agents run in parallel — on one machine, +or across a fleet of them behind a single address. ## The problem @@ -32,6 +33,26 @@ programmatic client the CLI and MCP frontends are themselves built on (see - Devices that sit unused are **cleaned up in tiers**: shut down after a short idle period (reclaim RAM), deleted after a longer one (reclaim disk). +## More than one machine: fleets + +One machine's worth of devices runs out eventually, and a team with several +Macs should not have to hand each agent a specific one. So a simlock daemon +runs in one of two modes ([ADR +0005](adr/0005-gateway-and-worker-modes.md)). A **worker** is what every +daemon is today — it owns the devices on its machine — and joining a fleet +costs it two config keys pointing at a gateway; it keeps serving its own +local agents exactly as before. A **gateway** owns no devices at all: workers +dial *out* to it over a single WebSocket **uplink** (so a machine behind NAT +needs no inbound port), and it fronts them with one fleet-wide queue, +dispatching each request to the worker best placed to serve it — a warm +device if one is free, otherwise the machine with the most free capacity. +Agents and the web console point at **one URL** and stop caring which machine +a device lives on: a gateway speaks the same contract a worker does, so +`lease`, `renew`, `release`, `status`, and even `simlock simctl` / `simlock +adb` (proxied to the owning worker) are the same commands they always were. +The gateway never touches a device itself — the capacity accounting, the +registry, and every safety invariant stay on the worker. + ## Key properties - **Advisory coordination.** Simlock does not sandbox anything. It works @@ -44,7 +65,7 @@ programmatic client the CLI and MCP frontends are themselves built on (see frees the device at once; `--detach` skips the staying alive and leaves the renewing to you. A holder that dies without releasing costs its device only until the TTL runs out. -- **One lease per agent** (v1). +- **One lease per agent** (v1) — fleet-wide when a gateway issued it. - **Managed-device registry.** Simlock only ever shuts down, erases, or deletes devices it created itself. Everything else on the machine is read-only to it. @@ -52,7 +73,9 @@ programmatic client the CLI and MCP frontends are themselves built on (see progress (e.g. provisioning ETAs) streams as JSON lines on stderr. The optional MCP server reserves stdout for MCP JSON-RPC. -See [ARCHITECTURE.md](ARCHITECTURE.md) for how it's built, [CLI.md](CLI.md) -for the command surface, [CLIENT.md](CLIENT.md) for the programmatic client, +See [ARCHITECTURE.md](ARCHITECTURE.md) for how it's built (and +[its gateway section](ARCHITECTURE.md#gateway-and-worker-modes-adr-0005) for +how a fleet fits together), [CLI.md](CLI.md) for the command surface, +[CLIENT.md](CLIENT.md) for the programmatic client, [HTTP-API.md](HTTP-API.md) for the network API, and [known-pitfalls.md](known-pitfalls.md) for accepted gaps. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7a8176199..770f9895e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -7,7 +7,7 @@ agent ──spawns──> simlock CLI ──┐ ├─ shared daemon client ──unix socket──> simlock daemon MCP client ──spawns──> stdio MCP ┘ │ │ -remote agent ──token auth──> HTTP gateway ──same role interfaces────────┤ +remote agent ──token auth──> HTTP frontend ─same role interfaces────────┤ ┌───┼─────────────┐ │ core (platform-│ │ agnostic) │ @@ -28,13 +28,18 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ emulator/adb) ``` -- **CLI, stdio MCP server, and HTTP gateway**: sibling thin frontends over one +That is one daemon, owning the devices on one machine — a **worker**, in ADR +0005's vocabulary, and the only shape simlock has today. A **gateway** fronting +several workers is the other one; see [Gateway and worker +modes](#gateway-and-worker-modes-adr-0005) below for that topology. + +- **CLI, stdio MCP server, and HTTP frontend**: sibling thin frontends over one typed contract (ADR 0003; see "Contract, dispatcher, and roles" below). The core never knows which frontend made a request. The CLI and MCP server sit over `simlock/client`/`simlock/admin` (the typed daemon client, see [CLIENT.md](CLIENT.md)) and the unix socket; the CLI is the full operator interface, and the MCP server intentionally limits its tool surface to - leasing and releasing for an agent session. The HTTP gateway is different in + leasing and releasing for an agent session. The HTTP frontend is different in kind, not just transport: it is the one frontend meant to be reached over a real network, so it calls the daemon's dispatcher **in-process** — the exact same one the socket path calls — rather than going through the unix socket at @@ -45,7 +50,7 @@ remote agent ──token auth──> HTTP gateway ──same role interfaces─ right after the socket claim, the same moment the unix socket itself starts accepting connections and before startup convergence runs (`DaemonServer`'s `onSocketClaimed` hook, see "Startup: claim first, converge after" below) — a - bug fix from the pre-ADR gateway, which started only once convergence had + bug fix from the pre-ADR HTTP frontend, which started only once convergence had already finished and so never needed to park anything. A request that arrives before convergence completes now waits on the shared dispatcher's readiness gate exactly like a socket request, instead of being refused. See @@ -118,7 +123,7 @@ declares one, park on startup readiness (every operation but `status.get`), call the handler, parse the output. Handlers never see a raw payload or run a role check themselves. The unix socket server (`DaemonServer`) is framing plus connection/session lifecycle around this one dispatcher instance; the -HTTP gateway (`src/http/app.ts`) calls the **exact same dispatcher +HTTP frontend (`src/http/app.ts`) calls the **exact same dispatcher in-process** — `DaemonServer` exposes it as the one privileged seam an auxiliary frontend gets — via a bearer-token-to-`DispatchSession` adapter (`src/http/dispatcher-session.ts`). **HTTP never routes through the unix @@ -131,13 +136,18 @@ applies to HTTP automatically because there is only one code path to fix. **Protocol versions are negotiated as `{min, max}` ranges** and honestly: a range widens only when a compatibility path is actually kept (ADR 0003 §6). -ADR 0004 removes `lease.heartbeat` and `mode` from the contract with no shim -behind them, so the range both sides advertise is `{min: 4, max: 4}` — a -protocol-3 client and a protocol-4 daemon simply do not overlap, and `hello` -fails with `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges. `daemon.stop` -stays the frozen exception, accepted at any version the daemon has ever -spoken, so the upgrade path (`simlock daemon stop`, then start the new -daemon) exists at all. +Two changes have moved it since. ADR 0004 removed `lease.heartbeat` and +`mode` from the contract with no shim behind them, taking the wire to +protocol 4; ADR 0005 adds `device.exec` and its `output` push family, again +with no compatibility path kept, taking it to 5. So the range both sides +advertise is `{min: 5, max: 5}`, an older client and a current daemon simply +do not overlap, and `hello` fails with `PROTOCOL_VERSION_UNSUPPORTED` naming +both ranges. The same negotiation runs over a worker's uplink, which is why a +worker older than ADR 0005 shows up in a gateway's views as `incompatible` +rather than as a mystery (see [Gateway and worker +modes](#gateway-and-worker-modes-adr-0005)). `daemon.stop` stays the frozen +exception, accepted at any version the daemon has ever spoken, so the upgrade +path (`simlock daemon stop`, then start the new daemon) exists at all. **Two roles**, `agent` and `admin`, declared in `src/contract/roles.ts`. Read-only and lease-lifecycle operations are `agent`; anything that reads or @@ -180,8 +190,8 @@ without adding real protection against the thing socket identity cannot stop anyway (see the ADR's "Alternatives considered"). **Admin authority comes only from a credential presented at `hello`, never -from the socket itself.** Two credentials are accepted, checked in this -order: +from the socket itself.** Three credentials are accepted, the first two +checked in this order on any client connection: 1. **An operator token**, minted with `simlock token create --role operator` and stored (hashed) in `tokens.json`. Long-lived, revocable — @@ -194,6 +204,29 @@ order: creation, and removed on graceful stop. `hello` verifies against the in-memory hash, so a credential can be checked before the file has even landed on disk. +3. **The worker's own uplink** (ADR 0005 §5). When a daemon joins a fleet it + dials the gateway named in *its own* `gateway.url` and presents its + `gateway.token`; the gateway checks that join token, and is then the + protocol client on the resulting session, which the worker grants the + `admin` role. What proves that role is the worker's configuration, not + anything the transport asserts — the same principle as the two above (ADR + 0003 §5) reached from the other end: nothing inbound is trusted, and the + worker is the party that decided which gateway to obey. + + **Joining a fleet therefore grants that gateway admin over the daemon that + joined.** That is the real scope of the decision, and it is not a side + effect: a gateway has to `lease.request`, `lease.release`, `list.get`, + `config.get`, and `events.subscribe` on its workers, which is exactly what + an admin CLI does. Point a worker only at a gateway you would hand an + operator token to. + + The join token is a **bearer credential**, presented in the + `Authorization` header of the uplink's upgrade request, so anything that + can read that request can replay it. `gateway.url` should therefore be + `wss://` — or plain `ws://` only over loopback or inside the operator's + own tunnel, the same rule the HTTP API already states for itself and for + the same reason: Simlock terminates no TLS in v1. Only those two schemes + are accepted; `http://`/`https://` are rejected at load. A missing or wrong credential fails the handshake with `ADMIN_AUTHENTICATION_FAILED` before any other request on that connection @@ -228,6 +261,401 @@ for the CLI's own walkthrough of the same resolution order, and [HTTP-API.md](HTTP-API.md#authentication) for how HTTP's bearer-token roles map onto `agent`/`admin`. +## Gateway and worker modes (ADR 0005) + +`config.mode` selects which of two shapes a daemon runs as, and one daemon +runs exactly one of them: + +- **`worker`** (the default) is everything described above and below in this + document: drivers, device roots, registry, capacity, reaper, health + monitor, leases. Every simlock daemon before ADR 0005 is a worker. +- **`gateway`** owns no devices at all. It starts no drivers, validates no + device roots, and runs no reaper, health monitor, or capacity strategy. + What it owns is *demand*: one fleet-wide queue of lease requests, a live + view of every worker connected to it, and the routing decision that puts + the two together. + +To a client the difference is invisible. A gateway implements the same typed +contract (ADR 0003) towards its own clients that a worker does, so the CLI, +MCP, the HTTP frontend, `simlock/client`, and the web console (#88) work +against one with no frontend change — `mode` in `status.get`'s daemon block +is the only field that tells them apart. + +``` + agents (CLI · MCP · simlock/client) + web console (#88) · agent-device + │ + one URL / one unix socket + │ + ▼ + ┌──────────────────────────────┐ + │ simlock daemon, mode gateway │ + │ worker views · fleet queue │ + │ routing policy · dispatch │ + │ lease index · event bus │ + │ (no drivers) │ + └───▲───────────────────────▲──┘ + │ │ the gateway is the + uplink │ uplink │ protocol client here + (each worker dials out: WebSocket + join token) + │ │ + ┌───────────────┴──────┐ ┌────────────┴─────────┐ + ┌───▶│ simlock daemon, │ │ simlock daemon, │◀───┐ + │ │ mode worker (Mac A) │ │ mode worker (Mac B) │ │ + │ │ core · drivers · │ │ core · drivers · │ │ + │ │ registry · capacity │ │ registry · capacity │ │ + │ └──────────┬───────────┘ └──────────┬───────────┘ │ + │ │ simctl / adb │ simctl / adb │ + │ ▼ ▼ │ + │ iOS / Android devices iOS / Android devices │ + │ │ + local agents on Mac A, local agents on Mac B + over that daemon's own unix socket — unchanged, and sharing its capacity +``` + +Only the gateway listens for inbound connections. Workers **dial out**, so a +machine behind NAT, a laptop, or a CI runner joins a fleet with a URL and a +token and needs no inbound port, no tunnel, and no address a client ever +learns. A machine that should both front a fleet and own devices runs **two +daemons** with distinct `SIMLOCK_HOME`s — a gateway and a worker, the worker +joining over localhost. There is no hybrid mode: every gateway code path +would need a "local" special case, and the gateway would hold device state. + +### The uplink + +A worker with `gateway.url` and `gateway.token` set opens one outbound +WebSocket to `/v1/uplink` on start, and again after any +disconnect on exponential backoff, presenting its join token (role `worker`) +and its instance id. The gateway verifies the token against its own token +store. A missing or unrecognized token is `401`; a **valid token of the wrong +role is `403`** (ADR 0005 §4) — two different facts, answered the way the +rest of the API already answers them. Either way nothing enters the worker +registry and the gateway emits `worker.rejected` (see [EVENTS.md](EVENTS.md)). + +Over that one socket **the gateway is the protocol client**. It sends `hello` +and issues ordinary contract operations to the worker's own dispatcher, +exactly as a local admin CLI would over the unix socket — there is no second +API and no second vocabulary between gateway and worker, so every operation +added to the contract is available over the uplink for free. The worker +grants that session the `admin` role because *it* opened the connection, to +the gateway named in its own config; the trust runs from the worker's +configuration, never from the transport (ADR 0003 §5). + +The uplink is also the reachability signal, so nothing polls for liveness: a +worker whose uplink is open is `connected`, one whose uplink is closed is +`disconnected` and keeps its last-known view (greyed, never dispatched to) +until an operator removes it or `gateway.disconnectedRetentionMs` (24 hours) +elapses. That clock is **held** while the gateway still knows of +gateway-issued leases on the worker, because forgetting a worker that is +holding someone's device is how a lease becomes unroutable — and the hold +ends when the last of those leases passes its deadline, since a lease nobody +can renew is one the worker has already expired on its own clock. The hold is +therefore bounded by a TTL rather than open-ended: a worker gone longer than +every lease it held has nothing left to protect. + +The uplink is a port on both sides — `UplinkListenerFactory` on the gateway, +`UplinkConnector` on the worker — with a WebSocket adapter (`ws`) as the one +real implementation, so tests script a whole fleet in memory against a +manually-advanced `Clock`, exactly as the core's tests script drivers. + +### The worker view + +A **worker view** is what the gateway currently knows about one worker: its +id, `label`, daemon health and version, negotiated protocol range, capacity +per platform, queue depth, leases, devices, catalog, effective download +policy, and drain state. On connect the gateway calls `status.get`, +`list.get`, `catalog.get`, `config.get`, and `events.subscribe` on the worker +and builds the view from the answers; it refreshes status and list on every +worker event that changes capacity or leases, and on a slow periodic tick as +a backstop. + +`config.get` is the one of those read **once per connect** rather than on the +refresh path: config is daemon input, read at start, so a worker whose +`downloads.policy` changed has already restarted and reconnected. It is an +admin operation, which the uplink session is. The gateway keeps exactly one +field out of it — the effective `downloads.policy` — because routing has to +know whether a worker is even *allowed* to install a missing runtime before +it sends that worker a request which depends on one. It is a routing input +and never an override: the worker still clamps `allowDownload` through its +own policy, whatever the view said. + +The view is **rebuilt, never persisted**. A gateway restart loses nothing it +cannot ask for again, and a worker stays the authority on its own state. Two +consequences are worth stating plainly: + +- The worker **id is the worker's existing instance identity** + (`${SIMLOCK_HOME}/instance.json`) — stable across restarts, unique by + construction, opaque to clients. `label` (`gateway.label`) is display-only + and need not be unique; nothing routes on it. +- A view can be **stale by a moment**, and the design assumes it. Dispatch + treats a `NO_CAPACITY` answer from a worker as a stale view rather than as + a failure (below), which is what lets routing be an ordinary pure function + over the last known numbers instead of a distributed reservation protocol. + +`worker.list` (admin) returns the views; `worker.drain`, `worker.undrain`, +and `worker.remove` are the operator's edits to them. A **drained** worker +keeps its existing leases and receives no new dispatches — the tool for +taking a machine down without killing anyone's device. + +Drain is the one piece of worker state the gateway *decides* rather than +observes, and it is why the **worker registry** and the worker *view* are two +different things. The view is the observation: rebuilt on every connect, +never persisted. The registry is the gateway's own record of which workers it +knows and which of them an operator has drained (ADR 0005, "Worker registry +(gateway side)"), and it **is** persisted — a small JSON file under the +gateway's `SIMLOCK_HOME`, written with owner-only permissions like everything +else simlock keeps there. + +A drain therefore survives both a worker reconnect and a gateway restart. +Both halves matter: a machine taken out of rotation for maintenance must not +rejoin it because its own daemon restarted, and must not rejoin because the +*gateway* restarted either — an operator who drained a worker and walked away +has no reason to expect a process they never touched to undo it. `undrain` is +the only thing that ends a drain. + +### The fleet queue and dispatch + +A lease request arriving at a gateway enters **one gateway-side FIFO queue**, +where `timeoutMs` (`QUEUE_TIMEOUT`), `noWait` (`NO_CAPACITY`), +`lease.cancel`, and the `queued` progress state with its `queuePosition` all +mean exactly what they mean on a worker. + +**Dispatch** runs whenever the queue or any worker view changes. For each +queued request, oldest first, the routing policy picks a worker and the +gateway sends it `lease.request` with **`noWait: true`**: + +- the request becomes `dispatched` on either of two signals from that + worker: the grant itself, or the first `progress` push for it + (`provisioning`, `booting`, `reclaiming`) — device work has started, so the + request belongs to that worker and dispatch stops considering it; +- an **immediate `NO_CAPACITY`** is the only answer that leaves it queued: it + means the view was stale, so the gateway refreshes that worker's view and + the request waits, no worse off than before. A failure *after* work has + begun is the request's own terminal failure, not a return to the queue; +- a request no worker can serve right now is **passed over, not blocked on**, + so an Android request behind an iOS one proceeds the moment Android + capacity frees. + +`noWait` is what keeps the two queues from becoming one problem. Because a +dispatch either takes immediately or refuses, **no gateway request ever sits +in a worker's queue**: it can still be granted by whichever worker frees +first, and local agents on the worker machine keep using their own daemon's +queue without ever competing with the fleet for a queue slot. The two contend +for *capacity* only, and the worker's own capacity accounting is the single +arbiter of that — the same accounting that already arbitrates between two +local agents. + +### Routing + +Routing is a pure function over the current worker views, in one module with +one entry point selected by `gateway.routing`, the same shape as +`CapacityStrategy`. Nothing else in the gateway knows how a worker is chosen. +The v1 policy (`warm-then-free`), in order: + +1. drop workers that are disconnected, drained, incompatible, or lacking the + requested platform, model, or runtime — a download counts as available + only on a worker whose own `downloads.policy` would allow it; +2. prefer a worker with an unleased `ready` device matching the request — a + **warm hit**, and a sub-second grant; +3. otherwise the worker with the **most free running capacity** for that + platform. + +There is no other placement rule in v1: no requester affinity, no label +selectors, no per-worker platform exclusions. Each of those is a future +routing policy behind `gateway.routing`, not a change to the request shape — +which is why a lease request has the same shape against a worker and against +a gateway. + +### Leases through the gateway + +TTL-first leases (ADR 0004) are what let the gateway hold almost no lease +state at all. `lease.renew`, `lease.release`, and single-lease reads are +**forwarded** to the owning worker, and the `expiresAt` a client sees is the +worker's own. There is nothing to emulate and no timer to run: a client that +stops renewing loses its lease on the worker's clock, gateway or no gateway. + +- **The lease id names its worker.** A gateway lease id is the owning + worker's id, then a `.`, then the worker's own lease id — so renew, + release, and reads route by splitting on the **first** `.` rather than by + consulting state a restart could lose. A worker id is its instance + identity, a UUID, so a real one reads + `3f81a2c4-9b7d-4e21-8a55-1c0e6f2d7b93.lse_9f2c`; every example in these + docs abbreviates it to its first segment for legibility. Clients treat the + whole thing as opaque, exactly as they already treat `lse_9f2c`. +- **The lease object gains `worker: { id, label }`** (additive) so a client + and the console can say *where* the device lives. A worker's network + address is never on it: clients reach devices through the gateway. +- **One lease per requester is fleet-wide.** A requester already holding a + gateway-issued lease on any worker gets `REQUESTER_ALREADY_LEASED` from the + gateway, naming the existing lease. The gateway enforces this from its own + index of the leases *it* issued, rebuilt from each worker's `lease.list` on + uplink connect. It picks its own out of that list by the requester prefix + it stamps on every lease it forwards — `gw::` — which + works precisely because the gateway's instance id is stable across + restarts: the index can be rebuilt from a worker's leases alone, with + nothing persisted on the gateway and no ambiguity about which of them are + its own, another gateway's, or the worker's local ones. `release --all` and + the disconnected-retention hold both use that same filter, which is what + keeps them from ever touching a lease this gateway did not issue. +- **The requester id the gateway forwards is namespaced**: + `gw::`. A local agent on the worker machine + and a remote agent behind the gateway therefore can never collide on the + worker's own one-lease rule, and every lease on the worker is attributable + to the fleet it came from. The namespace is worker-side bookkeeping: the + gateway reports the leases it issued under the client's own requester id. +- **The gateway keeps no per-connection lease state** and releases nothing + when a client connection closes, exactly as a worker (ADR 0004 §3). +- **Pushes are relayed, not re-invented.** Progress for a dispatched request, + and the lease-scoped `lease-lost` / `device-unhealthy` / `device-recovered` + facts the worker's event stream carries, are re-pushed to whichever gateway + connection owns the request or lease — the same owner routing rule a worker + applies (ADR 0003 §8). + +### Reaching a device: `device.exec` + +`driver.passthrough` resolves a root-scoped command string for the *caller* +to spawn, which only works on the worker's own machine. `device.exec` (role +`agent`) is the operation that works everywhere: +`{ leaseId, tool: "simctl" | "adb", args, stdin?, requesterId? }`. + +The **worker** resolves the command through the same driver passthrough logic +— same root scoping, same refusal list for verbs that would change a device's +lifecycle behind the registry's back (`PASSTHROUGH_REFUSED`, or +`UNKNOWN_PASSTHROUGH_TOOL` for a `tool` it does not wrap) — and runs it +through its `ProcessRunner`. Output streams back as request-scoped `output` +pushes (`stream: "stdout" | "stderr"` plus a chunk, keyed by the frame id +exactly like `progress`), and the operation resolves with `{ exitCode }`. The +refusal list gains one entry this operation needs and the local passthrough +does not: a bare `adb shell` with no command is refused +(`PASSTHROUGH_REFUSED`, "needs a terminal") rather than accepted into a +session nobody can type into, which would otherwise sit there until the +timeout killed it. + +**Ownership is proven on both hops.** A non-admin session is gated the +ordinary way — its principal against the lease's `ownerId` (ADR 0003 §4), +exactly as `lease.renew` and `lease.release` are. `requesterId` (optional, +defaulting to the principal) exists for the one session that would otherwise +bypass that check: the gateway's admin session on a worker. Unlike renew and +release, **admin does not bypass here** — the worker compares the supplied +`requesterId` to the lease's own `requesterId` and answers `FORBIDDEN` on a +mismatch. Without that, "the gateway checked its own lease index" would be +the only thing standing between one fleet agent and another agent's device. +Two independent checks, one per hop: the gateway checks its lease index and +forwards the namespaced requester, and the worker checks that requester +against the lease in front of it. + +The **gateway proxies** the call to the owning worker over the uplink and +relays those pushes to the calling connection unchanged. It parses nothing +about the command. Because output is streamed rather than buffered there is +no size cap; what bounds a command is a timeout on each hop. `exec.timeoutMs` +on the worker (ten minutes) is the authoritative one, because that is the +side owning the process and able to kill it; `gateway.execTimeoutMs` (eleven +minutes) is a backstop for the case where the worker never answers at all — +deliberately the longer of the two, so an ordinary timeout surfaces as the +worker's own `EXEC_TIMEOUT` instead of racing the gateway's (ADR 0005 §19e). + +Two deliberate limits: `stdin` is a single string sent with the request, not +an incremental channel, and there is no pseudo-terminal — line-oriented +commands work, full-screen ones do not. And `device.exec` runs against the +**worker's** filesystem, so an artifact a command names (`simctl install +`, `adb install `) has to get there out of band. The seam for a +later `device.upload` — chunks streamed as request-scoped pushes into a +per-lease scratch directory deleted on release — is left open by design, not +built. See [known-pitfalls.md](known-pitfalls.md). + +This is also what closes the gap that left `dataPlane` reserved: a remote +HTTP agent gets the same ability against a lone worker, with no gateway +involved at all. + +### Aggregated reads + +`status.get` on a gateway returns the same shape a worker returns — capacity +summed across connected workers, every gateway-issued and local lease, every +device, the gateway queue's depth — plus an additive `workers` array of +views, and `workerId` on every device and lease in the aggregate. +`catalog.get` is the union of the worker catalogs, each model and runtime +annotated with the workers that have it. + +Worker business events are republished on the gateway's bus with `workerId` +added to the payload and land in the gateway's own ring buffer, so `simlock +events --follow` against a gateway shows the whole fleet. The gateway also +emits its own facts — `worker.connected`, `worker.disconnected`, +`worker.rejected`, `worker.removed`, `worker.drain-started`, +`worker.drain-ended`, and `request.dispatched`; see [EVENTS.md](EVENTS.md). + +### Failure behaviour + +- **Uplink down.** No new dispatches to that worker. A renew or release for a + lease on it fails with `WORKER_UNREACHABLE` (`kind: "transport"`). The + worker's own TTL expires the lease and reclaims the device on its own + clock, and the gateway relays `lease-lost` once the uplink returns and it + sees the worker's `lease.expired` fact. **The gateway never guesses a lease + is gone before the worker says so** — it cannot tell a dead worker from an + unreachable one, and only one of those has released anything. +- **Dispatched, then the uplink drops.** The request's client sees + `WORKER_UNREACHABLE`. If the worker actually granted it, that lease exists + on the worker and expires there on its TTL. A retry hits the fleet-wide + one-lease rule only once the uplink is back and the index is rebuilt — + which is the `409 → GET` recovery loop the HTTP API already documents, + applied across the uplink gap. +- **Gateway restart.** In-flight requests are lost, exactly as a worker + restart loses them today (durable requests arrive with #72, for both). + Leases survive on their workers; workers reconnect on their backoff and the + gateway rebuilds every view and its lease index from them — picking its own + leases out of each `lease.list` by the `gw::` + requester prefix, which is why an instance id stable across restarts is + what makes a stateless rebuild possible at all. The worker registry, which + workers it knows and which are drained, comes back off disk rather than + being re-derived. Clients keep their leases and resume + renewing once the gateway answers again; a lease whose deadline passes + while the gateway is down expires on the worker, like any other unrenewed + lease. +- **Version skew.** `hello` over the uplink negotiates the protocol range + exactly as over the socket (ADR 0003 §6). ADR 0005 moves the wire to + protocol `{min: 5, max: 5}` with no compatibility shim — `device.exec` and + its `output` push family are new frames, and the honesty rule says a range + widens only where a compatibility path is actually kept — so **every worker + older than ADR 0005 is `incompatible` by range**, by construction rather + than by accident. That is the ordinary upgrade path, not a failure mode: + upgrade the worker. An incompatible worker is marked `incompatible` in its + view with both ranges shown and is never dispatched to, and it is not + hidden either — that is the machine an operator has to go and upgrade, and + it keeps serving its own local clients on its own protocol meanwhile. + +### Why this is safe + +**The gateway never touches a device.** Every invariant in +[agent-rules/safety.md](agent-rules/safety.md) keeps holding by construction +rather than through a second implementation of it: registry-only destruction, +never touching a leased device, reconcile-before-trusting, and +ownership-proven-not-inferred are all enforced where the registry and the +drivers are, on the worker. The gateway forwards `allowDownload` and the +worker clamps it through its own `downloads.policy`, so "no implicit multi-GB +downloads" is decided by the machine that would do the downloading. + +That is also why the machine-wide operations stay per-worker: `nuke.run`, +`cleanup.run`, `doctor.run`, and `driver.passthrough` answer +`UNSUPPORTED_IN_GATEWAY_MODE` on a gateway in v1. Fanning a destructive +command out to every machine in a fleet from one endpoint is not something v1 +should offer, and a passthrough command string the client cannot run is worse +than an error. `config.get` on a gateway returns the gateway's own config. + +### Boundaries + +The gateway is a second implementation of the contract's **handlers** (ADR +0003 §2), not a second contract: `src/gateway/` provides a `Dispatcher` whose +handlers read worker views and forward over uplinks instead of calling +`core`. That is the whole reason every existing frontend works against it +unchanged. + +`src/gateway/` **imports nothing from `drivers`** — it has no concept of a +UDID, an AVD, a snapshot, or an adb port — and from `core` only the +platform-agnostic queue and bus modules it reuses, never the registry, +capacity, or lifecycle modules. A boundary test in the same shape as +`src/contract/boundary.test.ts` enforces it. The rule is not stylistic: a +gateway that could reach a registry module is a gateway that could grow a +device-state opinion, and the safety argument above rests on it having none. + ## Core vs. drivers The core is platform-agnostic and written once: lease table, fair wait queue, diff --git a/docs/CLI.md b/docs/CLI.md index 1c66c21e7..26f8d2345 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -31,16 +31,24 @@ longer dumped to stderr on every failure, only on request via `--help`. |---|---|---| | 0 | — | success (for a `lease` that stayed alive: the lease ended normally) | | 1 | `INTERNAL` | internal / unexpected error | +| 1 | `WORKER_UNREACHABLE` | the gateway cannot reach the worker this lease or request lives on (its uplink is down) | | 2 | `USAGE` | usage error (bad flags, missing required args, unknown command) | | 2 | `BAD_FRAME` | malformed request frame sent to the daemon | | 2 | `BAD_REQUEST` | request payload failed validation | +| 2 | `UNSUPPORTED_IN_GATEWAY_MODE` | this command acts on one machine's devices and the daemon answering is a gateway; run it on the worker | +| 2 | `WORKER_CONNECTED` | `worker remove` on a worker whose uplink is still open; `drain` it and let it disconnect first | +| 2 | `UNKNOWN_REQUEST` | the daemon has no such operation — an operation this daemon's mode does not implement (`worker list` against a worker), or a client newer than the daemon | +| 2 | `PASSTHROUGH_REFUSED` | a `simctl`/`adb` verb simlock refuses, a caller-supplied `--set`/`-P`, or a bare `adb shell` where there is no terminal to give it | +| 2 | `UNKNOWN_PASSTHROUGH_TOOL` | a passthrough tool simlock does not wrap | | 10 | `QUEUE_TIMEOUT` | timed out waiting for a device (`--timeout` elapsed) | +| 10 | `EXEC_TIMEOUT` | a `simctl`/`adb` command run through `device.exec` outlived `exec.timeoutMs` and was killed | | 11 | `NO_CAPACITY` | capacity reached and `--no-wait` was set | | 12 | `NO_DRIVER` | no driver registered for the requested platform | | 12 | `RUNTIME_MISSING` | runtime not installed and no `--allow-download` | | 12 | `UNKNOWN_MODEL` | unknown device model for the platform | | 12 | `INSUFFICIENT_DISK_SPACE` | not enough free disk space to install a component | | 12 | `LICENSE_NOT_ACCEPTED` | a required license (e.g. an Android SDK license) is not accepted | +| 12 | `UNKNOWN_WORKER` | `worker drain`/`undrain` naming a worker the gateway does not know | | 13 | `REQUESTER_ALREADY_LEASED` | requester already holds a lease or has a pending request — one lease per agent in v1; release the named lease first | | 14 | — | `lease` without `--detach` only: the daemon ended the lease without the holder asking (TTL expiry, operator `release`, or an unrecoverable device) | @@ -54,6 +62,36 @@ surfaced by `lease renew`) falls back to exit 1; the structured stderr line still reports the specific code — a renew by a running `simlock lease` is the exception, and exits `14`. +The five ADR 0005 codes are placed on existing numbers rather than new ones, +and the numbers are fixed by the contract's error table in the PRs that +implement them ([ADR 0005](adr/0005-gateway-and-worker-modes.md)): + +- `WORKER_UNREACHABLE` is `kind: "transport"`, the fleet's version of + `DAEMON_CONNECTION_LOST`: the thing you were talking to went away. Both + exit `1`, and the stderr line's `code` is what distinguishes them. +- `WORKER_CONNECTED` and `UNSUPPORTED_IN_GATEWAY_MODE` are both "the request + as sent is not one this daemon will take", which is what exit `2` already + means for `USAGE` and `BAD_REQUEST`. Neither is retryable as written: the + fix is a different command, or the same command against a different daemon. + `UNSUPPORTED_IN_GATEWAY_MODE` in particular is permanent, not provisional: + `nuke`, `cleanup`, `doctor`, and `driver.passthrough` stay per-worker + operations rather than waiting on some later fleet-wide version (ADR 0005 + §34). +- `UNKNOWN_WORKER` takes `12`, the number the table already gives to "the + thing you named cannot be resolved" (`UNKNOWN_MODEL`, `NO_DRIVER`), because + that is what it is: a worker id the gateway has no record of. +- `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, and `UNKNOWN_REQUEST` + are not new codes at all — they are already in the contract's table at exit + `2`, and they are listed here because `device.exec` and the `worker.*` + operations are new ways to reach them. +- `EXEC_TIMEOUT` joins `QUEUE_TIMEOUT` on `10`, the number that already means + "a deadline elapsed". The two can never be confused, since only `lease` + produces one and only `simctl`/`adb` produce the other. What *can* collide + is a passthrough tool that itself exits `10` — `simlock simctl` and + `simlock adb` exit with the tool's own status — so for those two commands + branch on the stderr `{"error":{"code":...}}` line, which only simlock + writes, rather than on the number alone. + --- ## Agent identity @@ -360,13 +398,26 @@ or not, the path has to reach the command line: xcrun simctl --set "$SIMLOCK_IOS_DEVICE_SET" list devices ``` -## `simlock simctl ` +Both ways describe paths and ports **on the machine that owns the device**. +That is your own machine when you lease from a local worker, and somebody +else's when you lease through a gateway or over HTTP — a device set path from +another Mac is of no use locally, and `--export-env` cannot make it one. When +the device is remote, reach it with `simlock simctl` / `simlock adb`, which +run the command where the device is; see [Against a +gateway](#against-a-gateway). + +## `simlock simctl [--lease ] ` Run `xcrun simctl` against Simlock's iOS device set. Every argument is passed through unchanged with `--set ` inserted, so the command behaves exactly as documented by Apple — it just resolves the UDIDs Simlock manages, which a bare `simctl` cannot see. +`--lease` is only meaningful against a **gateway**, where the device is on +another machine and the command runs through `device.exec`, which is scoped +to a lease; see [Against a gateway](#against-a-gateway). Against a worker it +is unnecessary, and accepted so that one command line works against either. + ```bash simlock simctl install booted ./MyApp.app simlock simctl io booted screenshot shot.png @@ -389,10 +440,24 @@ Refused, all exit 2 with `USAGE` and a message naming what to run instead: a refused verb read as an ordinary operand. Run `xcrun simctl` directly if you mean to leave Simlock's set. -## `simlock adb ` +Against a **gateway**, the device is on another machine, so the command runs +there instead — see [Against a gateway](#against-a-gateway). The refusals +above are unchanged, and where they are enforced does not change either: +**the daemon refuses, the CLI reports.** The CLI holds no copy of the refusal +list in either direction — frontends render the contract, and the list lives +with the driver that owns the device (ADR 0003 §11). Locally that means +`driver.passthrough` refuses and the CLI relabels the answer as `USAGE` +(exit 2); through a gateway it sends `device.exec` and the worker refuses +with `PASSTHROUGH_REFUSED`, or `UNKNOWN_PASSTHROUGH_TOOL` for a tool it does +not wrap, which the CLI relabels exactly the same way it relabels the local +one. Same exit code, same message, one source of truth — and a caller +reaching `device.exec` over HTTP gets the daemon's own code, unrelabelled. + +## `simlock adb [--lease ] ` Run `adb` against Simlock's adb server. Arguments pass through unchanged with -`-P ` inserted. +`-P ` inserted. `--lease` behaves exactly as it does for +`simlock simctl` above. ```bash simlock adb shell input tap 100 200 @@ -412,7 +477,9 @@ Each is matched anywhere in the arguments, so `-s emu kill` and load into a full wipe. Use `simlock release` (which reclaims the device for you) or `simlock cleanup` -instead. +instead. As with `simlock simctl`, against a gateway the command runs on the +worker that owns the device (see [Against a gateway](#against-a-gateway)) and +the refusals above hold on both ends. ## `simlock release | --all` @@ -437,6 +504,264 @@ in-flight purges before exiting, so a graceful shutdown still leaves the pool settled; a daemon killed mid-purge leaves its devices `reclaiming` for the next startup to recover. +## Against a gateway + +A **gateway** is a simlock daemon that owns no devices and fronts the workers +that joined it ([ADR 0005](adr/0005-gateway-and-worker-modes.md); see +[CONFIGURATION.md](CONFIGURATION.md#modes-gateway-and-worker) for `mode` and +the keys each side reads). Point the CLI at one the way you point it at any +daemon: `SIMLOCK_HOME` selects the data directory, and the daemon socket in +it is what the CLI connects to. **The commands do not change.** A gateway +implements the same contract a worker does, so this whole document still +applies; what follows is only the handful of places where you can tell. + +The CLI speaks the unix socket and nothing else — it has no HTTP transport +and no `--url`, so "point the CLI at a gateway" means running it on the +gateway's own machine (or wherever that socket is), typically as the +operator. An agent on another machine reaches the fleet over the +[HTTP API](HTTP-API.md), which is what the gateway is listening on and what +that API exists for. Both get the identical contract; only the transport +differs. + +**Leasing is identical.** `simlock lease` takes the same flags and prints the +same grant line, including `--ttl`, `--no-wait`, `--timeout`, and +`--allow-download` (forwarded to the chosen worker, which clamps it through +its own `downloads.policy`). The request waits in the gateway's own +fleet-wide FIFO queue, reporting `queued` with a `queuePosition` exactly as a +worker's queue does, and is dispatched to the worker best placed to serve it +— a machine with a matching warm device first, otherwise the one with the +most free capacity. You do not name a machine and there is no flag to; where +a device lives is the gateway's decision. + +The grant carries one additional block so you can see where it landed: + +```json +{"lease":{"id":"3f81a2c4.lse_9f2c","worker":{"id":"3f81a2c4","label":"mac-studio-2"}}} +``` + +The lease id names its worker (that is how renew, release, and reads route +with no gateway-side state to lose), but it is **opaque** — do not parse it. +`worker.label` is display-only. + +**`lease renew`, `release`, and lease reads are forwarded** to the worker +that owns the lease, and the `ttlDeadline` you see is that worker's own. +Leases are TTL-first on every transport (ADR 0004), so a gateway emulates +nothing: a `simlock lease` left running renews on its timer as always, and a +client that stops renewing loses the lease on the worker's clock whether or +not a gateway is in the path. + +**One lease per requester is fleet-wide.** Leasing while you already hold a +gateway-issued lease on *any* worker in the fleet is `REQUESTER_ALREADY_LEASED` +(exit 13) naming that lease, the same rule and the same code as on one +machine. + +One thing an operator sees only from the other side: the requester id the +gateway forwards to a worker is **namespaced**, +`gw::`. So `simlock status` on the *worker* +shows a fleet lease as `gw:7c1e…:agent-1` while the gateway shows it as +plain `agent-1`. That is what keeps a local `agent-1` on that machine and a +remote `agent-1` behind the gateway from colliding on the worker's own +one-lease rule — and it means a lease's attribution says which fleet it came +from, not just who asked. + +**`simlock status` and `simlock list`** answer for the whole fleet: capacity +summed over connected workers, every lease and device carrying the +`workerId` it lives on, the gateway queue's depth — plus a `workers` block, +one entry per worker view, which is what `simlock worker list` prints on its +own. `status`'s daemon block carries `mode` (`"worker"` or `"gateway"`); that +field is the only way a client tells the two apart. + +**`simlock release --all`** releases only the leases **this gateway +issued**, on every connected worker, and never a worker's own local ones: the +gateway did not issue those, does not know who holds them, and taking a local +developer's device away from an endpoint they have never heard of is not an +operator action anyone asked for. A worker it cannot reach is reported as +`WORKER_UNREACHABLE` naming that worker while the reachable workers' leases +are still released — a partial result stated plainly beats an all-or-nothing +that leaves you guessing. Confirmation is still required unless `--yes`. +Releasing a single lease by id is unchanged. + +**`simlock catalog`** is the union of the workers' catalogs, each model and +runtime annotated with the workers that have it — so a `--device` the +catalog lists is leasable *somewhere*, not necessarily everywhere. + +**`simlock events`** shows the fleet: every worker's business events are +republished on the gateway's bus with `workerId` added to the payload, +alongside the gateway's own `worker.*` and `request.dispatched` facts (see +[EVENTS.md](EVENTS.md)). `--follow` and `--since` work as always, over the +gateway's own ring buffer. + +**`simlock simctl` and `simlock adb`** keep working, but not the same way +underneath. Against a **worker** they behave exactly as documented above: the +daemon resolves a root-scoped command through `driver.passthrough` and the +CLI spawns it locally with inherited stdio, so an interactive `adb shell` is +still an interactive `adb shell`. Against a **gateway** the device is on +another machine, so the CLI sends `device.exec` instead and prints the output +it streams back — stdout to stdout, stderr to stderr, as it arrives — exiting +with the tool's own exit code. + +The CLI picks between the two by reading `mode` off `status.get`, which it +already calls: `gateway` means `device.exec`, anything else means +`driver.passthrough`. It is not guesswork and not a flag — the daemon says +what it is, and there is exactly one thing to branch on. (A remote agent +reaches the same operation as `POST /v1/leases/{id}/exec`; see +[HTTP-API.md](HTTP-API.md).) Three consequences: + +- **It needs a lease**, because `device.exec` is scoped to one. The CLI uses + your own lease, which the one-lease-per-requester rule makes unambiguous; + `--lease ` names one explicitly (and is required if you hold none + under the identity you are running as — see [Agent + identity](#agent-identity)). An **agent-role** invocation sends no + `requesterId` at all and is gated the ordinary way, its principal against + the lease's `ownerId`, exactly as `lease renew` and `release` are. An + **admin-role** one — the usual case, since the CLI connects as admin + whenever `admin.token` is readable — sends its resolved agent id as + `requesterId`, because on this one operation **admin does not bypass the + ownership check** and the worker compares that id to the lease's own. So + `simlock simctl --lease ` fails even from an + admin-credentialed CLI; set `--agent-id`/`SIMLOCK_AGENT_ID` to the identity + that holds the lease if you mean to drive that device. +- **There is no pseudo-terminal.** Line-oriented commands work; full-screen + ones do not. If stdin is a pipe or a file, the CLI reads it to EOF *before* + sending, and it travels as the request's one `stdin` string, written to the + process and then closed — so `echo hello | simlock adb shell cat` works and + an interactive `adb shell` does not, because there is no channel to type + into once the request has gone. That last case does not hang waiting to + find out: the worker refuses a bare `adb shell` with no command outright, + `PASSTHROUGH_REFUSED` (exit 2) and a message saying it needs a terminal, + rather than starting a session nobody can type into and letting it sit + there for ten minutes until `EXEC_TIMEOUT`. +- **A command that outlives `exec.timeoutMs`** (10 minutes, worker-side and + authoritative) is killed and the command fails with `EXEC_TIMEOUT` + (exit 10). Output is streamed, never buffered, so there is no size cap. + +Files do not travel with the command: `simctl install ` and `adb +install ` resolve their path on the **worker's** filesystem, so the +artifact has to be there already (a shared volume, a CI checkout on that +machine). See [known-pitfalls.md](known-pitfalls.md). + +**Three commands refuse outright**, with `UNSUPPORTED_IN_GATEWAY_MODE` (exit +2): `simlock nuke`, `simlock cleanup`, and `simlock doctor`. Each acts on one +machine's devices as a whole, and in v1 they stay per-worker, direct +operations — run them against that worker's own daemon. A fleet-wide +destructive command from one endpoint is not something v1 offers. +`driver.passthrough`, the operation behind the *local* form of `simlock +simctl` / `simlock adb`, answers the same way for the same reason: a +root-scoped command string naming a device set on another machine is +something the client cannot run, and handing it one would be worse than an +error. That is why those two commands switch to `device.exec` here rather +than failing. + +`simlock config get` on a gateway returns the gateway's own configuration, +not any worker's. `simlock daemon ` manages the +gateway process itself, exactly as it manages a worker's. + +**When a worker is unreachable** — its uplink is down — anything routed to it +fails with `WORKER_UNREACHABLE` (exit 1, `kind: "transport"`): a renew, a +release, a `simctl`/`adb`, or a request that had already been dispatched to +it. The gateway does not guess that the lease is gone; the worker's own TTL +ends it on the worker's clock, and the loss reaches you once the uplink is +back. The recovery is the ordinary one: re-request, and if the worker had in +fact granted you a lease, the fleet-wide one-lease rule names it once the +gateway has rebuilt its index. + +## `simlock worker ` + +Operator commands for the workers connected to a **gateway**. All four need +the `admin` role (see [Admin credential +resolution](#admin-credential-resolution)). A worker has no workers of its +own, so it does not implement these operations at all and answers +`UNKNOWN_REQUEST` — they are not a gateway-mode refusal of something a worker +could otherwise do, they are simply not part of a worker's surface. Output is +JSON on stdout, unconditionally — `--json` is a usage error (exit 2), as +everywhere except `status`/`catalog`/`daemon`. + +``` +simlock worker list +simlock worker drain +simlock worker undrain +simlock worker remove +``` + +`list` prints one worker view per connected-or-remembered worker: + +```json +{"workers":[{"id":"3f81a2c4","label":"mac-studio-2","state":"connected","drained":false, + "daemonVersion":"0.4.0","protocol":{"min":5,"max":5}, + "connectedAt":1735689600000,"lastSeenAt":1735689930000, + "capacity":{"ios":{"running":2,"limit":4},"android":{"running":0,"limit":2}}, + "downloads":{"policy":"on-request"}, + "queueDepth":0,"leases":3,"devices":5}]} +``` + +`downloads.policy` is that worker's own effective policy, read once with +`config.get` when its uplink connects — routing needs it to know whether a +machine may install a missing runtime before sending it a request that needs +one. `protocol` is the range that worker negotiated; ADR 0005 moves the wire +to `{min: 5, max: 5}` with no shim, so a worker older than it does not +overlap and shows as `incompatible`. Worker ids are UUIDs — the examples here +abbreviate them to their first segment. + +`state` is `connected`, `disconnected`, or `incompatible`. A **disconnected** +worker keeps its last-known view (nothing is dispatched to it) until an +operator removes it or `gateway.disconnectedRetentionMs` (24 hours) elapses. +The retention clock is held while the gateway still knows of gateway-issued +leases on that worker — forgetting a worker that holds someone's device is +how a lease becomes unroutable — and that hold ends when the **last of those +leases passes its deadline**, since a lease the gateway cannot renew is one +the worker has expired on its own clock. A worker gone longer than every +lease it held is a worker with nothing left to protect. + +An **incompatible** worker is one whose protocol range does not overlap the +gateway's; its view shows both ranges and it is never dispatched to, but it +is not hidden — that is the machine an operator has to go and upgrade, and it +still serves its own local clients fine. + +`drain` is how a machine is taken out of service without killing anyone's +device: a drained worker **keeps its existing leases** and receives no new +dispatches. Wait for its leases to end (`simlock status` shows them), then do +the maintenance. `undrain` puts it back in rotation. + +Draining sticks until you undrain it. It is your intent about that machine, +not something read off it, so it lives in the gateway's **worker registry** — +the one piece of gateway state that is persisted (a small file under the +gateway's `SIMLOCK_HOME`, owner-only) as opposed to the worker *view*, which +is rebuilt on every connect. A drained worker that restarts comes back +drained, and so does one whose *gateway* restarted. Nothing but `undrain` +puts a machine back in rotation, which is the point: an operator who drained +a worker and walked away should not have a process they never touched undo +it. + +`remove` forgets a worker. A worker whose uplink is still open is refused +with `WORKER_CONNECTED` (exit 2) — a connected worker would simply reappear, +so removing one is a request that cannot mean what it says; drain it and stop +its daemon (or revoke its join token, which closes the uplink) first. + +On a worker the gateway knows, all three print the resulting state: + +```json +{"workerId":"3f81a2c4","drained":true} // drain +{"workerId":"3f81a2c4","drained":false} // undrain +{"workerId":"3f81a2c4","removed":true} // remove +``` + +For an id the gateway does **not** know they diverge, deliberately: + +- `drain` and `undrain` **fail** with `UNKNOWN_WORKER` (exit 12). Draining is + an instruction about one specific machine, usually typed just before + someone walks over to it; succeeding silently against an id that is not + there would hide a typo in exactly the moment an operator most needs to + know the instruction landed. +- `remove` **succeeds** with `{"removed":false}`, the way `token revoke` + answers for an unknown token id. "Forget this worker" is already true of a + worker the gateway has already forgotten, so there is nothing to report + and nothing for a script to special-case on a re-run. + +A worker is never *added* by a command. It appears by connecting: mint a join +token on the gateway with `simlock token create --role worker`, put it in the +worker's `gateway.token` alongside `gateway.url`, and start it. `simlock +token revoke ` closes any uplink that token opened. + ## `simlock mcp` Start Simlock's local stdio MCP server. It accepts no flags. Standard output is @@ -520,10 +845,21 @@ queue depth. `--json` for the structured equivalent. `overLimit` is true when a lowered limit cannot yet be met, for example because active leases consume all running slots. +The daemon block carries `mode` (`"worker"` or `"gateway"`) — the one field +that tells a client which kind of daemon answered. Against a **gateway** the +same view is the fleet's: capacity summed over the connected workers, every +lease and device tagged with the `workerId` it lives on, the gateway queue's +depth, plus a `workers` array of worker views (the same records +[`simlock worker list`](#simlock-worker-listdrainundrainremove) prints). See +[Against a gateway](#against-a-gateway). + ## `simlock list [--devices|--leases|--rules]` Scriptable listings of managed devices, active leases, or registered cleanup -rules. Defaults to `--devices`. Each lease record's `requesterId` is the +rules. Defaults to `--devices`. Against a gateway, `--devices` and `--leases` +are the fleet's (each record naming its `workerId`) while `--rules` lists +nothing at all: cleanup rules run where the devices and the reaper are, and a +gateway has neither. Each lease record's `requesterId` is the agent id (see [Agent identity](#agent-identity)) that holds it, and its `lastRenewedAt` is when the lease was last renewed (set at grant, then on every renew) — the same field `status` renders as "last renewed". @@ -551,7 +887,9 @@ structured equivalent: Run the cleanup reconciliation immediately. `--dry-run` prints the actions each rule *would* take (rule name, target, reason) without executing. `--rule` restricts to a single named rule (e.g. `--rule idle-destroy`); see -`simlock list --rules` for the registered rules. +`simlock list --rules` for the registered rules. A gateway owns no devices to +clean up, so it answers `UNSUPPORTED_IN_GATEWAY_MODE` (exit 2) — run this +against the worker whose machine you mean. ## `simlock doctor [--fix] [--purge-orphans] [--yes]` @@ -559,7 +897,9 @@ Reconcile the daemon's state with reality (`simctl list`, `adb devices`, running emulator processes): report orphaned processes, registry entries whose device vanished, devices booted outside simlock, expired leases whose device is still marked `leased`, devices stuck mid-transition, and orphans. `--fix` -applies the safe corrections. +applies the safe corrections. Reconciliation compares a registry against one +machine's driver reality, so a gateway — which has neither — answers +`UNSUPPORTED_IN_GATEWAY_MODE` (exit 2); run `doctor` on each worker. An **orphan** is a device sitting inside a Simlock device root with no registry record — almost always a daemon that died between creating a device and writing @@ -621,13 +961,28 @@ runtimes that support it. Emergency reset: force-release all leases, kill emulator/simulator processes simlock started, clear the queue. With `--delete-devices`, also destroy every -registry-managed device. Never touches devices outside the registry. +registry-managed device. Never touches devices outside the registry. It stays +a per-machine command: a gateway answers `UNSUPPORTED_IN_GATEWAY_MODE` (exit +2), because a fleet-wide wipe from one endpoint is a footgun v1 does not +offer. ## `simlock events [--follow] [--since ]` Stream the business-event ring buffer (see [EVENTS.md](EVENTS.md)) as JSON lines. `--follow` keeps streaming; `--since 1h` replays recent history. +Against a **gateway** this is the fleet's stream: every connected worker's +business events, republished on the gateway's bus with `workerId` added to +the payload, interleaved with the gateway's own `worker.connected` / +`worker.disconnected` / `worker.rejected` / `worker.removed` / +`worker.drain-started` / `worker.drain-ended` / `request.dispatched` facts. +`worker.rejected` is how you find out why a machine never appeared in +`simlock worker list` at all — it reports an uplink refused at the door, +which nothing else records. It is one ring buffer like +any other, so it resets when the gateway restarts and it holds only what +arrived while the gateway was up — a worker's events from before its uplink +connected are not backfilled. + ## `simlock daemon ` Manage the daemon explicitly. Other commands auto-start it on demand; `daemon` @@ -646,12 +1001,14 @@ answered but refused the connection (a bad admin credential, or a protocol version mismatch) — the two used to be reported identically as "stopped". A daemon that refuses to boot because of its configuration — a -`lease.defaultTtlMs` above `lease.maxTtlMs`, or a non-positive value for -either, see [CONFIGURATION.md](CONFIGURATION.md) — fails the start rather -than picking a value the operator did not write. That validation runs before -the socket is claimed, so a command that auto-starts the daemon (`simlock -lease`, the MCP server) never gets a daemon to talk to: the launch times out -and the command fails with exit 1 (`INTERNAL`). The error line says nothing +`lease.defaultTtlMs` above `lease.maxTtlMs` or a non-positive value for +either, `mode: "gateway"` with `http.enabled: false`, or, in worker mode, +`gateway.url` without `gateway.token` or the reverse; see +[CONFIGURATION.md](CONFIGURATION.md) for the full set — fails the start +rather than picking a value the operator did not write. That validation runs +before the socket is claimed, so a command that auto-starts the daemon +(`simlock lease`, the MCP server) never gets a daemon to talk to: the launch +times out and the command fails with exit 1 (`INTERNAL`). The error line says nothing about the config, because nothing ever answered — the reason is in `simlock daemon logs`, which reads the log file directly and so works even though the daemon never came up. @@ -666,20 +1023,45 @@ shows the current file with the immediately preceding one prepended. ## `simlock config [get |set ]` -Show the effective configuration (defaults + config file + overrides): -managed and running capacity limits, idle tiers T1/T2/T3, TTLs, disk-pressure -threshold, and the daemon's log level/rotation cap (`log.level`, -`log.rotateBytes`). With no args, prints everything. The capacity numbers +Show the effective configuration (defaults + config file + overrides): the +daemon's `mode`, managed and running capacity limits, idle tiers T1/T2/T3, +TTLs, disk-pressure threshold, and the daemon's log level/rotation cap +(`log.level`, `log.rotateBytes`). With no args, prints everything. The capacity numbers come from the selected capacity strategy (`capacity.strategy`, configured under `capacity.config` — see [CONFIGURATION.md](CONFIGURATION.md#capacity-strategies)). Whichever strategy is running, both a global and a per-platform running limit must have room before Simlock provisions or boots a shutdown device. +`simlock config set mode gateway` turns this daemon into a **gateway** — one +that owns no devices and fronts the workers that join it — and `simlock +config set mode worker` turns it back. Like every `config set`, it is a +validated file write, and config is daemon *input*, read at start: the +running daemon keeps running in the mode it started in until +`simlock daemon stop` and the next start. The same command sets a worker's +`gateway.url` and `gateway.token` to join a fleet. See +[CONFIGURATION.md](CONFIGURATION.md#modes-gateway-and-worker) for which keys +each mode reads. + +Switching to `gateway` is **two keys, not one**: `mode` and `http.enabled`. +A gateway is the fleet's contact point, so it must listen on HTTP — workers +open their uplinks there and remote agents lease through it — and +`mode: "gateway"` with `http.enabled: false` is therefore rejected at load +and the daemon does not start, naming the key. It is the one gateway config +pair that fails rather than warns, for the same reason a `lease.defaultTtlMs` +above `lease.maxTtlMs` fails: there is no safe way to read it. So: + +```sh +simlock config set mode gateway +simlock config set http.enabled true +simlock daemon stop && simlock daemon start +``` + ## Admin credential resolution Several commands (`list`, `cleanup`, `nuke`, `events`, `config get`, -`daemon stop`, `token create|list|revoke`, and cross-process `lease renew` +`daemon stop`, `token create|list|revoke`, +`worker list|drain|undrain|remove`, and cross-process `lease renew` and `release`) need the daemon's `admin` role. The CLI resolves a credential to send at handshake, in order: @@ -702,7 +1084,7 @@ pid-derived identity: all of them connect as admin (when the local file is readable), and admin bypasses the per-connection ownership check that would otherwise apply. -## `simlock token create --role [--label ]` / `list` / `revoke ` +## `simlock token create --role [--label ]` / `list` / `revoke ` Mint and manage bearer tokens for the HTTP API. `token.create|list|revoke` are daemon operations (admin role) — the daemon is the only process that @@ -725,6 +1107,23 @@ the secret and its hash. `revoke ` prints `{"revoked":true}` or `{"revoked":false}` for an id that does not exist — the daemon's `token.revoke` operation does not treat an unknown id as an error. +### The `worker` role: join tokens + +`--role worker` mints a **join token**: the credential a worker presents when +it opens its uplink to a gateway ([ADR +0005](adr/0005-gateway-and-worker-modes.md)). Mint it **on the gateway**, +then put the secret in that worker's `gateway.token` beside its +`gateway.url`. It is the narrowest role there is — a `worker` token can open +an uplink and nothing else, and presenting one on any `/v1` route other than +`/v1/uplink` is `403`, just as an `agent` or `operator` token presented at +`/v1/uplink` is. Tokens +do not cross machines either: a gateway's tokens are valid on that gateway +and nowhere else, and a worker's own tokens are its own. + +`simlock token revoke ` on the gateway closes any uplink that token +opened, which is the way to eject a worker that should no longer be in the +fleet; `simlock worker remove` then forgets its view. + ## Environment variables ### `SIMLOCK_HOME` diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 498cbfe50..7f9b733a5 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -178,6 +178,105 @@ provision/boot/reclaim — the daemon keeps doing the work, the caller just doesn't end up holding the result. This is recorded as a known gap in [known-pitfalls.md](known-pitfalls.md). +## Running a command on the leased device: `exec` + +`exec` runs one `simctl` / `adb` command against a device you hold a lease +on, wherever that device actually is, and streams its output back as it +arrives ([ADR 0005](adr/0005-gateway-and-worker-modes.md)): + +```ts +const { exitCode } = await client.exec( + { leaseId: grant.lease.id, tool: "simctl", args: ["install", "booted", "/tmp/MyApp.app"] }, + { + onOutput: ({ stream, chunk }) => { + (stream === "stderr" ? process.stderr : process.stdout).write(chunk); + }, + }, +); +``` + +`onOutput` fires per chunk, with `stream: "stdout" | "stderr"`, in the order +the process produced it; the promise resolves once the command exits, with +the tool's own `exitCode` — a non-zero one is the command's answer, not a +thrown error. Output is streamed rather than buffered, so there is no size +cap and nothing accumulates in memory unless your handler accumulates it. +Omit `onOutput` and the output is simply dropped. + +`exec` takes an optional `requesterId`, defaulting to the principal. An +agent-role connection does not need it: it is gated the ordinary way, its +principal against the lease's `ownerId` (ADR 0003 §4), exactly as +`renewLease` and `releaseLease` are. The field exists for the one session +that would otherwise bypass that check — the gateway's admin session on a +worker — and on this operation, unlike renew and release, **admin does not +bypass**: the worker compares the supplied `requesterId` to the lease's own +`requesterId` and answers `FORBIDDEN` on a mismatch. A host process proxying +several agents through an admin connection therefore passes the requester +that holds the lease: + +```ts +await admin.exec( + { leaseId, tool: "adb", args: ["shell", "getprop"], requesterId: "agent-7" }, + { onOutput }, +); +``` + +Five things to know before building on it: + +- **It is scoped to a lease the caller owns**, and it is the one + lease-scoped operation where **`admin` does not bypass the ownership + check**. `renewLease` and `releaseLease` let an admin connection act on any + lease; `exec` does not, because a gateway's session on a worker is itself + an admin session, and an admin bypass would leave one fleet agent's device + protected only by the gateway's own index. Pass the right `requesterId` or + get `FORBIDDEN`. +- **The command runs on the machine that owns the device**, against that + machine's filesystem. A path in `args` (`simctl install `, `adb + install `) resolves *there*, so getting an artifact to a remote worker + is out of band in v1 — see [known-pitfalls.md](known-pitfalls.md). +- **`stdin` is one string, sent with the request** and then closed, and there + is no pseudo-terminal. Line-oriented commands work; full-screen ones do + not. +- **It is bounded by one timeout** (`exec.timeoutMs`, ten minutes by + default, on the machine that runs the command). A command that outlives it + is killed and the call rejects with `EXEC_TIMEOUT`. +- **The refusals are the daemon's, not a client's.** A verb that would change + a device's lifecycle behind the registry's back rejects with + `PASSTHROUGH_REFUSED`, and a `tool` outside `simctl`/`adb` with + `UNKNOWN_PASSTHROUGH_TOOL` — the same list `simlock simctl` / + `simlock adb` document. One refusal is particular to `exec`: a bare `adb + shell` with no command is `PASSTHROUGH_REFUSED` ("needs a terminal") rather + than a call that hangs until the timeout, since there is no pseudo-terminal + for it to attach to. + +## A gateway is just a daemon, as far as this client knows + +`connectSimlock`/`connectSimlockAdmin` connect to a **gateway** — a daemon +that owns no devices and fronts a fleet of workers — exactly as they connect +to an ordinary worker daemon, over its unix socket, with the same methods, +the same types, and the same error codes ([ADR +0005](adr/0005-gateway-and-worker-modes.md)). That is the point of the +gateway implementing the same contract: nothing in this module knows the +difference, and neither does code written against it. + +**The one way to tell is `mode` in `getStatus()`'s daemon block** +(`"worker" | "gateway"`). Everything else you might reach for is a leaky +inference rather than an answer: a lease from a gateway carries an additive +`worker: { id, label }` block, but so might a future single-machine daemon's; +a lease id from a gateway names its worker, but ids are opaque and parsing +one is a bug waiting to happen. + +Two behaviours worth knowing when the daemon on the other end is a gateway, +neither of which changes a call's shape: + +- The one-lease-per-requester rule is **fleet-wide** — + `REQUESTER_ALREADY_LEASED` can name a lease on a machine you have never + heard of. +- A new error code, `WORKER_UNREACHABLE` (`kind: "transport"`), can come back + from any lease-scoped call when the worker holding that lease has lost its + uplink. Treat it as you would `DAEMON_CONNECTION_LOST` for that one lease: + the lease is not necessarily gone, you simply cannot reach it right now, + and it runs on the worker's TTL either way. + ## What this client does not do - It does not start or stop the daemon. `connectSimlock`/`connectSimlockAdmin` diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 4a51d5fad..3e285f502 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -7,6 +7,7 @@ a warning. Inspect the effective, merged configuration at any time with | Property | Description | Default | | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | +| `mode` | Which shape this daemon runs as: `worker` (owns devices on this machine) or `gateway` (owns none, fronts the workers that join it). See [Modes: gateway and worker](#modes-gateway-and-worker). | `worker` | | `capacity.strategy` | Which policy decides how many devices may exist and run at once: `resource` or `fixed`. The options under `capacity.config` are that strategy's own -- see [Capacity strategies](#capacity-strategies). | `resource` | | `idle.shutdownAfterMs` | How long an unused device sits idle before Simlock shuts it down (tier 1, reclaims RAM). | `10 minutes` | | `idle.deleteAfterMs` | How long a shut-down device sits idle before Simlock deletes it (tier 2, reclaims disk). | `1 hour` | @@ -16,7 +17,14 @@ a warning. Inspect the effective, merged configuration at any time with | `warmPool.quarantine.maxRetryBackoffMs` | Cap on the quarantine retry backoff. | `5 minutes` | | `lease.defaultTtlMs` | TTL applied to a lease whose `lease.request` carried no `ttlMs` — **that request only**. It is *not* the renew fallback: a renew given no explicit TTL re-applies the lease's own stored width, so a lease granted for longer keeps it. A lease not renewed before its deadline expires and its device is reclaimed. | `15 minutes` | | `lease.maxTtlMs` | Largest TTL a request or a renew may ask for. A larger `ttlMs` is rejected with `BAD_REQUEST` rather than silently clamped, so a caller is never left believing it has more time than it does. | `4 hours` | -| `http.enabled` | Master switch for the network-facing HTTP API (see [HTTP-API.md](HTTP-API.md)). Off by default; the daemon binds nothing until this is `true`. | `false` | +| `gateway.url` | **Worker side.** Base URL of the gateway this worker joins, e.g. `wss://gw.example:4700`; the worker dials `/v1/uplink` and upgrades it to a WebSocket. Joining grants that gateway the `admin` role on this daemon, and `gateway.token` rides on the upgrade request as a bearer credential, so use `wss://` — or plain `ws://` only over loopback or inside your own tunnel. `http://` and `https://` are rejected at load. Unset means "do not join a fleet": the default, and the only thing that changes about a joined worker. | unset | +| `gateway.token` | **Worker side.** The join token (`simlock token create --role worker`, minted on the gateway) this worker presents when it opens its uplink. Required whenever `gateway.url` is set. | unset | +| `gateway.label` | **Worker side.** Display name for this worker in `simlock worker list`, `status`, the console, and on the lease's `worker` block. Display-only: nothing routes on it and it need not be unique. | the worker's own id | +| `exec.timeoutMs` | **Worker side.** How long one `device.exec` command (`simlock simctl` / `simlock adb` against a gateway or over HTTP) may run before the worker kills it and the operation fails with `EXEC_TIMEOUT`. Authoritative: it bounds the process that actually runs. | `10 minutes` | +| `gateway.routing` | **Gateway side.** Which routing policy places a queued request on a worker. `warm-then-free` is the only policy in v1: warm hit first, then the most free running capacity for the platform. See [Routing](ARCHITECTURE.md#routing). | `warm-then-free` | +| `gateway.disconnectedRetentionMs` | **Gateway side.** How long a disconnected worker is kept (greyed, never dispatched to) before the gateway forgets it. The clock is held while the gateway still knows of gateway-issued leases on that worker, and that hold ends when the last of those leases passes its deadline. | `24 hours` | +| `gateway.execTimeoutMs` | **Gateway side.** How long the gateway waits on a proxied `device.exec` before giving up. A backstop for a worker that never answers at all — deliberately longer than the worker's own `exec.timeoutMs`, which is authoritative because that side owns the process and can kill it, so an ordinary timeout surfaces as the worker's `EXEC_TIMEOUT` rather than racing this one. See [ADR 0005](adr/0005-gateway-and-worker-modes.md) §19e. | `11 minutes` | +| `http.enabled` | Master switch for the network-facing HTTP API (see [HTTP-API.md](HTTP-API.md)). Off by default; the daemon binds nothing until this is `true`. A gateway is the fleet's contact point, so it must be `true` there — see [Modes](#modes-gateway-and-worker). | `false` | | `http.host` | Address the HTTP listener binds. `127.0.0.1` keeps it loopback-only; reaching it remotely is the operator's own tunnel (Tailscale, cloudflared, reverse proxy) — Simlock does no TLS termination in v1. | `127.0.0.1` | | `http.port` | Port the HTTP listener binds. Must be an integer `1`-`65535`. | `4700` | | `diskPressure.freeBytesThreshold` | Free disk space below which Simlock treats the machine as under disk pressure. | `10 GiB` | @@ -48,6 +56,18 @@ must be non-negative numbers (milliseconds and bytes, respectively). integer in `1`-`65535`. `ios.slim.enabled` is a boolean, `ios.slim.categories` an array of non-empty strings, and `ios.slim.bootTimeoutMs` a positive number. +`mode` must be exactly `"worker"` or `"gateway"`. `gateway.url` must be an +absolute `ws`/`wss` URL — `http`/`https` are rejected — and `gateway.token` a +non-empty +string; **in `mode: "worker"`**, setting either without the other is rejected +at load and the daemon does not start, because a half-configured uplink would +otherwise come up looking like an ordinary standalone worker. That rule does +not apply in `mode: "gateway"`, where both keys are worker-side and are +warned about and ignored like every other worker key — a gateway is not +misconfigured by leftovers from the config it was flipped out of. +`gateway.label` is a non-empty string, `gateway.routing` one of the +registered routing policies, and `exec.timeoutMs`, `gateway.execTimeoutMs`, +and `gateway.disconnectedRetentionMs` positive numbers. `lease.defaultTtlMs` and `lease.maxTtlMs` must be positive numbers, and `lease.defaultTtlMs` must be `<=` `lease.maxTtlMs`. A config that violates either rule is **rejected at load and the daemon does not start**, naming the @@ -84,6 +104,85 @@ A warning rather than a hard failure keeps an old config bootable, and a warning rather than an alias keeps the key set honest — there is one name for this setting, and it is the one in the table above. +## Modes: gateway and worker + +`mode` decides what the daemon this config belongs to *is*, so it also +decides which of the keys above mean anything ([ADR +0005](adr/0005-gateway-and-worker-modes.md)). One daemon runs exactly one +mode; `simlock daemon start` starts whichever is configured, and switching is +`simlock config set mode gateway` followed by a restart. + +**A worker (`mode: "worker"`, the default) reads every key in this +document.** It is today's simlock, unchanged. Joining a fleet adds exactly +two keys — `gateway.url` and `gateway.token` — plus the optional +`gateway.label`, and changes nothing else about it: same drivers, same +registry, same capacity limits, same local unix socket, and its own local +agents keep leasing from it as before. `http.enabled` is *not* required for a +worker, because the uplink is outbound. + +**A gateway (`mode: "gateway"`) owns no devices**, so most of this document +does not apply to it. It reads: + +| Key group | Why | +|---|---| +| `mode` | to be a gateway at all | +| `gateway.routing`, `gateway.disconnectedRetentionMs`, `gateway.execTimeoutMs` | how to run the fleet | +| `http.*` | it is the fleet's contact point | +| `lease.*` | `defaultTtlMs`/`maxTtlMs` bound what its own clients may ask for, before a request is dispatched — see below | +| `log.*`, `eventBuffer.*` | logging and the event ring buffer, as anywhere | + +**Both ends have a `lease.*` block, and on a fleet lease the gateway's is the +one that decides the width.** A request arriving at a gateway with no `ttlMs` +is filled in with the *gateway's* `lease.defaultTtlMs` before it is dispatched +anywhere, and one asking for more than the *gateway's* `lease.maxTtlMs` is +`BAD_REQUEST` at the gateway and never reaches a worker at all. The worker's +own cap still applies to what it is handed, though — it is an ordinary +`lease.request` to the worker, so a worker whose `lease.maxTtlMs` is lower +refuses it, and the client sees that failure after a dispatch rather than +before one. So **keep the gateway's `lease.maxTtlMs` at or below every +worker's**, or requests that the gateway happily accepts will fail on +whichever machine they land on, which is the least debuggable version of this +mistake. + +Everything else — `capacity.*`, `idle.*`, `warmPool.*`, `health.*`, +`stalledTransition.*`, `drivers.*`, `ios.slim.*`, `diskPressure.*`, +`downloads.*`, and the worker-side `gateway.url`/`gateway.token`/ +`gateway.label`/`exec.timeoutMs` — is **ignored with a warning**, exactly as +an unknown key is. That is deliberately the softer treatment: a gateway's +config file is usually a worker's config file with `mode` flipped, and a +warning names each key that stopped mattering rather than refusing to start +over a leftover. + +There is one hard failure: **`mode: "gateway"` with `http.enabled: false` is +rejected at load and the daemon does not start**, naming the key. A gateway +with no HTTP listener is unreachable by definition — no worker could open an +uplink to it and no agent could lease through it — so there is no safe way to +interpret that pair, the same reasoning that rejects a `lease.defaultTtlMs` +above `lease.maxTtlMs`. + +The `gateway.*` block reads in both directions on purpose: on a worker it +says *which gateway to join*, on a gateway it says *how to be one*. The table +above marks which is which, and each key is only ever read in one mode. + +A machine that should both front a fleet and own devices runs **two daemons**: +one gateway, one worker, the worker joining the gateway over localhost. There +is no hybrid mode. What the two need to keep apart is smaller than it looks, +because only one of them owns anything: + +- **Distinct `SIMLOCK_HOME`s.** That is what gives them separate config, + state, sockets, logs, instance ids, and token stores — and the separate + instance ids are what make the worker a distinct member of the fleet. +- **Only the gateway needs `http.enabled`** (and must have it). The worker + dials out, so it needs no listener of its own; leave its `http.enabled` + off unless you also want to reach that one worker directly. +- **Distinct `http.port`s, if you do enable HTTP on both.** A port is + machine-global and `SIMLOCK_HOME` cannot isolate it. +- **The worker keeps its `drivers.*` block** — device roots, adb server + port, the lot. It owns the devices; the gateway has no drivers to + configure. Two *workers* on one machine would additionally need distinct + `drivers.android.adbServerPort` values (see below), but a gateway plus a + worker is one driver set, so there is nothing to split. + ## Device roots Simlock keeps every device it creates inside a root it owns, one per platform, diff --git a/docs/EVENTS.md b/docs/EVENTS.md index d68ee3084..5c719bd5d 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -93,6 +93,67 @@ progress gap this leaves. | `driver.root-rejected` | platform, root path, reason (not-absolute/missing-marker/invalid-marker/wrong-instance/symlink/wrong-owner/wrong-permissions/non-empty-unowned-root/unreadable) | a driver's device root failed ownership validation at startup, so that platform's driver did not start | DaemonServer | implemented | | `driver.adb-server-rejected` | port, reason (occupied/start-failed/invalid-port) | Simlock's own adb server could not be established — the port was occupied by a server it does not own, the server it started never began listening, or the configured port is not usable — so the Android driver did not start | DaemonServer | implemented | +## Fleet (gateway mode) + +These are the facts a daemon running as a **gateway** emits about the workers +connected to it ([ADR 0005](adr/0005-gateway-and-worker-modes.md)). A worker +never emits them — it has no workers of its own — and a gateway emits none of +the device- or lease-lifecycle facts above on its own behalf, because it owns +no devices. All are **planned (ADR 0005)**. + +| Event | Payload (key fields) | Emitted when | Emitter | Status | +|---|---|---|---|---| +| `worker.connected` | worker id, label, daemon version, negotiated protocol range, platforms, capacity per platform, download policy | a worker's uplink completed its `hello` and the gateway committed the resulting worker view — including a reconnect, which is a new connection and so a new fact | WorkerRegistry | planned (ADR 0005) | +| `worker.rejected` | `{ reason, workerId?, label?, protocol? }` — reason is `unauthenticated` (the join token was missing or unrecognized, `401`) or `forbidden` (a valid token of the wrong role, `403`) | an uplink was refused at the door, before it could become a worker at all. Every field but `reason` is optional, because a dial that fails authentication proves no identity: there may be no worker id or label to report, and `protocol` is present only when the dial advertised a range before it was refused. Nothing enters the registry either way. A **version mismatch is not a rejection** — that uplink authenticated, so its worker enters the registry as `incompatible` (see the note under this table) | WorkerRegistry | planned (ADR 0005) | +| `worker.disconnected` | worker id, label, reason (closed/token-revoked), connected duration, leases still held on it | the uplink closed and the view was marked `disconnected`. The worker's leases are *not* ended by this: the gateway never guesses a lease is gone before the worker says so | WorkerRegistry | planned (ADR 0005) | +| `worker.removed` | worker id, label, initiator (operator/retention), time since disconnect | a disconnected worker's view was forgotten — by `worker.remove`, or because `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker (`WORKER_CONNECTED` refuses that), nor while gateway-issued leases on it are still known | WorkerRegistry | planned (ADR 0005) | +| `worker.drain-started` | worker id, label, leases held at that moment | `worker.drain` committed: the worker takes no new dispatches and keeps the leases it has | WorkerRegistry | planned (ADR 0005) | +| `worker.drain-ended` | worker id, label | `worker.undrain` committed and the worker became dispatchable again. Nothing else ends a drain: the flag lives in the gateway's persisted worker registry, so it survives both a worker reconnect and a gateway restart, and this fact only ever follows an explicit undrain | WorkerRegistry | planned (ADR 0005) | +| `request.dispatched` | request id, worker id, requester id, platform, model, selection reason (warm-hit/free-capacity), time spent queued | the gateway's dispatch sent a queued request to a worker and the worker took it (a grant, or device work already under way). A `NO_CAPACITY` refusal is a stale view, not a dispatch, and emits nothing — the request stays queued | FleetDispatcher | planned (ADR 0005) | + +`worker.rejected` exists because the alternative is silence (ADR 0005 §22): a +worker whose credential is refused produces no `worker.connected`, and +without this fact an operator staring at `simlock worker list` sees a machine +that simply never appears, with nothing anywhere to say why. It is deliberately *not* a +`worker.disconnected` with another reason — nothing connected, so nothing +disconnected, and a fact whose subject never existed should not borrow the +vocabulary of one that did. + +**A protocol mismatch is neither of those.** That uplink presented a valid +join token and authenticated; what failed was `hello`'s range negotiation. So +the worker *does* enter the registry, with `state: "incompatible"` and both +ranges on its view, visible in `simlock worker list` — which is the whole +point, since that is the machine an operator has to go and upgrade. It is +simply never dispatched to, and no `worker.connected` follows, because +nothing usable connected. That is also why `incompatible` is not one of +`worker.disconnected`'s reasons: an incompatible worker was never a connected +worker to lose. + +**`device.exec` emits no event, and that is deliberate.** It is the one new +operation here with no fact of its own. Running a command against a device is +not a state change simlock owns — the lease that authorizes it already +emitted `lease.granted`, the device's own state is untouched, and a fleet +where every `adb shell input tap` produced a bus event would push everything +else out of a 1000-entry ring buffer within minutes. An audit trail of what +agents ran on their devices is a different feature with different retention +needs, not a line in this catalogue. + +**Every worker's own business events are republished on the gateway's bus** +with `workerId` added to their payload, and land in the gateway's ring +buffer, so `simlock events --follow` against a gateway shows the fleet +(`lease.granted`, `device.ready`, `cleanup.executed`, and the rest, each +naming the machine it happened on). That addition is additive per events rule +6, and it is the only change: payloads are otherwise relayed as the worker +emitted them, with the worker's own emitting module intact — the gateway +observed the fact, it did not commit it, so re-attributing it would be a +lie. + +Two consequences of relaying rather than owning: the gateway's ring buffer +only holds what arrived while its uplinks were up (a worker's events from +before it connected are not backfilled), and a worker's own +`simlock events` keeps showing exactly what it always did, un-prefixed and +unaware that anything is watching. + ## Conventions recap - Every event carries: `timestamp`, `event`, `payload`, emitting module. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index cd5abafa3..4f460a8c0 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -8,7 +8,7 @@ another machine is the operator's own tunnel (Tailscale, cloudflared, a reverse proxy) — Simlock does no TLS termination in v1, and `Authorization` is required on every route regardless of how it's reached, loopback included. -The gateway calls the exact same in-process `Dispatcher` the unix socket +This frontend calls the exact same in-process `Dispatcher` the unix socket calls (ADR 0003 §2) — not a second copy of role/ownership logic, and not a loopback hop through the socket either. Every route that maps onto a daemon operation gets the same input parsing, role check, `authorize`/ownership @@ -48,8 +48,11 @@ terminal state. No route blocks on device work in flight. Every route requires `Authorization: Bearer slk_` except `GET /v1/healthz`. Missing or unrecognized tokens are `401 UNAUTHENTICATED`. -Tokens are minted and managed with `simlock token` (see [CLI.md](CLI.md)) — -a local, no-daemon-round-trip command, like `config`. Each token record is +Tokens are minted and managed with `simlock token` (see [CLI.md](CLI.md)). +Since 0.3.0 `token.create|list|revoke` are daemon operations (admin role) and +the daemon is the only process that reads or writes `tokens.json`, so unlike +`config set` these do go through the daemon (ADR 0003 §11). Each token record +is `{ id, role, label?, createdAt }`, hashed at rest in `~/.simlock/tokens.json` (SHA-256; the plaintext secret is shown exactly once, at `create`, and never persisted). The token id doubles as the requester identity over HTTP: unlike @@ -57,18 +60,28 @@ the CLI's `--agent-id`/`SIMLOCK_AGENT_ID`, identity is never client-declared here, so the one-lease-per-requester rule keys off which token authenticated the request, not anything the request body says. -Two roles: +Three roles: | Role | Can | |---|---| -| `agent` | catalog, status, its own lease requests and leases | -| `operator` | everything `agent` can, plus every other requester's leases/devices, event replay/stream, and releasing any lease | +| `agent` | catalog, status, its own lease requests and leases, `exec` on its own lease | +| `operator` | everything `agent` can, plus every other requester's leases/devices, the worker routes, event replay/stream, and releasing any lease | +| `worker` | open an uplink at [`/v1/uplink`](#get-v1uplink-websocket-upgrade), and nothing else | A valid token with the wrong role for a route is `403 FORBIDDEN`, not `401` — distinct from an unrecognized token. Reaching another requester's own resource (a lease/request an `agent` token didn't create) is the same `403`, enforced per-resource rather than as a role gate. +The `worker` role is deliberately not a superset or a subset of the other +two, it is disjoint from both. `/v1/uplink` is the one route a join token +opens and the only route it opens: presented on any other `/v1` route it is +`403`, and an `agent` or `operator` token presented at `/v1/uplink` is `403` +just the same. Join tokens are minted with `simlock token create --role +worker` on the **gateway**, and tokens never cross machines — a gateway's +tokens are valid on that gateway and nowhere else ([ADR +0005](adr/0005-gateway-and-worker-modes.md)). + ## Endpoints All routes are under `/v1`, JSON bodies both ways, additive evolution only — @@ -84,10 +97,18 @@ it applies below: - **A `ttlMs` above `lease.maxTtlMs` is `400 BAD_REQUEST`** where it used to be accepted. - **The `ttlMs` a lease reports is the lease's own width**, not a value the - gateway remembered per request. + HTTP frontend remembered per request. Routes, status codes, and every other field are unchanged. +[ADR 0005](adr/0005-gateway-and-worker-modes.md) is purely additive on top of +that: the same routes answer identically whether the daemon behind them is a +worker or a **gateway** fronting a fleet of workers, and what it adds are new +routes (`/v1/uplink`, `/v1/workers*`, `POST /v1/leases/{id}/exec`), new +fields (`mode` on status, `workers[]`, `workerId`, `worker` on the lease), +and new error codes. Nothing existing changes shape, and a client that +ignores every one of them keeps working against a gateway unchanged. + ### `GET /v1/healthz` Unauthenticated liveness for tunnels/load balancers. → `200 {"ok":true}`. @@ -98,10 +119,29 @@ Role: `agent`. The same view `simlock status --json` reads: daemon health (`starting`/`running`), managed/running capacity per platform, active leases, managed devices, queue depth. +The daemon block also carries **`mode`** (`"worker" | "gateway"`), which is +the only field that tells a client which kind of daemon answered. On a +**gateway** the numbers are the fleet's — capacity summed across connected +workers, every gateway-issued and local lease, every device, the gateway +queue's depth — every lease and device carries the **`workerId`** it lives +on, and an additive **`workers`** array carries one +[worker view](#worker-routes) per worker: + +```json +{ "daemon": { "health": "running", "mode": "gateway" }, + "workers": [ { "id": "3f81a2c4", "label": "mac-studio-2", "state": "connected", "drained": false } ] } +``` + +On a worker, `workers` is absent and `workerId` never appears. A client that +reads neither cannot tell the difference, which is the point. + ### `GET /v1/catalog?platform=ios|android` Role: `agent`. Exactly `simlock catalog --json`. Read-only; never triggers a -download. +download. On a **gateway** it is the union of the connected workers' +catalogs, each model and runtime annotated with the workers that have it — so +a model the catalog lists is leasable *somewhere* in the fleet, not +necessarily on every machine in it. ### `POST /v1/lease-requests` @@ -195,21 +235,43 @@ already reached a terminal state — the body names the lease id if it was ### The lease object +A lease issued by a **gateway** — a worker's own lease is the same object +without the `workerId` and `worker` fields: + ```json { "lease": { - "id": "lse_9f2c", "requestId": "req_7d1a", + "id": "3f81a2c4.lse_9f2c", "requestId": "req_7d1a", "platform": "ios", "device": "iPhone 17 Pro", "os": "26.5", "udid": "ABCD-...", "deviceId": "dev_1a2b", + "workerId": "3f81a2c4", "worker": { "id": "3f81a2c4", "label": "mac-studio-2" }, "createdAt": "2026-09-01T09:14:07Z", "expiresAt": "2026-09-01T09:29:07Z", "ttlMs": 900000, "dataPlane": null, "slim": true } } ``` -`dataPlane` is **reserved** and always `null` in this version: driving the -leased device remotely (the data plane) is a separate, not-yet-implemented -concern — see [Not implemented](#not-implemented) below. It is in the schema -now so its arrival is additive rather than a breaking shape change. +`worker` (and the flat `workerId`, which mirrors it for the aggregate lists) +is present when a **gateway** issued the lease and absent from a worker's own +— it says which machine the device lives on, so a client and the console can +show it. `label` is display-only. A worker's network address is deliberately +never here: clients reach the device through the gateway, with +[`POST /v1/leases/{id}/exec`](#post-v1leasesidexec). + +The lease `id` names its worker (`.`, split +on the **first** `.`), which is how a gateway routes renew, release, and +reads with no state of its own to lose across a restart. A worker id is a +UUID, so a real id reads +`3f81a2c4-9b7d-4e21-8a55-1c0e6f2d7b93.lse_9f2c`; the examples here and +elsewhere in these docs abbreviate it to its first segment for legibility. +**Treat the whole id as opaque** — pass it back verbatim in paths and bodies, +and read `worker.id` when you want the machine. + +`dataPlane` is **reserved** and always `null` in this version: streaming a +device's screen, forwarding a port, or opening an interactive TTY is a +separate, not-yet-implemented concern — see [Not +implemented](#not-implemented) below. It is in the schema now so its arrival +is additive rather than a breaking shape change. Running a *command* on the +device is not part of it and does not wait for it: that is `exec`, below. `slim` is `true` when the granted device had its feature set reduced (iOS slim mode applied and the request did not carry `full: true`), `false` @@ -231,14 +293,16 @@ and an id outside that set simply isn't in the list. `404` covers "doesn't exist" and "not yours" identically, the same way `lease.list` itself does not distinguish them. -`POST /v1/leases/{id}/renew` and `DELETE /v1/leases/{id}` are different: -both dispatch `lease.renew`/`lease.release` directly, so another requester's -own, still-live lease answers `403 FORBIDDEN` from those two routes — the +`POST /v1/leases/{id}/renew`, `DELETE /v1/leases/{id}`, and `POST +/v1/leases/{id}/exec` are different: all three dispatch their operation +(`lease.renew`, `lease.release`, `device.exec`) directly, so another +requester's own, still-live lease answers `403 FORBIDDEN` from them — the same answer the socket transport gives, via the same operation's `ownsLease` -authorize hook. (0.3.0 briefly had all four routes answering `404` here; +authorize hook. (0.3.0 briefly had every lease route answering `404` here; that overcorrected the lease-*request* routes' old `403` and is why renew and release were moved off the `lease.list`-filtered lookup — see -`docs/known-pitfalls.md`.) +`docs/known-pitfalls.md`. `exec` arrives on the dispatching side of that +split, with renew and release.) This is different again from the lease-*request* routes below (`/v1/lease-requests/{id}` and friends), which are still HTTP's own resource @@ -251,7 +315,7 @@ lease's own width — the TTL it was granted with, or last renewed with when a renew carried one. The daemon stores it on the lease record, so it survives a **daemon** restart along with the deadline and the restored TTL timer; a payload served after a restart may still omit `requestId`, which was only -ever gateway-side. Schedule renewals from `expiresAt` rather than from +ever HTTP-side. Schedule renewals from `expiresAt` rather than from `ttlMs` all the same: the deadline is the fact, the width is how far the next body-less renew will push it. @@ -298,10 +362,219 @@ The lease is gone the moment this responds; the driver-side purge continues in the background (existing release semantics — see "Release hands the purge off" in [ARCHITECTURE.md](ARCHITECTURE.md)), hence `202`, not `200`. +### `POST /v1/leases/{id}/exec` + +Role: `agent` (own lease). Runs one `simctl` / `adb` command against the +leased device on the machine that owns it, and streams its output back. This +is what lets a remote agent actually *drive* the device it leased — over +HTTP against a lone worker, and through a gateway to whichever worker holds +the lease, with the same request and the same response either way ([ADR +0005](adr/0005-gateway-and-worker-modes.md)). + +```json +{ "tool": "simctl", "args": ["install", "booted", "/tmp/MyApp.app"], + "stdin": null, "requesterId": null } +``` + +`tool` is `"simctl"` or `"adb"`; `args` is the argument vector, passed +through unchanged. The daemon that owns the device resolves the command the +same way `simlock simctl` / `simlock adb` do locally — same root scoping +(`--set` for iOS, `-P` for Android, supplied by simlock and refused from the +caller), and the same refusal list for verbs that would change a device's +lifecycle behind the registry's back (`create`/`erase`/`delete`, `shutdown +all`, `runtime delete`, `kill-server`, `emu kill`, …). A refused verb is +`422 PASSTHROUGH_REFUSED` and an unwrapped `tool` is `422 +UNKNOWN_PASSTHROUGH_TOOL` — the codes `driver.passthrough` already answers +with, at the status they already carry; `400 BAD_REQUEST` here means a +malformed body, nothing more. One refusal is particular to this route: a bare +`adb shell` with no command is `422 PASSTHROUGH_REFUSED` ("needs a +terminal"), because there is no pseudo-terminal to give it and accepting it +would only stall the stream until the timeout. A gateway in the path parses +none of this: it proxies the call to the owning worker and relays the stream +back unchanged. + +`requesterId` (optional, defaulting to the caller's own) is what a proxying +caller supplies. An `agent` token does not need it and may not use it: it is +gated the ordinary way, its own requester against the lease's `ownerId`, +exactly as on `renew` and `release`. Only an `operator` token may name +another requester here. The field exists for the one session that would +otherwise bypass the ownership check — the gateway's admin session on a +worker — and on this operation, unlike renew and release, **admin does not +bypass**: the worker compares the supplied `requesterId` to the lease's own +`requesterId` and answers `FORBIDDEN` on a mismatch. Ownership is therefore +checked on both hops, the gateway against its own lease index and the worker +against the lease it actually holds. + +`stdin` (optional) is a **single string, sent with the request** and written +to the process's stdin, which is then closed. There is no incremental stdin +channel and no pseudo-terminal, so line-oriented commands work and +full-screen ones (`adb shell` as an interactive session) do not. + +→ `200`, `Content-Type: text/event-stream` — the same SSE shape +`/v1/lease-requests/{id}/events` already uses. Output is streamed, never +buffered, so there is no size cap on it: + +``` +event: output +data: {"stream":"stdout","chunk":"Installing...\n"} + +event: output +data: {"stream":"stderr","chunk":"warning: ...\n"} + +: keepalive + +event: exit +data: {"exitCode":0} +``` + +`output` events carry `stream` (`"stdout"` or `"stderr"`) and a `chunk`, in +the order the process produced them. The stream ends with exactly one +terminal event: `exit` carrying the tool's own `exitCode` (a non-zero one is +the command's answer, not an API failure), or `error` carrying the usual +`{ code, message }` envelope. A `: keepalive` comment every ~15s keeps idle +tunnels from closing a long-running command's stream. + +Chunks are UTF-8 text. A command whose output is binary (`simctl io booted +screenshot -` to stdout) is not supported over this route — have it write to +a file on the device's own machine instead. + +Failures particular to this route: + +- `403 FORBIDDEN` — the lease belongs to another requester (same rule as + `renew`/`release`), an `agent` token supplied a `requesterId` at all, or an + `operator` token supplied one that does not match the lease's. +- `404 UNKNOWN_LEASE` — no such lease, or it has expired or been released. +- `422 PASSTHROUGH_REFUSED` — a refused verb, a caller-supplied `--set`/`-P`, + or a bare `adb shell`. `422 UNKNOWN_PASSTHROUGH_TOOL` for a `tool` outside + `simctl`/`adb`. +- `400 BAD_REQUEST` — a malformed body. +- `503 WORKER_UNREACHABLE` — a gateway could not reach the worker holding + the lease. +- `EXEC_TIMEOUT` (`504` in the contract's error table) — the command outlived + `exec.timeoutMs`, ten minutes by default and worker-side, which is the + authoritative one because the worker owns the process; + `gateway.execTimeoutMs` (eleven minutes) is the gateway's backstop for a + worker that never answers at all, deliberately the longer of the two. On + *this* route the status never reaches the client — the response is already + `200` and streaming by the time a command can time out — so it arrives as + the stream's terminal `error` event. The status is documented anyway, for a + client mapping the code without a route in front of it. + +The artifact a command names has to exist **on the device's own machine**: +`simctl install ` and `adb install ` resolve their path there, and +there is no file upload in this version. See +[known-pitfalls.md](known-pitfalls.md). + +### `GET /v1/uplink` (WebSocket upgrade) + +Role: `worker`. The endpoint a **worker** dials to join a fleet: it opens +one outbound WebSocket to `/v1/uplink`, presenting +`Authorization: Bearer slk_` on the upgrade request along with +its instance id. The gateway verifies the token against its own store and +requires role `worker`; a missing or unrecognized token is `401 +UNAUTHENTICATED`, and a valid token of any other role is `403 FORBIDDEN`. +Revoking the token closes the uplink. + +This is the fleet's **only** inbound connection. Workers dial out, so a +machine behind NAT, on a laptop, or on a CI runner joins with a URL and a +token and needs no inbound port of its own, and no client ever learns a +worker's address. + +What travels over the socket is not a new API: it is the same typed daemon +contract (ADR 0003), with **the gateway as the protocol client**. It sends +`hello`, negotiates the protocol range exactly as over the unix socket, and +then issues ordinary operations (`status.get`, `list.get`, `catalog.get`, +`events.subscribe`, `lease.request`, `device.exec`, …) to the worker's own +dispatcher, exactly as a local admin CLI would. A worker whose range does not +overlap the gateway's is marked `incompatible` and never dispatched to; it +keeps serving its own local clients. + +Nothing else about this endpoint is a REST resource: there is no `GET` body, +no polling, and no route to list uplinks. The connection *is* the worker's +liveness signal — [`GET /v1/workers`](#worker-routes) is how you look at it. + +### Worker routes + +Role: `operator` for all four. They exist on a **gateway**; a worker has no +workers of its own and does not implement the underlying operations at all. + +- `GET /v1/workers` — every worker view the gateway currently holds. +- `POST /v1/workers/{id}/drain` — stop dispatching new requests to this + worker; it keeps the leases it already has. +- `DELETE /v1/workers/{id}/drain` — undrain it, putting it back in rotation. +- `DELETE /v1/workers/{id}` — forget a worker's view. + +```json +{ "workers": [ { + "id": "3f81a2c4", "label": "mac-studio-2", + "state": "connected", "drained": false, + "daemonVersion": "0.4.0", "protocol": { "min": 5, "max": 5 }, + "connectedAt": "2026-09-01T09:00:00Z", "lastSeenAt": "2026-09-01T09:14:30Z", + "capacity": { "ios": { "running": 2, "limit": 4 }, "android": { "running": 0, "limit": 2 } }, + "downloads": { "policy": "on-request" }, + "queueDepth": 0, "leases": 3, "devices": 5 +} ] } +``` + +`downloads.policy` is that worker's own effective policy, read once with +`config.get` when its uplink connects. Routing needs it to know whether a +worker may install a missing runtime at all before sending it a request that +depends on one; it is never an override, since the worker clamps +`allowDownload` through the same policy regardless. + +`protocol` is the range that worker negotiated. ADR 0005 moves the wire to +`{min: 5, max: 5}` with no compatibility shim, so a worker from before it +does not overlap and shows as `incompatible` — the ordinary upgrade path, not +a fault. + +`state` is `connected`, `disconnected`, or `incompatible`. A worker view is +rebuilt over the uplink and never persisted, so these are current facts, not +a registry: a worker appears by connecting, and there is deliberately no +route that *adds* one. + +A **disconnected** worker keeps its last-known view (greyed in the console, +never dispatched to) until an operator removes it or +`gateway.disconnectedRetentionMs` (24 hours) elapses. The clock is held while +the gateway still knows of gateway-issued leases on that worker — forgetting +a worker that holds someone's device is how a lease becomes unroutable — and +that hold ends when the last of those leases passes its deadline, since a +lease nobody can renew is one the worker has expired on its own clock. + +`POST /v1/workers/{id}/drain` → `200 { "workerId": "3f81a2c4", "drained": +true }`; `DELETE /v1/workers/{id}/drain` → `200 { "workerId": "3f81a2c4", +"drained": false }`. Both are `404 UNKNOWN_WORKER` for an id the gateway does +not know: draining is an instruction about a specific machine, and silently +succeeding against one that is not there would hide a typo in exactly the +situation — taking a machine out of service — where an operator most needs to +know the instruction landed. + +`DELETE /v1/workers/{id}` → `200 { "workerId": "3f81a2c4", "removed": true }`, +or `409 WORKER_CONNECTED` when its uplink is still open — a connected worker +would simply reappear, so drain it and stop it (or revoke its join token) +first. Unknown ids are the one place remove differs: `200 { "removed": false +}`, not `404`, because "forget this worker" is already true of a worker the +gateway has already forgotten — the same reading `token.revoke` gives an +unknown token id. + +On a **worker** daemon none of these routes exist: they are not registered at +all, so they answer `404` like any other unrouted path rather than a +gateway-mode refusal. There is nothing for them to act on. + ### Operator routes Role: `operator` for all four. +`DELETE /v1/leases/{id}` with an `operator` token already releases any single +lease, on a gateway as anywhere else. The fleet-wide form of that — the CLI's +`simlock release --all` — releases **only gateway-issued leases**, on every +connected worker, and never a worker's own local leases: the gateway did not +issue those, does not know who is holding them, and taking a local +developer's device away from an endpoint they have never heard of is not an +operator action anyone asked for. A worker it cannot reach is reported as +`WORKER_UNREACHABLE` naming that worker, and the leases on the workers it +could reach are still released — a partial result, said plainly, rather than +an all-or-nothing that leaves the operator guessing. + - `GET /v1/leases` — every active lease (`simlock list --leases`). - `GET /v1/devices` — every managed device, with state and `transitionAgeMs` (`simlock list --devices`). @@ -310,6 +583,13 @@ Role: `operator` for all four. - `GET /v1/events/stream` — Server-Sent Events follow of the event bus (`simlock events --follow`). +On a **gateway** all four are fleet-wide, which is what makes a single +console possible: `/v1/leases` and `/v1/devices` return every connected +worker's, each record carrying the `workerId` it lives on, and the two event +routes carry the workers' republished events (also `workerId`-tagged) +interleaved with the gateway's own `worker.*` and `request.dispatched` +facts. + ## Errors Every failure is the same shape the daemon protocol uses: @@ -322,11 +602,39 @@ Every failure is the same shape the daemon protocol uses: |---|---| | 400 | `BAD_REQUEST` (malformed body, bad query param, validation) | | 401 | `UNAUTHENTICATED` (missing or unrecognized token) | -| 403 | `FORBIDDEN` (role doesn't permit the route; a `/v1/lease-requests/*` route whose request belongs to another requester; or `POST /v1/leases/{id}/renew`/`DELETE /v1/leases/{id}` naming another requester's still-live lease) | -| 404 | `UNKNOWN_LEASE_REQUEST` (unknown request id), `UNKNOWN_LEASE` (unknown lease id, expired/released, **or `GET /v1/leases/{id}`/`GET /v1/leases/{id}/events` naming another requester's lease** — see [`GET /v1/leases/{id}`](#get-v1leasesid)) | -| 409 | `REQUESTER_ALREADY_LEASED` (body names the existing lease id), `REQUEST_NOT_CANCELLABLE` (body names the lease id if the request had already been granted) | -| 422 | `UNKNOWN_MODEL`, `RUNTIME_MISSING`, `NO_DRIVER` | -| 503 | `NO_CAPACITY` (only with `noWait: true`; response carries `Retry-After`) | +| 403 | `FORBIDDEN` (role doesn't permit the route — including a `worker` token on any `/v1` route other than `/v1/uplink`, and an `agent`/`operator` token at `/v1/uplink`; a `/v1/lease-requests/*` route whose request belongs to another requester; or `POST /v1/leases/{id}/renew`/`DELETE /v1/leases/{id}`/`POST /v1/leases/{id}/exec` naming another requester's still-live lease) | +| 404 | `UNKNOWN_WORKER` (`POST`/`DELETE /v1/workers/{id}/drain` naming a worker the gateway does not know), `UNKNOWN_LEASE_REQUEST` (unknown request id), `UNKNOWN_LEASE` (unknown lease id, expired/released, **or `GET /v1/leases/{id}`/`GET /v1/leases/{id}/events` naming another requester's lease** — see [`GET /v1/leases/{id}`](#get-v1leasesid)) | +| 409 | `REQUESTER_ALREADY_LEASED` (body names the existing lease id; fleet-wide on a gateway), `REQUEST_NOT_CANCELLABLE` (body names the lease id if the request had already been granted), `WORKER_CONNECTED` (`DELETE /v1/workers/{id}` while its uplink is open) | +| 422 | `UNKNOWN_MODEL`, `RUNTIME_MISSING`, `NO_DRIVER`, `PASSTHROUGH_REFUSED` (a refused `exec` verb, a caller-supplied `--set`/`-P`, a bare `adb shell`), `UNKNOWN_PASSTHROUGH_TOOL` | +| 501 | `UNSUPPORTED_IN_GATEWAY_MODE` (an operation that acts on one machine's devices, asked of a gateway) | +| 503 | `NO_CAPACITY` (only with `noWait: true`; response carries `Retry-After`), `WORKER_UNREACHABLE` (a gateway could not reach the worker holding this lease or request) | +| 504 | `EXEC_TIMEOUT` (a `device.exec` command outlived `exec.timeoutMs`) | + +Three notes on the ADR 0005 codes. + +`WORKER_UNREACHABLE` sits on `503` with `NO_CAPACITY` rather than on `502`, +because its `kind` is `transport` and every other `transport`-kind code in +the contract's table (`DAEMON_STOPPING`, `DAEMON_STARTUP_FAILED`, +`DAEMON_CONNECTION_LOST`) is already a `503`. "Try again shortly, the thing +behind this is not reachable right now" is the same answer in all four cases, +and a client with one retry rule for `transport` should not need a second one +because the unreachable thing happened to be a worker. + +`UNSUPPORTED_IN_GATEWAY_MODE` has no route that can produce it *in this +version* — `nuke`, `cleanup`, and `doctor` are absent from the HTTP surface +(see [Not implemented](#not-implemented)) — but the status is fixed now so +adding `POST /v1/doctor` or `POST /v1/cleanup` later is additive rather than +a fresh decision. `501` is also the honest status for it: this is not a +temporary condition to retry past, it is an operation this daemon will never +perform, and `nuke`/`cleanup`/`doctor`/`driver.passthrough` stay per-worker +permanently rather than pending some later fan-out. + +`EXEC_TIMEOUT`'s `504` is documented for completeness rather than for the +exec route: `POST /v1/leases/{id}/exec` has already answered `200` and begun +streaming by the time a command can outlive `exec.timeoutMs`, so on that +route it arrives as the stream's terminal `error` event — as does a +`WORKER_UNREACHABLE` that only happens mid-stream. The status is what a +client mapping the code without a route in front of it should use. ## Lifecycle semantics @@ -341,15 +649,24 @@ Every failure is the same shape the daemon protocol uses: (including across a restart) creates a fresh request rather than erroring — the `409` above is the real backstop against a double grant, not the idempotency cache. -- **Startup.** The gateway's listener now starts the moment the daemon +- **Startup.** The HTTP listener now starts the moment the daemon claims its socket — the same instant the unix socket itself starts accepting connections, before startup convergence (`doctor.reconcile()`, - running-capacity convergence) has run (**bug fix, 0.3.0**: the gateway + running-capacity convergence) has run (**bug fix, 0.3.0**: it used to start only once convergence had already finished, so it could not observe or need this). A request that arrives before convergence completes now waits on the shared dispatcher's readiness gate exactly like a socket request, instead of being refused — every route but the routes that don't dispatch at all (`GET /v1/healthz`) can block briefly on a cold start. +- **Gateway restart, and a worker that goes away.** A gateway's queue is + in-memory too, so a restart loses in-flight lease requests exactly as a + worker's does — and leases survive it, on their workers, which reconnect on + their own backoff and let the gateway rebuild every view and its lease + index. The recovery loop is the same one: `404` → re-request → (maybe) + `409` → `GET`. While a worker's uplink is down, anything routed to it is + `503 WORKER_UNREACHABLE`; the gateway never reports a lease as gone before + the worker says so, and the lease meanwhile runs out its TTL on the + worker's own clock. - **Shutdown.** `simlock daemon stop` closes the HTTP listener (and any open connection, in-flight SSE streams included) before tearing down the lease engine, so no HTTP request can run against a stopping daemon. Stopping the @@ -364,9 +681,17 @@ Every failure is the same shape the daemon protocol uses: - `nuke` is absent from the HTTP surface entirely, deliberately: a remote fleet-wipe endpoint is a footgun even behind auth. It stays SSH/local-only (`simlock nuke`). -- `dataPlane` on the lease object is reserved and always `null` — driving - the leased device remotely is tracked separately (the agent-device - integration work), not in this version. -- MCP-over-HTTP, in-process TLS, and multi-host brokering are all out of - scope for this version too (a per-lease `dataPlane.baseUrl` already leaves - room for the last one, once it exists). +- `dataPlane` on the lease object is reserved and always `null` — a + byte-heavy data plane (live screen streaming, port forwarding, an + interactive TTY) is tracked separately, not in this version. Running a + command on the leased device is *not* waiting on it: that is + [`POST /v1/leases/{id}/exec`](#post-v1leasesidexec), which works over HTTP + against a lone worker and through a gateway alike. +- **File transfer for `exec`.** A command that names a path resolves it on + the machine that owns the device; there is no upload route in this version, + and the seam for a later `device.upload` is left open by design (ADR 0005). +- MCP-over-HTTP and in-process TLS are out of scope for this version too. + Multi-host brokering is no longer on this list: [ADR + 0005](adr/0005-gateway-and-worker-modes.md) designs it as gateway and + worker modes, and its routes (`/v1/uplink`, `/v1/workers*`) are documented + above. diff --git a/docs/IDEAS.md b/docs/IDEAS.md index d9d2e601a..64b042b7a 100644 --- a/docs/IDEAS.md +++ b/docs/IDEAS.md @@ -81,10 +81,62 @@ small addition, and the daemon-side `component.install-started` bus event already gives an operator visibility via `simlock events --follow` even though the waiting requester itself does not see it yet. -## Cross-machine coordination - -A fleet-level broker over multiple hosts. Explicitly out of scope for v1 -(single host only). +## Gateway-side file upload for `device.exec` + +`device.exec` runs a `simctl`/`adb` command on the machine that owns the +device, so a path in its arguments (`simctl install `, `adb install +`) resolves on *that* filesystem. Getting an artifact there is out of +band in v1 — a shared volume, a CI checkout on the worker. The designed shape +for closing this is `device.upload`: chunks streamed as request-scoped pushes +over the same wire `device.exec` already uses, into a per-lease scratch +directory deleted on release. [ADR +0005](adr/0005-gateway-and-worker-modes.md) leaves that seam open on purpose +and does not build it; a remote agent that has to install a build it just +produced is the case that will decide when it is worth it. + +## Capacity slices reserved for the gateway + +A worker's capacity is shared between its local agents and the fleet, with +the worker's own accounting as the single arbiter (ADR 0005 §12). A worker +could instead reserve a slice for gateway traffic, so a busy local developer +cannot starve the fleet. Deferred: it adds a worker-side concept for a +problem the worker views already make *visible*, and an operator who sees one +machine's local load can drain it instead. + +## A fleet-wide doctor, as a new operation + +`nuke.run`, `cleanup.run`, and `doctor.run` stay per-worker, and a gateway's +`UNSUPPORTED_IN_GATEWAY_MODE` for them is permanent rather than a placeholder +([ADR 0005](adr/0005-gateway-and-worker-modes.md), "Alternatives +considered"). What is deferred is not those three answering differently one +day — it is a **new operation** that fans the read-only half out to every +worker and merges the findings, which is exactly what a multi-worker console +wants to render. Giving it its own name is the point: `doctor.run` means "one +machine", a fleet-wide reconnaissance pass means something else, and a caller +should be able to tell which one it invoked from the name rather than from +which daemon happened to answer. The destructive half (`--fix`, `cleanup`, +`nuke`) is deferred harder still: a fleet-wide destructive command from one +endpoint is not something this tool should offer casually, whatever it is +called. + +## Richer routing: label selectors and requester affinity + +The v1 routing policy is warm hit, then most free capacity, and nothing else +— no requester affinity, no label selectors, no per-worker platform +exclusions (`label` is display-only). Each is a future policy behind +`gateway.routing`, which is a pure function over worker views with one entry +point, so adding one is a new module rather than a change to the request +shape. Affinity ("give this agent the machine its build cache is on") is the +one with the clearest payoff; selectors ("only the M4 Macs") the one most +likely to be asked for first. + +## A byte-heavy data plane + +Device *commands* travel through the gateway (`device.exec`); live screen +streaming, port forwarding, and interactive TTYs do not, and `dataPlane` on +the lease object stays reserved for them. They need sustained throughput and +a session, not a request/response with output pushes, which is a different +transport decision from the one ADR 0005 makes. ## Priorities / preemption diff --git a/docs/adr/0005-gateway-and-worker-modes.md b/docs/adr/0005-gateway-and-worker-modes.md index 8bf4cfe9f..704da7da5 100644 --- a/docs/adr/0005-gateway-and-worker-modes.md +++ b/docs/adr/0005-gateway-and-worker-modes.md @@ -1,6 +1,6 @@ # 0005. Gateway and worker modes -- **Status:** Proposed +- **Status:** Accepted — not yet implemented - **Date:** 2026-09-05 - **Issue:** [#115](https://github.com/callstackincubator/simlock/issues/115) (sub-issues #116–#120, one per sequenced PR) @@ -9,8 +9,9 @@ > This record is a PRD and an ADR in one file: the first half says what the > feature is and who it is for, the second half records the shape it takes -> and why. Everything under [Open questions](#open-questions) is still being -> decided; everything else is the current proposal. +> and why. Nothing is left open: the documentation now describes the decided +> end state, and the code catches up in the PRs sequenced under +> [Consequences](#consequences). ## Summary @@ -65,7 +66,7 @@ against a single simlock has to change. stays reserved for that. - **File transfer.** A command that names a file (`simctl install `, `adb install `) runs on the worker's filesystem; getting the - file there is out of scope for v1 (see open question 5). + file there is out of scope for v1 (see requirement 19b'). - **A gateway that also owns devices.** One process, one mode. A machine that should do both runs two daemons. - **Durable gateway queue.** Pending requests on the gateway are in-memory, @@ -100,11 +101,29 @@ physical machine. reads only `http.*`, `log.*`, `lease.*`, and `eventBuffer.*`; worker-only keys in a gateway's config are ignored with a warning, as unknown keys are today. A gateway always listens on HTTP (it is the fleet's contact point) - and on its unix socket (so the local CLI works against it). + and on its unix socket (so the local CLI works against it). `http.enabled` + is therefore not optional in this mode: `mode: "gateway"` with + `http.enabled: false` is rejected at load and the daemon does not start, + naming the key. A gateway nothing can reach has no safe reading — no + worker could open an uplink to it and no agent could lease through it — + so it fails rather than warns, the way a contradictory `lease.*` pair + already does. 3. A worker joins a fleet with two keys: `gateway.url` and `gateway.token` (a join token), plus an optional `gateway.label` shown in views and on the lease. Nothing else on the worker changes; `http.enabled` is not - required for a worker. + required for a worker. `gateway.url` is the gateway's WebSocket base + URL, from which the worker derives the uplink endpoint (requirement 4); + it must be `wss://`, or plain `ws://` only over loopback or inside the + operator's own tunnel, since Simlock terminates no TLS in v1. + **`http://` and `https://` are rejected at load.** The uplink is a + WebSocket and nothing else is ever fetched from this URL, so one scheme + spelling keeps the key unambiguous, and a worker that names the wrong + scheme learns at start rather than at its first dial. The two + keys are a pair: **in `mode: "worker"`, one without the other is + rejected at load** and the daemon does not start, because a + half-configured uplink would otherwise come up looking like an ordinary + standalone worker. In `mode: "gateway"` both are worker-side keys and are + warned about and ignored like the rest (requirement 2). 3a. A worker's fleet id is its existing instance identity (`${SIMLOCK_HOME}/instance.json`): stable across restarts, unique by construction, opaque to clients. Two daemons on one machine have two @@ -114,9 +133,15 @@ physical machine. ### The uplink 4. On start, and again after any disconnect with exponential backoff, a - worker opens one WebSocket to `gateway.url`, presenting its join token and + worker opens one WebSocket to **`/v1/uplink`** (an ordinary + HTTP upgrade), presenting its join token as an `Authorization` bearer and its instance id (`instance.json`). The gateway verifies the token against - its token store (role `worker`) and rejects anything else with `401`. + its token store. The two ways that can fail are different facts and get + different answers, as everywhere else in the API: a **missing or + unrecognized token is `401`**, and a **valid token whose role is not + `worker` is `403`**. Either way nothing enters the worker registry and + the gateway emits `worker.rejected` (requirement 22), which is the only + trace an uplink refused at the door leaves. 5. Over the uplink the **gateway is the protocol client**: it sends `hello` and issues contract operations to the worker's own dispatcher, exactly as a local admin CLI would over the unix socket. The worker grants that @@ -124,16 +149,40 @@ physical machine. named in its own config — the credential in this handshake is the join token the worker presented, checked by the gateway, and the trust runs from the worker's configuration, never from the transport (ADR 0003 §5). + + This is a **third admin path**, alongside ADR 0003 §5's operator token + and per-start admin secret, and it is the first one reached from the + outside in. Its scope is worth stating plainly rather than deriving: + **joining a fleet grants that gateway admin over the daemon that + joined.** That is not a side effect to be narrowed later — a gateway has + to `lease.request`, `lease.release`, `list.get`, `config.get`, and + `events.subscribe` on its workers, which is exactly what an admin CLI + does. Point a worker only at a gateway you would hand an operator token + to. And because the join token is a bearer credential on the upgrade + request, anything that can read that request can replay it, which is why + requirement 3 puts `gateway.url` on `wss://` or inside the operator's own + tunnel. 6. The uplink is the reachability signal. A worker whose uplink is open is `connected`; a worker whose uplink is closed is `disconnected` and stays in the gateway's views (with its last-known state, greyed) until the operator removes it or `gateway.disconnectedRetentionMs` (default 24 hours) elapses — never while the gateway still knows of gateway-issued - leases on it. No polling is needed to detect loss. + leases on it, since forgetting a worker that holds someone's device is + how a lease becomes unroutable. That hold is **bounded by a TTL, not + open-ended: it ends when the last of those leases passes its deadline**, + because a lease nobody can renew is one the worker has already expired on + its own clock. No polling is needed to detect loss. 7. On connect the gateway calls `status.get`, `list.get`, `catalog.get`, - and `events.subscribe` on the worker. It refreshes status and list on - every worker event that changes capacity or leases, and on a slow - periodic tick as a backstop. + `config.get`, and `events.subscribe` on the worker. It refreshes status + and list on every worker event that changes capacity or leases, and on a + slow periodic tick as a backstop. `config.get` is read **once per + connect** and not on the refresh path — config is daemon input, read at + start, so a worker whose configuration changed has restarted and + reconnected anyway — and the gateway keeps exactly one field out of it: + the worker's effective `downloads.policy`, which the view carries and + routing (requirement 13) needs in order to know whether a worker may + install a missing runtime at all. It is a routing input, never an + override: the worker still clamps `allowDownload` through its own policy. ### Worker registry (gateway side) @@ -142,9 +191,34 @@ physical machine. worker's view (a connected one is refused with `WORKER_CONNECTED`). Join tokens are minted with the existing `simlock token create --role worker` and revoked with `simlock token revoke`; revoking closes the uplink. + Each answers with the resulting state — `{ workerId, drained: true }`, + `{ workerId, drained: false }`, `{ workerId, removed: true }` — and they + diverge deliberately on a worker id the gateway does not know: `drain` + and `undrain` **fail** with a new closed code `UNKNOWN_WORKER`, because + draining is an instruction about one specific machine and succeeding + silently against a typo would hide it in exactly the moment an operator + most needs to know the instruction landed; `remove` **succeeds** with + `{ removed: false }`, because "forget this worker" is already true of one + the gateway has already forgotten (the reading `token.revoke` gives an + unknown token id). A worker has no workers of its own, so it implements + none of these operations: on a worker they answer `UNKNOWN_REQUEST`, and + the `/v1/workers*` routes are simply not registered there (`404`). +8a. The gateway keeps a **worker registry**: which workers it knows, and + which of them an operator has drained. Unlike a worker *view*, which is + an observation rebuilt on every connect and never persisted, the registry + is the gateway's own record and **is** persisted — a small JSON file + under the gateway's `SIMLOCK_HOME`, written with owner-only permissions + like everything else Simlock keeps there. It is the only gateway state + that survives a restart, and requirement 9 is why it has to. 9. A **drained** worker keeps its existing leases and receives no new dispatches. Draining is the operator's tool for taking a machine down - without killing anyone's device. + without killing anyone's device. It is an operator's *intent* about a + machine rather than something observed on one, so it lives in the + persisted worker registry (requirement 8a) and **survives both a worker + reconnect and a gateway restart**; only `undrain` ends it. Both halves + matter: a machine taken out of rotation for maintenance must not rejoin + it because its own daemon restarted, and must not rejoin because a + process the operator never touched restarted either. ### The fleet queue @@ -155,9 +229,14 @@ physical machine. 11. **Dispatch** runs whenever the queue or any worker view changes. For each queued request, oldest first, the routing policy picks an eligible worker with free capacity; the gateway sends it `lease.request` with - `noWait: true`. A grant or a provisioning-in-progress answer moves the - request to `dispatched`; `NO_CAPACITY` (a stale view) refreshes that - worker's view and the request stays queued. A request no worker can + `noWait: true`. The request becomes `dispatched` on either of two + signals from that worker — the grant itself, or the **first `progress` + push** for it (`provisioning`, `booting`, `reclaiming`), since device + work having started means the request is that worker's now. An + **immediate `NO_CAPACITY` is the only answer that leaves it queued**: it + means the view was stale, so the gateway refreshes that worker's view + and the request waits. A failure after work has begun is the request's + own terminal failure, not a return to the queue. A request no worker can serve right now is passed over, not blocked on, so an Android request behind an iOS one proceeds when only Android capacity is free. 12. **Worker queues never hold gateway traffic.** Because every dispatch is @@ -181,7 +260,15 @@ physical machine. gateway-issued lease on any worker gets `REQUESTER_ALREADY_LEASED` from the gateway, naming the existing lease. The gateway enforces this from its own index of leases it issued, rebuilt from each worker's - `lease.list` on uplink connect. + `lease.list` on uplink connect. It recognizes its own in that list by + the requester prefix it stamps on everything it forwards — + `gw::` (requirement 27) — which works because an + instance id is stable across restarts. That one filter is what lets the + index be rebuilt from a worker's leases alone, with nothing persisted + about leases on the gateway and no ambiguity about which are its own, + another gateway's, or the worker's local ones; `lease.release-all` + (requirement 34) and the retention hold (requirement 6) use the same + filter, which is what keeps them off leases this gateway did not issue. ### Lease lifecycle through the gateway @@ -189,9 +276,21 @@ physical machine. no emulation: `lease.renew`, `lease.release`, and single-lease reads forward to the owning worker, and `expiresAt` reported to the client is the worker's. A client that stops renewing loses its lease on the - worker's clock, gateway or no gateway. + worker's clock, gateway or no gateway. Both daemons have a `lease.*` + block and both apply: the **gateway's** `lease.defaultTtlMs` fills in a + request that names no `ttlMs` and its `lease.maxTtlMs` caps what its own + clients may ask for, both before anything is dispatched, so a fleet + lease's width is decided at the gateway — but what it dispatches is an + ordinary `lease.request`, so a worker with a lower cap still refuses it. + Keep a gateway's `lease.maxTtlMs` at or below every worker's, or + requests the gateway accepts fail on whichever machine they land on. 16. A gateway lease id names its worker, so renew, release, and reads route - without consulting any state of its own. Clients treat the id as opaque. + without consulting any state of its own: it is the owning worker's id, + then a `.`, then the worker's own lease id, and routing **splits on the + first `.`** (a worker id is a UUID, so a real one reads + `3f81a2c4-9b7d-4e21-8a55-1c0e6f2d7b93.lse_9f2c`; docs abbreviate it). + The separator is path-safe because the id appears in + `/v1/leases/{id}` routes. Clients treat the whole id as opaque. 17. The gateway keeps no per-connection lease state and releases nothing when a client connection closes, exactly as a worker (ADR 0004 §3). A gateway client that stops renewing loses its lease on the worker's @@ -212,23 +311,48 @@ the CLI spawns it locally. That only works on the worker's own machine. A remote agent — over HTTP today, through a gateway tomorrow — has no way to drive the device it leased. -19a. New contract operation **`device.exec`** (role `agent`, ownership: the - caller must own the lease): `{ leaseId, tool: "simctl" | "adb", args, - stdin? }`. The **worker** resolves the command through the same driver - passthrough logic (same root scoping, same refusal list for verbs that - would change a device's lifecycle behind the registry's back) and runs - it through its `ProcessRunner`. Output streams back as request-scoped - pushes (`output`, carrying `stream: "stdout" | "stderr"` and a chunk, - keyed by the frame id like `progress`); the operation resolves with - `{ exitCode }`. It is a contract operation, so it works on the unix - socket, over HTTP (`POST /v1/leases/{id}/exec`, response streamed as - Server-Sent Events, the same shape `/events` already uses), and over - the uplink. +19a. New contract operation **`device.exec`** (role `agent`): + `{ leaseId, tool: "simctl" | "adb", args, stdin?, requesterId? }`. The + **worker** resolves the command through the same driver passthrough + logic (same root scoping, same refusal list for verbs that would change + a device's lifecycle behind the registry's back) and runs it through + its `ProcessRunner`. A refused verb reuses the existing + `PASSTHROUGH_REFUSED`, and a `tool` outside the wrapped set the + existing `UNKNOWN_PASSTHROUGH_TOOL` — the codes `driver.passthrough` + already answers with, at the status and exit code they already carry + (`422` / exit 2). The list gains exactly one entry this operation needs + and the local passthrough does not: **a bare `adb shell` with no + command is refused** ("needs a terminal"), because there is no + pseudo-terminal to attach it to and accepting it would only stall until + the timeout. Output streams back as request-scoped pushes (`output`, + carrying `stream: "stdout" | "stderr"` and a chunk, keyed by the frame + id like `progress`); chunks are UTF-8 text, so a command whose output + is binary should write a file on the worker instead. The operation + resolves with `{ exitCode }` — the tool's own, so a non-zero one is the + command's answer and not an API failure. `stdin` is a **single string + sent with the request** and written to the process, which is then + closed; there is no incremental stdin channel. It is a contract + operation, so it works on the unix socket, over HTTP + (`POST /v1/leases/{id}/exec`, response streamed as Server-Sent Events, + the same shape `/events` already uses), and over the uplink. +19a'. **Ownership on `device.exec`, and the one place `admin` does not + bypass.** A non-admin session is gated the ordinary way — its principal + against the lease's `ownerId`, exactly as `lease.renew` and + `lease.release` are (ADR 0003 §4) — and needs no `requesterId` at all. + The optional `requesterId` (defaulting to the principal, and namable + only by an admin session) exists for the one session that would + otherwise bypass that check: the gateway's admin session on a worker. + There, unlike renew and release, **admin does not bypass** — the worker + compares the supplied `requesterId` to the lease's own and answers + `FORBIDDEN` on a mismatch. Without that second check, "the gateway + checked its own lease index" would be the only thing standing between + one fleet agent and another agent's device. 19b. The **gateway proxies** `device.exec` to the owning worker over its uplink and relays the output pushes to the calling connection, - unchanged. It parses nothing about the command; ownership is checked at - the gateway (its own lease index) and again at the worker (the - forwarded namespaced requester owns the lease there). + unchanged. It parses nothing about the command; ownership is checked + twice, once per hop — at the gateway against its own lease index, and + again at the worker, which compares the forwarded namespaced requester + to the lease in front of it (19a'). 19b'. `device.exec` runs against the worker's filesystem. Getting an artifact there (an `.app`, an `.apk`) is out of scope for v1; it arrives out of band (a shared volume, a CI checkout on the worker). The @@ -237,18 +361,49 @@ drive the device it leased. on release — is left open by design, not built. 19c. The CLI's `simlock simctl` / `simlock adb` keep spawning locally with inherited stdio when they talk to a worker over its unix socket (an - interactive `adb shell` keeps working there). Against a gateway or over - HTTP they use `device.exec` and print the streamed output; `stdin` is - forwarded as a stream but there is no pseudo-terminal, so - line-oriented commands work and full-screen ones do not. + interactive `adb shell` keeps working there). Against a gateway they + use `device.exec` and print the streamed output, exiting with the + tool's own status; a piped stdin is read to EOF first and sent as + 19a's one-shot string. There is no pseudo-terminal either way, so + line-oriented commands work and full-screen ones do not. `device.exec` + is scoped to a lease, so these commands need one: the caller's own by + default, which one-lease-per-requester makes unambiguous, or + `--lease ` to name it. Two details the CLI does not get to decide + for itself: + - **It switches on `mode` from `status.get`**, which it already calls: + `gateway` means `device.exec`, anything else means + `driver.passthrough`. Not a flag, not a guess — the daemon says what + it is. (The CLI speaks the unix socket only; a remote agent reaches + the same operation over the HTTP API.) + - **It holds no copy of the refusal list**, in either direction. + Frontends render the contract and the list lives with the driver that + owns the device (ADR 0003 §11), so the daemon refuses and the CLI + relabels: `driver.passthrough`'s refusal locally, `device.exec`'s + `PASSTHROUGH_REFUSED` / `UNKNOWN_PASSTHROUGH_TOOL` through a gateway, + both surfacing as the `USAGE` exit 2 the local path already produces. + A caller reaching `device.exec` over HTTP gets the daemon's own code, + unrelabelled. 19d. `driver.passthrough` answers `UNSUPPORTED_IN_GATEWAY_MODE` on a - gateway: a command string the client cannot run is worse than an error. -19e. Limits: one per-command timeout, `gateway.execTimeoutMs` on the - gateway and `exec.timeoutMs` on the worker (both default ten minutes; - the worker's is authoritative), after which the process is killed and - the operation fails with `EXEC_TIMEOUT`. Output is streamed, never - buffered, so there is no size cap. No concurrency cap per lease beyond - what the tool itself tolerates. + gateway: a root-scoped command string naming a device set on another + machine is something the client cannot run, and handing it one would be + worse than an error. That answer is permanent rather than provisional — + see requirement 34 — which is why `501` is the honest HTTP status for + it and not a temporary condition to retry past. +19e. Limits: one per-command timeout per hop. **`exec.timeoutMs` on the + worker (ten minutes) is authoritative**, because that side owns the + process and is the only one that can kill it; + **`gateway.execTimeoutMs` (eleven minutes) is a backstop** for the case + where the worker never answers at all. The gateway's is deliberately + the longer of the two: equal defaults would make the worker's authority + a coin toss on every timeout, where the point is that an ordinary + timeout surfaces as the worker's own `EXEC_TIMEOUT` rather than racing + the gateway's. `EXEC_TIMEOUT` is CLI exit 10 and HTTP `504` — though on + `POST /v1/leases/{id}/exec` the status never reaches the client, since + the response is already `200` and streaming by the time a command can + time out, so it arrives as that stream's terminal `error` event; the + status is for a client mapping the code without a route in front of it. + Output is streamed, never buffered, so there is no size cap. No + concurrency cap per lease beyond what the tool itself tolerates. ### Status, events, catalog @@ -263,9 +418,19 @@ drive the device it leased. `workerId` added to the payload and land in the gateway's own ring buffer, so `simlock events --follow` against a gateway shows the fleet. The gateway emits its own facts: `worker.connected`, - `worker.disconnected`, `worker.removed`, `worker.drain-started`, - `worker.drain-ended`, `request.dispatched` (documented in `EVENTS.md` - in the same change). + `worker.disconnected`, `worker.rejected`, `worker.removed`, + `worker.drain-started`, `worker.drain-ended`, `request.dispatched` + (documented in `EVENTS.md` in the same change). + `worker.rejected` covers an uplink refused at the door (requirement 4): + payload `{ reason, workerId?, label?, protocol? }` with `reason` either + `unauthenticated` (`401`) or `forbidden` (`403`), everything else + optional because a dial that fails authentication proves no identity. + Without it a refused uplink leaves no trace at all, and "why did that + machine never appear" is exactly what an operator comes to the event + stream to answer. `device.exec` deliberately emits **no** event: running + a command is not a state change Simlock owns, the lease authorizing it + already emitted `lease.granted`, and one event per `adb shell input tap` + would empty the ring buffer of everything else. 23. New admin operation `worker.list` and HTTP route `GET /v1/workers` return the worker views; `worker.drain|undrain|remove` map to `POST /v1/workers/{id}/drain`, `DELETE /v1/workers/{id}/drain`, @@ -276,9 +441,12 @@ drive the device it leased. 24. Client → gateway: the gateway has its own token store and mints its own `agent` and `operator` tokens with `simlock token`, exactly as a worker does. A gateway token is never valid on a worker and vice versa. -25. Worker → gateway: the join token (role `worker`). It can open an uplink - and nothing else; a `worker`-role token presented on a `/v1` route is - `403`. +25. Worker → gateway: the join token (role `worker`). `/v1/uplink` + (requirement 4) is the one route it opens and the only route it opens: + presented on any **other** `/v1` route it is `403`, and an + `agent`- or `operator`-role token presented at `/v1/uplink` is `403` + just the same. The role is disjoint from the other two rather than above + or below them. 26. The gateway enforces per-requester ownership itself before forwarding anything on the uplink's admin session, so an agent token on the gateway can never reach another requester's lease through it. @@ -286,12 +454,30 @@ drive the device it leased. (`gw::`) so a local agent on the worker machine and a remote one behind the gateway can never collide on the one-lease rule or on attribution. +27a. The gateway also forwards the lease's **owner** — the principal it + authorized the request against — as an explicit field on + `lease.request`, and the worker stores that as the lease's `ownerId` + rather than deriving one from the calling connection. Without it the + owner is unrecoverable after a gateway restart: `requesterId` + round-trips through requirement 27's prefix, but every lease a gateway + issues is owned by its own uplink principal, so a rebuild + (requirement 30) could not tell one gateway client's lease from + another's and would have to either guess or fail open. **Only an + `admin` session may set the field**; from any other role the request is + rejected. `ownerId` is what `lease.renew`, `lease.release` and + `lease.list` authorize against, so a caller free to name someone else + as owner would be naming its way into their lease. Omitting the field + keeps today's behaviour — the owner is the calling connection — so this + is additive and no existing caller changes. ### Failure behaviour 28. **Uplink down.** No new dispatches to that worker. A renew or release for a lease on it fails with a new closed error code `WORKER_UNREACHABLE` - (`kind: "transport"`); the worker's own TTL eventually expires the lease + (`kind: "transport"`, CLI exit 1, HTTP `503` — where every other + `transport`-kind code in the contract's table already sits, since "the + thing behind this is not reachable right now" is the same answer in all + of them); the worker's own TTL eventually expires the lease and reclaims the device, and the gateway relays `lease-lost` once the uplink returns and it sees the worker's `lease.expired` fact. The gateway never guesses a lease is gone before the worker says so. @@ -304,12 +490,28 @@ drive the device it leased. 30. **Gateway restart.** In-flight requests are lost, exactly as a worker restart loses them today. Leases survive on workers; workers reconnect on their backoff and the gateway rebuilds every view and its lease index - from them. Gateway clients keep their leases and simply resume renewing - once the gateway answers again. + from them — picking its own leases out of each `lease.list` by the + `gw::` prefix (requirement 14), which is what makes + a rebuild possible with nothing about leases persisted. Ownership comes + back with them: the owner was forwarded on the way in (requirement 27a) + and is returned by `lease.list`, so a rebuilt lease is authorized to the + same principal it was before the restart, not to the gateway at large. + The worker + registry (requirement 8a) comes back off disk instead of being + re-derived, so drains survive. Gateway clients keep their leases and + simply resume renewing once the gateway answers again. 31. **Version skew.** `hello` over the uplink negotiates the protocol range exactly as over the socket (ADR 0003 §6). A worker outside the gateway's range is marked `incompatible` in its view, with both ranges, and is - never dispatched to. + never dispatched to. That uplink **authenticated**, so this is not a + `worker.rejected` (requirement 22): the worker enters the registry and + is visible in `simlock worker list` — which is the point, since it is + the machine an operator has to go and upgrade — while no + `worker.connected` follows, because nothing usable connected. It keeps + serving its own local clients on its own protocol meanwhile. Since this + record takes the wire to protocol 5 with no shim (see Consequences), + every worker older than it is `incompatible` by range: the ordinary + upgrade path, not a failure mode. ### Engineering @@ -328,7 +530,19 @@ drive the device it leased. 34. Operations that act on a machine's devices as a whole — `nuke.run`, `cleanup.run`, `doctor.run` — and `driver.passthrough` answer `UNSUPPORTED_IN_GATEWAY_MODE` in v1; they stay per-worker, direct - operations. `config.get` returns the gateway's own config. + operations, permanently rather than pending a later fan-out. + `config.get` returns the gateway's own config. + `lease.release-all` is the one operation in this family that a gateway + *does* implement, because it is scoped to leases rather than to a + machine's devices: it releases **only the leases that gateway issued** + (requirement 14's prefix filter), across every connected worker, and + never a worker's own local leases — the gateway did not issue those, + does not know who holds them, and taking a local developer's device away + from an endpoint they have never heard of is not an operator action + anyone asked for. A worker it cannot reach is reported as + `WORKER_UNREACHABLE` naming that worker while the reachable ones still + complete: a partial result stated plainly beats an all-or-nothing that + leaves the operator guessing. 35. Tests: one suite per gateway handler against scripted uplinks and a manually-advanced `Clock` (dispatch order and pass-over, stale-view `NO_CAPACITY`, drained and disconnected workers, fleet-wide one-lease @@ -354,7 +568,10 @@ drive the device it leased. accounting stays the single arbiter between gateway and local agents. 5. **Leases need no gateway state.** TTL-first leases (ADR 0004) make renew a forwarded operation and the lease id the only routing key. A gateway - restart loses nothing a worker restart would not also lose. + restart loses nothing a worker restart would not also lose. The one thing + a gateway does persist is the worker registry (requirement 8a) — which + workers it knows and which are drained — because drain is an operator's + intent and not an observation; nothing about a *lease* is written there. 6. **Capacity and safety stay on the worker.** The gateway never touches a device, so every rule in `docs/agent-rules/safety.md` keeps holding by construction: registry-only destruction, never touching a leased device, @@ -378,15 +595,45 @@ drive the device it leased. - The contract gains: `mode` in `status.get`'s daemon block, `workerId` on devices and leases, `worker` on the lease object, `workers` on status, `worker.*` operations, `device.exec` with its `output` push family, the - `worker` token role, and error codes `WORKER_UNREACHABLE`, - `WORKER_CONNECTED`, `UNSUPPORTED_IN_GATEWAY_MODE`. All additive. + `worker` token role, and five error codes. All additive. +- **The five new error codes, with the columns the contract's table already + has for every other code** (`kind`, `cliExitCode`, `httpStatus`): + `WORKER_UNREACHABLE` (`transport`, exit 1, `503`, requirement 28); + `WORKER_CONNECTED` (`domain`, exit 2, `409`, requirement 8); + `UNKNOWN_WORKER` (`domain`, exit 12, `404`, requirement 8); + `UNSUPPORTED_IN_GATEWAY_MODE` (`domain`, exit 2, `501`, permanent rather + than provisional, requirements 19d and 34); `EXEC_TIMEOUT` (`domain`, + exit 10, `504`, requirement 19e). `device.exec`'s refusals add no code at + all: they reuse `PASSTHROUGH_REFUSED` and `UNKNOWN_PASSTHROUGH_TOOL` + (requirement 19a), which already carry exit 2 and `422`. +- **The socket wire moves to protocol 5 with no compatibility shim**, so + both sides advertise `{min: 5, max: 5}`: `device.exec` and its `output` + push family are new frames and no compatibility path is kept for them, and + under ADR 0003 §6's honesty rule a range widens only where one is. This is + the same wire ADR 0004 took to 4, so what ships carries both moves at + once. Over the uplink it is ordinary negotiation (requirement 31). - New config: `mode`, `gateway.url`, `gateway.token`, `gateway.label`, - `exec.timeoutMs` (worker side); `gateway.routing`, - `gateway.disconnectedRetentionMs`, `gateway.execTimeoutMs` (gateway - side). New error code `EXEC_TIMEOUT`. + `exec.timeoutMs` (worker side, ten minutes and authoritative); + `gateway.routing` (`warm-then-free`, requirement 13), + `gateway.disconnectedRetentionMs` (24 hours), + `gateway.execTimeoutMs` (gateway side, eleven minutes — a backstop + deliberately longer than the worker's, requirement 19e). Two pairs are + rejected at load rather than warned about, because neither has a safe + reading: `mode: "gateway"` with `http.enabled: false` (requirement 2), and + in `mode: "worker"` one of `gateway.url`/`gateway.token` without the other + (requirement 3). - The two-Mac case runs two daemons on the machine that should do both: a worker and a gateway with distinct `SIMLOCK_HOME`s, the worker joining the - gateway over localhost. + gateway over localhost. What has to be kept apart is small, because only + one of them owns anything: distinct `SIMLOCK_HOME`s (which is what gives + them separate config, state, sockets, logs, token stores, and the distinct + instance ids that make the worker its own fleet member); distinct + `http.port`s if both listen, since a port is machine-global and + `SIMLOCK_HOME` cannot isolate it; and only the gateway needing + `http.enabled` at all, since the worker dials out. The worker keeps its + whole `drivers.*` block — it owns the devices, the gateway has no drivers + to configure — so unlike two *workers* on one machine there is no + `drivers.android.adbServerPort` to split. - `docs/HTTP-API.md` gains the `/v1/workers` routes and the uplink endpoint, and drops "multi-host brokering" from "Not implemented"; `docs/IDEAS.md` drops "Cross-machine coordination"; #88 drops its "one console per daemon" @@ -405,7 +652,11 @@ drive the device it leased. and progress pushes relayed; 3. drain semantics, `WORKER_UNREACHABLE` paths, reconnect rebuild, e2e test; - 4. docs, changelog, and the #88 endpoints. + 4. the #88 endpoints. The documentation half of this sequence is the + exception to its ordering: it lands **first**, with this record's + acceptance, because "Accepted — not yet implemented" means the docs are + the specification the PRs above are written against rather than a + write-up of what they did. ## Alternatives considered @@ -437,12 +688,18 @@ drive the device it leased. Rejected in favour of proxying `device.exec`. - **Fanning `doctor.run` / `cleanup.run` out to every worker.** Useful for the console later; a fleet-wide destructive command from one endpoint is - not something v1 should offer. Deferred; all four stay per-worker. + not something v1 should offer. Rejected for these operations, and the + gateway's `UNSUPPORTED_IN_GATEWAY_MODE` is therefore permanent rather than + a placeholder: a fleet-wide form, if it is ever wanted, is a **new + operation** with its own name, role, and blast radius — not `doctor.run` + or `cleanup.run` growing a second meaning on a gateway. All four stay + per-worker. - **Naming the modes `host` / `worker`.** Rejected: agent-device already has a Host process (#70) and the docs use "host" for the machine. - **A gateway that is also a worker (hybrid).** Every gateway code path would need a "local" special case and the gateway would hold device - state. Rejected; run two daemons with distinct `SIMLOCK_HOME`s. + state. Rejected; run two daemons with distinct `SIMLOCK_HOME`s and + distinct `http.port`s (see Consequences). ## Open questions diff --git a/docs/adr/README.md b/docs/adr/README.md index d1600078a..16d0ea873 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -24,4 +24,4 @@ Status values: | [0002](0002-opt-in-slim-ios-simulators.md) | Opt-in slim iOS simulators | Accepted | | [0003](0003-one-typed-daemon-contract-behind-every-frontend.md) | One typed daemon contract behind every frontend | Accepted | | [0004](0004-ttl-first-leases-on-every-transport.md) | TTL-first leases on every transport | Accepted — not yet implemented | -| [0005](0005-gateway-and-worker-modes.md) | Gateway and worker modes | Proposed | +| [0005](0005-gateway-and-worker-modes.md) | Gateway and worker modes | Accepted — not yet implemented | diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index 23088f8c6..a9d85798c 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -387,7 +387,7 @@ an unowned lease, the same way the mutating routes do today. ## HTTP error codes outside the closed contract union ADR §7: `SimlockError` has a `code` from the contract's closed union, and "a code the client -does not know... wraps as `UNKNOWN_DAEMON_ERROR`". Four codes the HTTP gateway answers with +does not know... wraps as `UNKNOWN_DAEMON_ERROR`". Four codes the HTTP frontend answers with today (`src/http/errors.ts`) have no row in that union (`src/contract/errors.ts`'s `ERROR_TABLE`), so a typed client built against the contract can only ever see them as `UNKNOWN_DAEMON_ERROR` with the real code buried in `details`: @@ -527,3 +527,173 @@ a permanent orphan: the idle-shutdown and idle-destroy cleanup rules reap it on the same timers as any other idle device, since neither rule cares what a device's spec matches. Until those timers fire, though, it occupies a pool slot doing nothing. + +## `device.exec` carries no files (ADR 0005) + +A remote agent drives its leased device with `device.exec` — `simlock simctl` +/ `simlock adb` against a gateway, or `POST /v1/leases/{id}/exec` over HTTP. +The command runs on the machine that owns the device, which is what makes it +work at all across a fleet. + +**The pitfall:** the *arguments* travel, the *files* do not. `simctl install +/tmp/MyApp.app` and `adb install ./app-debug.apk` resolve their path on the +worker's filesystem, so a build sitting on the agent's own machine is simply +not there — the command fails with the tool's own "no such file" rather than +with anything simlock says, which reads like a broken lease until you notice +which machine ran it. The same applies in reverse for output: `simctl io +booted screenshot shot.png` writes `shot.png` on the worker. + +**Why it is accepted:** a file transfer is a second, byte-heavy concern with +its own questions (size caps, resumability, where the bytes land, who deletes +them), and answering them badly inside the lease path is worse than not +answering them. v1's honest position is that artifacts arrive out of band — a +shared volume, a checkout the CI job already did on that machine, an +`scp` the operator's own tooling does. + +**Status:** accepted for v1 and designed around rather than designed out. +[ADR 0005](adr/0005-gateway-and-worker-modes.md) leaves the seam open +deliberately: `device.upload` would stream chunks as request-scoped pushes +over the same wire, into a per-lease scratch directory deleted on release. +Nothing about `device.exec`'s shape has to change to add it. + +**Possible future fix:** `device.upload`, tracked in +[IDEAS.md](IDEAS.md#gateway-side-file-upload-for-deviceexec). + +## `device.exec` has no pseudo-terminal, so interactive commands break + +Locally — `simlock simctl` / `simlock adb` against a worker over its unix +socket — the CLI spawns the tool with inherited stdio, so an interactive `adb +shell` is a real interactive shell and always has been. + +**The pitfall:** through a gateway, or over HTTP, the same command goes +through `device.exec` instead, and there is no PTY on the far end. `stdin` is +one string sent with the request and then closed. Line-oriented commands are +fine (`adb shell getprop`, `adb shell input tap 100 200`, `simctl install`); +anything that wants a terminal is not — a full-screen program renders as +escape sequences, and a tool that stops to ask a question waits for input +that can never come until the timeout kills it. The failure is quiet in the +worst case: the command hangs until `exec.timeoutMs` (ten minutes) and then +fails `EXEC_TIMEOUT`. + +The one shape of this that is *not* quiet is the most likely one. A bare `adb +shell` with no command — the thing a human types first — is refused up front +by the worker with `PASSTHROUGH_REFUSED` (CLI exit 2, HTTP `422`) and a +message saying it needs a terminal. It is the only refusal `device.exec` adds +to the passthrough list, and it exists precisely because the honest failure +for that command is immediate and legible, while the natural one is a +ten-minute stall ending in a timeout that says nothing about terminals. It +does not generalize: simlock cannot tell in advance which *other* commands +will block for input, so everything past this one case is still bounded by +the timeout rather than by a refusal. + +**Why it is accepted:** a PTY is not a bigger version of a pipe. It needs +terminal allocation on the worker, window-size propagation, signal +forwarding, and a bidirectional stream where v1 has request-scoped pushes — +and it exists to serve a human at a keyboard, which is not who this control +plane is for. Agents send commands and read output. + +**Status:** accepted by design, and the boundary is drawn where the docs say +it is: same command, same refusals, same exit code, no terminal. The local +path keeps its inherited stdio, so nobody loses an interactive shell they had +before. + +**Possible future fix:** an interactive TTY is part of the reserved +`dataPlane` (see [IDEAS.md](IDEAS.md#a-byte-heavy-data-plane)), not a +follow-up to `device.exec`. + +## A dispatched request whose uplink drops may have granted a lease anyway + +The gateway dispatches a queued request to a worker with `noWait: true` and +waits for the answer. If the uplink drops in that window, the client's +request fails with `WORKER_UNREACHABLE`. + +**The pitfall:** "the request failed" does not mean "no lease exists". The +worker may have granted one just before the socket died — the grant is +committed *there*, on the worker's registry, and it stands. So the device is +leased to you on a machine you cannot currently reach, burning TTL, while +your client believes it got nothing. An immediate retry then meets the +fleet-wide one-lease rule only *after* the uplink is back and the gateway has +rebuilt its lease index from the worker's `lease.list` — until then, the +gateway does not know that lease exists, and the retry is admitted and can +land you a second device. + +**Why it is accepted:** the alternative is for the gateway to decide, on its +own, that a lease it cannot see is gone — and that is the one thing it must +never do. A worker that is unreachable is not a worker that is dead, and a +gateway that guessed wrong would release a device out from under a running +agent. The uncertainty window is bounded by the uplink's reconnect backoff, +and the lease itself is bounded by its TTL: an orphan from this race expires +on the worker's own clock without anyone intervening. + +**Status:** accepted, with the recovery loop documented rather than +automated. It is the same `409 → GET` shape the HTTP API already documents +for a daemon restart, applied across an uplink gap: re-request, and if the +answer is `REQUESTER_ALREADY_LEASED`, read the lease it names — that is your +earlier grant, found again. + +**Possible future fix:** durable, idempotent lease requests in the core +([#72](https://github.com/callstackincubator/simlock/issues/72)) would let a +retry be recognized as the same request rather than a new one, on a gateway +and on a worker alike. + +## A lease survives a gateway restart, but nothing can renew it until the gateway is back + +Leases live on workers, not on the gateway, so a gateway restart destroys +none of them — the same property that makes a gateway need no lease state at +all (ADR 0004, ADR 0005). + +**The pitfall:** surviving is not the same as being reachable. While the +gateway is down, a client behind it has no route to the worker at all — +`renew`, `release`, and `exec` all fail, and there is deliberately no worker +address on the lease for a client to fall back to. The lease keeps counting +down on the worker's clock throughout. If the gateway is down for longer than +the remaining TTL, the lease expires and the device is reclaimed, and the +client's first successful renew afterwards answers `UNKNOWN_LEASE`. In-flight +lease *requests* are lost outright, exactly as a worker restart loses them. + +**Why it is accepted:** the two alternatives are both worse. Giving clients a +worker address reopens the NAT problem the uplink exists to remove and needs +per-worker client credentials; having the gateway renew on the client's +behalf reintroduces exactly the emulation ADR 0004 deleted, and would keep +devices alive for clients that are themselves long gone. A gateway restart +costing a lease *only if it outlasts the TTL* is the same bargain a worker +restart already makes with its own clients. + +**Status:** accepted. The bound is the lease's own TTL, so `lease.defaultTtlMs` +and `--ttl` are the knobs — the **gateway's** `lease.defaultTtlMs` for a +fleet lease, since that is what fills in a request naming no `ttlMs` before +it is dispatched anywhere. A longer TTL buys more tolerance for a gateway +outage and costs more time to reclaim a device from a holder that vanished. +Restarting a gateway is fast, and workers reconnect on their own backoff with +no operator action. + +## Local agents and the gateway share a worker's capacity + +A worker that joins a fleet keeps serving its own local clients. Nothing +changes on it: same socket, same queue, same limits. + +**The pitfall:** the fleet does not get its own slice of that machine. A +developer running builds against their local simlock, or an agent leasing +over the worker's own unix socket, consumes the same running capacity the +gateway is trying to dispatch into — so a machine that `simlock worker list` +shows as part of the fleet can be, from the gateway's point of view, +persistently full for reasons no one looking at the gateway can see. The +gateway's dispatch handles it correctly (a `NO_CAPACITY` answer is treated as +a stale view, the request stays queued and goes elsewhere), so this is a +visibility and fairness problem rather than a correctness one. + +**Why it is accepted:** the worker's own capacity accounting is the single +arbiter of its machine, and it should be — it is the thing that actually +knows what is running there, and it already arbitrates between two local +agents the same way. A reservation on the worker would add a fleet-shaped +concept to a component whose whole job is to be local, for a problem the +worker views already surface: local leases appear in the gateway's aggregate +too, so an operator can see *why* a machine is full. + +**Status:** accepted for v1. `simlock worker drain` is the operator's tool +when a machine should be left to its owner for a while — it stops new +dispatches without touching the leases anyone already holds. + +**Possible future fix:** a reserved capacity slice per worker, deferred in +[ADR 0005](adr/0005-gateway-and-worker-modes.md) and recorded in +[IDEAS.md](IDEAS.md#capacity-slices-reserved-for-the-gateway).