diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 916ea9c17..5c5ec67bf 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -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 `/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` | @@ -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. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 9e5b5f354..cb62dd649 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -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 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 @@ -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: `: 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 diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index d4be5bf4e..c37e7bc6d 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -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`, diff --git a/docs/internal/COMPONENTS.md b/docs/internal/COMPONENTS.md index 0a868f7c5..11b06e453 100644 --- a/docs/internal/COMPONENTS.md +++ b/docs/internal/COMPONENTS.md @@ -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..`; 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. | diff --git a/docs/internal/adr/0026-agent-device-through-a-gateway-relays-over-the-uplink.md b/docs/internal/adr/0026-agent-device-through-a-gateway-relays-over-the-uplink.md index fff562939..428557603 100644 --- a/docs/internal/adr/0026-agent-device-through-a-gateway-relays-over-the-uplink.md +++ b/docs/internal/adr/0026-agent-device-through-a-gateway-relays-over-the-uplink.md @@ -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::`, the prefix the gateway already puts -on the requester of every lease it dispatches. Tokens minted on a gateway and +`gw..`, 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 diff --git a/src/agent-device/dispose.test.ts b/src/agent-device/dispose.test.ts new file mode 100644 index 000000000..18df538df --- /dev/null +++ b/src/agent-device/dispose.test.ts @@ -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); + }); +}); diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 272776db9..4fd685e44 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -521,14 +521,14 @@ async function runningCommand(rig: Rig, n: number, options: Omit { - 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); }); diff --git a/src/agent-device/front/allocate.test.ts b/src/agent-device/front/allocate.test.ts index 1a02cc2a9..355238d4c 100644 --- a/src/agent-device/front/allocate.test.ts +++ b/src/agent-device/front/allocate.test.ts @@ -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 }; const context = { clock, dispatch, - link: { forward: vi.fn(), status: vi.fn() }, + link: link.value, logger: new NoopLogger(), map, } as unknown as FrontContext; @@ -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. @@ -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[] = []; + 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).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(); + }); }); diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index b3543ea55..91572a155 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -5,7 +5,7 @@ import { buildHttpSession } from "../../http/dispatcher-session.js"; import { mapError } from "../../http/errors.js"; import type { TokenIdentity } from "../../http/token-store.js"; import type { Clock } from "../../ports/index.js"; -import { frontReply, failure, refusal, type FrontReply } from "../shared/replies.js"; +import { frontReply, failure, notAvailable, refusal, type FrontReply } from "../shared/replies.js"; import { validDeviceKey } from "../shared/release-scope.js"; import { leaseCallFields, leaseIdOf, replyData, type RpcRead } from "../shared/rpc.js"; import { addressField, asRecord } from "../shared/selectors.js"; @@ -19,12 +19,14 @@ import { releaseSimlock, relay, scopeOf, + unreachableReply, type FrontContext, } from "./context.js"; import { chosenTtl } from "./ttl.js"; type Grant = z.infer<(typeof OPERATIONS)["lease.request"]["output"]>; +const NO_CEILING = "agent-device reported no lease ceiling for this lease"; const QUEUE_WAIT_MS = 330_000; const CANCEL_RETRY_MS = 1_000; const LEASE_GONE = new Set(["LEASE_NOT_FOUND", "LEASE_EXPIRED", "LEASE_REVOKED"]); @@ -135,6 +137,11 @@ async function stillWaiting( return Promise.race([ready, gone]); } +function requiresOf(context: FrontContext): { readonly requires?: string[] } { + const required = context.link.leaseRequires ?? []; + return required.length === 0 ? {} : { requires: [...required] }; +} + async function requestLease( context: FrontContext, identity: TokenIdentity, @@ -188,6 +195,7 @@ async function requestLease( ...(plan.model === undefined ? {} : { model: plan.model }), ...(plan.class === undefined ? {} : { class: plan.class }), ...(plan.ttlMs === undefined ? {} : { ttlMs: plan.ttlMs }), + ...requiresOf(context), }, buildHttpSession(identity, { onRequestAdmitted: () => { @@ -235,7 +243,6 @@ export interface AllocateArguments { readonly request: Request; readonly identity: TokenIdentity; readonly call: RpcRead & { readonly kind: "request" }; - readonly leaseMaxTtlMs: number; } interface Granted { @@ -249,7 +256,7 @@ interface Granted { export async function allocate( context: FrontContext, - { request, identity, call, leaseMaxTtlMs }: AllocateArguments, + { request, identity, call }: AllocateArguments, ): Promise { const refused = refusalFor(call.params); if (refused !== undefined) return frontReply(refused, call); @@ -267,12 +274,20 @@ export async function allocate( ? undefined : frontReply(failure("simlock granted a device with no address; nothing was leased"), call); } + const holder = await context.link.status(plan.leaseId, identity); + if (holder.state === "unavailable" || holder.leaseMaxTtlMs === undefined) { + await releaseSimlock(context, identity, plan.leaseId); + return frontReply( + notAvailable(holder.state === "unavailable" ? holder.reason : NO_CEILING), + call, + ); + } const forwarded = new Request(request.url, { - body: JSON.stringify(forwardedBody(call, plan, address, leaseMaxTtlMs)), + body: JSON.stringify(forwardedBody(call, plan, address, holder.leaseMaxTtlMs)), headers: leaseCall(request, "agent_device.lease.allocate", {}, null).headers, method: "POST", }); - const reply = await exchange(context, forwarded, identity, "allocate"); + const reply = await exchange(context, forwarded, identity, "allocate", plan.leaseId); const made = { address, call, grant, identity, plan, request }; if (reply.reading.kind === "success") return keepOrRelease(context, made, reply, reply.reading); if (reply.reading.kind === "error") { @@ -280,7 +295,7 @@ export async function allocate( return relay(reply); } await settleNoReply(context, made); - return frontReply(failure("agent-device did not answer the allocate"), call); + return unreachableReply(reply, call, "agent-device did not answer the allocate"); } async function keepOrRelease( diff --git a/src/agent-device/front/context.ts b/src/agent-device/front/context.ts index 6ea70ec82..e5170d556 100644 --- a/src/agent-device/front/context.ts +++ b/src/agent-device/front/context.ts @@ -3,6 +3,7 @@ import type { TokenIdentity } from "../../http/token-store.js"; import type { Clock, Logger } from "../../ports/index.js"; import { buildHttpSession } from "../../http/dispatcher-session.js"; import { mapError } from "../../http/errors.js"; +import { failure, frontReply, notAvailable } from "../shared/replies.js"; import { readReply, type CallClass, type ReplyReading } from "../shared/rpc.js"; import type { FrontMap } from "./front-map.js"; import type { HostLink } from "./host-link.js"; @@ -26,6 +27,8 @@ export interface Exchange { readonly response: Response | undefined; readonly text: string | undefined; readonly reading: ReplyReading; + // why: the link's own reason when it could not carry the call, so the reply names it as a call passed through does. + readonly unreachable?: string; } export async function exchange( @@ -33,9 +36,10 @@ export async function exchange( request: Request, identity: TokenIdentity, call?: CallClass, + leaseId?: string, ): Promise { try { - const response = await context.link.forward(request, identity); + const response = await context.link.forward(request, identity, leaseId); const text = await response.text(); const reading = readReply(text, call); // why: the reason for a 5xx or a body that is not a JSON-RPC reply is only in what agent-device sent. @@ -47,13 +51,29 @@ export async function exchange( } return { reading, response, text }; } catch (error) { - context.logger.warn("agent-device lease call got no usable reply", { - message: error instanceof Error ? error.message : String(error), - }); - return { reading: { kind: "unusable" }, response: undefined, text: undefined }; + const message = error instanceof Error ? error.message : String(error); + context.logger.warn("agent-device lease call got no usable reply", { message }); + return { + reading: { kind: "unusable" }, + response: undefined, + text: undefined, + unreachable: message, + }; } } +// why: a lease call the link could not carry answers the notAvailable reply naming the link's reason, or `fallback` when the link gave none. +export function unreachableReply( + reply: Exchange, + call: { readonly id: unknown }, + fallback: string, +): Response { + return frontReply( + reply.unreachable === undefined ? failure(fallback) : notAvailable(reply.unreachable), + call, + ); +} + export function relay(reply: { response: Response | undefined; text: string | undefined; @@ -132,9 +152,26 @@ export async function releaseAgentDevice( context, leaseCall(request, "agent_device.lease.release", { ...scope, leaseId }, "simlock-release"), identity, + undefined, + leaseId, ); } +// why: a lease the token holds under another requester than its own id was made by something else (a gateway, for a worker's token of the same name), so this front has no claim to end it. +export async function heldForAnother( + context: FrontContext, + identity: TokenIdentity, + leaseId: string, +): Promise { + try { + const { leases } = await context.dispatch("lease.list", {}, buildHttpSession(identity)); + const found = leases.find((lease) => lease.id === leaseId); + return found !== undefined && found.requesterId !== leaseId; + } catch { + return false; + } +} + const LIST_TIMEOUT_MS = 5_000; export async function listLeases(context: FrontContext, identity: TokenIdentity) { diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index 160dcb39c..925522f18 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -7,6 +7,8 @@ import { commandName, asRecord } from "../shared/selectors.js"; import { classifyCall, commandLeaseId, + leaseCallFields, + leaseIdOf, methodName, readRpcBody, type CallClass, @@ -24,13 +26,26 @@ type RpcRequest = RpcRead & { readonly kind: "request" }; interface Routed { readonly identity: TokenIdentity; readonly kind: CallClass; - readonly leaseMaxTtlMs: number; + readonly leaseMaxTtlMs: number | undefined; readonly read: RpcRequest; readonly request: Request; } +// why: the lease id the link's status and a command's route are read with; a new lease has none yet, so its status is read without one. +function leaseOf( + kind: CallClass, + read: RpcRead & { readonly kind: "request" }, +): string | undefined { + if (kind === "heartbeat" || kind === "release") { + return leaseIdOf(leaseCallFields(read.params).leaseId); + } + return kind === "command" ? commandLeaseId(read.params) : undefined; +} + const AGENT_TOKEN_ONLY = "refused: agent-device through simlock needs an agent token"; const CLIENT_GONE = 499; +// why: the agent-device CLI counts a /health answer of 500 or more as an unreachable daemon and prints only "Remote daemon is unavailable"; a lower status lets its first RPC run and print the reason. +const HEALTH_STATUS = 200; function carry(request: Request, body: string): Request { const headers = new Headers(request.headers); @@ -67,9 +82,9 @@ async function handleRpc( if (read.kind === "malformed") { return frontReply(refusal("refused: send one JSON-RPC request"), { id: null }); } - const status = await context.link.status(); - if (status.state === "unavailable") return frontReply(notAvailable(status.reason), read); const kind = classifyCall(read.method, read.params); + const status = await context.link.status(leaseOf(kind, read), identity); + if (status.state === "unavailable") return frontReply(notAvailable(status.reason), read); if (kind === "wrapped-lease") { return frontReply(refusal("refused: send lease calls as lease RPCs"), read); } @@ -89,14 +104,12 @@ async function routeCall( { identity, kind, leaseMaxTtlMs, read, request }: Routed, ): Promise { if (kind === "allocate") { - const work = allocate(context, { call: read, identity, leaseMaxTtlMs, request }).catch( - (error: unknown) => { - context.logger.error("agent-device allocate failed", { - message: error instanceof Error ? error.message : String(error), - }); - return frontReply(failure("agent-device allocate failed"), read); - }, - ); + const work = allocate(context, { call: read, identity, request }).catch((error: unknown) => { + context.logger.error("agent-device allocate failed", { + message: error instanceof Error ? error.message : String(error), + }); + return frontReply(failure("agent-device allocate failed"), read); + }); return untilHangUp(request.signal, work); } const forwarded = carry(request, read.text); @@ -104,8 +117,8 @@ async function routeCall( return heartbeat(context, { call: read, identity, leaseMaxTtlMs, request: forwarded }); } if (kind === "release") return release(context, identity, read, forwarded); - const leaseId = kind === "command" ? commandLeaseId(read.params) : undefined; - if (leaseId === undefined) return forwardCommand(context, forwarded, identity, read); + const leaseId = leaseOf(kind, read); + if (leaseId === undefined) return forwardCommand(context, forwarded, identity, read, leaseId); return runCommand(context, request, identity, read, leaseId); } @@ -120,7 +133,7 @@ async function runCommand( request.signal.addEventListener("abort", end, { once: true }); let response: Response; try { - response = await forwardCommand(context, carry(request, read.text), identity, read); + response = await forwardCommand(context, carry(request, read.text), identity, read, leaseId); } catch (error) { end(); throw error; @@ -166,8 +179,9 @@ async function forwardCommand( request: Request, identity: TokenIdentity, read: RpcRequest, + leaseId: string | undefined, ): Promise { - const response = await passThrough(context, request, identity, read); + const response = await passThrough(context, request, identity, read, leaseId); const isDevices = methodName(read.method) === "command" && commandName(asRecord(read.params)?.["command"]) === "devices"; @@ -205,13 +219,16 @@ async function passThrough( request: Request, identity: TokenIdentity, rpc: { readonly id: unknown } | undefined, + leaseId?: string, + probe = false, ): Promise { try { - const response = await context.link.forward(request, identity); + const response = await context.link.forward(request, identity, leaseId); if (response.status >= 500) logFailedReply(context, response); return response; } catch (error) { - return frontReply(notAvailable(error instanceof Error ? error.message : String(error)), rpc); + const reply = notAvailable(error instanceof Error ? error.message : String(error)); + return frontReply(probe ? { ...reply, status: HEALTH_STATUS } : reply, rpc); } } @@ -226,11 +243,10 @@ export function createFront(context: FrontContext): HttpMount { if (isRpc) return handleRpc(context, request, identity); const status = await context.link.status(); const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length); + const probe = request.method === "GET" && path === "/health"; if (status.state === "unavailable") { - // why: the agent-device CLI counts a /health answer of 500 or more as an unreachable daemon and prints only "Remote daemon is unavailable"; a lower status lets its first RPC run and print the reason. const reply = notAvailable(status.reason); - const probe = request.method === "GET" && path === "/health"; - return frontReply(probe ? { ...reply, status: 200 } : reply, undefined); + return frontReply(probe ? { ...reply, status: HEALTH_STATUS } : reply, undefined); } if (!isKnownRoute(request.method, path)) { return frontReply( @@ -238,7 +254,7 @@ export function createFront(context: FrontContext): HttpMount { undefined, ); } - return passThrough(context, request, identity, undefined); + return passThrough(context, request, identity, undefined, undefined, probe); }, prefix: FRONT_MOUNT, }; diff --git a/src/agent-device/front/heartbeat.ts b/src/agent-device/front/heartbeat.ts index 21d26e49b..7b5ef44e6 100644 --- a/src/agent-device/front/heartbeat.ts +++ b/src/agent-device/front/heartbeat.ts @@ -10,9 +10,11 @@ import { import { REPLY_SCOPE_KEYS, exchange, + heldForAnother, releaseAgentDevice, releaseSimlock, relay, + unreachableReply, scopeOf, type Exchange, type FrontContext, @@ -23,11 +25,12 @@ import { chosenTtl } from "./ttl.js"; type Call = RpcRead & { readonly kind: "request" }; -function forwardedHeartbeat(request: Request, call: Call, ceiling: number): Request { +function forwardedHeartbeat(request: Request, call: Call, ceiling: number | undefined): Request { const headers = new Headers(request.headers); headers.delete("content-length"); + const params = ceiling === undefined ? call.params : { ...call.params, ttlMs: ceiling }; return new Request(request.url, { - body: JSON.stringify({ ...call.body, params: { ...call.params, ttlMs: ceiling } }), + body: JSON.stringify({ ...call.body, params }), headers, method: "POST", signal: request.signal, @@ -64,7 +67,7 @@ async function leaseStillThere( scopeOf(call.params, REPLY_SCOPE_KEYS), ); if (ended.response === undefined) { - return frontReply(failure("agent-device did not answer the release"), call); + return unreachableReply(ended, call, "agent-device did not answer the release"); } if (ended.reading.kind !== "success") return relay(ended); return releaseOurs(context, identity, leaseId, call, false); @@ -113,7 +116,7 @@ export async function heartbeat( readonly request: Request; readonly identity: TokenIdentity; readonly call: Call; - readonly leaseMaxTtlMs: number; + readonly leaseMaxTtlMs: number | undefined; }, ): Promise { const { request, identity, call, leaseMaxTtlMs } = arguments_; @@ -125,8 +128,16 @@ export async function heartbeat( if (leaseId !== undefined && entry?.endedBy === "simlock") { return frontReply(leaseEndedByHost(), call); } - const reply = await exchange(context, forwardedHeartbeat(request, call, leaseMaxTtlMs), identity); - if (leaseId === undefined || reply.response === undefined) return relay(reply); + const reply = await exchange( + context, + forwardedHeartbeat(request, call, leaseMaxTtlMs), + identity, + undefined, + leaseId, + ); + if (reply.response === undefined) + return unreachableReply(reply, call, "agent-device did not answer the heartbeat"); + if (leaseId === undefined) return relay(reply); const reading: ReplyReading = reply.reading; if (reading.kind === "success") { if (entry === undefined) return leaseStillThere(context, arguments_, leaseId); @@ -135,5 +146,8 @@ export async function heartbeat( } if (leaseGoneReason(reading) === undefined) return relay(reply); if (entry?.endedBy === "agent") return relay(reply); + if (entry === undefined && (await heldForAnother(context, identity, leaseId))) { + return relay(reply); + } return releaseOurs(context, identity, leaseId, call, entry !== undefined); } diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index b24a01a91..2f3f729d2 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -2,16 +2,21 @@ import type { TokenIdentity } from "../../http/token-store.js"; import type { AgentDevicePlatform } from "../host/agent-device-supervisor.js"; import type { AgentDeviceHost } from "../host/host.js"; +export type LinkStatus = + | { + readonly state: "running"; + // why: a link that serves many hosts names the ceiling only for a lease it can place; the front reads it from `status(leaseId)`. + readonly leaseMaxTtlMs?: number; + readonly platforms: readonly AgentDevicePlatform[]; + } + | { readonly state: "unavailable"; readonly reason: string }; + export interface HostLink { - status(): Promise< - | { - readonly state: "running"; - readonly leaseMaxTtlMs: number; - readonly platforms: readonly AgentDevicePlatform[]; - } - | { readonly state: "unavailable"; readonly reason: string } - >; - forward(request: Request, identity: TokenIdentity): Promise; + // why: capabilities a lease request must require so it lands on a host that can serve agent-device; none means any worker. + readonly leaseRequires?: readonly string[]; + status(leaseId?: string, identity?: TokenIdentity): Promise; + forward(request: Request, identity: TokenIdentity, leaseId?: string): Promise; + dispose?(): void; } export class InProcessHostLink implements HostLink { diff --git a/src/agent-device/front/relay-host-link.test.ts b/src/agent-device/front/relay-host-link.test.ts new file mode 100644 index 000000000..d5da83227 --- /dev/null +++ b/src/agent-device/front/relay-host-link.test.ts @@ -0,0 +1,187 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { TokenIdentity } from "../../http/token-store.js"; +import { FakeClock } from "../../ports/index.js"; +import { + RelayHostLink, + type FleetPort, + type FleetWorker, + type PlacedLease, +} from "./relay-host-link.js"; + +const agent: TokenIdentity = { requesterId: "tok_a", role: "agent" }; +const worker: FleetWorker = { id: "w1", leaseMaxTtlMs: 1_000, platforms: ["ios"] }; +const maxTtlMs = 120_000; + +function setUp() { + const clock = new FakeClock(1_000); + const index = new Map(); + let removed: ((lease: PlacedLease & { readonly leaseId: string }) => void) | undefined; + const relay = vi.fn((_worker: string, _request: Request, _tenant: string, _lease?: string) => + Promise.resolve(new Response("relayed")), + ); + const fleet: FleetPort = { + capableWorkers: () => [worker], + holder: () => worker, + instanceId: "gw1", + leaseOf: (leaseId) => index.get(leaseId), + onLeaseRemoved: (listener) => { + removed = listener; + }, + relay, + }; + const link = new RelayHostLink({ clock, fleet, leaseMaxTtlMs: maxTtlMs }); + const drop = (leaseId: string) => { + const lease = index.get(leaseId); + if (lease === undefined) throw new Error("no such lease"); + index.delete(leaseId); + removed?.({ ...lease, leaseId }); + }; + return { clock, drop, index, link, relay }; +} + +function request(path = "/rpc"): Request { + return new Request(`http://gateway.test/v1/agent-device${path}`, { + body: JSON.stringify({ id: 7, jsonrpc: "2.0", method: "agent_device.command", params: {} }), + method: "POST", + }); +} + +describe("RelayHostLink", () => { + it.each([ + { principal: "tok.a b/é:x", row: "characters agent-device refuses" }, + { principal: "t".repeat(300), row: "a 300 character ID" }, + { principal: "tok_a", row: "an underscore" }, + ])( + "sends agent-device a tenant of 1 to 128 letters, digits, dots, underscores and hyphens for a token with $row, and relays it", + async ({ principal }) => { + const { index, link, relay } = setUp(); + index.set("L", { ownerId: principal, workerId: "w1" }); + + await link.forward(request(), { requesterId: principal, role: "agent" }, "L"); + + expect(relay).toHaveBeenCalledTimes(1); + expect(relay.mock.calls[0]?.[2]).toMatch(/^[A-Za-z0-9._-]{1,128}$/); + }, + ); + + it("sends agent-device different tenants for different tokens, even when they differ only in characters it refuses or past the 128th", async () => { + const { index, link, relay } = setUp(); + const principals = ["a b", "a_b", "a.b", "a:b", "t".repeat(300), `${"t".repeat(299)}u`]; + for (const principal of principals) { + index.set("L", { ownerId: principal, workerId: "w1" }); + await link.forward(request(), { requesterId: principal, role: "agent" }, "L"); + } + + const tenants = relay.mock.calls.map((call) => call[2]); + expect(new Set(tenants).size).toBe(principals.length); + }); + + it("relays a lease the token holds to its worker under the tenant `gw..`", async () => { + const { index, link, relay } = setUp(); + index.set("L", { ownerId: "tok_a", workerId: "w1" }); + + await link.forward(request(), agent, "L"); + + expect(relay).toHaveBeenCalledWith("w1", expect.any(Request), "gw.gw1.tok_5f_a", "L"); + }); + + it("answers the flat refusal shape for a request that is not an rpc call", async () => { + const { link } = setUp(); + + const answer = await link.forward(request("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/upload/preflight"), agent); + + expect(await answer.json()).toEqual({ + code: "INVALID_ARGS", + error: "refused: this agent-device is too old to use through a gateway; update it", + ok: false, + }); + }); + + it("refuses a bare GET that is not /health, and relays nothing", async () => { + const { link, relay } = setUp(); + + const answer = await link.forward( + new Request("http://gateway.test/v1/agent-device/artifacts/a1"), + agent, + ); + + expect(await answer.json()).toEqual({ + code: "INVALID_ARGS", + error: "refused: this agent-device is too old to use through a gateway; update it", + ok: false, + }); + expect(relay).not.toHaveBeenCalled(); + }); + + it("answers a body that is not JSON under a null id", async () => { + const { link } = setUp(); + const broken = new Request("http://gateway.test/v1/agent-device/rpc", { + body: "not json", + method: "POST", + }); + + const answer = await link.forward(broken, agent); + + expect(await answer.json()).toMatchObject({ id: null }); + }); + + it("fails a health probe when no capable worker is left between the status and the forward", async () => { + const { link } = setUp(); + const none = new RelayHostLink({ + clock: new FakeClock(0), + fleet: { + capableWorkers: () => [], + holder: () => undefined, + instanceId: "gw1", + leaseOf: () => undefined, + onLeaseRemoved: () => undefined, + relay: () => Promise.reject(new Error("never")), + }, + leaseMaxTtlMs: maxTtlMs, + }); + + await expect( + none.forward(new Request("http://gateway.test/v1/agent-device/health"), agent), + ).rejects.toThrow("no worker connected to this gateway can serve agent-device"); + expect((await link.status()).state).toBe("running"); + }); + + it("reports the holder's ceiling only for a lease it can place and the token owns", async () => { + const { index, link } = setUp(); + index.set("L", { ownerId: "tok_a", workerId: "w1" }); + + expect(await link.status("L", agent)).toMatchObject({ leaseMaxTtlMs: 86_400_000 }); + expect(await link.status("L", { ...agent, requesterId: "tok_b" })).not.toHaveProperty( + "leaseMaxTtlMs", + ); + expect(await link.status()).not.toHaveProperty("leaseMaxTtlMs"); + }); + + it("keeps routing a lease the index dropped until the gateway's lease.maxTtlMs has passed, then forgets it, and its sweep stops with nothing kept", async () => { + const { clock, drop, index, link, relay } = setUp(); + index.set("L", { ownerId: "tok_a", workerId: "w1" }); + drop("L"); + expect(clock.pendingTimerCount).toBe(1); + + clock.advance(maxTtlMs); + await link.forward(request(), agent, "L"); + expect(relay).toHaveBeenCalledTimes(1); + + clock.advance(60_000); + expect(clock.pendingTimerCount).toBe(0); + const answer = await link.forward(request(), agent, "L"); + expect(answer.status).toBe(403); + expect(relay).toHaveBeenCalledTimes(1); + }); + + it("cancels its sweep when disposed", () => { + const { clock, drop, index, link } = setUp(); + index.set("L", { ownerId: "tok_a", workerId: "w1" }); + drop("L"); + + link.dispose(); + + expect(clock.pendingTimerCount).toBe(0); + }); +}); diff --git a/src/agent-device/front/relay-host-link.ts b/src/agent-device/front/relay-host-link.ts new file mode 100644 index 000000000..bcac03a08 --- /dev/null +++ b/src/agent-device/front/relay-host-link.ts @@ -0,0 +1,168 @@ +import { createHash } from "node:crypto"; + +import type { TokenIdentity } from "../../http/token-store.js"; +import type { Clock, TimerHandle } from "../../ports/index.js"; +import type { AgentDevicePlatform } from "../host/agent-device-supervisor.js"; +import { agentDeviceLeaseMaxTtlMs } from "../shared/daemon-environment.js"; +import { FRONT_PREFIX } from "../shared/paths.js"; +import { frontReplyFor, refusal } from "../shared/replies.js"; +import type { HostLink, LinkStatus } from "./host-link.js"; + +export interface FleetWorker { + readonly id: string; + readonly platforms: readonly AgentDevicePlatform[]; + readonly leaseMaxTtlMs: number; +} + +export interface PlacedLease { + readonly workerId: string; + readonly ownerId: string; +} + +// why: the edge imports nothing from the gateway, so the gateway's parts reach the link only through this port, built where the gateway is composed. +export interface FleetPort { + readonly instanceId: string; + leaseOf(leaseId: string): PlacedLease | undefined; + // why: connected, not drained, agent-device available, catalog read and `lease.maxTtlMs` known. + capableWorkers(): readonly FleetWorker[]; + // why: a drained worker keeps serving the leases it holds, so a lease's holder is judged without the drain flag. + holder(workerId: string): FleetWorker | undefined; + relay(workerId: string, request: Request, tenant: string, leaseId?: string): Promise; + onLeaseRemoved(listener: (lease: PlacedLease & { readonly leaseId: string }) => void): void; +} + +export interface RelayHostLinkOptions { + readonly fleet: FleetPort; + readonly clock: Clock; + // why: the gateway's own `lease.maxTtlMs`, the longest a lease it granted can live, bounds how long the link still routes a lease its index dropped. + readonly leaseMaxTtlMs: number; +} + +const NO_WORKER = "no worker connected to this gateway can serve agent-device"; +const HOLDER_CANNOT = "the worker holding this lease cannot serve agent-device"; +const TOO_OLD = "refused: this agent-device is too old to use through a gateway; update it"; +// why: agent-device accepts a tenant of 1 to 128 letters, digits, dots, underscores and hyphens. +const MAX_TENANT_CHARS = 128; +const HASH_CHARS = 27; +const SWEEP_MS = 60_000; +const FORBIDDEN = 403; + +// why: a character agent-device refuses (or a dot, the separator) becomes `__`, so two names never share a tenant. +function tenantPart(value: string): string { + return value.replace(/[^A-Za-z0-9-]/gu, (char) => `_${char.codePointAt(0)?.toString(16)}_`); +} + +// why: `gw..`, cut to 128 characters with a hash of the whole name when longer, so every input gives a tenant agent-device accepts and distinct inputs stay distinct. +function relayTenant(instanceId: string, principal: string): string { + const tenant = `gw.${tenantPart(instanceId)}.${tenantPart(principal)}`; + if (tenant.length <= MAX_TENANT_CHARS) return tenant; + const hash = createHash("sha256") + .update(JSON.stringify([instanceId, principal])) + .digest("hex"); + return `${tenant.slice(0, MAX_TENANT_CHARS - HASH_CHARS - 1)}.${hash.slice(0, HASH_CHARS)}`; +} + +interface Kept extends PlacedLease { + readonly since: number; +} + +function notYours(leaseId: string): string { + return `refused: lease ${leaseId} is not one of yours on this gateway`; +} + +function refuseRequest(request: Request, message: string, status?: number): Promise { + return frontReplyFor(request, refusal(message, status)); +} + +export class RelayHostLink implements HostLink { + readonly leaseRequires: readonly string[] = ["agent-device"]; + readonly #kept = new Map(); + #sweep: TimerHandle | undefined; + #disposed = false; + + constructor(private readonly options: RelayHostLinkOptions) { + options.fleet.onLeaseRemoved((lease) => this.#keep(lease)); + } + + status(leaseId?: string, identity?: TokenIdentity): Promise { + if (leaseId !== undefined && identity !== undefined) { + const placed = this.#place(leaseId); + if (placed?.ownerId === identity.requesterId) { + const holder = this.options.fleet.holder(placed.workerId); + return Promise.resolve( + holder === undefined + ? { reason: HOLDER_CANNOT, state: "unavailable" } + : { + leaseMaxTtlMs: agentDeviceLeaseMaxTtlMs(holder.leaseMaxTtlMs), + platforms: holder.platforms, + state: "running", + }, + ); + } + } + return Promise.resolve(this.#anyStatus()); + } + + async forward(request: Request, identity: TokenIdentity, leaseId?: string): Promise { + const tenant = relayTenant(this.options.fleet.instanceId, identity.requesterId); + if (leaseId === undefined) return this.#forwardBare(request, tenant); + const placed = this.#place(leaseId); + if (placed === undefined || placed.ownerId !== identity.requesterId) { + return refuseRequest(request, notYours(leaseId), FORBIDDEN); + } + return this.options.fleet.relay(placed.workerId, request, tenant, leaseId); + } + + dispose(): void { + this.#disposed = true; + if (this.#sweep !== undefined) this.options.clock.cancel(this.#sweep); + this.#sweep = undefined; + this.#kept.clear(); + } + + #anyStatus(): LinkStatus { + const capable = this.options.fleet.capableWorkers(); + if (capable.length === 0) return { reason: NO_WORKER, state: "unavailable" }; + const platforms = new Set(capable.flatMap((worker) => worker.platforms)); + return { platforms: [...platforms], state: "running" }; + } + + async #forwardBare(request: Request, tenant: string): Promise { + const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length); + if (request.method !== "GET" || path !== "/health") return refuseRequest(request, TOO_OLD); + const worker = this.options.fleet.capableWorkers()[0]; + if (worker === undefined) throw new Error(NO_WORKER); + return this.options.fleet.relay(worker.id, request, tenant); + } + + #place(leaseId: string): PlacedLease | undefined { + this.#expire(); + return this.options.fleet.leaseOf(leaseId) ?? this.#kept.get(leaseId); + } + + #keep(lease: PlacedLease & { readonly leaseId: string }): void { + if (this.#disposed) return; + this.#kept.set(lease.leaseId, { + ownerId: lease.ownerId, + since: this.options.clock.now(), + workerId: lease.workerId, + }); + this.#armSweep(); + } + + #expire(): void { + const now = this.options.clock.now(); + for (const [leaseId, kept] of this.#kept) { + if (now - kept.since > this.options.leaseMaxTtlMs) this.#kept.delete(leaseId); + } + } + + #armSweep(): void { + if (this.#sweep !== undefined) return; + this.#sweep = this.options.clock.setTimer(SWEEP_MS, () => { + this.#sweep = undefined; + this.#expire(); + if (this.#kept.size > 0 && !this.#disposed) this.#armSweep(); + }); + } +} diff --git a/src/agent-device/front/release.ts b/src/agent-device/front/release.ts index ff0ccca93..964b88d6c 100644 --- a/src/agent-device/front/release.ts +++ b/src/agent-device/front/release.ts @@ -1,7 +1,6 @@ import type { TokenIdentity } from "../../http/token-store.js"; -import { failure, frontReply } from "../shared/replies.js"; import { leaseCallFields, leaseIdOf, type RpcRead } from "../shared/rpc.js"; -import { exchange, relay, releaseSimlock, type FrontContext } from "./context.js"; +import { exchange, relay, releaseSimlock, unreachableReply, type FrontContext } from "./context.js"; export async function release( context: FrontContext, @@ -9,11 +8,11 @@ export async function release( call: RpcRead & { readonly kind: "request" }, forwarded: Request, ): Promise { - const reply = await exchange(context, forwarded, identity); + const leaseId = leaseIdOf(leaseCallFields(call.params).leaseId); + const reply = await exchange(context, forwarded, identity, undefined, leaseId); if (reply.response === undefined) { - return frontReply(failure("agent-device did not answer the release"), call); + return unreachableReply(reply, call, "agent-device did not answer the release"); } - const leaseId = leaseIdOf(leaseCallFields(call.params).leaseId); if (leaseId === undefined || reply.reading.kind !== "success") return relay(reply); const entry = context.map.get(leaseId); if (entry === undefined || entry.identity.requesterId !== identity.requesterId) { diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts new file mode 100644 index 000000000..a43a333a4 --- /dev/null +++ b/src/agent-device/gateway-front.test.ts @@ -0,0 +1,1267 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { FakeDriver } from "../core/testing.js"; +import { startDaemon, type StartDaemonOptions } from "../daemon/main.js"; +import { DispatchError } from "../daemon/dispatch.js"; +import type { DaemonServer } from "../daemon/server.js"; +import type { GatewayRelay } from "../gateway/index.js"; +import { + CryptoTokenSecrets, + FakeClock, + JsonLinesLogger, + MemoryFilesystem, + MemoryLogSink, + type Filesystem, +} from "../ports/index.js"; +import { FakeAgentDevice } from "./testing.js"; + +const runningDaemons: DaemonServer[] = []; +const temporaryDirectories: string[] = []; + +afterEach(async () => { + await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test"))); + await Promise.all( + temporaryDirectories.splice(0).map((path) => rm(path, { force: true, recursive: true })), + ); +}); + +const secrets = { + direct: "slk_test_agent_direct_on_worker", + one: "slk_test_agent_one", + operator: "slk_test_operator", + two: "slk_test_agent_two", +} as const; +const principals = { one: "tok_one", two: "tok_two" } as const; + +const notAvailable = "agent-device is not available on this simlock: "; +const noWorker = "no worker connected to this gateway can serve agent-device"; +const holderCannot = "the worker holding this lease cannot serve agent-device"; +const missingMessage = + "No worker connected to this gateway can serve agent-device for this request"; +const tooOld = "refused: this agent-device is too old to use through a gateway; update it"; +// why: shorter than the gateway's 10 s call timeout, so the read can finish once the fake clock moves past it. +const slowCatalogMs = 8_000; +const defaultTtlMs = 600_000; +const gatewayMaxTtlMs = 1_800_000; +const workerMaxTtlMs = 50_000_000; +const workerCeilingMs = 2 * workerMaxTtlMs; +const scope = { clientId: "client-1", leaseProvider: "proxy", runId: "run-1" } as const; +const endedMessage = "lease ended by simlock; run disconnect, then open"; + +const adminSession = { + manageEventSubscription: () => undefined, + principal: "admin", + role: "admin", +} as const; + +function sessionFor(principal: string) { + return { manageEventSubscription: () => undefined, principal, role: "agent" } as const; +} + +interface Envelope { + readonly id?: unknown; + readonly jsonrpc?: string; + readonly result?: Record; + readonly error?: { + readonly code: number; + readonly message: string; + readonly data?: { + readonly code: string; + readonly message: string; + readonly details?: { readonly reason: string }; + }; + }; +} + +interface WorkerSpec { + readonly label: string; + readonly platform?: "ios" | "android"; + readonly model?: string; + readonly capability?: "available" | "off" | "unavailable"; + readonly maxRunning?: number; + // why: a worker that is reachable by an agent on its own HTTP port, the way a worker without a gateway is. + readonly direct?: boolean; + // why: a catalog read that waits for the fake clock, so a worker's catalog stays unread. + readonly slowCatalog?: boolean; +} + +interface Member { + readonly spec: WorkerSpec; + readonly label: string; + readonly daemon: Promise; + readonly fake: FakeAgentDevice; + readonly driver: FakeDriver; + readonly directory: string; + readonly filesystem: Filesystem; + readonly secret: string; + readonly origin: string; +} + +interface Rig { + readonly clock: FakeClock; + readonly gateway: DaemonServer; + readonly directory: string; + readonly logs: MemoryLogSink; + readonly origin: string; + readonly relay: GatewayRelay; + readonly members: Member[]; + readonly addWorker: (spec: WorkerSpec, existing?: Member) => Promise; +} + +interface SetUpOptions { + readonly agentDevice?: "enabled" | "unset"; + readonly command?: string; + readonly leaseTtlCapMs?: number; + readonly maxTtlMs?: number; + readonly defaultTtlMs?: number; + readonly workers?: readonly WorkerSpec[]; +} + +async function freeLoopbackPort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (typeof address !== "object" || address === null) throw new Error("no port bound"); + return address.port; +} + +async function sleep(ms: number): Promise { + await new Promise((resolve) => setTimeout(resolve, ms)); +} + +function driverFor(spec: WorkerSpec, clock: FakeClock): FakeDriver { + if (spec.platform === "android") { + const model = spec.model ?? "Pixel 8"; + return new FakeDriver({ + availableOsVersions: ["35"], + clock, + defaultModels: { phone: [model] }, + ...(spec.slowCatalog === true ? { latencyMs: { listCatalog: slowCatalogMs } } : {}), + knownModels: [model], + modelClasses: { [model]: "phone" }, + platform: "android", + }); + } + const model = spec.model ?? "iPhone 16"; + return new FakeDriver({ + availableOsVersions: ["26.5"], + clock, + defaultModels: { phone: [model] }, + ...(spec.slowCatalog === true ? { latencyMs: { listCatalog: slowCatalogMs } } : {}), + knownModels: [model], + modelClasses: { [model]: "phone" }, + platform: "ios", + }); +} + +async function agentTokensFile(filesystem: Filesystem, directory: string, records: string[][]) { + await filesystem.mkdirp(directory); + const hasher = new CryptoTokenSecrets(); + await filesystem.writeFileAtomic( + join(directory, "tokens.json"), + JSON.stringify( + records.map(([id, secret, role]) => ({ + createdAt: 0, + hash: hasher.hash(secret as string), + id, + role, + })), + ), + ); +} + +// fallow-ignore-next-line complexity -- one rig that starts a gateway and any number of workers over a real uplink. +async function setUp(options: SetUpOptions = {}): Promise { + const directory = await mkdtemp(join(tmpdir(), "sl-gw-")); + temporaryDirectories.push(directory); + const clock = new FakeClock(1_000); + const filesystem = new MemoryFilesystem(); + await agentTokensFile(filesystem, directory, [ + [principals.one, secrets.one, "agent"], + [principals.two, secrets.two, "agent"], + ["tok_operator", secrets.operator, "operator"], + ]); + const port = await freeLoopbackPort(); + const logs = new MemoryLogSink(); + let relay: GatewayRelay | undefined; + const agentDevice = + options.agentDevice === "unset" + ? {} + : { + enabled: true, + ...(options.command === undefined ? {} : { command: options.command }), + ...(options.leaseTtlCapMs === undefined ? {} : { leaseTtlCapMs: options.leaseTtlCapMs }), + }; + const gateway = await startDaemon({ + clock, + configOverrides: { + agentDevice, + http: { enabled: true, host: "127.0.0.1", port }, + lease: { + defaultTtlMs: options.defaultTtlMs ?? defaultTtlMs, + maxTtlMs: options.maxTtlMs ?? gatewayMaxTtlMs, + }, + mode: "gateway", + }, + dataDirectory: directory, + filesystem, + gatewayRelay: (created) => { + relay = created; + }, + logger: new JsonLinesLogger({ clock, level: "debug", sink: logs }), + statePath: join(directory, "state.json"), + version: "1.2.3", + } as StartDaemonOptions); + runningDaemons.push(gateway); + const members: Member[] = []; + // fallow-ignore-next-line complexity -- one worker daemon with its own token, directory, fake agent-device and optional direct port. + const addWorker = async (spec: WorkerSpec, existing?: Member): Promise => { + const secret = + existing?.secret ?? + (await gateway.dispatch("token.create", { label: spec.label, role: "worker" }, adminSession)) + .secret; + const workerDirectory = existing?.directory ?? (await mkdtemp(join(tmpdir(), "sl-w-"))); + if (existing === undefined) temporaryDirectories.push(workerDirectory); + const workerFilesystem = existing?.filesystem ?? new MemoryFilesystem(); + const fake = existing?.fake ?? new FakeAgentDevice(); + if (spec.capability === "unavailable") fake.setUnavailable("down"); + const driver = driverFor(spec, clock); + let directPort: number | undefined; + if (spec.direct === true) { + directPort = await freeLoopbackPort(); + await agentTokensFile(workerFilesystem, workerDirectory, [ + [principals.one, secrets.direct, "agent"], + ]); + } + const started = startDaemon({ + agentDeviceUpstream: fake, + clock, + configOverrides: { + agentDevice: { enabled: spec.capability !== "off" }, + capacity: { config: { maxRunning: spec.maxRunning ?? 4 }, strategy: "fixed" }, + gateway: { label: spec.label, token: secret, url: `ws://127.0.0.1:${String(port)}` }, + ...(directPort === undefined + ? {} + : { http: { enabled: true, host: "127.0.0.1", port: directPort } }), + lease: { defaultTtlMs, maxTtlMs: workerMaxTtlMs }, + }, + dataDirectory: workerDirectory, + drivers: [driver], + filesystem: workerFilesystem, + logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), + statePath: join(workerDirectory, "state.json"), + version: "1.2.3", + } as StartDaemonOptions).then((daemon) => { + runningDaemons.push(daemon); + return daemon; + }); + const member: Member = { + daemon: started, + directory: workerDirectory, + driver, + fake, + filesystem: workerFilesystem, + label: spec.label, + origin: directPort === undefined ? "" : `http://127.0.0.1:${String(directPort)}`, + secret, + spec, + }; + members.push(member); + return member; + }; + const rig: Rig = { + addWorker, + clock, + directory, + gateway, + logs, + members, + origin: `http://127.0.0.1:${String(port)}`, + get relay() { + if (relay === undefined) throw new Error("the gateway never handed over its relay"); + return relay; + }, + }; + for (const spec of options.workers ?? [{ label: "w1" }]) { + const member = await addWorker(spec); + await member.daemon; + } + for (const member of members) await untilRead(rig, member); + return rig; +} + +async function viewOf(rig: Rig, label: string) { + const { workers } = await rig.gateway.dispatch("worker.list", {}, adminSession); + return workers.find((worker) => worker.label === label); +} + +// why: a worker is usable for a gateway request only once its view carries capacity, capabilities and a catalog that has been read. +async function untilRead(rig: Rig, member: Member): Promise { + await vi.waitFor( + async () => { + const view = await viewOf(rig, member.label); + expect(view?.connection).toBe("connected"); + expect(view?.capacity).toBeDefined(); + expect(view?.capabilities).toBeDefined(); + expect(view?.catalogReadAt).toBeDefined(); + }, + { timeout: 10_000 }, + ); +} + +async function turn(rig: Rig, member: Member, state: "available" | "unavailable"): Promise { + member.fake.setUnavailable(state === "available" ? undefined : "down"); + const worker = await member.daemon; + await vi.waitFor( + async () => { + // why: a refused request is a lease event on the worker, which makes the gateway read it again. + await worker + .dispatch( + "lease.request", + { model: "Nope", noWait: true, platform: member.spec.platform ?? "ios" }, + sessionFor("poke"), + ) + .catch(() => undefined); + expect((await viewOf(rig, member.label))?.capabilities?.[0]?.state).toBe(state); + }, + { timeout: 10_000 }, + ); +} + +async function advance(rig: Rig, ms: number, step = 5_000): Promise { + for (let elapsed = 0; elapsed < ms; elapsed += step) { + rig.clock.advance(Math.min(step, ms - elapsed)); + await sleep(15); + } +} + +interface SendOptions { + readonly body?: string; + readonly headers?: Record; + readonly method?: string; + readonly signal?: AbortSignal; + readonly token?: string | null; +} + +function send( + target: { readonly origin: string }, + path: string, + options: SendOptions = {}, +): Promise { + const token = options.token === undefined ? secrets.one : options.token; + return fetch(`${target.origin}/v1/agent-device${path}`, { + ...(options.body === undefined ? {} : { body: options.body }), + headers: { + connection: "close", + ...(token === null ? {} : { authorization: `Bearer ${token}` }), + ...(options.body === undefined ? {} : { "content-type": "application/json" }), + ...options.headers, + }, + method: options.method ?? (options.body === undefined ? "GET" : "POST"), + ...(options.signal === undefined ? {} : { signal: options.signal }), + }); +} + +function rpcBody(method: string, params: Record, id: unknown = 1): string { + return JSON.stringify({ id, jsonrpc: "2.0", method, params }); +} + +function rpc( + target: { readonly origin: string }, + method: string, + params: Record, + options: Omit = {}, +): Promise { + return send(target, "/rpc", { ...options, body: rpcBody(method, params) }); +} + +async function envelopeOf(response: Response): Promise { + const text = await response.text(); + expect( + text.trimStart().startsWith("{"), + `expected a JSON object body, got ${String(response.status)} ${text.slice(0, 80)}`, + ).toBe(true); + return JSON.parse(text) as Envelope; +} + +const hex = (n: number): string => n.toString(16).padStart(32, "0"); + +function allocateParams(n: number, extra: Record = {}): Record { + return { ...scope, leaseId: hex(n), platform: "ios", ttlMs: 120_000, ...extra }; +} + +function allocate( + target: { readonly origin: string }, + n: number, + extra: Record = {}, + options: Omit = {}, +): Promise { + return rpc(target, "agent_device.lease.allocate", allocateParams(n, extra), options); +} + +async function granted( + target: { readonly origin: string }, + n: number, + extra: Record = {}, + options: Omit = {}, +): Promise { + const answer = await envelopeOf(await allocate(target, n, extra, options)); + expect(answer.result).toMatchObject({ ok: true }); +} + +function release(rig: Rig, n: number, options: Omit = {}): Promise { + return rpc(rig, "agent_device.lease.release", { ...scope, leaseId: hex(n) }, options); +} + +function heartbeat( + target: { readonly origin: string }, + n: number, + extra: Record = {}, + options: Omit = {}, +): Promise { + return rpc( + target, + "agent_device.lease.heartbeat", + { ...scope, leaseId: hex(n), ...extra }, + options, + ); +} + +function command( + target: { readonly origin: string }, + name: string, + n: number | undefined, + options: Omit = {}, + extra: Record = {}, +): Promise { + const { meta, ...rest } = extra; + return rpc( + target, + "agent_device.command", + { + command: name, + ...(n === undefined && meta === undefined + ? {} + : { meta: { ...(n === undefined ? {} : { leaseId: hex(n) }), ...(meta as object) } }), + ...rest, + }, + options, + ); +} + +interface LeaseView { + readonly id: string; + readonly requesterId: string; + readonly ownerId: string; + readonly ttlMs: number; + readonly ttlDeadline: number; + readonly worker?: { readonly id: string; readonly label?: string }; +} + +async function workerLeases(member: Member): Promise { + return (await ( + await member.daemon + ).dispatch("list.get", { kind: "leases" }, adminSession)) as unknown as readonly LeaseView[]; +} + +async function fleetLeases(rig: Rig, principal: string = principals.one) { + const { leases } = await rig.gateway.dispatch("lease.list", {}, sessionFor(principal)); + return leases as unknown as readonly LeaseView[]; +} + +async function waiting(rig: Rig): Promise { + const requests = (await rig.gateway.dispatch( + "list.get", + { kind: "requests" }, + adminSession, + )) as unknown as readonly { readonly requesterId: string }[]; + return requests.map((request) => request.requesterId); +} + +async function workerLeaseFor(member: Member, n: number): Promise { + const found = (await workerLeases(member)).find((lease) => + lease.requesterId.endsWith(`:${hex(n)}`), + ); + expect(found, `the worker holds no lease for ${hex(n)}`).toBeDefined(); + return found as LeaseView; +} + +async function deadlineOf(member: Member, n: number): Promise { + return (await workerLeases(member)).find((lease) => lease.requesterId.endsWith(`:${hex(n)}`)) + ?.ttlDeadline; +} + +// why: the worker's lease requester is `gw::`, which is where the gateway's instance id is read from; the tenant spells it with dots and writes each `_` of the principal as `_5f_`. +async function tenantOf(member: Member, n: number, principal: string = principals.one) { + const lease = await workerLeaseFor(member, n); + const prefix = lease.requesterId.slice(0, -(hex(n).length + 1)); + expect(prefix).toMatch(/^gw:[^:]+$/); + return `gw.${prefix.slice("gw:".length)}.${principal.replaceAll("_", "_5f_")}`; +} + +async function grantedDevice(member: Member) { + const devices = (await ( + await member.daemon + ).dispatch("list.get", { kind: "devices" }, adminSession)) as unknown as readonly { + readonly address?: string; + readonly state: string; + }[]; + const device = devices.find((entry) => entry.address !== undefined); + expect(device?.address).toBeDefined(); + return device as { readonly address: string }; +} + +async function deviceStates(member: Member): Promise { + return ( + (await ( + await member.daemon + ).dispatch("list.get", { kind: "devices" }, adminSession)) as unknown as readonly { + readonly state: string; + }[] + ).map((device) => device.state); +} + +function track(promise: Promise): { + readonly done: () => boolean; + readonly promise: Promise; +} { + let settled = false; + const tracked = promise.finally(() => { + settled = true; + }); + tracked.catch(() => undefined); + return { done: () => settled, promise: tracked }; +} + +function expectEndedBySimlock(answer: Envelope): void { + expect(answer.result).toBeUndefined(); + expect(answer.error).toMatchObject({ + data: { + code: "UNAUTHORIZED", + details: { reason: "LEASE_ENDED_BY_HOST" }, + message: endedMessage, + }, + }); +} + +type RawDispatch = (operation: string, input: unknown, session: unknown) => Promise; + +interface DispatchTap { + readonly operations: string[]; + readonly inputs: { readonly operation: string; readonly input: Record }[]; + afterNext(operation: string, run: () => Promise): void; +} + +// why: the front reaches simlock through `daemon.dispatch` looked up at call time, so a wrapper on the daemon object sits between the front and leasing. +function tapDispatch(daemon: DaemonServer): DispatchTap { + const target = daemon as unknown as { dispatch: RawDispatch }; + const original = target.dispatch.bind(target); + const operations: string[] = []; + const inputs: { operation: string; input: Record }[] = []; + const afters = new Map Promise>(); + target.dispatch = async (operation, input, session) => { + operations.push(operation); + inputs.push({ input: (input ?? {}) as Record, operation }); + const result = await original(operation, input, session); + const after = afters.get(operation); + afters.delete(operation); + await after?.(); + return result; + }; + return { afterNext: (operation, run) => afters.set(operation, run), inputs, operations }; +} + +type RelayFn = (workerId: string, call: unknown) => Promise; + +// why: the relay is the gateway's own object, so a test decides what the next relays do before they reach the worker. +function interceptRelay( + rig: Rig, + before: (call: { readonly target: string; readonly request: Request }) => Promise | void, +): void { + const target = rig.relay as unknown as { relay: RelayFn }; + const original = target.relay.bind(target); + target.relay = async (workerId, call) => { + await before(call as { readonly target: string; readonly request: Request }); + return original(workerId, call); + }; +} + +function relayFailsWith(rig: Rig, code: string, message: string): void { + const target = rig.relay as unknown as { relay: RelayFn }; + target.relay = () => Promise.reject(new DispatchError(code, message)); +} + +const wipeOperations = new Set(["reclaim", "shutdown", "destroy"]); + +function wipes(member: Member): number { + return member.driver.calls.filter((call) => wipeOperations.has(call.operation)).length; +} + +function heartbeatsReceived(member: Member): number { + return member.fake.rpcRequests("agent_device.lease.heartbeat").length; +} + +function allocatesReceived(member: Member, n?: number) { + return member.fake + .rpcRequests("agent_device.lease.allocate") + .filter((request) => n === undefined || request.params?.["leaseId"] === hex(n)); +} + +async function runningCommand( + rig: Rig, + member: Member, + n: number, + options: Omit = {}, +) { + member.fake.holdCommand(); + const before = member.fake.rpcRequests("agent_device.command").length; + const running = track(command(rig, "snapshot", n, options)); + await expect.poll(() => member.fake.rpcRequests("agent_device.command").length).toBe(before + 1); + return running; +} + +function first(rig: Rig): Member { + const member = rig.members[0]; + if (member === undefined) throw new Error("the rig has no worker"); + return member; +} + +describe("the agent-device front, through a gateway", { timeout: 60_000 }, () => { + it("with agentDevice.enabled unset on the gateway, /v1/agent-device/health answers 404, as today", async () => { + const rig = await setUp({ agentDevice: "unset" }); + + expect((await send(rig, "/health")).status).toBe(404); + }); + + it("with agentDevice.command set on a gateway, the gateway logs that it ignores it and starts; with agentDevice.leaseTtlCapMs above lease.maxTtlMs on a gateway, the gateway fails to start, as a worker does", async () => { + const rig = await setUp({ command: "agent-device-elsewhere", workers: [] }); + + expect((await send(rig, "/health")).status).toBe(200); + expect( + rig.logs.records.some( + (record) => + record.level === "warn" && + record.message.includes("agentDevice.command") && + record.message.includes("Ignoring"), + ), + ).toBe(true); + + await expect(setUp({ leaseTtlCapMs: gatewayMaxTtlMs + 1, workers: [] })).rejects.toThrow( + /agentDevice\.leaseTtlCapMs/, + ); + }); + + it("with agentDevice.enabled unset on the gateway, /rpc, upload/preflight, artifacts/ and a diagnostics URL each answer 404", async () => { + const rig = await setUp({ agentDevice: "unset" }); + + const answers = await Promise.all([ + send(rig, "/rpc", { body: rpcBody("agent_device.command", { command: "snapshot" }) }), + send(rig, "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/upload/preflight", { body: "{}" }), + send(rig, "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/artifacts/a.png"), + send(rig, "/sessions/tok_one:s1/requests/r1/diagnostics"), + ]); + + expect(answers.map((answer) => answer.status)).toEqual([404, 404, 404, 404]); + }); + + it("/health answers the proxy's health when a worker is capable, and the notAvailable reply naming `no worker connected to this gateway can serve agent-device`, with status 200, when none is; when the relay to the capable worker fails, it answers the notAvailable reply with status 200", async () => { + const capable = await setUp(); + const health = await send(capable, "/health"); + expect(health.status).toBe(200); + expect(await health.json()).toMatchObject({ + service: "agent-device-proxy", + upstream: { service: "agent-device-daemon" }, + }); + + const none = await setUp({ workers: [{ capability: "off", label: "off" }] }); + const empty = await send(none, "/health"); + expect(empty.status).toBe(200); + expect(await empty.text()).toContain(`${notAvailable}${noWorker}`); + + relayFailsWith(capable, "WORKER_UNREACHABLE", "Worker is not reachable"); + const failed = await send(capable, "/health"); + expect(failed.status).toBe(200); + expect(await failed.text()).toContain(`${notAvailable}Worker is not reachable`); + }); + + it("with the only capable worker drained, allocate answers the notAvailable reply, while a command on a lease it already holds still works", async () => { + const rig = await setUp(); + const member = first(rig); + await granted(rig, 1); + const view = await viewOf(rig, member.label); + await rig.gateway.dispatch("worker.drain", { workerId: view?.id ?? "" }, adminSession); + await vi.waitFor(async () => expect((await viewOf(rig, member.label))?.drained).toBe(true)); + + const refused = await allocate(rig, 2); + + expect(refused.status).toBe(503); + expect((await envelopeOf(refused)).error?.message).toBe(`${notAvailable}${noWorker}`); + const before = member.fake.rpcRequests("agent_device.command").length; + const held = await envelopeOf(await command(rig, "snapshot", 1)); + expect(held.result).toMatchObject({ command: "snapshot", ok: true }); + expect(member.fake.rpcRequests("agent_device.command").length).toBe(before + 1); + }); + + it("a worker that disconnected does not count as capable", async () => { + const rig = await setUp(); + const original = first(rig); + expect((await send(rig, "/health")).status).toBe(200); + const stopped = await original.daemon; + await stopped.stop("test"); + runningDaemons.splice(runningDaemons.indexOf(stopped), 1); + await vi.waitFor(async () => + expect((await viewOf(rig, original.label))?.connection).toBe("disconnected"), + ); + + const answer = await send(rig, "/health"); + + expect(answer.status).toBe(200); + expect(await answer.text()).toContain(`${notAvailable}${noWorker}`); + }); + + it("a worker whose view says `available` but whose catalog was not read yet does not count as capable", async () => { + const rig = await setUp(); + const original = first(rig); + const stopped = await original.daemon; + await stopped.stop("test"); + runningDaemons.splice(runningDaemons.indexOf(stopped), 1); + await vi.waitFor(async () => + expect((await viewOf(rig, original.label))?.connection).toBe("disconnected"), + ); + + const restarted = await rig.addWorker({ ...original.spec, slowCatalog: true }, original); + void restarted.daemon; + await vi.waitFor( + async () => { + const view = await viewOf(rig, original.label); + expect(view?.connection).toBe("connected"); + expect(view?.capabilities?.[0]?.state).toBe("available"); + expect(view?.catalogReadAt).toBeUndefined(); + }, + { timeout: 10_000 }, + ); + + const unread = await send(rig, "/health"); + expect(await unread.text()).toContain(`${notAvailable}${noWorker}`); + + await advance(rig, 9_000, 1_000); + await vi.waitFor(async () => expect((await send(rig, "/health")).status).toBe(200), { + timeout: 10_000, + }); + await expect + .poll( + async () => ((await (await send(rig, "/health")).json()) as { service?: string }).service, + ) + .toBe("agent-device-proxy"); + }); + + it("allocate through the gateway makes a simlock lease on the capable worker, owned by the token's principal, whose id and gateway requester are the CLI's lease id, and its `lease.request` carries `requires: [\"agent-device\"]`", async () => { + const rig = await setUp(); + const tap = tapDispatch(rig.gateway); + + await granted(rig, 1); + + await expect.poll(async () => (await fleetLeases(rig)).length).toBe(1); + expect(await fleetLeases(rig)).toMatchObject([ + { + id: hex(1), + ownerId: principals.one, + requesterId: hex(1), + worker: { label: first(rig).label }, + }, + ]); + expect(await workerLeases(first(rig))).toHaveLength(1); + const request = tap.inputs.find((entry) => entry.operation === "lease.request"); + expect(request?.input).toMatchObject({ requesterId: hex(1), requires: ["agent-device"] }); + }); + + it("allocate on a worker, directly, sends no `requires`, as today", async () => { + const rig = await setUp({ workers: [{ direct: true, label: "w1" }] }); + const member = first(rig); + const tap = tapDispatch(await member.daemon); + + await granted(member, 1, {}, { token: secrets.direct }); + + const request = tap.inputs.find((entry) => entry.operation === "lease.request"); + expect(request).toBeDefined(); + expect(request?.input).not.toHaveProperty("requires"); + }); + + it("with two workers, one capable, every allocate over 5 tries lands on the capable one", async () => { + const rig = await setUp({ + workers: [ + { capability: "off", label: "plain" }, + { capability: "available", label: "capable" }, + ], + }); + + const labels: (string | undefined)[] = []; + for (let n = 1; n <= 5; n += 1) { + await granted(rig, n); + await expect.poll(async () => (await fleetLeases(rig)).length).toBe(1); + labels.push((await fleetLeases(rig))[0]?.worker?.label); + expect((await envelopeOf(await release(rig, n))).result).toMatchObject({ ok: true }); + await expect.poll(async () => (await fleetLeases(rig)).length).toBe(0); + } + + expect(labels).toEqual(Array.from({ length: 5 }, () => "capable")); + }); + + it("the allocate the worker's agent-device daemon receives names the granted device, carries `ttlMs` equal to that worker's ceiling, and has tenant `gw..`", async () => { + const rig = await setUp(); + const member = first(rig); + + await granted(rig, 1); + + const received = allocatesReceived(member, 1); + expect(received).toHaveLength(1); + const device = await grantedDevice(member); + expect(received[0]?.params).toMatchObject({ ttlMs: workerCeilingMs, udid: device.address }); + expect(received[0]?.tenant).toBe(await tenantOf(member, 1)); + }); + + it("allocate with no capable worker answers the notAvailable reply, and nothing is leased", async () => { + const rig = await setUp({ workers: [{ capability: "off", label: "off" }] }); + const member = first(rig); + + const answer = await allocate(rig, 1); + + expect(answer.status).toBe(503); + expect((await envelopeOf(answer)).error?.message).toBe(`${notAvailable}${noWorker}`); + expect(await fleetLeases(rig)).toEqual([]); + expect(await workerLeases(member)).toEqual([]); + expect(member.fake.requests).toEqual([]); + }); + + it("allocate `--platform ios` when the capable workers have Android only is refused `refused: ios is not available on this simlock`", async () => { + const rig = await setUp({ workers: [{ label: "droid", platform: "android" }] }); + await granted(rig, 1, { platform: "android" }); + await release(rig, 1); + + const answer = await envelopeOf(await allocate(rig, 2)); + + expect(answer.error?.message).toBe("refused: ios is not available on this simlock"); + await expect.poll(async () => (await fleetLeases(rig)).length).toBe(0); + }); + + it("allocate when only an incapable worker knows the model answers `refused by simlock: No worker connected to this gateway can serve agent-device for this request`, and nothing is leased", async () => { + const rig = await setUp({ + workers: [ + { label: "capable", model: "iPhone 16" }, + { capability: "off", label: "plain", model: "iPhone 17 Pro" }, + ], + }); + await granted(rig, 1, { device: "iPhone 16" }); + await release(rig, 1); + await expect.poll(async () => (await fleetLeases(rig)).length).toBe(0); + + const answer = await envelopeOf(await allocate(rig, 2, { device: "iPhone 17 Pro" })); + + expect(answer.error?.message).toBe(`refused by simlock: ${missingMessage}`); + expect(await fleetLeases(rig)).toEqual([]); + for (const member of rig.members) expect(await workerLeases(member)).toEqual([]); + }); + + it("allocate whose lease's worker stops being capable between the grant and the forward releases the simlock lease and answers the notAvailable reply naming `the worker holding this lease cannot serve agent-device`", async () => { + const rig = await setUp(); + const member = first(rig); + const tap = tapDispatch(rig.gateway); + tap.afterNext("lease.request", () => turn(rig, member, "unavailable")); + + const answer = await envelopeOf(await allocate(rig, 1)); + + expect(answer.error?.message).toBe(`${notAvailable}${holderCannot}`); + await expect.poll(async () => (await workerLeases(member)).length).toBe(0); + expect(await fleetLeases(rig)).toEqual([]); + expect(allocatesReceived(member)).toEqual([]); + }); + + it("allocate relayed to a worker whose own agent-device went down while the gateway's view still said `available` answers the notAvailable reply with the worker's reason, and the simlock lease is released", async () => { + const rig = await setUp(); + const member = first(rig); + interceptRelay(rig, () => member.fake.setUnavailable("agent-device crashed")); + + const answer = await envelopeOf(await allocate(rig, 1)); + + expect(answer.error?.message).toBe(`${notAvailable}agent-device crashed`); + await expect.poll(async () => (await workerLeases(member)).length).toBe(0); + expect(await fleetLeases(rig)).toEqual([]); + }); + + it("with every matching device leased, allocate waits and is granted once one is released", async () => { + const rig = await setUp({ workers: [{ label: "w1", maxRunning: 1 }] }); + await granted(rig, 1); + + const second = track(allocate(rig, 2, {}, { token: secrets.two })); + await expect.poll(() => waiting(rig)).toEqual([hex(2)]); + expect(second.done()).toBe(false); + + await release(rig, 1); + const answer = await envelopeOf(await second.promise); + + expect(answer.result).toMatchObject({ data: { lease: { leaseId: hex(2) } }, ok: true }); + await expect + .poll(async () => (await fleetLeases(rig, principals.two)).map((lease) => lease.id)) + .toEqual([hex(2)]); + }); + + it("a CLI that hangs up while its allocate waits leaves the gateway's queue, and nothing is granted later", async () => { + const rig = await setUp({ workers: [{ label: "w1", maxRunning: 1 }] }); + const member = first(rig); + await granted(rig, 1); + const hangUp = new AbortController(); + const second = track(allocate(rig, 2, {}, { signal: hangUp.signal, token: secrets.two })); + await expect.poll(() => waiting(rig)).toEqual([hex(2)]); + + hangUp.abort(); + await second.promise.catch(() => undefined); + await expect.poll(() => waiting(rig)).toEqual([]); + await release(rig, 1); + await sleep(100); + + expect(await fleetLeases(rig, principals.two)).toEqual([]); + expect(await workerLeases(member)).toEqual([]); + expect(allocatesReceived(member, 2)).toEqual([]); + }); + + it("a command for the lease reaches that worker's agent-device daemon with the prefixed tenant, and its streamed reply reaches the CLI unchanged", async () => { + const rig = await setUp(); + const member = first(rig); + await granted(rig, 1); + const chunks = ['{"progress":1}\n', '{"progress":2}\n', '{"done":true}\n']; + member.fake.streamNextCommand(chunks); + + const streamed = await command(rig, "snapshot", 1); + + expect(await streamed.text()).toBe(chunks.join("")); + expect( + member.fake.rpcRequests("agent_device.command").map((request) => request.tenant), + ).toEqual([await tenantOf(member, 1)]); + }); + + it("a heartbeat reaches the worker's agent-device daemon first, then renews the simlock lease to now plus its `ttlMs`", async () => { + const rig = await setUp(); + const member = first(rig); + await granted(rig, 1, { ttlMs: 60_000 }); + const allocated = await deadlineOf(member, 1); + let deadlineAtDaemon: number | undefined; + member.fake.onHeartbeat = async () => { + deadlineAtDaemon = await deadlineOf(member, 1); + }; + await advance(rig, 10_000, 5_000); + + const answer = await envelopeOf(await heartbeat(rig, 1, { ttlMs: 120_000 })); + + expect(answer.result).toMatchObject({ ok: true }); + expect(deadlineAtDaemon).toBe(allocated); + expect(member.fake.rpcRequests("agent_device.lease.heartbeat")[0]?.params).toMatchObject({ + ...scope, + leaseId: hex(1), + ttlMs: workerCeilingMs, + }); + expect(await deadlineOf(member, 1)).toBe(rig.clock.now() + 120_000); + }); + + it("a heartbeat for a lease whose worker stopped being capable answers the notAvailable reply naming `the worker holding this lease cannot serve agent-device`", async () => { + const rig = await setUp(); + const member = first(rig); + await granted(rig, 1); + expect((await envelopeOf(await heartbeat(rig, 1))).result).toMatchObject({ ok: true }); + await turn(rig, member, "unavailable"); + const received = heartbeatsReceived(member); + + const answer = await envelopeOf(await heartbeat(rig, 1)); + + expect(answer.error?.message).toBe(`${notAvailable}${holderCannot}`); + expect(heartbeatsReceived(member)).toBe(received); + }); + + it("while a command runs longer than the TTL, the simlock lease is renewed every TTL/3 through the gateway and does not expire", async () => { + const rig = await setUp(); + const member = first(rig); + await granted(rig, 1, { ttlMs: 30_000 }); + await runningCommand(rig, member, 1); + const tap = tapDispatch(rig.gateway); + const deadlines: (number | undefined)[] = []; + + for (let tick = 0; tick < 9; tick += 1) { + await advance(rig, 10_000, 5_000); + await sleep(30); + deadlines.push(await deadlineOf(member, 1)); + } + + expect(deadlines.every((deadline) => deadline !== undefined)).toBe(true); + expect(deadlines.at(-1)).toBeGreaterThan(rig.clock.now()); + expect(new Set(deadlines).size).toBeGreaterThan(4); + expect(tap.operations.filter((name) => name === "lease.renew").length).toBeGreaterThanOrEqual( + 7, + ); + member.fake.releaseCommand(); + }); + + it("release goes to the worker's agent-device daemon first, then releases the simlock lease, and the device is reclaimed", async () => { + const rig = await setUp(); + const member = first(rig); + let heldAtDaemonRelease: readonly string[] = []; + member.fake.onRelease = async () => { + heldAtDaemonRelease = (await workerLeases(member)).map((lease) => lease.requesterId); + }; + await granted(rig, 1); + + const released = await envelopeOf(await release(rig, 1)); + + expect(released.result).toMatchObject({ ok: true, released: true }); + expect(heldAtDaemonRelease).toHaveLength(1); + expect(await workerLeases(member)).toEqual([]); + await expect.poll(() => deviceStates(member)).toEqual(["ready"]); + expect(await fleetLeases(rig)).toEqual([]); + }); + + it("a release the agent-device daemon fails keeps the simlock lease", async () => { + const rig = await setUp(); + const member = first(rig); + await granted(rig, 1); + member.fake.failNextRelease({ code: "COMMAND_FAILED", message: "daemon could not release" }); + + const answer = await envelopeOf(await release(rig, 1)); + + expect(answer.error).toMatchObject({ + data: { code: "COMMAND_FAILED" }, + message: "daemon could not release", + }); + expect(await workerLeases(member)).toHaveLength(1); + expect((await fleetLeases(rig)).map((lease) => lease.id)).toEqual([hex(1)]); + }); + + it("after `simlock release --all` on the gateway, the worker's agent-device lease is released before the wipe, and the next heartbeat reaches that worker and answers `LEASE_ENDED_BY_HOST`", async () => { + const rig = await setUp(); + const member = first(rig); + const wipesAtRelease: number[] = []; + member.fake.onRelease = async () => { + wipesAtRelease.push(wipes(member)); + }; + await granted(rig, 1); + const before = wipes(member); + + await rig.gateway.dispatch("lease.release-all", {}, adminSession); + + await expect.poll(() => member.fake.rpcRequests("agent_device.lease.release").length).toBe(1); + expect(wipesAtRelease).toEqual([before]); + const received = heartbeatsReceived(member); + + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + + expect(heartbeatsReceived(member)).toBe(received + 1); + }); + + it("a command with no device selector naming a lease id another token holds, and one the gateway does not know, answer `refused: lease is not one of yours on this gateway` with status 403, and no worker receives it; with `--udid`, the same command answers `refused: simlock picks the device`, as on a worker", async () => { + const rig = await setUp(); + const member = first(rig); + await granted(rig, 1); + const own = await envelopeOf(await command(rig, "snapshot", 1)); + expect(own.result).toMatchObject({ ok: true }); + const received = member.fake.rpcRequests("agent_device.command").length; + + const other = await command(rig, "snapshot", 1, { token: secrets.two }); + const unknown = await command(rig, "snapshot", 9); + + expect(other.status).toBe(403); + expect((await envelopeOf(other)).error?.message).toBe( + `refused: lease ${hex(1)} is not one of yours on this gateway`, + ); + expect(unknown.status).toBe(403); + expect((await envelopeOf(unknown)).error?.message).toBe( + `refused: lease ${hex(9)} is not one of yours on this gateway`, + ); + const picked = await envelopeOf( + await command(rig, "snapshot", 1, { token: secrets.two }, { flags: { udid: "ABC" } }), + ); + expect(picked.error?.message).toBe("refused: simlock picks the device"); + expect(member.fake.rpcRequests("agent_device.command").length).toBe(received); + }); + + it("after `simlock release --all`, once the fake clock has moved the gateway's `lease.maxTtlMs` plus 1 s past the index's removal of the lease, the link's memory no longer holds it, and a heartbeat for it answers `refused: lease is not one of yours on this gateway`; one second before that, the heartbeat is still relayed", async () => { + const options = { defaultTtlMs: 60_000, maxTtlMs: 120_000 } as const; + const early = await setUp(options); + const earlyMember = first(early); + await granted(early, 1, { ttlMs: 30_000 }); + await early.gateway.dispatch("lease.release-all", {}, adminSession); + await expect.poll(async () => (await fleetLeases(early)).length).toBe(0); + await advance(early, 119_000, 10_000); + const received = heartbeatsReceived(earlyMember); + + expectEndedBySimlock(await envelopeOf(await heartbeat(early, 1))); + expect(heartbeatsReceived(earlyMember)).toBe(received + 1); + + const late = await setUp(options); + const lateMember = first(late); + await granted(late, 1, { ttlMs: 30_000 }); + await late.gateway.dispatch("lease.release-all", {}, adminSession); + await expect.poll(async () => (await fleetLeases(late)).length).toBe(0); + await advance(late, 121_000, 10_000); + const lateReceived = heartbeatsReceived(lateMember); + + const answer = await envelopeOf(await heartbeat(late, 1)); + + expect(answer.error?.message).toBe( + `refused: lease ${hex(1)} is not one of yours on this gateway`, + ); + expect(heartbeatsReceived(lateMember)).toBe(lateReceived); + }); + + it("a request with no lease id other than `/health` is refused with `refused: this agent-device is too old to use through a gateway; update it`", async () => { + const rig = await setUp(); + const member = first(rig); + expect((await send(rig, "/health")).status).toBe(200); + const before = member.fake.requests.length; + + const bare = await envelopeOf(await command(rig, "snapshot", undefined)); + const upload = await send(rig, "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/upload/preflight", { body: "{}" }); + + expect(bare.error?.message).toBe(tooOld); + expect(await upload.text()).toContain(tooOld); + expect(member.fake.requests.length).toBe(before); + }); + + it("a relay that fails with `RELAY_TARGET_MISSING` answers the notAvailable reply with that message", async () => { + const rig = await setUp(); + await granted(rig, 1); + expect((await envelopeOf(await command(rig, "snapshot", 1))).result).toMatchObject({ + ok: true, + }); + relayFailsWith(rig, "RELAY_TARGET_MISSING", "no relay target agent-device on this worker"); + + const answer = await command(rig, "snapshot", 1); + + expect(answer.status).toBe(503); + expect((await envelopeOf(answer)).error?.message).toBe( + `${notAvailable}no relay target agent-device on this worker`, + ); + }); + + it("an agent on a worker token with the same principal name as a gateway agent, connected to the worker directly, does not see the gateway agent's agent-device session, and the gateway agent's commands still work", async () => { + const rig = await setUp({ workers: [{ direct: true, label: "w1" }] }); + const member = first(rig); + await granted(rig, 1); + expect((await envelopeOf(await heartbeat(rig, 1))).result).toMatchObject({ ok: true }); + + const direct = await envelopeOf(await heartbeat(member, 1, {}, { token: secrets.direct })); + + expect(direct.result).toBeUndefined(); + expect(direct.error).toBeDefined(); + const seen = member.fake.rpcRequests("agent_device.lease.heartbeat").map((r) => r.tenant); + expect(seen).toContain(principals.one); + expect(seen).toContain(await tenantOf(member, 1)); + expect((await envelopeOf(await heartbeat(rig, 1))).result).toMatchObject({ ok: true }); + expect((await envelopeOf(await command(rig, "snapshot", 1))).result).toMatchObject({ + ok: true, + }); + }); + + it("`agentDevice.leaseTtlCapMs` on the gateway caps the TTL of a lease made through it", async () => { + const rig = await setUp({ leaseTtlCapMs: 10_000 }); + const member = first(rig); + + await granted(rig, 1, { ttlMs: 300_000 }); + + expect((await workerLeaseFor(member, 1)).ttlMs).toBe(10_000); + await expect.poll(async () => (await fleetLeases(rig))[0]?.ttlMs).toBe(10_000); + }); + + it("stopping the gateway while an allocate waits ends its lease request `cancelled`, not `DAEMON_STOPPING`, and a running command's renewals stop", async () => { + const rig = await setUp({ workers: [{ label: "w1", maxRunning: 1 }] }); + const member = first(rig); + await granted(rig, 1, { ttlMs: 30_000 }, { token: secrets.two }); + await runningCommand(rig, member, 1, { token: secrets.two }); + const tap = tapDispatch(rig.gateway); + await advance(rig, 20_000, 5_000); + const renewedBefore = tap.operations.filter((name) => name === "lease.renew").length; + const second = track(allocate(rig, 2)); + await expect.poll(() => waiting(rig)).toEqual([hex(2)]); + + await rig.gateway.stop("test"); + await second.promise.catch(() => undefined); + const afterStop = tap.operations.length; + await advance(rig, 60_000, 10_000); + + expect(renewedBefore).toBeGreaterThan(0); + expect(tap.operations.length).toBe(afterStop); + const lines = (await readFile(join(rig.directory, "events.jsonl"), "utf8")) + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => JSON.parse(line) as { event?: string; payload?: Record }); + expect( + lines.filter( + (entry) => + entry.event === "lease.rejected" && + entry.payload?.["requester"] === hex(2) && + entry.payload["reason"] === "cancelled", + ), + ).toHaveLength(1); + member.fake.releaseCommand(); + }); + + it("stopping the gateway cancels the link's sweep of a lease the fleet removed, leaving the timers a gateway with no agent-device activity leaves", async () => { + const idle = await setUp(); + await idle.gateway.stop("test"); + const rig = await setUp(); + await granted(rig, 1); + expect((await envelopeOf(await release(rig, 1))).result).toMatchObject({ ok: true }); + await expect.poll(async () => (await fleetLeases(rig)).length).toBe(0); + expect(rig.clock.pendingTimerCount).toBeGreaterThan(idle.clock.pendingTimerCount); + + await rig.gateway.stop("test"); + + expect(rig.clock.pendingTimerCount).toBe(idle.clock.pendingTimerCount); + }); + + it("a heartbeat, a release and an allocate whose relay fails with `RELAY_TARGET_MISSING` answer the notAvailable reply with that message, and the failed allocate leaves no lease", async () => { + const rig = await setUp(); + const member = first(rig); + await granted(rig, 1); + const missing = `${notAvailable}no relay target agent-device on this worker`; + relayFailsWith(rig, "RELAY_TARGET_MISSING", "no relay target agent-device on this worker"); + + const beat = await heartbeat(rig, 1); + const released = await release(rig, 1); + const made = await allocate(rig, 2); + + expect((await envelopeOf(beat)).error?.message).toBe(missing); + expect((await envelopeOf(released)).error?.message).toBe(missing); + expect((await envelopeOf(made)).error?.message).toBe(missing); + await expect.poll(async () => (await workerLeases(member)).length).toBe(1); + }); + + it("a heartbeat for a lease the front's memory lacks, whose release relay then fails with `RELAY_TARGET_MISSING`, answers the notAvailable reply with that message and leaves the simlock lease", async () => { + const rig = await setUp(); + const member = first(rig); + await granted(rig, 1); + const held = member.fake.leases.get(hex(1)); + expect(held).toBeDefined(); + member.fake.leases.set(hex(2), { ...(held as NonNullable), leaseId: hex(2) }); + await rig.gateway.dispatch( + "lease.request", + { leaseId: hex(2), platform: "ios", requesterId: hex(2), requires: ["agent-device"] }, + sessionFor(principals.one), + ); + interceptRelay(rig, async ({ request }) => { + const body = (await request.clone().json()) as { method?: string }; + if (body.method === "agent_device.lease.release") { + throw new DispatchError( + "RELAY_TARGET_MISSING", + "no relay target agent-device on this worker", + ); + } + }); + + const beat = await envelopeOf(await heartbeat(rig, 2)); + + expect(beat.error?.message).toBe(`${notAvailable}no relay target agent-device on this worker`); + expect((await fleetLeases(rig)).map((lease) => lease.id)).toContain(hex(2)); + }); +}); diff --git a/src/agent-device/index.ts b/src/agent-device/index.ts index 6c939faf5..fd3c1c641 100644 --- a/src/agent-device/index.ts +++ b/src/agent-device/index.ts @@ -4,12 +4,15 @@ import type { Clock, Logger } from "../ports/index.js"; import { FrontMap } from "./front/front-map.js"; import { createFront } from "./front/front.js"; import { InProcessHostLink, type HostLink } from "./front/host-link.js"; +import { RelayHostLink, type FleetPort } from "./front/relay-host-link.js"; +import { frontReplyFor, notAvailable } from "./shared/replies.js"; import { Renewals } from "./front/renewals.js"; import type { AgentDevicePlatform } from "./host/agent-device-supervisor.js"; import { AgentDeviceHost } from "./host/host.js"; import { AgentDeviceLeaseEnd, ReleaseScopeRecord } from "./host/lease-end.js"; import type { AgentDeviceUpstream } from "./host/upstream.js"; +export type { FleetPort, FleetWorker } from "./front/relay-host-link.js"; export { agentDeviceFindings } from "./host/availability-findings.js"; export { AgentDeviceSupervisor } from "./host/agent-device-supervisor.js"; // fallow-ignore-next-line unused-type -- the shape `AgentDeviceSupervisor.availability()` returns, which `agentDeviceFindings` reads. @@ -18,13 +21,28 @@ export type { AgentDeviceUpstream } from "./host/upstream.js"; export { SupervisorAgentDeviceUpstream } from "./host/upstream.js"; export { type AgentDeviceHealthProbe, NodeAgentDeviceHealthProbe } from "./host/health.js"; -export interface AgentDeviceEdgeParts { - readonly leaseEnd: AgentDeviceLeaseEnd; +export interface AgentDeviceFrontParts { readonly link: HostLink; readonly map: FrontMap; readonly renewals: Renewals; } +export interface AgentDeviceEdgeParts extends AgentDeviceFrontParts { + readonly leaseEnd: AgentDeviceLeaseEnd; +} + +export function createGatewayAgentDeviceFrontParts( + fleet: FleetPort, + clock: Clock, + leaseMaxTtlMs: number, +): AgentDeviceFrontParts { + return { + link: new RelayHostLink({ clock, fleet, leaseMaxTtlMs }), + map: new FrontMap(clock), + renewals: new Renewals(clock), + }; +} + export function createAgentDeviceEdgeParts( upstream: AgentDeviceUpstream, clock: Clock, @@ -39,6 +57,19 @@ export function createAgentDeviceEdgeParts( }; } +// why: a relayed request's tenant is the gateway's prefixed principal, which the host treats as the requester, so the worker's own tokens never share a session with it. +export function agentDeviceRelayTarget( + parts: AgentDeviceEdgeParts, +): (request: Request, tenant: string) => Promise { + return async (request, tenant) => { + const status = await parts.link.status(); + if (status.state === "unavailable") { + return frontReplyFor(request, notAvailable(status.reason)); + } + return parts.link.forward(request, { requesterId: tenant, role: "agent" }); + }; +} + export function agentDeviceCapabilitySource(parts: AgentDeviceEdgeParts): { readonly name: string; readonly read: () => Promise<{ @@ -58,20 +89,21 @@ export function agentDeviceCapabilitySource(parts: AgentDeviceEdgeParts): { } // why: a stop ends the gateway's sockets, so the calls that end then must send no renewal that races leasing teardown. -export function disposeAgentDeviceEdge(parts: AgentDeviceEdgeParts): void { +export function disposeAgentDeviceEdge(parts: AgentDeviceFrontParts): void { parts.renewals.dispose(); + parts.link.dispose?.(); } // why: a stop refuses every dispatch, so waiting allocates' lease requests are cancelled through leasing directly, before the gateway stops; otherwise they stay open across a restart. export async function cancelWaitingAllocates( - parts: AgentDeviceEdgeParts, + parts: AgentDeviceFrontParts, cancel: (requesterId: string) => Promise, ): Promise { await Promise.allSettled(parts.map.waitingIds().map((id) => cancel(id))); } export function createAgentDeviceFront( - parts: AgentDeviceEdgeParts, + parts: AgentDeviceFrontParts, deps: { readonly dispatch: HttpDispatch; readonly clock: Clock; diff --git a/src/agent-device/shared/release-scope.ts b/src/agent-device/shared/release-scope.ts index 974bf1bb4..7b930ce36 100644 --- a/src/agent-device/shared/release-scope.ts +++ b/src/agent-device/shared/release-scope.ts @@ -23,7 +23,8 @@ export function readReleaseScope(lease: unknown): ReleaseScope | undefined { const fields = lease as Record; const tenantId = fields["tenantId"]; const runId = fields["runId"]; - if (!validScopeValue(tenantId) || !validScopeValue(runId)) return undefined; + if (typeof tenantId !== "string" || !SCOPE_VALUE.test(tenantId)) return undefined; + if (!validScopeValue(runId)) return undefined; const optional: { -readonly [K in (typeof OPTIONAL_KEYS)[number]]?: string } = {}; for (const key of OPTIONAL_KEYS) { const value = fields[key]; diff --git a/src/agent-device/shared/replies.ts b/src/agent-device/shared/replies.ts index 304f64ad7..f55042daf 100644 --- a/src/agent-device/shared/replies.ts +++ b/src/agent-device/shared/replies.ts @@ -1,3 +1,5 @@ +import { FRONT_PREFIX } from "./paths.js"; + export type ReplyCode = "INVALID_ARGS" | "COMMAND_FAILED" | "UNAUTHORIZED"; export interface FrontReply { @@ -59,3 +61,17 @@ export function frontReply(reply: FrontReply, rpc: { readonly id: unknown } | un { status: reply.status }, ); } + +// why: a reply made for a request the front did not read itself answers a JSON-RPC call under that call's id, and any other request in the flat shape. +export async function frontReplyFor(request: Request, reply: FrontReply): Promise { + if (request.method !== "POST" || new URL(request.url).pathname !== `${FRONT_PREFIX}/rpc`) { + return frontReply(reply, undefined); + } + try { + const body: unknown = await request.clone().json(); + const id = typeof body === "object" && body !== null && "id" in body ? body.id : null; + return frontReply(reply, { id }); + } catch { + return frontReply(reply, { id: null }); + } +} diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index c19892bac..ee89980da 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -75,7 +75,7 @@ const ROLE_MATRIX: ReadonlyArray<{ method: "GET", relayId: "r-1", target: "agent-device", - tenant: "gw:g:a", + tenant: "gw.g.a", url: "http://gateway.test/x", }, role: "admin", @@ -157,7 +157,7 @@ const EFFECT_MATRIX: ReadonlyArray<{ method: "GET", relayId: "r-1", target: "agent-device", - tenant: "gw:g:a", + tenant: "gw.g.a", url: "http://gateway.test/x", }, effect: "write", diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 8bc2673b2..d58f6d4f4 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -1773,6 +1773,24 @@ describe("loadConfig modes (ADR 0005)", () => { ); }); + it("reads agentDevice.enabled and leaseTtlCapMs on a gateway without a warning, and warns that it ignores agentDevice.command", async () => { + const warn = vi.fn(); + + const config = await load( + { + agentDevice: { enabled: true, leaseTtlCapMs: 10_000 }, + mode: "gateway", + }, + { warn }, + ); + expect(config.agentDevice).toMatchObject({ enabled: true, leaseTtlCapMs: 10_000 }); + expect(warn).not.toHaveBeenCalled(); + + await load({ agentDevice: { command: "elsewhere" }, mode: "gateway" }, { warn }); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "agentDevice.command"')); + expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('Ignoring "agentDevice"')); + }); + it("says nothing about worker keys on a worker, which is every daemon today", async () => { const warn = vi.fn(); await load({ capacity: { strategy: "fixed", config: { maxRunning: 3 } } }, { warn }); @@ -2022,13 +2040,4 @@ describe("agentDevice config", () => { expect(dottedValue(parsed, "agentDevice.enabled")).toBe(true); expect(dottedValue(parsed, "agentDevice.command")).toBe("ad"); }); - - it("loads a gateway config with agentDevice and warns that the key is worker-only", async () => { - const warn = vi.fn(); - - const config = await loadWith({ agentDevice: { enabled: true }, mode: "gateway" }, warn); - - expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "agentDevice"')); - expect(dottedValue(config, "agentDevice.enabled")).toBe(true); - }); }); diff --git a/src/core/config.ts b/src/core/config.ts index 58167d532..b3a6a3beb 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -482,6 +482,7 @@ const GATEWAY_CONFIG_KEYS: readonly string[] = [ "eventBuffer", "eventLog", "gateway", + "agentDevice", ]; /** The `gateway.*` sub-keys a *worker* reads. A gateway ignores these three (it dials nobody); @@ -489,6 +490,9 @@ const GATEWAY_CONFIG_KEYS: readonly string[] = [ * gateway itself reads. */ const WORKER_ONLY_GATEWAY_KEYS: readonly string[] = ["url", "token", "label"]; +// why: `command` names the program a worker runs, and a gateway runs none. +const WORKER_ONLY_AGENT_DEVICE_KEYS: readonly string[] = ["command"]; + /** * ADR 0005 §2: "worker-only keys in a gateway's config are ignored with a warning, as unknown * keys are today". Warned per key the operator actually wrote (the file and override layers), @@ -506,16 +510,38 @@ function warnWorkerOnlyKeys(layers: readonly unknown[], warn: Warn): void { warn(`Ignoring "${key}": it configures a worker, and this daemon runs in gateway mode.`); } } - const gateway = object["gateway"]; - if (gateway === undefined) continue; - for (const key of Object.keys(requireObject(gateway, "gateway"))) { - if (WORKER_ONLY_GATEWAY_KEYS.includes(key)) { - warn( - `Ignoring "gateway.${key}": it points a worker at its gateway, ` + - `and this daemon runs in gateway mode.`, - ); - } - } + warnWorkerOnlySubKeys( + object, + "gateway", + WORKER_ONLY_GATEWAY_KEYS, + warn, + (key) => + `Ignoring "gateway.${key}": it points a worker at its gateway, ` + + `and this daemon runs in gateway mode.`, + ); + warnWorkerOnlySubKeys( + object, + "agentDevice", + WORKER_ONLY_AGENT_DEVICE_KEYS, + warn, + (key) => + `Ignoring "agentDevice.${key}": it names the program a worker runs, ` + + `and this daemon runs in gateway mode.`, + ); + } +} + +function warnWorkerOnlySubKeys( + layer: Record, + section: string, + workerOnly: readonly string[], + warn: Warn, + message: (key: string) => string, +): void { + const value = layer[section]; + if (value === undefined) return; + for (const key of Object.keys(requireObject(value, section))) { + if (workerOnly.includes(key)) warn(message(key)); } } diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 70c85258c..cafc4d02e 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -5,14 +5,18 @@ import { pathToFileURL } from "node:url"; import { agentDeviceCapabilitySource, agentDeviceFindings, + agentDeviceRelayTarget, AgentDeviceSupervisor, cancelWaitingAllocates, createAgentDeviceEdgeParts, disposeAgentDeviceEdge, createAgentDeviceFront, + createGatewayAgentDeviceFrontParts, SupervisorAgentDeviceUpstream, type AgentDeviceHealthProbe, type AgentDeviceUpstream, + type FleetPort, + type FleetWorker, NodeAgentDeviceHealthProbe, } from "../agent-device/index.js"; import { EVENT_FILE_NAME, EventBus, EventHistory, type EventBusLogger } from "../bus/index.js"; @@ -101,6 +105,7 @@ import { GatewayRelay, GatewayService, type GatewayServiceOptions, + type FleetViews, } from "../gateway/index.js"; import { WebSocketUplinkConnector, @@ -157,11 +162,13 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise configWarnings.push(message), }); const logger = options.logger ?? @@ -173,6 +180,8 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise leasing.corePorts.notifyAvailability()), nuke, registry, @@ -781,8 +795,21 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise Promise) | undefined; let resolveHttpStarted: (() => void) | undefined; @@ -848,6 +875,10 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise { + if (agentDeviceParts !== undefined) { + disposeAgentDeviceEdge(agentDeviceParts); + await cancelWaitingAllocates(agentDeviceParts, (id) => fleetCoordinator.cancelPending(id)); + } await httpStarted.catch(() => undefined); await stopHttpGateway?.(); }, @@ -865,15 +896,32 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise { const httpLogger = logger.child("http"); + // why: looked up at each call, so a wrapper placed on the daemon's dispatch sits between the front and leasing. + const dispatch: HttpDispatch = (operation, input, session) => + daemon.dispatch(operation, input, session); const app = createHttpApp({ clock, config, - dispatch: (operation, input, session) => daemon.dispatch(operation, input, session), + dispatch, eventBus, idGenerator, // The fleet coordinator's in-memory request book: a gateway stores nothing on disk. leaseRequests: fleetCoordinator.requests, logger: httpLogger, + mounts: + agentDeviceParts === undefined + ? [] + : [ + createAgentDeviceFront(agentDeviceParts, { + clock, + dispatch, + logger: logger.child("agent-device"), + maxRunMs: config.lease.maxTtlMs, + ...(config.agentDevice.leaseTtlCapMs === undefined + ? {} + : { leaseTtlCapMs: config.agentDevice.leaseTtlCapMs }), + }), + ], // Inert in gateway mode: the gateway issues no leases of its own in this PR, so there // are no owner-routed facts to buffer (see `DaemonServer`'s constructor). ownerRoutedFacts: daemon.ownerRoutedFacts, @@ -921,6 +969,72 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise>; + +// why: the agent-device edge imports nothing from the gateway, so this is the one place the gateway's parts become its port. +function agentDeviceFleetPort({ instanceId, leaseIndex, relay, views }: FleetPortParts): FleetPort { + const serving = (view: WorkerView, withDrained: boolean): FleetWorker | undefined => { + const maxTtlMs = view.lease?.maxTtlMs; + const available = view.capabilities?.some( + (entry) => entry.name === AGENT_DEVICE && entry.state === "available", + ); + if ( + view.connection !== "connected" || + (view.drained && !withDrained) || + available !== true || + view.catalogReadAt === undefined || + maxTtlMs === undefined + ) { + return undefined; + } + const platforms = (view.catalog ?? []).flatMap((entry) => + entry.platform === "ios" || entry.platform === "android" ? [entry.platform] : [], + ); + return { id: view.id, leaseMaxTtlMs: maxTtlMs, platforms }; + }; + return { + capableWorkers: () => + views.views().flatMap((view) => { + const worker = serving(view, false); + return worker === undefined ? [] : [worker]; + }), + holder: (workerId) => { + const view = views.view(workerId); + return view === undefined ? undefined : serving(view, true); + }, + instanceId, + leaseOf: (leaseId) => { + const entry = leaseIndex.resolve(leaseId); + return entry === undefined ? undefined : { ownerId: entry.ownerId, workerId: entry.workerId }; + }, + onLeaseRemoved: (listener) => + leaseIndex.onRemoved((entry) => + listener({ + leaseId: entry.gatewayLeaseId, + ownerId: entry.ownerId, + workerId: entry.workerId, + }), + ), + // why: looked up at each call, so a test that replaces the relay's method sits between the link and the worker. + relay: (workerId, request, tenant, leaseId) => + relay.relay(workerId, { + request, + target: AGENT_DEVICE, + tenant, + ...(leaseId === undefined ? {} : { leaseId }), + }), + }; +} + function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index 8e0895e0a..bbc8a2b16 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -55,7 +55,7 @@ function buildCall(init: CallInit) { return { request, target: init.target ?? "echo", - tenant: init.tenant ?? "gw:g1:alice", + tenant: init.tenant ?? "gw.g1.alice", ...(init.leaseId === undefined ? {} : { leaseId: init.leaseId }), }; } @@ -264,7 +264,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(seen?.method).toBe("GET"); expect(seen?.headers.get("accept")).toBe("text/plain"); expect(seen?.headers.get("x-test")).toBe("1"); - expect(seen?.tenant).toBe("gw:g1:alice"); + expect(seen?.tenant).toBe("gw.g1.alice"); expect(seen?.leaseId).toBe("lease_1"); expect(response.status).toBe(201); expect(response.headers.get("x-reply")).toBe("yes"); diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index 3fedbaff6..a2dc9729c 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -204,7 +204,7 @@ export function relayInput(overrides: Record = {}): Record[0]> = {}) { } describe("FleetLeaseIndex", () => { + describe("onRemoved", () => { + it("tells the listener each entry the index drops, by release, by a worker's relayed fact and by forgetting the worker", () => { + const index = new FleetLeaseIndex(PREFIX); + const dropped: string[] = []; + index.onRemoved((gone) => dropped.push(gone.gatewayLeaseId)); + index.add(entry({ gatewayLeaseId: "a", workerLeaseId: "la" })); + index.add(entry({ gatewayLeaseId: "b", workerLeaseId: "lb" })); + index.add(entry({ gatewayLeaseId: "c", workerLeaseId: "lc", workerId: "wrk_2" })); + + index.remove("a"); + index.removeByWorkerLease("wrk_1", "lb"); + index.forgetWorker("wrk_2"); + + expect(dropped).toEqual(["a", "b", "c"]); + }); + + it("tells the listener nothing for a lease the index never held", () => { + const index = new FleetLeaseIndex(PREFIX); + const dropped: string[] = []; + index.onRemoved((gone) => dropped.push(gone.gatewayLeaseId)); + + index.remove("missing"); + + expect(dropped).toEqual([]); + }); + }); + describe("add / resolve / lookups", () => { it("resolves an entry by gateway id, by (workerId, workerLeaseId), by ownerId and by requesterId", () => { const index = new FleetLeaseIndex(PREFIX); diff --git a/src/gateway/lease-index.ts b/src/gateway/lease-index.ts index 2dc3c6f0c..35ad2b867 100644 --- a/src/gateway/lease-index.ts +++ b/src/gateway/lease-index.ts @@ -61,6 +61,7 @@ export class FleetLeaseIndex { readonly #byGatewayId = new Map(); readonly #byRequester = new Map>(); readonly #byWorkerLease = new Map(); + readonly #removalListeners: ((entry: FleetLeaseEntry) => void)[] = []; /** C3 (round 2 review): one strictly-increasing counter per worker, bumped on every * `rebuildFromWorker` call for that worker -- what lets reconciliation (below) tell "missing * from this snapshot" apart from "missing for a whole extra snapshot in a row" without @@ -354,11 +355,17 @@ export class FleetLeaseIndex { if (ids?.size === 0) this.#byRequester.delete(entry.requesterId); } + // why: every way the index drops a lease (a release, an expiry, a reconciled miss, a forgotten worker) tells the listener after the entry is gone. + onRemoved(listener: (entry: FleetLeaseEntry) => void): void { + this.#removalListeners.push(listener); + } + #forget(entry: FleetLeaseEntry): void { this.#byGatewayId.delete(entry.gatewayLeaseId); this.#dropRequesterLink(entry); this.#byWorkerLease.delete(workerKey(entry.workerId, entry.workerLeaseId)); this.#missingSince.delete(entry.gatewayLeaseId); + for (const listener of this.#removalListeners) listener(entry); } }