Skip to content
Merged
13 changes: 7 additions & 6 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ edit yourself keeps the mode you give it until the next `config set`; run
| `gateway.url` | **Worker side.** Base URL of the gateway this worker joins, e.g. `wss://gw.example:4700`; the worker dials `<url>/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. `simlock config` shows it; the daemon log and the `daemon.started` event show `[redacted]`. It is stored in plain text in `config.json`, which `simlock config set` writes owner-only. | 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 |
| `agentDevice.enabled` | **Worker side.** Run one agent-device daemon on this worker, started and watched by Simlock. It sees Simlock's devices and no others, refuses `boot` and `shutdown`, and keeps its files in `~/.simlock/agent-device`. If agent-device is missing, older than 0.21.25, speaks another RPC protocol or needs a newer Node than Simlock runs on, it is not started and Simlock runs on without it. A daemon a killed Simlock left behind is stopped at the next start. With `http.enabled` also `true`, the agent-device CLI reaches it at `/v1/agent-device` (see [HTTP-API.md](HTTP-API.md#v1agent-device)). | `false` |
| `agentDevice.leaseTtlCapMs` | **Worker side.** Caps the TTL of the leases the agent-device CLI makes and renews through Simlock: a longer `ttlMs` is lowered to it, and a lease that sends none gets it. A whole number of milliseconds from `5000` to `lease.maxTtlMs`; a value outside that range stops the daemon at start. Used only when `agentDevice.enabled` is `true`. | unset (no cap) |
| `agentDevice.command` | **Worker side.** The agent-device executable: a name looked up on `PATH`, or a path. Used only when `agentDevice.enabled` is `true`. | `agent-device` |
| `agentDevice.enabled` | **Both sides.** On a worker: run one agent-device daemon on this worker, started and watched by Simlock. It sees Simlock's devices and no others, refuses `boot` and `shutdown`, and keeps its files in `~/.simlock/agent-device`. If agent-device is missing, older than 0.21.25, speaks another RPC protocol or needs a newer Node than Simlock runs on, it is not started and Simlock runs on without it. A daemon a killed Simlock left behind is stopped at the next start. With `http.enabled` also `true`, the agent-device CLI reaches it at `/v1/agent-device` (see [HTTP-API.md](HTTP-API.md#v1agent-device)). On a gateway: serve `/v1/agent-device` and send each agent to a worker whose agent-device is available; the gateway runs no daemon of its own. | `false` |
| `agentDevice.leaseTtlCapMs` | **Both sides.** Caps the TTL of the leases the agent-device CLI makes and renews through Simlock: a longer `ttlMs` is lowered to it, and a lease that sends none gets it. A whole number of milliseconds from `5000` to `lease.maxTtlMs`; a value outside that range stops the daemon at start, on a gateway too. Used only when `agentDevice.enabled` is `true`. | unset (no cap) |
| `agentDevice.command` | **Worker side.** The agent-device executable: a name looked up on `PATH`, or a path. A gateway ignores it and logs a warning. Used only when `agentDevice.enabled` is `true`. | `agent-device` |
| `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. Among the workers that can serve the request, in order: a worker whose health is not `running`, or that has requests of its own waiting, is left out; a worker holding a ready device that fits goes first (the device's mode must fit the request, a request with no mode fits a device that serves the worker's default mode, and its runtime must be the one requested or, with none requested, the one the worker would pick: the newest runtime the model pairs with); otherwise a worker with no free running slot for the platform or overall is left out (a running device that is not leased counts as free: the worker shuts it down to make room), a worker under its RAM budget for the platform is preferred over one at it (a worker at its budget is still asked when it is the only one left), and the one with the most free running capacity for the platform wins. A worker that is left out is busy, not unable: the request waits for it. Ties go to the lowest worker id. | `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` |
Expand Down Expand Up @@ -160,12 +160,13 @@ local agents whether or not its gateway is reachable, and `http.enabled` stays
off by default.

**A gateway reads a deliberately small slice of this file**: `mode`, `http.*`,
`log.*`, `lease.*`, `eventBuffer.*`, `eventLog.*` and `gateway.*`. Every other key —
`log.*`, `lease.*`, `eventBuffer.*`, `eventLog.*`, `gateway.*` and
`agentDevice.*` (`enabled` and `leaseTtlCapMs` only). Every other key —
capacity, drivers, downloads, idle, warmPool, health, ios, android, stalledTransition —
configures devices, which a gateway does not have; each one present in a
gateway's config is reported with a warning and ignored, the same treatment an
unknown key gets. The worker-side `gateway.url`/`token`/`label` are warned
about there too. Nothing is stripped: the same file can be copied between a
unknown key gets. The worker-side `gateway.url`/`token`/`label` and
`agentDevice.command` are warned about there too. Nothing is stripped: the same file can be copied between a
worker and a gateway with only `mode` differing, and the warning is what makes
the difference visible rather than silent.

Expand Down
28 changes: 25 additions & 3 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -1489,8 +1489,29 @@ agent-device snapshot
agent-device close
```

With `agentDevice.enabled` `false`, and on a gateway, every `/v1/agent-device`
URL answers `404`.
With `agentDevice.enabled` `false` or unset, on a worker or a gateway, every
`/v1/agent-device` URL answers `404`.

A **gateway** with `agentDevice.enabled` serves the same URL, and the CLI is
pointed at the gateway the same way. `open` lands only on a worker whose
agent-device is available, and the commands, heartbeats and `close` of that
lease go to the same worker. An agent on a gateway never shares an
agent-device session with an agent on a worker's own tokens. Through a gateway:

- `GET /health` answers the proxy's health from a worker whose agent-device is
available. With no such worker it answers `agent-device is not available on
this simlock: no worker connected to this gateway can serve agent-device`
with status 200.
- A worker that is draining takes no new `open`, and keeps serving the leases
it holds.
- A request that names no lease, other than `/health`, is refused with
`refused: this agent-device is too old to use through a gateway; update it`.
That includes `devices`, uploads, artifact downloads and diagnostics.
- A request that names a lease the token does not hold, or the gateway does not
know, is refused with `refused: lease <id> is not one of yours on this
gateway` (status 403). A lease `simlock release --all` ended stays known for
one `lease.maxTtlMs` afterwards, so its next heartbeat answers `lease ended
by simlock; run disconnect, then open`.

- **Every route needs the Simlock token.** No token is `401`, a worker join
token is `403`, and so is an `operator` token, with
Expand Down Expand Up @@ -1535,7 +1556,8 @@ Messages the route prints. The agent-device CLI reads the message in the body
the status.

- `agent-device is not available on this simlock: <reason>`: agent-device is
turned on but missing, too old, starting or crashed. The rest of Simlock
turned on but missing, too old, starting or crashed (on a gateway: no
connected worker can serve it, or the worker holding the lease cannot). The rest of Simlock
works as before. `GET /health` answers it with status 200, because the
agent-device CLI treats a `/health` status of 500 or more as an unreachable
daemon and would print only `Remote daemon is unavailable`; the first
Expand Down
2 changes: 1 addition & 1 deletion docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ agent / console ──token auth──> │ HTTP frontend + unix socket
- **What a gateway does not do.** It starts no drivers, validates no device
roots, and runs no reaper, health monitor or capacity strategy; of the
config it reads only `mode`, `http.*`, `log.*`, `lease.*`, `eventBuffer.*`,
`eventLog.*` and `gateway.*` (worker-only keys warn and are ignored). It always listens
`eventLog.*`, `gateway.*` and `agentDevice.*` (worker-only keys warn and are ignored). It always listens
on HTTP — that is how agents reach it and what the uplink upgrades from — so
`http.enabled: false` in gateway mode fails the start rather than being
silently overridden. `nuke.run`, `cleanup.run`, `doctor.run`,
Expand Down
1 change: 1 addition & 0 deletions docs/internal/COMPONENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ modules with.
| Install lookup, compatibility, daemon environment | `src/agent-device/host/install.ts`, `src/agent-device/shared/` | Finding the agent-device install and its daemon entry; the minimum versions and RPC protocol; the environment and policy data. | Run a process. |
| `AgentDeviceHealthProbe` | `src/agent-device/host/health.ts` | The `GET /health` read, with a time limit. | Judge the answer. |
| Front | `src/agent-device/front/` | The `/v1/agent-device/*` mount: the role check, the route list, the `/rpc` body check, the request rules (platform, device selectors, device set, sharding, install, `devices`) and the `devices` filter, turning an agent-device `allocate` into a simlock `lease.request` (and its cancel when the CLI leaves) and a `release` into a `lease.release`, the front map of the leases it made, and who ended each; the heartbeat, which renews the simlock lease after agent-device answers, and the renewals while a command runs. | Check a token (the app does); run the proxy. |
| Relay host link | `src/agent-device/front/relay-host-link.ts` | On a gateway: the front's host link. It finds the worker that holds a lease (the gateway's lease index, and a memory of a lease the index dropped, kept for the gateway's `lease.maxTtlMs`), checks the lease is the token's, and relays the request there with the tenant `gw.<gateway instance id>.<principal>`; it reports whether any capable worker exists. | Import from `src/gateway` (it reads a port the daemon builds); decide which worker a new lease lands on (leasing does, from `requires`). |
| `AgentDeviceHost`, `AgentDeviceUpstream` | `src/agent-device/host/host.ts`, `host/upstream.ts` | `@agent-device/proxy` in front of the daemon, one proxy per daemon start; the tenant each request acts as; the port the daemon is reached through and its supervisor adapter. | Know simlock leases. |
| `ReleaseScopeRecord`, `AgentDeviceLeaseEnd` | `src/agent-device/host/lease-end.ts` | The host's record of each agent-device lease's release scope (filled by a recording wrapper around the proxy's upstream fetch), and the `LeaseEndParticipant` that, when simlock ends a lease, waits for a running allocate or release and releases the agent-device lease with that scope before the wipe. | Write to the front map; bound a wait with a timer (leasing's signal bounds it). |
| Wire rules | `src/agent-device/shared/` | The path prefixes, the route and RPC method lists, the selector reader, the `/rpc` body reader, the call classifier, the lease-call field reader, the release scope reader, the reply reader (an allocate reply is a success only when its release scope passes) and the front's replies. | Decide what a call means. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,11 @@ sequenceDiagram
### 6. The tenant on the worker carries the gateway's prefix

A relayed request's agent-device tenant on the worker is
`gw:<gateway instance id>:<principal>`, the prefix the gateway already puts
on the requester of every lease it dispatches. Tokens minted on a gateway and
`gw.<gateway instance id>.<principal>`, the prefix the gateway already puts
on the requester of every lease it dispatches, with dots for colons because
agent-device accepts only letters, digits, dot, underscore and hyphen (up to
128 characters; a character it refuses is escaped, and a longer name is cut and
ends in a hash). Tokens minted on a gateway and
on a worker are separate, so two agents can share a principal name; with the
prefix they never share an agent-device tenant, and neither can drive the
other's device. The simlock lease's owner stays the bare principal, as for
Expand Down
32 changes: 32 additions & 0 deletions src/agent-device/dispose.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { FakeClock } from "../ports/clock.js";
import { disposeAgentDeviceEdge, type AgentDeviceFrontParts } from "./index.js";
import { FrontMap } from "./front/front-map.js";
import { Renewals } from "./front/renewals.js";
import type { HostLink } from "./front/host-link.js";

describe("disposeAgentDeviceEdge", () => {
it("disposes the renewals, so a command that begins afterwards arms no timer, and disposes the link", () => {
const clock = new FakeClock(0);
const renewals = new Renewals(clock);
let linkDisposed = 0;
const link: HostLink = {
dispose: () => {
linkDisposed += 1;
},
forward: () => Promise.reject(new Error("unused")),
leaseRequires: [],
status: () => Promise.resolve({ reason: "unused", state: "unavailable" }),
};
const parts: AgentDeviceFrontParts = { link, map: new FrontMap(clock), renewals };

disposeAgentDeviceEdge(parts);

expect(linkDisposed).toBe(1);
const context = {
map: { get: () => ({ endedAt: undefined, identity: { requesterId: "a" }, ttlMs: 30_000 }) },
};
renewals.begin(context as never, "lease", "a", 60_000);
expect(clock.pendingTimerCount).toBe(0);
});
});
4 changes: 2 additions & 2 deletions src/agent-device/edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -521,14 +521,14 @@ async function runningCommand(rig: Rig, n: number, options: Omit<SendOptions, "b
}

describe("the agent-device front, through the whole worker daemon", () => {
it("with agentDevice.enabled false, and on a gateway-mode daemon, /v1/agent-device/health answers 404, as today", async () => {
it("with agentDevice.enabled false, and unset on a gateway-mode daemon, /v1/agent-device/health answers 404, as today", async () => {
const enabled = await setUp();
expect((await send(enabled, "/health")).status).toBe(200);

const off = await setUp({ enabled: false });
expect((await send(off, "/health")).status).toBe(404);

const gateway = await setUp({ gatewayMode: true });
const gateway = await setUp({ enabled: "unset", gatewayMode: true });
expect((await send(gateway, "/health")).status).toBe(404);
});

Expand Down
42 changes: 39 additions & 3 deletions src/agent-device/front/allocate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@ function setUp() {
if (handler === undefined) throw new Error(`unexpected ${operation}`);
return handler(input, session);
}) as unknown as HttpDispatch;
const link = { value: { forward: vi.fn(), status: vi.fn() } as Record<string, unknown> };
const context = {
clock,
dispatch,
link: { forward: vi.fn(), status: vi.fn() },
link: link.value,
logger: new NoopLogger(),
map,
} as unknown as FrontContext;
Expand All @@ -50,12 +51,11 @@ function setUp() {
text: "",
},
identity: agent,
leaseMaxTtlMs: 600_000,
request: new Request("http://front.test/rpc", { method: "POST", signal: hangUp.signal }),
});
const requests = () => calls.filter((call) => call.operation === "lease.request");
const cancels = () => calls.filter((call) => call.operation === "lease.cancel");
return { cancels, clock, handlers, hangUp, map, requests, run };
return { cancels, clock, handlers, hangUp, link: link.value, map, requests, run };
}

// why: the request must stay open until the test admits and settles it, to hang up in between.
Expand Down Expand Up @@ -153,4 +153,40 @@ describe("the allocate front", () => {
expect(rig.requests()).toHaveLength(1);
expect(rig.map.get("old")?.endedAt).toBeUndefined();
});

it("sends the host link's leaseRequires on the lease request, and none when the link names none", async () => {
const plain = setUp();
await plain.run();
const needing = setUp();
needing.link["leaseRequires"] = ["agent-device"];
await needing.run();

expect(plain.requests()[0]?.input).not.toHaveProperty("requires");
expect(needing.requests()[0]?.input).toMatchObject({ requires: ["agent-device"] });
});

it("releases the simlock lease and answers notAvailable when the link names no ceiling for the granted lease", async () => {
const rig = setUp();
const releases: Record<string, unknown>[] = [];
rig.handlers["lease.request"] = async () => ({
device: { address: "udid-1", spec: { model: "iPhone 16" } },
lease: { ttlDeadline: 5_000, ttlMs: 60_000 },
});
rig.handlers["lease.release"] = async (input) => {
releases.push(input);
return {};
};
(rig.link["status"] as ReturnType<typeof vi.fn>).mockResolvedValue({
platforms: ["ios"],
state: "running",
});

const answer = await rig.run();

expect(releases).toEqual([{ leaseId }]);
expect(await answer?.text()).toContain(
"agent-device is not available on this simlock: agent-device reported no lease ceiling for this lease",
);
expect(rig.link["forward"]).not.toHaveBeenCalled();
});
});
Loading
Loading