From 120be5012b01a3eb43f0fa4567e851ed00ad0965 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 20:56:08 +0200 Subject: [PATCH 1/5] test: a lease request may require a capability (#513) --- src/contract/errors.test.ts | 21 + src/contract/operations.test.ts | 50 +++ src/contract/operations.ts | 2 + src/daemon/dispatcher.test.ts | 179 ++++++++ src/daemon/lease-requires.e2e.test.ts | 410 ++++++++++++++++++ src/gateway/fleet-coordinator.test.ts | 94 ++++ src/gateway/routing/pipeline.ts | 1 + src/gateway/routing/serviceability.test.ts | 74 ++++ .../routing/stages/has-capabilities.test.ts | 92 ++++ .../routing/stages/has-capabilities.ts | 9 + src/gateway/worker-registry.ts | 1 + src/leasing/wait-queue.ts | 1 + src/mcp/contracts.test.ts | 14 + src/mcp/server.test.ts | 13 + src/simlock-client/client.test.ts | 28 ++ 15 files changed, 989 insertions(+) create mode 100644 src/daemon/lease-requires.e2e.test.ts create mode 100644 src/gateway/routing/stages/has-capabilities.test.ts create mode 100644 src/gateway/routing/stages/has-capabilities.ts diff --git a/src/contract/errors.test.ts b/src/contract/errors.test.ts index dbf5286af..612a5c5a3 100644 --- a/src/contract/errors.test.ts +++ b/src/contract/errors.test.ts @@ -86,3 +86,24 @@ describe("SimlockError", () => { } }); }); + +describe("CAPABILITY_MISSING", () => { + it("maps CAPABILITY_MISSING to HTTP 422 and CLI exit 12 as a domain error whose details name the capabilities", () => { + const table: Record = ERROR_TABLE; + const error = fromWireError("CAPABILITY_MISSING", "This worker cannot serve agent-device", { + capabilities: ["agent-device"], + }); + + expect(table["CAPABILITY_MISSING"]).toEqual({ + cliExitCode: 12, + code: "CAPABILITY_MISSING", + httpStatus: 422, + kind: "domain", + }); + expect(error).toMatchObject({ + code: "CAPABILITY_MISSING", + details: { capabilities: ["agent-device"] }, + kind: "domain", + }); + }); +}); diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index e44347105..2ad82ab6a 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -1476,3 +1476,53 @@ describe("device.add and device.remove ids (ADR 0022 §2)", () => { expect(OPERATIONS["device.remove"].input.safeParse({}).success).toBe(false); }); }); + +describe("lease.request requires", () => { + const base = { model: "iPhone 17", platform: "ios" } as const; + const parse = (extra: Record) => + OPERATIONS["lease.request"].input.safeParse({ ...base, ...extra }); + const names = (count: number) => + Array.from({ length: count }, (_, index) => `cap-${String(index)}`); + + it.each([ + ["one name", ["agent-device"]], + ["an empty list", []], + ["8 names", names(8)], + ])("accepts %s", (_label, requires) => { + expect(parse({ requires }).success).toBe(true); + }); + + it("accepts a request without requires, and one with requires: [] parses to the same device", () => { + expect(parse({}).success).toBe(true); + const input = parse({ requires: [] }); + expect(input.success && requestedDevice(input.data)).toEqual({ + model: "iPhone 17", + platform: "ios", + }); + }); + + it.each([ + ["an upper-case name", ["Agent-Device"]], + ["a duplicate name", ["agent-device", "agent-device"]], + ["9 names", names(9)], + ])("refuses requires with %s with BAD_REQUEST-shaped issues on requires", (_label, requires) => { + const parsed = parse({ requires }); + + expect(parsed.success).toBe(false); + expect( + !parsed.success && parsed.error.issues.every((issue) => issue.path[0] === "requires"), + ).toBe(true); + }); + + it("refuses requires together with idempotencyKey, naming both, where each alone is accepted", () => { + expect(parse({ idempotencyKey: "key-1" }).success).toBe(true); + expect(parse({ requires: ["agent-device"] }).success).toBe(true); + + const both = parse({ idempotencyKey: "key-1", requires: ["agent-device"] }); + + expect(both.success).toBe(false); + expect(!both.success && both.error.issues.map((issue) => issue.message)).toContain( + "requires cannot be combined with idempotencyKey", + ); + }); +}); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index bd3004f75..043970f5a 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -13,6 +13,7 @@ import { CONSOLE_URL_MAX_LENGTH } from "./console-url.js"; import { parseOsConstraint } from "./os-range.js"; import { ownsLease, type AuthorizeContext, type Role } from "./roles.js"; import { + capabilityNameSchema, cleanupRuleSummarySchema, configSchema, daemonHealthSchema, @@ -177,6 +178,7 @@ const leaseRequestBaseSchema = z * Bounded as `idempotencyKey` is, because the worker stores it. */ fleetRequestId: z.string().min(1).max(200).optional(), + requires: z.array(capabilityNameSchema).optional(), }) .strict(); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index e4c8a5706..87f0f3a7b 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -4083,3 +4083,182 @@ describe("Dispatcher: status.get capabilities", () => { ); }); }); + +describe("Dispatcher: lease.request requires", () => { + const IOS = { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" } as const; + const REQUIRES = { ...IOS, requires: ["agent-device"] } as const; + type SourceState = { state: "available" | "off" | "unavailable" }; + + function sources(initial: SourceState["state"]) { + const current: SourceState = { state: initial }; + return { + current, + list: [{ name: "agent-device", read: async () => ({ state: current.state }) }] as NonNullable< + DispatcherOptions["capabilitySources"] + >, + }; + } + + it("refuses a request on a worker whose agent-device is off with CAPABILITY_MISSING, message `This worker cannot serve agent-device`, details naming it, stores nothing and emits no event", async () => { + const capability = sources("available"); + const { dispatcher, eventBus, registry } = await buildDispatcher({ + capabilitySources: capability.list, + }); + const grant = await dispatcher.dispatch( + "lease.request", + { ...REQUIRES, requesterId: "a" }, + session(), + ); + await dispatcher.dispatch("lease.release", { leaseId: grant.lease.id }, session()); + capability.current.state = "off"; + const requestsBefore = registry.leaseRequests().length; + const eventsBefore = eventBus.replay().length; + + await expect( + dispatcher.dispatch("lease.request", { ...REQUIRES, requesterId: "b" }, session()), + ).rejects.toMatchObject({ + code: "CAPABILITY_MISSING", + details: { capabilities: ["agent-device"] }, + message: "This worker cannot serve agent-device", + }); + + expect(registry.leaseRequests()).toHaveLength(requestsBefore); + expect(eventBus.replay()).toHaveLength(eventsBefore); + }); + + it("refuses the same request from the gateway uplink as a probe, the same way, with no lease.declined", async () => { + const capability = sources("unavailable"); + const { dispatcher, eventBus, registry } = await buildDispatcher({ + capabilitySources: capability.list, + }); + + await expect( + dispatcher.dispatch( + "lease.request", + { ...REQUIRES, fleetRequestId: "req_gw1", noWait: true }, + session({ isGatewayUplink: true, principal: "tok_gateway", role: "admin" }), + ), + ).rejects.toMatchObject({ code: "CAPABILITY_MISSING" }); + + expect(registry.leaseRequests()).toEqual([]); + expect(eventBus.replay().map((event) => event.event)).not.toContain("lease.declined"); + }); + + it("names only x-other when requires is [x-other, agent-device] and only agent-device is available", async () => { + const { dispatcher } = await buildDispatcher({ + capabilitySources: sources("available").list, + }); + + await expect( + dispatcher.dispatch( + "lease.request", + { ...IOS, requires: ["x-other", "agent-device"] }, + session(), + ), + ).rejects.toMatchObject({ + code: "CAPABILITY_MISSING", + details: { capabilities: ["x-other"] }, + message: "This worker cannot serve x-other", + }); + }); + + it("refuses within 1.5 s with CAPABILITY_MISSING when the capability source takes 2 s", async () => { + const clock = new FakeClock(1_000); + const { dispatcher } = await buildDispatcher({ + capabilitySources: [ + { + name: "agent-device", + read: () => + new Promise((resolve) => clock.setTimer(2_000, () => resolve({ state: "available" }))), + }, + ], + clock, + }); + let settled = false; + const answer = dispatcher.dispatch("lease.request", REQUIRES, session()).then( + () => "granted", + (error: unknown) => error, + ); + void answer.then(() => { + settled = true; + }); + + for (let elapsed = 0; elapsed < 1_500; elapsed += 100) { + await new Promise((resolve) => setImmediate(resolve)); + clock.advance(100); + } + await new Promise((resolve) => setImmediate(resolve)); + + expect(settled).toBe(true); + expect(await answer).toMatchObject({ code: "CAPABILITY_MISSING" }); + }); + + it("grants a queued request with requires once a device frees, even though the capability turned unavailable while it waited", async () => { + const capability = sources("available"); + const { dispatcher, engine } = await buildDispatcher({ capabilitySources: capability.list }); + const first = await dispatcher.dispatch( + "lease.request", + { ...IOS, requesterId: "h1" }, + session(), + ); + await dispatcher.dispatch("lease.request", { ...IOS, requesterId: "h2" }, session()); + const waiting = dispatcher.dispatch( + "lease.request", + { ...REQUIRES, requesterId: "w" }, + session(), + ); + await expect.poll(() => engine.queueDepth).toBe(1); + capability.current.state = "unavailable"; + + await dispatcher.dispatch("lease.release", { leaseId: first.lease.id }, session()); + + await expect(waiting).resolves.toMatchObject({ lease: { requesterId: "w" } }); + }); + + it("refuses requires together with idempotencyKey with BAD_REQUEST and stores nothing", async () => { + const { dispatcher, registry } = await buildDispatcher({ + capabilitySources: sources("available").list, + }); + + await expect( + dispatcher.dispatch("lease.request", { ...REQUIRES, idempotencyKey: "key-1" }, session()), + ).rejects.toMatchObject({ + code: "BAD_REQUEST", + message: expect.stringContaining("requires cannot be combined with idempotencyKey"), + }); + + expect(registry.leaseRequests()).toEqual([]); + expect(registry.snapshot.leases).toEqual([]); + }); + + it.each([ + ["absent", {}], + ["[]", { requires: [] }], + ])( + "a request with requires %s is granted on a worker whose agent-device is off, and lease.requested's requestSpec has no requires", + async (_label, extra) => { + const { dispatcher, eventBus } = await buildDispatcher({ + capabilitySources: sources("off").list, + }); + + await dispatcher.dispatch("lease.request", { ...IOS, ...extra }, session()); + + const requested = eventBus.replay().find((event) => event.event === "lease.requested"); + expect(requested?.payload).toMatchObject({ requestSpec: IOS }); + expect(JSON.stringify(requested?.payload)).not.toContain("requires"); + }, + ); + + it("a request with requires is granted as today on a worker with the capability, and its requestSpec has no requires", async () => { + const { dispatcher, eventBus } = await buildDispatcher({ + capabilitySources: sources("available").list, + }); + + const grant = await dispatcher.dispatch("lease.request", REQUIRES, session()); + + expect(grant.device.spec).toMatchObject({ model: "iPhone 17 Pro", platform: "ios" }); + const requested = eventBus.replay().find((event) => event.event === "lease.requested"); + expect(requested?.payload).toMatchObject({ requestSpec: IOS }); + expect(JSON.stringify(requested?.payload)).not.toContain("requires"); + }); +}); diff --git a/src/daemon/lease-requires.e2e.test.ts b/src/daemon/lease-requires.e2e.test.ts new file mode 100644 index 000000000..d52ea325b --- /dev/null +++ b/src/daemon/lease-requires.e2e.test.ts @@ -0,0 +1,410 @@ +import { mkdtemp, 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 { FakeAgentDevice } from "../agent-device/testing.js"; +import { FakeDriver } from "../core/testing.js"; +import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import type { DispatchSession } from "./dispatch.js"; +import { startDaemon } from "./main.js"; +import type { DaemonServer } from "./server.js"; + +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; +} + +const admin: DispatchSession = { + manageEventSubscription: () => undefined, + principal: "test-operator", + role: "admin", +}; + +function agent(principal: string): DispatchSession { + return { manageEventSubscription: () => undefined, principal, role: "agent" }; +} + +type CapabilityState = "available" | "off" | "unavailable"; + +interface Member { + readonly label: string; + readonly daemon: DaemonServer; + readonly fake: FakeAgentDevice; +} + +const MISSING_MESSAGE = + "No worker connected to this gateway can serve agent-device for this request"; + +describe("lease.request requires, through a gateway", () => { + const daemons: DaemonServer[] = []; + const directories: string[] = []; + + afterEach(async () => { + await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); + await Promise.all( + directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), + ); + }); + + async function startGateway() { + const directory = await mkdtemp(join(tmpdir(), "simlock-e2e-requires-gateway-")); + directories.push(directory); + const port = await freeLoopbackPort(); + const gateway = await startDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + dataDirectory: directory, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + statePath: join(directory, "state.json"), + version: "1.0.0-e2e", + }); + daemons.push(gateway); + return { gateway, port }; + } + + async function startWorker( + fleet: { readonly gateway: DaemonServer; readonly port: number }, + options: { + readonly label: string; + readonly capability: CapabilityState; + readonly model?: string; + readonly maxRunning?: number; + }, + ): Promise { + const token = ( + await fleet.gateway.dispatch("token.create", { label: options.label, role: "worker" }, admin) + ).secret; + const directory = await mkdtemp(join(tmpdir(), `simlock-e2e-requires-${options.label}-`)); + directories.push(directory); + const fake = new FakeAgentDevice(); + if (options.capability === "unavailable") fake.setUnavailable("down"); + const daemon = await startDaemon({ + agentDeviceUpstream: fake, + configOverrides: { + agentDevice: { enabled: options.capability !== "off" }, + capacity: { config: { maxRunning: options.maxRunning ?? 2 }, strategy: "fixed" }, + gateway: { + label: options.label, + token, + url: `ws://127.0.0.1:${String(fleet.port)}`, + }, + }, + dataDirectory: directory, + drivers: [ + new FakeDriver({ + availableOsVersions: ["18.0"], + clock: new SystemClock(), + knownModels: [options.model ?? "Pixel-A"], + platform: "android", + }), + ], + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + statePath: join(directory, "state.json"), + version: "1.0.0-e2e", + } as Parameters[0]); + daemons.push(daemon); + return { daemon, fake, label: options.label }; + } + + async function viewOf(gateway: DaemonServer, label: string) { + const { workers } = await gateway.dispatch("worker.list", {}, admin); + return workers.find((worker) => worker.label === label); + } + + async function untilRead(gateway: DaemonServer, member: Member, model = "Pixel-A") { + await vi.waitFor( + async () => { + const view = await viewOf(gateway, member.label); + expect(view?.connection).toBe("connected"); + expect(view?.capacity).toBeDefined(); + expect(view?.capabilities).toBeDefined(); + expect(view?.catalog?.some((entry) => entry.models.includes(model))).toBe(true); + }, + { timeout: 10_000 }, + ); + } + + async function turn(gateway: DaemonServer, member: Member, state: "available" | "unavailable") { + member.fake.setUnavailable(state === "available" ? undefined : "down"); + await vi.waitFor( + async () => { + // why: a refused request is a lease event on the worker, which makes the gateway read it again. + await member.daemon + .dispatch( + "lease.request", + { model: "Nope", noWait: true, platform: "android" }, + agent("poke"), + ) + .catch(() => undefined); + const view = await viewOf(gateway, member.label); + expect(view?.capabilities?.[0]?.state).toBe(state); + }, + { timeout: 10_000 }, + ); + } + + async function byId(gateway: DaemonServer, first: Member, second: Member) { + const [one, two] = await Promise.all([ + viewOf(gateway, first.label), + viewOf(gateway, second.label), + ]); + return (one?.id ?? "") < (two?.id ?? "") ? [first, second] : [second, first]; + } + + const lease = (gateway: DaemonServer, principal: string, extra: Record = {}) => + gateway.dispatch( + "lease.request", + { model: "Pixel-A", platform: "android", requires: ["agent-device"], ...extra }, + agent(principal), + ); + + const settle = (promise: Promise) => { + const outcome: { settled: boolean } = { settled: false }; + void promise.then( + () => { + outcome.settled = true; + }, + () => { + outcome.settled = true; + }, + ); + return outcome; + }; + + const settledWithin = async (outcome: { settled: boolean }, timeout = 5_000) => + vi.waitFor(() => expect(outcome.settled).toBe(true), { timeout }); + + const rejectedEvents = async (gateway: DaemonServer) => + (await gateway.dispatch("events.replay", {}, admin)).filter( + (entry: { event: string }) => entry.event === "lease.rejected", + ) as Array<{ payload: { reason: string } }>; + + it("through the gateway, a request with requires: [agent-device] is granted on the worker that has it available, never on the one without, over 10 requests", async () => { + const fleet = await startGateway(); + const alpha = await startWorker(fleet, { capability: "available", label: "worker-a" }); + const beta = await startWorker(fleet, { capability: "available", label: "worker-b" }); + await untilRead(fleet.gateway, alpha); + await untilRead(fleet.gateway, beta); + const [lower, higher] = await byId(fleet.gateway, alpha, beta); + await turn(fleet.gateway, lower!, "unavailable"); + + const labels: string[] = []; + for (let index = 0; index < 10; index += 1) { + const grant = await lease(fleet.gateway, `agent-${String(index)}`); + labels.push(grant.lease.worker?.label ?? "none"); + await fleet.gateway.dispatch( + "lease.release", + { leaseId: grant.lease.id }, + agent(`agent-${String(index)}`), + ); + } + + expect(labels).toEqual(Array.from({ length: 10 }, () => higher!.label)); + }, 60_000); + + it("through the gateway, when the only capable worker's matching devices are all leased, the request waits and is granted there once one is released", async () => { + const fleet = await startGateway(); + const capable = await startWorker(fleet, { + capability: "available", + label: "worker-a", + maxRunning: 1, + }); + const lacking = await startWorker(fleet, { capability: "off", label: "worker-b" }); + await untilRead(fleet.gateway, capable); + await untilRead(fleet.gateway, lacking); + const holder = await lease(fleet.gateway, "holder"); + expect(holder.lease.worker?.label).toBe("worker-a"); + + const waiting = lease(fleet.gateway, "waiter"); + const outcome = settle(waiting); + await vi.waitFor( + async () => { + expect((await fleet.gateway.dispatch("status.get", {}, admin)).waiting).toHaveLength(1); + }, + { timeout: 5_000 }, + ); + expect(outcome.settled).toBe(false); + await fleet.gateway.dispatch("lease.release", { leaseId: holder.lease.id }, agent("holder")); + + await settledWithin(outcome); + expect((await waiting).lease.worker?.label).toBe("worker-a"); + }, 60_000); + + it("through the gateway, with no worker listing it available, the request fails at once with CAPABILITY_MISSING, message `No worker connected to this gateway can serve agent-device for this request`, details.capabilities [agent-device], and lease.rejected carries reason unresolvable-spec", async () => { + const fleet = await startGateway(); + const off = await startWorker(fleet, { capability: "off", label: "worker-a" }); + await untilRead(fleet.gateway, off); + + await expect(lease(fleet.gateway, "agent-1")).rejects.toMatchObject({ + code: "CAPABILITY_MISSING", + details: { capabilities: ["agent-device"] }, + message: MISSING_MESSAGE, + }); + + expect((await rejectedEvents(fleet.gateway)).map((event) => event.payload.reason)).toEqual([ + "unresolvable-spec", + ]); + }, 60_000); + + it("through the gateway, when only a worker without the capability knows the model, the request fails at once with CAPABILITY_MISSING", async () => { + const fleet = await startGateway(); + const capable = await startWorker(fleet, { + capability: "available", + label: "worker-a", + model: "Pixel-A", + }); + const lacking = await startWorker(fleet, { + capability: "off", + label: "worker-b", + model: "Pixel-B", + }); + await untilRead(fleet.gateway, capable); + await untilRead(fleet.gateway, lacking, "Pixel-B"); + + await expect(lease(fleet.gateway, "agent-1", { model: "Pixel-B" })).rejects.toMatchObject({ + code: "CAPABILITY_MISSING", + }); + }, 60_000); + + it("through the gateway, a request for an unknown model when no worker has the capability fails with UNKNOWN_MODEL, as today", async () => { + const fleet = await startGateway(); + const off = await startWorker(fleet, { capability: "off", label: "worker-a" }); + await untilRead(fleet.gateway, off); + + await expect(lease(fleet.gateway, "agent-1", { model: "Nope" })).rejects.toMatchObject({ + code: "UNKNOWN_MODEL", + }); + }, 60_000); + + it("through the gateway, with no connected worker at all, a request with requires fails with NO_CAPACITY, as today", async () => { + const fleet = await startGateway(); + + await expect(lease(fleet.gateway, "agent-1")).rejects.toMatchObject({ code: "NO_CAPACITY" }); + }, 60_000); + + it("through the gateway, a request waiting for the only capable worker fails with CAPABILITY_MISSING at the next pass after that worker's view says unavailable", async () => { + const fleet = await startGateway(); + const capable = await startWorker(fleet, { + capability: "available", + label: "worker-a", + maxRunning: 1, + }); + await untilRead(fleet.gateway, capable); + const holder = await lease(fleet.gateway, "holder"); + const waiting = lease(fleet.gateway, "waiter"); + const outcome = settle(waiting); + await vi.waitFor( + async () => { + expect((await fleet.gateway.dispatch("status.get", {}, admin)).waiting).toHaveLength(1); + }, + { timeout: 5_000 }, + ); + expect(outcome.settled).toBe(false); + + await turn(fleet.gateway, capable, "unavailable"); + + await settledWithin(outcome); + await expect(waiting).rejects.toMatchObject({ + code: "CAPABILITY_MISSING", + message: MISSING_MESSAGE, + }); + await fleet.gateway.dispatch("lease.release", { leaseId: holder.lease.id }, agent("holder")); + }, 60_000); + + it("through the gateway, a request waiting for a busy capable worker is granted on a second worker once that worker's capability turns available and it has a free device", async () => { + const fleet = await startGateway(); + const busy = await startWorker(fleet, { + capability: "available", + label: "worker-a", + maxRunning: 1, + }); + const second = await startWorker(fleet, { capability: "unavailable", label: "worker-b" }); + await untilRead(fleet.gateway, busy); + await untilRead(fleet.gateway, second); + await lease(fleet.gateway, "holder"); + const waiting = lease(fleet.gateway, "waiter"); + const outcome = settle(waiting); + await vi.waitFor( + async () => { + expect((await fleet.gateway.dispatch("status.get", {}, admin)).waiting).toHaveLength(1); + }, + { timeout: 5_000 }, + ); + expect(outcome.settled).toBe(false); + + await turn(fleet.gateway, second, "available"); + + await settledWithin(outcome); + expect((await waiting).lease.worker?.label).toBe("worker-b"); + }, 60_000); + + it("through the gateway, a worker whose view says available but whose own check answers CAPABILITY_MISSING is skipped, and the request is granted on the next capable worker; with no next worker, the caller gets that CAPABILITY_MISSING", async () => { + const fleet = await startGateway(); + const alpha = await startWorker(fleet, { capability: "available", label: "worker-a" }); + const beta = await startWorker(fleet, { capability: "available", label: "worker-b" }); + await untilRead(fleet.gateway, alpha); + await untilRead(fleet.gateway, beta); + const [lower, higher] = await byId(fleet.gateway, alpha, beta); + // why: nothing makes the gateway read the worker again before the request, so its view still says available. + lower!.fake.setUnavailable("down"); + + const grant = await lease(fleet.gateway, "agent-1"); + expect(grant.lease.worker?.label).toBe(higher!.label); + await fleet.gateway.dispatch("lease.release", { leaseId: grant.lease.id }, agent("agent-1")); + + higher!.fake.setUnavailable("down"); + await expect(lease(fleet.gateway, "agent-2")).rejects.toMatchObject({ + code: "CAPABILITY_MISSING", + message: "This worker cannot serve agent-device", + }); + }, 60_000); + + it("through the gateway, requires: [agent-device, x-other] when no worker lists x-other fails with details.capabilities [agent-device, x-other] and a message naming agent-device, x-other", async () => { + const fleet = await startGateway(); + const capable = await startWorker(fleet, { capability: "available", label: "worker-a" }); + await untilRead(fleet.gateway, capable); + const grant = await lease(fleet.gateway, "agent-0"); + await fleet.gateway.dispatch("lease.release", { leaseId: grant.lease.id }, agent("agent-0")); + + await expect( + lease(fleet.gateway, "agent-1", { requires: ["agent-device", "x-other"] }), + ).rejects.toMatchObject({ + code: "CAPABILITY_MISSING", + details: { capabilities: ["agent-device", "x-other"] }, + message: expect.stringContaining("agent-device, x-other"), + }); + }, 60_000); + + it.each([ + ["absent", {}], + ["[]", { requires: [] }], + ])( + "through the gateway, a request with requires %s is routed as today and its lease.requested requestSpec has no requires", + async (_label, extra) => { + const fleet = await startGateway(); + const off = await startWorker(fleet, { capability: "off", label: "worker-a" }); + await untilRead(fleet.gateway, off); + + const grant = await fleet.gateway.dispatch( + "lease.request", + { model: "Pixel-A", platform: "android", ...extra }, + agent("agent-1"), + ); + + expect(grant.lease.worker?.label).toBe("worker-a"); + const requested = (await fleet.gateway.dispatch("events.replay", {}, admin)).find( + (entry: { event: string }) => entry.event === "lease.requested", + ) as { payload: { requestSpec: unknown } }; + expect(requested.payload.requestSpec).toEqual({ model: "Pixel-A", platform: "android" }); + }, + 60_000, + ); +}); diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index fd39750bb..78d3616ca 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -3485,6 +3485,100 @@ describe("FleetLeaseCoordinator routes a class or range request (ADR 0015 §8)", }); }); +describe("FleetLeaseCoordinator: requires", () => { + const available = [{ name: "agent-device", state: "available" }] as const; + const off = [{ name: "agent-device", state: "off" }] as const; + const missing = () => + fromWireError("CAPABILITY_MISSING", "This worker cannot serve agent-device", { + capabilities: ["agent-device"], + }); + + it("sends requires to the worker on every dispatch, beside the request and not inside it", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + workers.refresh("wrk_a", { capabilities: [...available] }); + + await coordinator.request(REQUEST, requestOptions({ requires: ["agent-device"] })); + + expect(client.lastRequestLeaseInput).toMatchObject({ requires: ["agent-device"] }); + }); + + it("leaves a worker whose own check answers CAPABILITY_MISSING out for this request and tries the next, and gives the caller that error when no worker is left", async () => { + const { coordinator, directory, workers } = harness(); + const stale = new ScriptedWorkerClient(); + const next = new ScriptedWorkerClient(); + stale.requestLeaseQueue.push({ error: missing(), kind: "error" }); + next.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + directory.add("wrk_a", stale); + directory.add("wrk_b", next); + for (const id of ["wrk_a", "wrk_b"]) { + connectWorker(workers, id); + workers.refresh(id, { capabilities: [...available] }); + } + + await expect( + coordinator.request(REQUEST, requestOptions({ requires: ["agent-device"] })), + ).resolves.toMatchObject({ lease: { worker: { id: "wrk_b" } } }); + expect(stale.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + + stale.requestLeaseQueue.push({ error: missing(), kind: "error" }); + next.requestLeaseQueue.push({ error: missing(), kind: "error" }); + await expect( + coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-2", requesterId: "agent-2", requires: ["agent-device"] }), + ), + ).rejects.toMatchObject({ + code: "CAPABILITY_MISSING", + message: "This worker cannot serve agent-device", + }); + }); + + it("fails a request waiting only on the capable worker with CAPABILITY_MISSING when that worker's view turns starting", async () => { + const { coordinator, directory, workers } = harness(); + directory.add("wrk_a", new ScriptedWorkerClient()); + connectWorker(workers, "wrk_a", { capacity: saturatedIos() }); + workers.refresh("wrk_a", { capabilities: [...available] }); + const waiting = coordinator.request(REQUEST, requestOptions({ requires: ["agent-device"] })); + const outcome = { settled: false }; + waiting.then( + () => (outcome.settled = true), + () => (outcome.settled = true), + ); + await tick(); + expect(coordinator.queueDepth).toBe(1); + expect(outcome.settled).toBe(false); + + workers.refresh("wrk_a", { health: "starting", host: hostFixture() }); + await tick(); + + expect(outcome.settled).toBe(true); + await expect(waiting).rejects.toMatchObject({ code: "CAPABILITY_MISSING" }); + }); + + it("keeps a request with requires waiting for a busy capable worker while a free worker lists the capability off", async () => { + const { coordinator, directory, workers } = harness(); + directory.add("wrk_a", new ScriptedWorkerClient()); + const free = new ScriptedWorkerClient(); + directory.add("wrk_b", free); + connectWorker(workers, "wrk_a", { capacity: saturatedIos() }); + workers.refresh("wrk_a", { capabilities: [...available] }); + connectWorker(workers, "wrk_b"); + workers.refresh("wrk_b", { capabilities: [...off] }); + + void coordinator + .request(REQUEST, requestOptions({ requires: ["agent-device"] })) + .catch(() => undefined); + await tick(); + + expect(coordinator.queueDepth).toBe(1); + expect(free.calls.filter((call) => call.startsWith("lease.request"))).toEqual([]); + }); +}); + describe("FleetLeaseCoordinator: a worker that is still starting", () => { const gatewayLease = { deviceId: "dev_1", diff --git a/src/gateway/routing/pipeline.ts b/src/gateway/routing/pipeline.ts index 9f19de986..9c8e3bb5a 100644 --- a/src/gateway/routing/pipeline.ts +++ b/src/gateway/routing/pipeline.ts @@ -10,6 +10,7 @@ export interface RoutableRequest { readonly imageTag?: string; readonly mode?: "slim" | "full"; readonly physical?: boolean; + readonly requires?: readonly string[]; } export interface FilterStage { diff --git a/src/gateway/routing/serviceability.test.ts b/src/gateway/routing/serviceability.test.ts index 8dd3864a6..10a3ef59f 100644 --- a/src/gateway/routing/serviceability.test.ts +++ b/src/gateway/routing/serviceability.test.ts @@ -367,3 +367,77 @@ describe("assess for a physical request", () => { expect(rejectionOf(views, PHYSICAL).code).toBe("UNKNOWN_MODEL"); }); }); + +describe("assess with requires", () => { + const AGENT_DEVICE = { ...REQUEST, requires: ["agent-device"] }; + const available = [{ name: "agent-device", state: "available" }] as const; + const off = [{ name: "agent-device", state: "off" }] as const; + const message = "No worker connected to this gateway can serve agent-device for this request"; + + it("routes or waits when a worker that can serve the request lists every required name as available", () => { + const views = [ + view("wrk_a", IOS, { capabilities: [...off] }), + view("wrk_b", IOS, { capabilities: [...available] }), + ]; + + expect(assess(AGENT_DEVICE, views).kind).toBe("route-or-wait"); + expect( + assess({ ...AGENT_DEVICE, requires: [] }, [view("wrk_a", IOS, { capabilities: [...off] })]) + .kind, + ).toBe("route-or-wait"); + }); + + it("answers CAPABILITY_MISSING, reason unresolvable-spec, naming the required names in the order requested, when no worker that can serve the request has them available", () => { + const views = [view("wrk_a", IOS, { capabilities: [...off] })]; + + expect(rejectionOf(views, AGENT_DEVICE)).toMatchObject({ + code: "CAPABILITY_MISSING", + details: { capabilities: ["agent-device"] }, + message, + reason: "unresolvable-spec", + }); + expect( + rejectionOf(views, { ...AGENT_DEVICE, requires: ["agent-device", "x-other"] }), + ).toMatchObject({ + code: "CAPABILITY_MISSING", + details: { capabilities: ["agent-device", "x-other"] }, + message: expect.stringContaining("agent-device, x-other"), + }); + }); + + it("answers CAPABILITY_MISSING when only a worker without the capability lists the model", () => { + const views = [ + view( + "wrk_a", + { models: ["iPhone 16"], platform: "ios", runtimes: ["26.0"] }, + { capabilities: [...available] }, + ), + view("wrk_b", IOS, { capabilities: [...off] }), + ]; + + expect(rejectionOf(views, AGENT_DEVICE)).toMatchObject({ code: "CAPABILITY_MISSING" }); + }); + + it("keeps the first table's rejection when it rejects: UNKNOWN_MODEL and NO_CAPACITY stand", () => { + const unknown = { ...AGENT_DEVICE, model: "iPhone 99" }; + + expect(rejectionOf([view("wrk_a", IOS, { capabilities: [...off] })], unknown)).toMatchObject({ + code: "UNKNOWN_MODEL", + }); + expect(rejectionOf([], AGENT_DEVICE)).toMatchObject({ + code: "NO_CAPACITY", + reason: "no-worker", + }); + }); + + it("answers CAPABILITY_MISSING for a request waiting only on a capable worker once that worker's view is starting, because a starting view has no capability list", () => { + const running = view("wrk_a", IOS, { capabilities: [...available], health: "running" }); + const { capabilities: _dropped, ...restarted } = { ...running, health: "starting" as const }; + + expect(assess(AGENT_DEVICE, [running]).kind).toBe("route-or-wait"); + expect(rejectionOf([restarted as WorkerView], AGENT_DEVICE)).toMatchObject({ + code: "CAPABILITY_MISSING", + reason: "unresolvable-spec", + }); + }); +}); diff --git a/src/gateway/routing/stages/has-capabilities.test.ts b/src/gateway/routing/stages/has-capabilities.test.ts new file mode 100644 index 000000000..5c8100ec8 --- /dev/null +++ b/src/gateway/routing/stages/has-capabilities.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "vitest"; + +import { createRoutingPolicy } from "../../routing.js"; +import { catalogFixture, physicalDeviceFixture, statusFixture } from "../../test-support.js"; +import type { WorkerView } from "../../worker-registry.js"; +import { hasCapabilities } from "./has-capabilities.js"; + +type Capabilities = NonNullable; + +function view( + id: string, + capabilities: Capabilities | undefined, + overrides: Partial = {}, +): WorkerView { + return { + capacity: statusFixture().capacity, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + catalogReadAt: 1, + ...(capabilities === undefined ? {} : { capabilities }), + connection: "connected", + devices: [], + drained: false, + health: "running", + id, + lastSeenAt: 1, + leases: [], + queueDepth: 0, + ...overrides, + } as WorkerView; +} + +const REQUEST = { model: "iPhone 17", platform: "ios" as const }; +const REQUIRES_AGENT_DEVICE = { ...REQUEST, requires: ["agent-device"] }; + +describe("has-capabilities", () => { + const policy = createRoutingPolicy("warm-then-free"); + + it("keeps a worker listing every required name as available, drops one listing it unavailable, off or not at all, keeps every worker when requires is empty, and applies to physical requests", () => { + const available = view("wrk_a", [{ name: "agent-device", state: "available" }]); + const unavailable = view("wrk_b", [ + { name: "agent-device", reason: "starting", state: "unavailable" }, + ]); + const off = view("wrk_c", [{ name: "agent-device", state: "off" }]); + const absent = view("wrk_d", [{ name: "x-other", state: "available" }]); + const unread = view("wrk_e", undefined); + const partly = view("wrk_f", [ + { name: "agent-device", state: "available" }, + { name: "x-other", state: "off" }, + ]); + + expect(hasCapabilities.keeps(available, REQUIRES_AGENT_DEVICE)).toBe(true); + for (const lacking of [unavailable, off, absent, unread]) { + expect(hasCapabilities.keeps(lacking, REQUIRES_AGENT_DEVICE)).toBe(false); + } + expect(hasCapabilities.keeps(partly, { ...REQUEST, requires: ["agent-device"] })).toBe(true); + expect( + hasCapabilities.keeps(partly, { ...REQUEST, requires: ["agent-device", "x-other"] }), + ).toBe(false); + for (const worker of [available, unavailable, off, absent, unread]) { + expect(hasCapabilities.keeps(worker, { ...REQUEST, requires: [] })).toBe(true); + expect(hasCapabilities.keeps(worker, REQUEST)).toBe(true); + } + expect(hasCapabilities.appliesToPhysical).toBe(true); + }); + + it("is a stage of warm-then-free that runs for a virtual request: the capable worker is picked over a lower-id worker without the capability", () => { + const lacking = view("wrk_a", [{ name: "agent-device", state: "off" }]); + const capable = view("wrk_b", [{ name: "agent-device", state: "available" }]); + + expect(policy.select(REQUEST, [lacking, capable])).toMatchObject({ workerId: "wrk_a" }); + expect(policy.select(REQUIRES_AGENT_DEVICE, [lacking, capable])).toMatchObject({ + workerId: "wrk_b", + }); + expect(policy.select(REQUIRES_AGENT_DEVICE, [lacking])).toBeUndefined(); + }); + + it("a physical request with requires is routed only to a capable worker", () => { + const physical = { model: "iPhone 17", physical: true as const, platform: "ios" as const }; + const devices = [physicalDeviceFixture("dev_p", "ready", { model: "iPhone 17" })]; + const lacking = view("wrk_a", [{ name: "agent-device", state: "unavailable", reason: "x" }], { + devices, + }); + const capable = view("wrk_b", [{ name: "agent-device", state: "available" }], { devices }); + + expect(policy.select(physical, [lacking, capable])).toMatchObject({ workerId: "wrk_a" }); + expect( + policy.select({ ...physical, requires: ["agent-device"] }, [lacking, capable]), + ).toMatchObject({ workerId: "wrk_b" }); + expect(policy.select({ ...physical, requires: ["agent-device"] }, [lacking])).toBeUndefined(); + }); +}); diff --git a/src/gateway/routing/stages/has-capabilities.ts b/src/gateway/routing/stages/has-capabilities.ts new file mode 100644 index 000000000..9338d1796 --- /dev/null +++ b/src/gateway/routing/stages/has-capabilities.ts @@ -0,0 +1,9 @@ +import type { FilterStage } from "../pipeline.js"; + +export const hasCapabilities: FilterStage = { + keeps() { + return true; + }, + appliesToPhysical: true, + kind: "filter", +}; diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index d1839a42c..5f76cce39 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -28,6 +28,7 @@ export type WorkerView = z.infer; * state, connection state -- is this registry's own bookkeeping, never a worker's to report. */ export type WorkerViewSnapshot = Pick< WorkerView, + | "capabilities" | "capacity" | "catalog" | "devices" diff --git a/src/leasing/wait-queue.ts b/src/leasing/wait-queue.ts index 5a732ffd9..f8d52ba5a 100644 --- a/src/leasing/wait-queue.ts +++ b/src/leasing/wait-queue.ts @@ -11,6 +11,7 @@ export interface LeaseRequestOptions { readonly timeoutMs?: number; readonly noWait?: boolean; readonly allowDownload?: boolean; + readonly requires?: readonly string[]; readonly onProgress?: (progress: LeaseProgress) => void; /** ADR 0004 §4: this lease's initial TTL, accepted on every request. Omitted means * `lease.defaultTtlMs`; the cap against `lease.maxTtlMs` is applied at the daemon boundary diff --git a/src/mcp/contracts.test.ts b/src/mcp/contracts.test.ts index 3f9bd75f2..f4b0385b0 100644 --- a/src/mcp/contracts.test.ts +++ b/src/mcp/contracts.test.ts @@ -116,3 +116,17 @@ describe("MCP contracts", () => { expect(leaseStatusOutputSchema.parse({ held: false })).toEqual({ held: false }); }); }); + +describe("MCP contracts: requires", () => { + it("rejects requires -- the MCP lease tool has no capability parameter, and the contract's field list has it", () => { + expect(Object.keys(leaseRequestFields.shape)).toContain("requires"); + expect(Object.keys(leaseSimulatorInputSchema.shape)).not.toContain("requires"); + expect( + leaseSimulatorInputSchema.safeParse({ + model: "iPhone 17 Pro", + platform: "ios", + requires: ["agent-device"], + }).success, + ).toBe(false); + }); +}); diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index e876a1999..0f9b1c84b 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -159,6 +159,19 @@ describe("MCP server (smoke)", () => { } }); + it("the lease tool's input schema in tools/list has no requires", async () => { + const { mcpClient, close } = await connectedServer(new FakeSimlockClient()); + try { + const tools = await mcpClient.request({ method: "tools/list" }, ListToolsResultSchema); + const leaseTool = tools.tools.find((tool) => tool.name === "lease_simulator"); + + expect(Object.keys(leaseTool?.inputSchema.properties ?? {})).toContain("noWait"); + expect(Object.keys(leaseTool?.inputSchema.properties ?? {})).not.toContain("requires"); + } finally { + await close(); + } + }); + it("the lease tool's input schema in tools/list lists physical", async () => { const { mcpClient, close } = await connectedServer(new FakeSimlockClient()); try { diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index 6a0007573..c09c78534 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -1107,6 +1107,34 @@ describe("requestLease abort: ADR §4 identity cases (B3)", () => { }); }); +describe("requestLease requires", () => { + it("sends requires on the lease.request frame and rejects with CAPABILITY_MISSING, its details naming the capabilities, when the worker lacks the capability", async () => { + const connection = new ScriptedConnection(); + const connectPromise = connectSimlock({ connection }); + await flushMicrotasks(); + completeHello(connection); + const client = await connectPromise; + + const pending = client.requestLease({ + model: "iPhone 17", + platform: "ios", + requires: ["agent-device"], + }); + await flushMicrotasks(); + const call = connection.lastSentOf("lease.request")!; + connection.fail(call.id, "CAPABILITY_MISSING", "This worker cannot serve agent-device", { + capabilities: ["agent-device"], + }); + + expect(call.payload).toMatchObject({ requires: ["agent-device"] }); + await expect(pending).rejects.toMatchObject({ + code: "CAPABILITY_MISSING", + details: { capabilities: ["agent-device"] }, + kind: "domain", + }); + }); +}); + describe("simlock/admin", () => { it("exposes the admin operations and sends daemon.stop like any other request", async () => { const connection = new ScriptedConnection(); From 70f3f705f625f06b50f336c4a919cde16e3eac55 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 21:01:12 +0200 Subject: [PATCH 2/5] feat: a lease request may require a capability (#513) Spec tests: 25 failing -> 0 failing. Adds requires to lease.request, the CAPABILITY_MISSING code, the has-capabilities stage, the second fast-fail run, the worker check, and bumps the protocol to 34. --- docs/CLI.md | 2 + docs/CLIENT.md | 11 ++++++ docs/EVENTS.md | 2 +- docs/HTTP-API.md | 3 +- docs/internal/EVENTS.md | 2 +- src/contract/errors.ts | 8 ++++ src/contract/operations.ts | 26 ++++++++++++- src/contract/protocol.ts | 2 +- src/contract/schemas.ts | 1 - src/daemon-protocol/index.test.ts | 2 +- src/daemon/dispatcher.ts | 20 ++++++++++ src/daemon/server.test.ts | 4 +- src/gateway/dispatcher.ts | 1 + src/gateway/fleet-coordinator.ts | 5 +++ src/gateway/routing.ts | 2 + src/gateway/routing/index.ts | 1 + src/gateway/routing/serviceability.ts | 39 +++++++++++++++---- .../routing/stages/has-capabilities.ts | 14 ++++++- src/gateway/service.test.ts | 2 +- src/mcp/contracts.test.ts | 4 +- src/mcp/contracts.ts | 3 +- 21 files changed, 130 insertions(+), 24 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 88fb6ef7b..6ad6203ed 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -96,6 +96,7 @@ command starts it again) to bring the platform up. | 11 | `DEVICE_BUSY` | `device add` or `device remove` of a device that is leased, being reclaimed or held by another operation, such as another `device add`; try again once that ends | | 11 | `COMPONENT_BUSY` | `component remove` while a component install or removal runs or waits on that platform; try again once it ends | | 12 | `NO_DRIVER` | no driver registered for the requested platform | +| 12 | `CAPABILITY_MISSING` | through a gateway, no worker that could serve the request has every capability it requires available; direct to a worker, that worker lacks one (a request names capabilities only through the programmatic client) | | 12 | `RUNTIME_MISSING` | runtime not installed and no `--allow-download`, or no installed image of the `--image-tag` asked for | | 12 | `UNKNOWN_MODEL` | unknown device model for the platform | | 12 | `INSUFFICIENT_DISK_SPACE` | not enough free disk space to install a component | @@ -947,6 +948,7 @@ catalog has not arrived, is neither. | ... and no known worker lists the model, or, for a class, a model of it | `UNKNOWN_MODEL` (exit 12) at once | | ... and no known worker has the runtime, or can pair it with the model (or with a model of the class) | `RUNTIME_MISSING` (exit 12) at once; `downloadable` is `false`, and `osVersion` is the range as you typed it, or `default` when you named none | | A known worker could serve it, but none that takes requests can | `NO_CAPACITY` (exit 11) at once | +| The request requires capabilities (programmatic client only), and no connected worker that could serve it has all of them available | `CAPABILITY_MISSING` (exit 12) at once; `capabilities` names the required ones | | A worker that takes requests can serve it but is busy | Waits in the queue; `NO_CAPACITY` only with `--no-wait` | "At once" holds with and without `--no-wait` and `--timeout`, and the same diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 7520a7956..0f49aeb71 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -177,6 +177,17 @@ code, not something this client does for you. There is no heartbeat to declare and no connection-liveness mode to opt into: a renew arriving before the deadline is the whole mechanism. +**Requiring a capability.** `requestLease` also takes `requires`: up to 8 +lowercase capability names, none twice, such as `["agent-device"]`. Simlock +places the lease only on a worker whose status lists every one of them as +`available`. Through a gateway, a request that no connected worker able to +serve it can take fails at once with `CAPABILITY_MISSING`, and so does one +already waiting when the last such worker loses the capability, restarts, or +goes. Direct to a worker that lacks one it fails the same way. The error's +`details.capabilities` names the missing capabilities. `requires` cannot be +combined with `idempotencyKey` (`BAD_REQUEST`). The CLI, the MCP tool and the +HTTP lease body do not take it. + **Getting an answer back after a disconnect.** Pass `idempotencyKey` to make a request repeatable: diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 5d31de8a3..9ecd50940 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -15,7 +15,7 @@ through `simlock events` and `simlock events --follow`. | `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented | | `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock, or a daemon start found its device not running, or (device-lost) a physical device was not present for the grace period (`health.stableObservations` reads in a row, `health.probeIntervalMs` apart; the device becomes `absent` and nothing is wiped), and the device of that lease was wiped and returned to the pool, left waiting in `reclaiming` on a platform the daemon could not list, or marked missing. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented | | `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented | -| `lease.rejected` | request id, requester, request spec (as on `lease.requested`: a request that named a class or nothing has no model, and one that named an OS range carries it as typed), reason (timeout/no-wait/unresolvable-spec/no-worker/already-leased/lease-id-taken/boot-timeout/killed/cancelled/daemon-restarted/worker-failed), and for `worker-failed` also `code` and `worker` | a request ended without a grant. A worker emits it only for its own, local requests: a request a gateway sent it ends in `lease.declined` there instead. `already-leased` means the requester already has a waiting request, or already holds `lease.maxPerRequester` leases. A worker declines a gateway's request (`lease.declined`) as `already-leased` only for a waiting request, never for a lease it holds. A request refused before it was stored (`killed`, `already-leased`, `lease-id-taken`) emits no `lease.requested`, and its `lease.rejected` carries the id it would have been stored under (on a gateway, `lease-id-taken` can also end a request that was stored, when a worker's grant carries an ID the gateway already routes elsewhere: that one has its `lease.requested`); on a gateway, `no-worker` is a request no worker that takes requests can serve, `NO_CAPACITY` at once, and `unresolvable-spec` is one no known worker has the platform, model, or runtime for (for a physical request, an enrolled device that fits it), and such a request emits no `lease.queued`. A request a worker refused as unable to serve (`RUNTIME_MISSING`, `UNKNOWN_MODEL`, `NO_DRIVER`) while another worker was busy waits in the gateway queue, unless it is a `noWait` request, which is rejected at once with reason `no-wait` and emits no `lease.queued`; a request that finds no worker left emits `unresolvable-spec`, after its `lease.queued` when it had queued; `worker-failed` is a request that failed on the worker it went to (a refusal that is final, a failure after the worker began work, an unreachable worker, or a dispatch that timed out), with `code` the error code the caller got and `worker` the worker's id; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again. The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter — one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses; a physical request has no such work, only a presence read, so it is cancelled in any state | LeaseAcquisitionCoordinator / WaitQueue / LeaseStartup (worker) / FleetLeaseCoordinator (gateway) | implemented | +| `lease.rejected` | request id, requester, request spec (as on `lease.requested`: a request that named a class or nothing has no model, and one that named an OS range carries it as typed), reason (timeout/no-wait/unresolvable-spec/no-worker/already-leased/lease-id-taken/boot-timeout/killed/cancelled/daemon-restarted/worker-failed), and for `worker-failed` also `code` and `worker` | a request ended without a grant. A worker emits it only for its own, local requests: a request a gateway sent it ends in `lease.declined` there instead. `already-leased` means the requester already has a waiting request, or already holds `lease.maxPerRequester` leases. A worker declines a gateway's request (`lease.declined`) as `already-leased` only for a waiting request, never for a lease it holds. A request refused before it was stored (`killed`, `already-leased`, `lease-id-taken`) emits no `lease.requested`, and its `lease.rejected` carries the id it would have been stored under (on a gateway, `lease-id-taken` can also end a request that was stored, when a worker's grant carries an ID the gateway already routes elsewhere: that one has its `lease.requested`); on a gateway, `no-worker` is a request no worker that takes requests can serve, `NO_CAPACITY` at once, and `unresolvable-spec` is one no known worker has the platform, model, or runtime for (for a physical request, an enrolled device that fits it), or one that requires capabilities (`CAPABILITY_MISSING`) no connected worker able to serve it has available, and such a request emits no `lease.queued`. A request a worker refused as unable to serve (`RUNTIME_MISSING`, `UNKNOWN_MODEL`, `NO_DRIVER`, `CAPABILITY_MISSING`) while another worker was busy waits in the gateway queue, unless it is a `noWait` request, which is rejected at once with reason `no-wait` and emits no `lease.queued`; a request that finds no worker left emits `unresolvable-spec`, after its `lease.queued` when it had queued; `worker-failed` is a request that failed on the worker it went to (a refusal that is final, a failure after the worker began work, an unreachable worker, or a dispatch that timed out), with `code` the error code the caller got and `worker` the worker's id; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again. The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter — one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses; a physical request has no such work, only a presence read, so it is cancelled in any state | LeaseAcquisitionCoordinator / WaitQueue / LeaseStartup (worker) / FleetLeaseCoordinator (gateway) | implemented | | `lease.declined` | request id, gateway request id (`fleetRequestId`), requester, request spec (as on `lease.rejected`), reason (the values of `lease.rejected`) | a worker refused or failed a request a gateway sent it, for any reason and however far the work got. The gateway owns that request's outcome and may try another worker, so the worker declines rather than rejects, and never queues such a request. A worker that was asked and has no room declines with `no-wait`; one that cannot serve the request, or fails it, declines with the reason it would have rejected a local request with. A request still open when the worker stopped is declined with `daemon-restarted` at the next start | LeaseAcquisitionCoordinator / WaitQueue / LeaseStartup (worker) | implemented | On a **gateway**, `lease.requested`, `lease.queued` and `lease.rejected` are its own fleet queue's facts, diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index da5e710ac..9e5b5f354 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -536,6 +536,7 @@ known and a reconnecting one stays known from its last catalog. | ... and no known worker lists the model | `422 UNKNOWN_MODEL` | | ... and no known worker has the runtime, or can pair it with the model | `422 RUNTIME_MISSING`, with `downloadable: false` and `osVersion: "default"` when `os` is absent | | A known worker could serve it, but none that takes requests can | `503 NO_CAPACITY` | +| The request requires capabilities (not a body field; the programmatic client sends it), and no connected worker that could serve it has all of them available | `422 CAPABILITY_MISSING`, with `capabilities` naming the required ones | | A worker that takes requests can serve it but is busy | queues; `503 NO_CAPACITY` only with `noWait: true` | A request that is already waiting is held to the same table: when the only @@ -1599,7 +1600,7 @@ Every failure is the same shape the daemon protocol uses: | 403 | `FORBIDDEN` (role doesn't permit the route — including a `worker` token on any `/v1` route other than `/v1/uplink`, and an `agent`/`operator` token at `/v1/uplink`; a `/v1/lease-requests/*` route whose request another token sent; or `POST /v1/leases/{id}/renew`/`DELETE /v1/leases/{id}`/`POST /v1/leases/{id}/exec` naming another requester's still-live lease), `DOWNLOADS_DISABLED` (`POST /v1/components/install` under `downloads.policy: "never"`) | | 404 | `UNKNOWN_WORKER` (`POST`/`DELETE /v1/workers/{id}/drain` naming a worker the gateway does not know), `UNKNOWN_LEASE_REQUEST` (unknown request id), `UNKNOWN_LEASE` (unknown lease id, expired/released, **or `GET /v1/leases/{id}`/`GET /v1/leases/{id}/events` naming another requester's lease** — see [`GET /v1/leases/{id}`](#get-v1leasesid)) , `UNKNOWN_DEVICE` (`DELETE /v1/devices/{id}` naming a device that is not enrolled) | | 409 | `REQUESTER_ALREADY_LEASED` (body names the existing lease id; fleet-wide on a gateway), `LEASE_ID_TAKEN` (a `leaseId` an active lease or a waiting request holds; body carries `leaseId`; on a gateway, one of the gateway's own leases or requests, or a worker that refused it), `IDEMPOTENCY_CONFLICT` (an `Idempotency-Key` repeated with a different device or `leaseId`), `REQUEST_NOT_CANCELLABLE` (body names the lease id if the request had already been granted), `WORKER_CONNECTED` (`DELETE /v1/workers/{id}` while its uplink is open), `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE` (body carries `devices` and `foreignDevices`), `COMPONENT_BUSY` (the three refusals of `DELETE /v1/components/{platform}/{version}`), `DEVICE_BUSY` (`POST /v1/devices`, `DELETE /v1/devices/{id}` of a leased, reclaiming or held device; body carries `id` and `reason`) | -| 422 | `UNKNOWN_MODEL`, `RUNTIME_MISSING`, `NO_DRIVER`, `DEVICE_NOT_ENROLLABLE` (`POST /v1/devices`; body carries `id`, `platform`, `reason`, and `canonicalId` when known), `PASSTHROUGH_REFUSED` (a refused `exec` verb or `devicectl` command, a caller-supplied `--set`/`-P`, a bare `adb shell`), `UNKNOWN_PASSTHROUGH_TOOL` | +| 422 | `UNKNOWN_MODEL`, `RUNTIME_MISSING`, `NO_DRIVER`, `CAPABILITY_MISSING` (a request required capabilities no worker able to serve it has available; body carries `capabilities`), `DEVICE_NOT_ENROLLABLE` (`POST /v1/devices`; body carries `id`, `platform`, `reason`, and `canonicalId` when known), `PASSTHROUGH_REFUSED` (a refused `exec` verb or `devicectl` command, a caller-supplied `--set`/`-P`, a bare `adb shell`), `UNKNOWN_PASSTHROUGH_TOOL` | | 501 | `UNSUPPORTED_IN_GATEWAY_MODE` (an operation that acts on one machine, asked of a gateway: `POST /v1/components/install`, `GET /v1/components`, `DELETE /v1/components/{platform}/{version}`, `POST /v1/devices`, `DELETE /v1/devices/{id}`), `UNSUPPORTED_IN_WORKER_MODE` (an operation on a gateway's workers, asked of a single host: `POST`/`DELETE /v1/workers/{id}/drain`, `DELETE /v1/workers/{id}`, `POST /v1/components/install` with `workers`) | | 503 | `NO_CAPACITY` (with `noWait: true`, or, on a gateway, when no worker that takes requests can serve the request; response carries `Retry-After`), `WORKER_UNREACHABLE` (a gateway could not reach the worker holding this lease or request) | | 504 | `EXEC_TIMEOUT` (a `device.exec` command outlived `exec.timeoutMs`), `DOWNLOAD_TIMEOUT` (a runtime download, waiting for another download included, outlived `downloads.timeoutMs`) | diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index d566be9b3..60679e593 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -52,7 +52,7 @@ in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. | `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock, or a daemon start found its device not running, or (device-lost, ADR 0022 §7) a physical device was not present for the grace period (`health.stableObservations` reads in a row, `health.probeIntervalMs` apart; emitted by the `PhysicalDeviceWatcher` through `LeaseReleaseCoordinator.endForAbsentDevice`; the device becomes `absent` in the same write and nothing is wiped), and the device of that lease was wiped and returned to the pool, left waiting in `reclaiming` on a platform the daemon could not list, or marked missing. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented (payload per ADR 0004 pending) | -| `lease.rejected` | request id, requester (both required on every reason, additive, ADR 0016 §2), request spec (as on `lease.requested`; `full` replaced by `mode`, ADR 0007 §13; `model` optional and `class` added, ADR 0015 §9; `osVersion` may be a range as typed, ADR 0015 §2), reason (timeout/no-wait/unresolvable-spec/no-worker/already-leased/lease-id-taken/boot-timeout/killed/cancelled/daemon-restarted/worker-failed), `code` and `worker` on `worker-failed` (ADR 0021 §4, additive; `worker`, never `workerId`, which marks a relayed event, ADR 0014 §6) | a request ended without a grant. A worker emits it only for its local requests; a probe ends in `lease.declined` there (ADR 0021 §2). A gateway emits it for every ending that is not a grant (ADR 0021 §4): its own reasons, `unresolvable-spec` for the last cannot-serve refusal whether or not the request had queued, and `worker-failed` for any other failure on the worker it went to -- a terminal refusal, a failure after progress, `WORKER_UNREACHABLE`, `INTERNAL`, a dispatch timeout, a worker's own `REQUESTER_ALREADY_LEASED` or `LEASE_ID_TAKEN` -- with `code` the error code the caller got and `worker` the worker. `dispose()` emits nothing, so a request still open when a gateway stops has no ending event (ADR 0021 §5 plans for usage to close those at the next `daemon.started`; not built yet). `already-leased` means the requester already has a waiting request, or already holds `lease.maxPerRequester` leases (ADR 0023); a worker skips the held-lease count for a probe, so it declines a probe `already-leased` only for a waiting one. A request refused at admission (`killed`, `already-leased`, `lease-id-taken`) was never stored and has no `lease.requested` (except a gateway's `lease-id-taken` after a grant, below); it carries the id minted for it before the check, the one the stored request would have had; on a gateway (ADR 0009 §4, §8) `no-worker` is rows 1 and 5 of the fast-fail table (`NO_CAPACITY`: no worker takes requests, or none that does can serve it) and `unresolvable-spec` rows 2 to 4 (`NO_DRIVER`, `UNKNOWN_MODEL`, `RUNTIME_MISSING`), emitted in the dispatch walk before the request is queued, so a request rejected on arrival emits no `lease.queued`, and a waiting one is rejected when the views change (additive, events rule 6). A request a worker refused with one of those codes (ADR 0009 §5) and the table later ends with that stored refusal gets a gateway `unresolvable-spec`, whether or not it had entered the gateway queue (the worker only declined it, ADR 0021 §4); `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again (#72; widens a published vocabulary, which events rule 6 allows as additive). The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (`cancelPending` on the leasing module, backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter -- one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses; a physical waiter has no device work, only a presence read, so it is cancelled in any state | LeaseAcquisitionCoordinator / WaitQueue / LeaseStartup (worker) / FleetLeaseCoordinator (gateway) | implemented | +| `lease.rejected` | request id, requester (both required on every reason, additive, ADR 0016 §2), request spec (as on `lease.requested`; `full` replaced by `mode`, ADR 0007 §13; `model` optional and `class` added, ADR 0015 §9; `osVersion` may be a range as typed, ADR 0015 §2), reason (timeout/no-wait/unresolvable-spec/no-worker/already-leased/lease-id-taken/boot-timeout/killed/cancelled/daemon-restarted/worker-failed), `code` and `worker` on `worker-failed` (ADR 0021 §4, additive; `worker`, never `workerId`, which marks a relayed event, ADR 0014 §6) | a request ended without a grant. A worker emits it only for its local requests; a probe ends in `lease.declined` there (ADR 0021 §2). A gateway emits it for every ending that is not a grant (ADR 0021 §4): its own reasons, `unresolvable-spec` for the last cannot-serve refusal whether or not the request had queued, and `worker-failed` for any other failure on the worker it went to -- a terminal refusal, a failure after progress, `WORKER_UNREACHABLE`, `INTERNAL`, a dispatch timeout, a worker's own `REQUESTER_ALREADY_LEASED` or `LEASE_ID_TAKEN` -- with `code` the error code the caller got and `worker` the worker. `dispose()` emits nothing, so a request still open when a gateway stops has no ending event (ADR 0021 §5 plans for usage to close those at the next `daemon.started`; not built yet). `already-leased` means the requester already has a waiting request, or already holds `lease.maxPerRequester` leases (ADR 0023); a worker skips the held-lease count for a probe, so it declines a probe `already-leased` only for a waiting one. A request refused at admission (`killed`, `already-leased`, `lease-id-taken`) was never stored and has no `lease.requested` (except a gateway's `lease-id-taken` after a grant, below); it carries the id minted for it before the check, the one the stored request would have had; on a gateway (ADR 0009 §4, §8) `no-worker` is rows 1 and 5 of the fast-fail table (`NO_CAPACITY`: no worker takes requests, or none that does can serve it) and `unresolvable-spec` rows 2 to 4 (`NO_DRIVER`, `UNKNOWN_MODEL`, `RUNTIME_MISSING`) and `CAPABILITY_MISSING` (a request whose `requires` no connected worker able to serve it meets with every name `available`, run on the table a second time on the capable views; ADR 0026, narrows ADR 0009), emitted in the dispatch walk before the request is queued, so a request rejected on arrival emits no `lease.queued`, and a waiting one is rejected when the views change (additive, events rule 6). A request a worker refused with one of those codes or with `CAPABILITY_MISSING` (ADR 0009 §5, ADR 0026) and the table later ends with that stored refusal gets a gateway `unresolvable-spec`, whether or not it had entered the gateway queue (the worker only declined it, ADR 0021 §4); `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again (#72; widens a published vocabulary, which events rule 6 allows as additive). The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (`cancelPending` on the leasing module, backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter -- one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses; a physical waiter has no device work, only a presence read, so it is cancelled in any state | LeaseAcquisitionCoordinator / WaitQueue / LeaseStartup (worker) / FleetLeaseCoordinator (gateway) | implemented | | `lease.declined` | `{ requestId, fleetRequestId, requester, requestSpec, reason }` -- `reason` takes `lease.rejected`'s values; `requestSpec` is there for the same reason as on `lease.rejected`: a decline at admission has no `lease.requested` (ADR 0021 §2) | a worker refused or failed a probe, a `lease.request` carrying `fleetRequestId` (ADR 0021 §1), whatever the reason (`no-wait`, `unresolvable-spec`, `already-leased`, `lease-id-taken`, `boot-timeout`, `killed`, `daemon-restarted` at the next start) and however far the work got. The gateway owns the outcome of a probe, so the worker never rejects one and never queues one: where it would queue (a second failed provision) it declines with `no-wait` and answers `NO_CAPACITY`. The event depends only on the request being a probe, never on whether the gateway will retry. A local request is rejected exactly as before | LeaseAcquisitionCoordinator / WaitQueue / LeaseStartup (worker) | implemented | On a **gateway**, `lease.requested`, `lease.queued` and `lease.rejected` are its own fleet queue's facts (ADR 0005 §11/§14), diff --git a/src/contract/errors.ts b/src/contract/errors.ts index b38c711a8..eb8c8c9c7 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -46,6 +46,7 @@ export interface ErrorDetailsMap { * request, when a worker's grant carries an ID the gateway already routes elsewhere. */ LEASE_ID_TAKEN: { readonly leaseId: string }; NO_DRIVER: { readonly platform: Platform }; + CAPABILITY_MISSING: { readonly capabilities: readonly string[] }; RUNTIME_MISSING: { readonly platform: Platform; readonly osVersion: string; @@ -149,6 +150,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record REQUESTER_ALREADY_LEASED: true, LEASE_ID_TAKEN: true, NO_DRIVER: true, + CAPABILITY_MISSING: true, RUNTIME_MISSING: true, UNKNOWN_MODEL: true, INSUFFICIENT_DISK_SPACE: true, @@ -244,6 +246,12 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry httpStatus: 409, }, NO_DRIVER: { code: "NO_DRIVER", kind: "domain", cliExitCode: 12, httpStatus: 422 }, + CAPABILITY_MISSING: { + code: "CAPABILITY_MISSING", + kind: "domain", + cliExitCode: 12, + httpStatus: 422, + }, RUNTIME_MISSING: { code: "RUNTIME_MISSING", kind: "domain", cliExitCode: 12, httpStatus: 422 }, UNKNOWN_MODEL: { code: "UNKNOWN_MODEL", kind: "domain", cliExitCode: 12, httpStatus: 422 }, INSUFFICIENT_DISK_SPACE: { diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 043970f5a..0e9937f75 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -178,7 +178,11 @@ const leaseRequestBaseSchema = z * Bounded as `idempotencyKey` is, because the worker stores it. */ fleetRequestId: z.string().min(1).max(200).optional(), - requires: z.array(capabilityNameSchema).optional(), + requires: z + .array(capabilityNameSchema) + .max(8) + .refine((names) => new Set(names).size === names.length, "a capability name appears twice") + .optional(), }) .strict(); @@ -229,6 +233,23 @@ function refusePhysicalWithImageFields(): < }; } +// why: a replay would have to be checked against a capability state that changed since. +function refuseRequiresWithIdempotencyKey(): < + T extends { readonly requires?: unknown; readonly idempotencyKey?: string | undefined }, +>( + input: T, + context: z.RefinementCtx, +) => void { + return (input, context) => { + if (input.requires === undefined || input.idempotencyKey === undefined) return; + context.addIssue({ + code: z.ZodIssueCode.custom, + message: "requires cannot be combined with idempotencyKey", + path: ["requires"], + }); + }; +} + function refuseBadOsVersion(): ( input: T, context: z.RefinementCtx, @@ -251,7 +272,8 @@ export const leaseRequestFields = leaseRequestBaseSchema; const leaseRequestInputSchema = leaseRequestBaseSchema .superRefine(refuseModelWithClass()) .superRefine(refuseBadOsVersion()) - .superRefine(refusePhysicalWithImageFields()); + .superRefine(refusePhysicalWithImageFields()) + .superRefine(refuseRequiresWithIdempotencyKey()); // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const leaseRequest = defineOperation({ diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 4eca8d816..2df08cb0a 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 33, max: 33 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 34, max: 34 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index a080b5cc6..63bf85642 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -997,7 +997,6 @@ export const statusInstallsSchema = boundedInstalls( */ export const INSTALL_LIST_LIMIT = MAX_LISTED_INSTALLS; -// fallow-ignore-next-line unused-export -- exported on its own so the tasks that name a capability reuse it (#513). export const capabilityNameSchema = z.string().regex(/^[a-z][a-z0-9-]{0,31}$/); // why: \p{Cc} is exactly U+0000-U+001F and U+007F-U+009F, the spec's control characters. diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index b4e3a092d..8d6a138e0 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(33); + expect(DAEMON_PROTOCOL_VERSION).toBe(34); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 163a9835a..c561e00ac 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -410,6 +410,25 @@ export class Dispatcher { } } + // why: a request that waits in the worker's queue is not checked again; the check runs once, before leasing. + async #requireCapabilities(requires: readonly string[] | undefined): Promise { + if (requires === undefined || requires.length === 0) return; + const sources = this.options.capabilitySources ?? []; + const states = await Promise.all( + requires.map(async (name) => { + const source = sources.find((candidate) => candidate.name === name); + return source === undefined ? undefined : this.#readCapability(source); + }), + ); + const missing = requires.filter((_name, index) => states[index]?.state !== "available"); + if (missing.length === 0) return; + throw new DispatchError( + "CAPABILITY_MISSING", + `This worker cannot serve ${missing.join(", ")}`, + { capabilities: missing }, + ); + } + // fallow-ignore-next-line complexity -- lease payload assembly and the download-policy rewrite are one transaction, moved verbatim from DaemonServer's former #requestLease. #leaseRequest: Handler<"lease.request"> = async (input, session) => { const request: DeviceRequest = requestedDevice(input); @@ -440,6 +459,7 @@ export class Dispatcher { ); } } + await this.#requireCapabilities(input.requires); const ownerId = input.owner ?? session.principal; try { const grant = await this.options.leases.request(request, { diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 92171ba66..31cb505a9 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -195,7 +195,7 @@ describe("DaemonServer", () => { [30, "cannot read the agent-device-unavailable finding in doctor.run"], [32, "cannot read status.get's capabilities"], ])( - "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 33, to a client on protocol %i, which %s", + "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 34, to a client on protocol %i, which %s", async (version) => { const harness = await createHarness(); const previous = await createClient(harness.socketPath); @@ -205,7 +205,7 @@ describe("DaemonServer", () => { ).resolves.toMatchObject({ error: { code: "PROTOCOL_VERSION_UNSUPPORTED", - details: { client: { min: version, max: version }, daemon: { min: 33, max: 33 } }, + details: { client: { min: version, max: version }, daemon: { min: 34, max: 34 } }, }, ok: false, }); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index fa5b56269..b533fac57 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -455,6 +455,7 @@ export class GatewayDispatcher { ...(input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }), // ADR 0020: forwarded to the worker as sent, and the gateway's own lease ID when it grants. ...(input.leaseId === undefined ? {} : { leaseId: input.leaseId }), + ...(input.requires === undefined ? {} : { requires: input.requires }), ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }), // Always explicit past this point (§15): a request that named none is filled in here, // before dispatch, rather than left for whichever worker happens to grant it to default diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index 80791c9cf..fba6c9232 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -94,6 +94,7 @@ const CANNOT_SERVE_CODES: ReadonlySet = new Set([ "UNKNOWN_MODEL", "RUNTIME_MISSING", "NO_DRIVER", + "CAPABILITY_MISSING", ]); export interface FleetExecInput { @@ -892,6 +893,9 @@ export class FleetLeaseCoordinator { // declines a probe it refuses (`lease.declined`) rather than rejecting it, and names // the id on the lease events of the dispatch. fleetRequestId: waiter.id, + ...(waiter.options.requires === undefined + ? {} + : { requires: [...waiter.options.requires] }), }, { onProgress: (progress) => { @@ -1340,5 +1344,6 @@ function routable(waiter: FleetWaiter): RoutableRequest { ...(waiter.request.imageTag === undefined ? {} : { imageTag: waiter.request.imageTag }), ...(waiter.request.mode === undefined ? {} : { mode: waiter.request.mode }), ...(lineOf(waiter.request) === "physical" ? { physical: true as const } : {}), + ...(waiter.options.requires === undefined ? {} : { requires: waiter.options.requires }), }; } diff --git a/src/gateway/routing.ts b/src/gateway/routing.ts index 72ecb421f..4779f1bcc 100644 --- a/src/gateway/routing.ts +++ b/src/gateway/routing.ts @@ -4,6 +4,7 @@ import { canServe, freeCapacity, freeSlot, + hasCapabilities, healthy, idleQueue, ramBudget, @@ -48,6 +49,7 @@ function composeRoutingPolicy(stages: readonly RoutingStage[]): RoutingPolicy { const routingPolicies = { "warm-then-free": [ takesRequests, + hasCapabilities, canServe, healthy, idleQueue, diff --git a/src/gateway/routing/index.ts b/src/gateway/routing/index.ts index 66dca9585..6a48175d6 100644 --- a/src/gateway/routing/index.ts +++ b/src/gateway/routing/index.ts @@ -4,6 +4,7 @@ export { type Assessment, assess, type Rejection } from "./serviceability.js"; export { canServe } from "./stages/can-serve.js"; export { freeCapacity } from "./stages/free-capacity.js"; export { freeSlot } from "./stages/free-slot.js"; +export { hasCapabilities } from "./stages/has-capabilities.js"; export { healthy } from "./stages/healthy.js"; export { idleQueue } from "./stages/idle-queue.js"; export { ramBudget } from "./stages/ram-budget.js"; diff --git a/src/gateway/routing/serviceability.ts b/src/gateway/routing/serviceability.ts index 01a06828a..9ba277935 100644 --- a/src/gateway/routing/serviceability.ts +++ b/src/gateway/routing/serviceability.ts @@ -14,9 +14,15 @@ import { physicalMatch, wantedClass, } from "./request-match.js"; +import { hasCapabilities } from "./stages/has-capabilities.js"; import { takesRequests } from "./stages/takes-requests.js"; -export type RejectionCode = "NO_CAPACITY" | "NO_DRIVER" | "UNKNOWN_MODEL" | "RUNTIME_MISSING"; +export type RejectionCode = + | "NO_CAPACITY" + | "NO_DRIVER" + | "UNKNOWN_MODEL" + | "RUNTIME_MISSING" + | "CAPABILITY_MISSING"; /** What a request the fleet cannot serve is told: the code and details a worker gives the same * request, and the `lease.rejected` reason the gateway records it under. */ @@ -24,19 +30,36 @@ export interface Rejection { readonly kind: "reject"; readonly code: RejectionCode; readonly message: string; - readonly details?: { - readonly platform: Platform; - readonly model?: string; - readonly class?: DeviceClass; - readonly osVersion?: string; - readonly downloadable?: false; - }; + readonly details?: + | { + readonly platform: Platform; + readonly model?: string; + readonly class?: DeviceClass; + readonly osVersion?: string; + readonly downloadable?: false; + } + | { readonly capabilities: readonly string[] }; readonly reason: "no-worker" | "unresolvable-spec"; } export type Assessment = { readonly kind: "route-or-wait" } | Rejection; export function assess(request: RoutableRequest, views: readonly WorkerView[]): Assessment { + const answer = assessTable(request, views); + const requires = request.requires; + if (answer.kind === "reject" || requires === undefined || requires.length === 0) return answer; + const capable = views.filter((worker) => hasCapabilities.keeps(worker, request)); + if (assessTable(request, capable).kind === "route-or-wait") return answer; + return { + code: "CAPABILITY_MISSING", + details: { capabilities: requires }, + kind: "reject", + message: `No worker connected to this gateway can serve ${requires.join(", ")} for this request`, + reason: "unresolvable-spec", + }; +} + +function assessTable(request: RoutableRequest, views: readonly WorkerView[]): Assessment { const takers = views.filter((worker) => takesRequests.keeps(worker, request)); if (takers.length === 0) return noWorker(); diff --git a/src/gateway/routing/stages/has-capabilities.ts b/src/gateway/routing/stages/has-capabilities.ts index 9338d1796..e2310053e 100644 --- a/src/gateway/routing/stages/has-capabilities.ts +++ b/src/gateway/routing/stages/has-capabilities.ts @@ -1,9 +1,19 @@ import type { FilterStage } from "../pipeline.js"; export const hasCapabilities: FilterStage = { - keeps() { - return true; + keeps(worker, request) { + return listsAllAvailable(worker.capabilities, request.requires); }, appliesToPhysical: true, kind: "filter", }; + +function listsAllAvailable( + capabilities: readonly { readonly name: string; readonly state: string }[] | undefined, + requires: readonly string[] | undefined, +): boolean { + if (requires === undefined) return true; + return requires.every((name) => + capabilities?.some((entry) => entry.name === name && entry.state === "available"), + ); +} diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 6250c3d47..2bfdf5724 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -1207,7 +1207,7 @@ describe("GatewayService", () => { min: PROTOCOL_VERSION_RANGE.max - 1, max: PROTOCOL_VERSION_RANGE.max - 1, }; - expect(PROTOCOL_VERSION_RANGE.max).toBe(33); + expect(PROTOCOL_VERSION_RANGE.max).toBe(34); expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, previous)).toBeUndefined(); const harness = fleet(); await harness.service.start(); diff --git a/src/mcp/contracts.test.ts b/src/mcp/contracts.test.ts index f4b0385b0..5cfee87d6 100644 --- a/src/mcp/contracts.test.ts +++ b/src/mcp/contracts.test.ts @@ -64,10 +64,10 @@ describe("MCP contracts", () => { ).toEqual({ model: "iPhone 17 Pro", platform: "ios", ttlMs: 1_000 }); }); - it("is the same schema the contract validates lease.request input against, minus requesterId and fleetRequestId", () => { + it("is the same schema the contract validates lease.request input against, minus requesterId, fleetRequestId and requires", () => { expect(Object.keys(leaseSimulatorInputSchema.shape).sort()).toEqual( Object.keys(leaseRequestFields.shape) - .filter((key) => key !== "requesterId" && key !== "fleetRequestId") + .filter((key) => key !== "requesterId" && key !== "fleetRequestId" && key !== "requires") .sort(), ); }); diff --git a/src/mcp/contracts.ts b/src/mcp/contracts.ts index 8720ab778..0edf272a0 100644 --- a/src/mcp/contracts.ts +++ b/src/mcp/contracts.ts @@ -23,7 +23,7 @@ import { // ---- lease_simulator --------------------------------------------------------------------- /** - * `lease.request`'s input, minus the two fields this tool never lets the caller set: + * why: `lease.request`'s input, minus the fields this tool never lets the caller set (also `requires`, ADR 0026): * `requesterId` (session-controlled -- see `main.ts`'s requester resolution, never * caller-supplied, for the same reason the daemon never lets a request rename its own * principal) and `fleetRequestId` (a gateway's own mark on its dispatch to a worker, ADR 0021). @@ -40,6 +40,7 @@ import { export const leaseSimulatorInputSchema = leaseRequestFields.omit({ fleetRequestId: true, requesterId: true, + requires: true, }); /** From 8d7cf591f427243208759ab9504d2c87904b994d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 21:15:49 +0200 Subject: [PATCH 3/5] docs(client): a waiting request fails NO_CAPACITY when no worker stays --- docs/CLIENT.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 0f49aeb71..7b7185c7a 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -182,8 +182,8 @@ lowercase capability names, none twice, such as `["agent-device"]`. Simlock places the lease only on a worker whose status lists every one of them as `available`. Through a gateway, a request that no connected worker able to serve it can take fails at once with `CAPABILITY_MISSING`, and so does one -already waiting when the last such worker loses the capability, restarts, or -goes. Direct to a worker that lacks one it fails the same way. The error's +already waiting when the last such worker loses the capability or restarts. If +no worker stays connected, it fails with `NO_CAPACITY` instead. Direct to a worker that lacks one it fails the same way. The error's `details.capabilities` names the missing capabilities. `requires` cannot be combined with `idempotencyKey` (`BAD_REQUEST`). The CLI, the MCP tool and the HTTP lease body do not take it. From eb9625e8e136777ba12e3baef77e05a2cfb11620 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 21:16:10 +0200 Subject: [PATCH 4/5] docs(client): reflow --- docs/CLIENT.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 7b7185c7a..fef7a0320 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -183,7 +183,8 @@ places the lease only on a worker whose status lists every one of them as `available`. Through a gateway, a request that no connected worker able to serve it can take fails at once with `CAPABILITY_MISSING`, and so does one already waiting when the last such worker loses the capability or restarts. If -no worker stays connected, it fails with `NO_CAPACITY` instead. Direct to a worker that lacks one it fails the same way. The error's +no worker stays connected, it fails with `NO_CAPACITY` instead. Direct to a worker that lacks one it fails the same way. +The error's `details.capabilities` names the missing capabilities. `requires` cannot be combined with `idempotencyKey` (`BAD_REQUEST`). The CLI, the MCP tool and the HTTP lease body do not take it. From 7983207d1c3953b34edf112c301ebb01ee4cc7b1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 11:38:29 +0200 Subject: [PATCH 5/5] fix: the stack bumps the protocol once, to 33 (#513) --- src/contract/protocol.ts | 2 +- src/daemon-protocol/index.test.ts | 2 +- src/daemon/server.test.ts | 6 +++--- src/gateway/service.test.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 2df08cb0a..4eca8d816 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 34, max: 34 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 33, max: 33 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 8d6a138e0..b4e3a092d 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(34); + expect(DAEMON_PROTOCOL_VERSION).toBe(33); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 31cb505a9..b37d658ae 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -193,9 +193,9 @@ describe("DaemonServer", () => { [28, "cannot read config.get's lease.endWaitMs"], [29, "cannot read config.get's agentDevice"], [30, "cannot read the agent-device-unavailable finding in doctor.run"], - [32, "cannot read status.get's capabilities"], + [32, "cannot read status.get's capabilities or send lease.request's requires"], ])( - "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 34, to a client on protocol %i, which %s", + "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 33, to a client on protocol %i, which %s", async (version) => { const harness = await createHarness(); const previous = await createClient(harness.socketPath); @@ -205,7 +205,7 @@ describe("DaemonServer", () => { ).resolves.toMatchObject({ error: { code: "PROTOCOL_VERSION_UNSUPPORTED", - details: { client: { min: version, max: version }, daemon: { min: 34, max: 34 } }, + details: { client: { min: version, max: version }, daemon: { min: 33, max: 33 } }, }, ok: false, }); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 2bfdf5724..6250c3d47 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -1207,7 +1207,7 @@ describe("GatewayService", () => { min: PROTOCOL_VERSION_RANGE.max - 1, max: PROTOCOL_VERSION_RANGE.max - 1, }; - expect(PROTOCOL_VERSION_RANGE.max).toBe(34); + expect(PROTOCOL_VERSION_RANGE.max).toBe(33); expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, previous)).toBeUndefined(); const harness = fleet(); await harness.service.start();