diff --git a/docs/internal/adr/0046-a-standalone-worker-serves-agent-device-by-default-with-a-private-profile.md b/docs/internal/adr/0046-a-standalone-worker-serves-agent-device-by-default-with-a-private-profile.md index c883b9e54..009986f92 100644 --- a/docs/internal/adr/0046-a-standalone-worker-serves-agent-device-by-default-with-a-private-profile.md +++ b/docs/internal/adr/0046-a-standalone-worker-serves-agent-device-by-default-with-a-private-profile.md @@ -93,6 +93,7 @@ whether or not the command is found), the module host writes `/agent-d ```json { + "clientId": "a51a51a51a51a51a", "daemonAuthToken": "slk_…", "daemonBaseUrl": "http://127.0.0.1:4701/v1/agent-device", "daemonTransport": "http", diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index e7d575a1a..d66793a87 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -252,6 +252,15 @@ export async function startDaemon( ...(mode === "worker" ? FAKE_CAPACITY : {}), http: httpConfig, ...extraConfig, + // why: a standalone worker has agent-device on by default (ADR 0046); the console specs do not ask for it, and a test's own `capabilities` (a stream, say) must not replace this pin, so it merges one level deep. + ...(mode === "worker" + ? { + capabilities: { + "agent-device": { enabled: false }, + ...(extraConfig.capabilities as object | undefined), + }, + } + : {}), }), ); if (options.driverScript !== undefined) { diff --git a/e2e/helpers/agent-device.ts b/e2e/helpers/agent-device.ts index e85c6ab64..ae591837f 100644 --- a/e2e/helpers/agent-device.ts +++ b/e2e/helpers/agent-device.ts @@ -37,6 +37,8 @@ interface MadeAgent { readonly env: SharedTestEnv; readonly agent: Agent; readonly background: Set; + // why: the profile token belongs to the worker, not to the agent, so cleanup leaves it. + readonly keepToken?: boolean; } const made: MadeAgent[] = []; @@ -159,16 +161,75 @@ export async function makeAgent(env: SharedTestEnv, name: string): Promise { + const profilePath = join(env.dataDirectory, "agent-device-profile.json"); + const secret = (JSON.parse(await readFile(profilePath, "utf8")) as { daemonAuthToken: string }) + .daemonAuthToken; + const listed = await env.cli(["token", "list"], { timeout: 60_000 }); + const labelled = ( + listed.json as { tokens: readonly { id: string; label?: string }[] } + ).tokens.filter((token) => token.label === PROFILE_TOKEN_LABEL); + const tokenId = labelled[0]?.id; + if (labelled.length !== 1 || tokenId === undefined) { + throw new Error( + `expected one "${PROFILE_TOKEN_LABEL}" token, found ${String(labelled.length)}`, + ); + } + const home = await mkdtemp(join(tmpdir(), `simlock-ad-${name}-`)); + const entry = agentDeviceEntry(); + const inherited = Object.fromEntries( + Object.entries(process.env).filter(([key]) => !key.startsWith("AGENT_DEVICE_")), + ); + const childEnv: NodeJS.ProcessEnv = { + ...inherited, + HOME: home, + AGENT_DEVICE_STATE_DIR: home, + AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1", + }; + const background = new Set(); + const agent: Agent = { + name, + home, + token: secret, + tokenId, + async run(args, options = {}) { + const result = await cli(["--json", ...args, "--session", name], childEnv, { + entry, + timeout: options.timeout ?? 60_000, + }); + return parseResult(result.code, result.stdout, result.stderr); + }, + start(args) { + const handle = cliBackground(["--json", ...args, "--session", name], childEnv, { entry }); + background.add(handle); + return handle; + }, + }; + made.push({ env, agent, background, keepToken: true }); + const connected = await agent.run(["connect", "--remote-config", profilePath]); + if (connected.code !== 0) { + throw new Error(`agent-device connect failed: ${connected.stdout}\n${connected.stderr}`); + } + return agent; +} + export async function cleanupAgents(): Promise { const agents = made.splice(0); await Promise.allSettled( - agents.map(async ({ env, agent, background }) => { + agents.map(async ({ env, agent, background, keepToken }) => { for (const handle of background) handle.kill("SIGKILL"); await Promise.all( [...background].map((handle) => handle.waitForExit(10_000).catch(() => undefined)), ); await agent.run(["disconnect"], { timeout: 60_000 }).catch(() => undefined); - await env.cli(["token", "revoke", agent.tokenId], { timeout: 30_000 }).catch(() => undefined); + if (keepToken !== true) { + await env + .cli(["token", "revoke", agent.tokenId], { timeout: 30_000 }) + .catch(() => undefined); + } await rm(agent.home, { force: true, recursive: true }); }), ); diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 1e6fa6ef5..70500c89f 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -214,17 +214,29 @@ function processEnv( }; } +// why: a standalone worker serves HTTP and agent-device by default (ADR 0046); a test gets neither unless it asks, and two daemons would clash on port 4701. A gateway keeps its HTTP, which it cannot do without. +const STANDALONE_OFF: Record = { + capabilities: { "agent-device": { enabled: false } }, + http: { enabled: false }, +}; + function seedConfig( options: WithDaemonOptions, adbServerPort: number | undefined, ): Record | undefined { + const pinned = options.role === "gateway" ? {} : STANDALONE_OFF; if (options.driver === undefined || options.driver === "fake") { - return mergeDeep(FAKE_LANE_BASE_CONFIG, options.configOverrides ?? {}); + return mergeDeep(mergeDeep(pinned, FAKE_LANE_BASE_CONFIG), options.configOverrides ?? {}); } if (options.driver === "real") { - return mergeDeep({ drivers: { android: { adbServerPort } } }, options.configOverrides ?? {}); + return mergeDeep( + mergeDeep(pinned, { drivers: { android: { adbServerPort } } }), + options.configOverrides ?? {}, + ); } - return options.configOverrides; + return options.role === "gateway" + ? options.configOverrides + : mergeDeep(pinned, options.configOverrides ?? {}); } async function buildEnv( diff --git a/e2e/helpers/index.ts b/e2e/helpers/index.ts index 601bc0da0..448d064bb 100644 --- a/e2e/helpers/index.ts +++ b/e2e/helpers/index.ts @@ -7,6 +7,7 @@ export { assertPinnedAgentDevice, cleanupAgents, makeAgent, + makeProfileAgent, newAgentToken, waitForAgentDevice, } from "./agent-device.js"; diff --git a/e2e/slow-agent-device.test.ts b/e2e/slow-agent-device.test.ts index 111e9b57c..8b3a72e73 100644 --- a/e2e/slow-agent-device.test.ts +++ b/e2e/slow-agent-device.test.ts @@ -18,6 +18,7 @@ import { cleanupAgents, freeLoopbackPort, makeAgent, + makeProfileAgent, newAgentToken, waitForAgentDevice, waitFor, @@ -194,6 +195,20 @@ function defineSuite(target: Target): void { }, ); + it( + "an agent with no token in its environment connects with the worker's profile file, opens a device, installs the fixture app as an upload and closes; the lease's owner is the profile token", + { timeout: 600_000 }, + async () => { + const a = await makeProfileAgent(env, "profile"); + ok(await open(a)); + const leases = await listLeases(env); + expect(leases.map((lease) => lease.ownerId)).toEqual([a.tokenId]); + ok(await a.run(["install", "Appduct", target.app])); + ok(await a.run(["close"])); + await waitForFree(env); + }, + ); + it( "with this working agent-device, simlock doctor reports no module-unavailable finding and no finding whose message names agent-device", { timeout: 600_000 }, diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index 55b95c23f..7433fed67 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -4,7 +4,7 @@ Does: runs two agent-device daemons per worker (the simulator daemon over Simloc Entry: `index.ts` → `agentDeviceModule`. The front parts live in `front/edge-parts.ts` (`createGatewayAgentDeviceFrontParts`, `createAgentDeviceFront`, `disposeAgentDeviceEdge`, `cancelWaitingAllocates`). The gateway half is `gateway.ts` (`createGateway`, builds the `FleetPort` from the gateway context); the worker half is `worker.ts` (`createAgentDeviceEdgeParts`, builds one `AgentDeviceSupervisor` per role). The module host loads both. Uses: ports, auth (`Identity`), http (session, errors), contract types, core and leasing types. Never imports: gateway, drivers, `fs`, `child_process`. Imported by: the module registry (`index.ts` only); `daemon/main.ts` imports nothing from it (tests may use `testing.ts`). Pinned in `lint-rules.test.ts`. -Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no daemon. +On unless `capabilities.agent-device.enabled` is set false, on a standalone worker (`definition.ts` declares `enabledByDefault: "standalone-worker"`); off on a joined worker and a gateway unless set true. Off: nothing mounted, no daemon. When on only by default and the command is not found, the capability reads `off` and `agentDeviceFindings` says nothing (`isAbsentByDefault`); every other trouble, and a not-found with `enabled: true` set, stays `unavailable` with its finding. ## Files diff --git a/src/agent-device/definition.test.ts b/src/agent-device/definition.test.ts index a3674449c..36347843b 100644 --- a/src/agent-device/definition.test.ts +++ b/src/agent-device/definition.test.ts @@ -18,7 +18,15 @@ async function loadWith( return loadConfig({ configPath, filesystem, - modules: [{ ...agentDeviceModule.config, name: agentDeviceModule.name }], + modules: [ + { + ...agentDeviceModule.config, + ...(agentDeviceModule.enabledByDefault === undefined + ? {} + : { enabledByDefault: agentDeviceModule.enabledByDefault }), + name: agentDeviceModule.name, + }, + ], ...(role === undefined ? {} : { role }), systemStats: new FakeSystemStats({ cpuCount: 4, totalRamBytes: 16 * 1024 ** 3 }), ...(warn === undefined ? {} : { warn }), @@ -32,10 +40,18 @@ function section(config: Config): Record | undefined { } describe("agent-device's definition: capabilities.agent-device config", () => { - it("defaults capabilities.agent-device.enabled to false and command to agent-device, with leaseTtlCapMs unset", async () => { - const config = await loadWith({}); - - expect(section(config)).toEqual({ command: "agent-device", enabled: false }); + it("defaults capabilities.agent-device.enabled to true on a standalone worker and false on a joined worker and a gateway, with command agent-device and leaseTtlCapMs unset", async () => { + const joined = { gateway: { token: "join-secret", url: "wss://fleet.example" } }; + + expect(section(await loadWith({}))).toEqual({ command: "agent-device", enabled: true }); + expect( + section(await loadWith({ capabilities: { "agent-device": { enabled: false } } })), + ).toEqual({ command: "agent-device", enabled: false }); + expect(section(await loadWith(joined))).toEqual({ command: "agent-device", enabled: false }); + expect(section(await loadWith({}, undefined, "gateway"))).toEqual({ + command: "agent-device", + enabled: false, + }); }); it("keeps an explicit capabilities.agent-device section", async () => { @@ -132,12 +148,12 @@ describe("agent-device's definition: capabilities.agent-device config", () => { ); }); - it("refuses the old top-level agentDevice key as unknown, and leaves agent-device off", async () => { + it("refuses the old top-level agentDevice key as unknown, and leaves agent-device at its default", async () => { const warn = vi.fn(); const config = await loadWith({ agentDevice: { enabled: true } }, warn); expect(warn).toHaveBeenCalledWith('Unknown config key: "agentDevice"'); - expect(section(config)?.["enabled"]).toBe(false); + expect(section(config)?.["enabled"]).toBe(true); }); }); diff --git a/src/agent-device/definition.ts b/src/agent-device/definition.ts index 94364b488..466977363 100644 --- a/src/agent-device/definition.ts +++ b/src/agent-device/definition.ts @@ -36,11 +36,14 @@ export const agentDeviceModule: OptionalModuleDefinition `${JSON.stringify( { + // why: agent-device refuses a proxy open without a clientId; it is a constant so the file's bytes stay stable. + clientId: "a51a51a51a51a51a", daemonAuthToken: secret, daemonBaseUrl: `${origin}/v1/agent-device`, daemonTransport: "http", diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 29e9970a0..b12a4e02f 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -4268,13 +4268,13 @@ describe("a worker's capabilities in status.get, through the whole worker daemon return (await rig.daemon.dispatch("status.get", {}, adminSession)).capabilities; } - it("a worker with no capabilities.agent-device section answers status.get with capabilities [{name: agent-device, state: off}], and so does one with it false", async () => { + it("a standalone worker with no capabilities.agent-device section answers status.get with capabilities [{name: agent-device, state: available}], and one with it false answers state off", async () => { const unset = await setUp({ enabled: "unset" }); const off = await setUp({ enabled: false }); const running = await setUp(); expect(await capabilities(running)).toEqual([{ name: "agent-device", state: "available" }]); - expect(await capabilities(unset)).toEqual([{ name: "agent-device", state: "off" }]); + expect(await capabilities(unset)).toEqual([{ name: "agent-device", state: "available" }]); expect(await capabilities(off)).toEqual([{ name: "agent-device", state: "off" }]); }); diff --git a/src/agent-device/host/availability-findings.ts b/src/agent-device/host/availability-findings.ts index 568dd60f2..af4164ed6 100644 --- a/src/agent-device/host/availability-findings.ts +++ b/src/agent-device/host/availability-findings.ts @@ -1,11 +1,23 @@ import type { OptionalModuleFinding } from "../../core/index.js"; import type { AgentDeviceAvailability, AgentDeviceRole } from "./agent-device-supervisor.js"; +// why: ADR 0046 §1: a command never found while the module is on only by default is no fault of this Mac, so it is neither reported nor an unavailable capability. +export function isAbsentByDefault( + availability: AgentDeviceAvailability, + enabledByDefault: boolean, +): boolean { + return ( + enabledByDefault && availability.state === "unavailable" && availability.reason === "not-found" + ); +} + export function agentDeviceFindings( availability: AgentDeviceAvailability, role: AgentDeviceRole = "simulators", + enabledByDefault = false, ): readonly OptionalModuleFinding[] { if (availability.state !== "unavailable") return []; + if (isAbsentByDefault(availability, enabledByDefault)) return []; return [ { kind: "module-unavailable", diff --git a/src/agent-device/local-profile.test.ts b/src/agent-device/local-profile.test.ts index e4da5bb48..cf604b0d1 100644 --- a/src/agent-device/local-profile.test.ts +++ b/src/agent-device/local-profile.test.ts @@ -51,6 +51,7 @@ interface Switches { readonly http?: boolean; readonly agentDevice?: boolean; readonly role?: "gateway"; + readonly defaults?: "standalone" | "joined"; } interface LaunchOptions extends Switches { @@ -82,10 +83,24 @@ async function launch(options: LaunchOptions = {}): Promise { } const daemon = await startDaemon({ clock, - configOverrides: { - capabilities: { "agent-device": { enabled: options.agentDevice ?? true } }, - http: { enabled: options.http ?? true, host, port }, - }, + configOverrides: + options.defaults === undefined + ? { + capabilities: { "agent-device": { enabled: options.agentDevice ?? true } }, + http: { enabled: options.http ?? true, host, port }, + } + : { + capabilities: { "agent-device": { command: "fake-agent-device" } }, + ...(options.defaults === "joined" + ? { + gateway: { + token: "slk_join", + url: `ws://127.0.0.1:${String(await freeLoopbackPort())}`, + }, + } + : {}), + http: { port }, + }, ...(options.role === undefined ? {} : { role: options.role }), dataDirectory: directory, deviceDataTables: fakeDeviceDataTables, @@ -229,6 +244,7 @@ describe("the local agent-device profile", () => { const profile = JSON.parse(text) as Record; expect((await rig.filesystem.stat(rig.profilePath)).mode).toBe(0o600); expect(Object.keys(profile)).toEqual([ + "clientId", "daemonAuthToken", "daemonBaseUrl", "daemonTransport", @@ -239,6 +255,7 @@ describe("the local agent-device profile", () => { ]); expect(text).toBe(`${JSON.stringify(profile, null, 2)}\n`); expect(profile).toMatchObject({ + clientId: "a51a51a51a51a51a", daemonBaseUrl: `http://127.0.0.1:${rig.port}/v1/agent-device`, daemonTransport: "http", leaseProvider: "proxy", @@ -380,4 +397,25 @@ describe("the local agent-device profile", () => { const made = await rig.daemon.dispatch("token.create", { role: "agent" }, adminSession); expect((await allocateWith(rig, made.secret, 1)).status).toBe(200); }); + + it("is written and served by a standalone worker on its defaults, and not by a joined one", async () => { + const standalone = await launch({ defaults: "standalone" }); + const config = await standalone.daemon.dispatch("config.get", {}, adminSession); + expect(config.http.enabled).toBe(true); + expect(config.capabilities["agent-device"]?.enabled).toBe(true); + const profile = JSON.parse(await standalone.filesystem.readFile(standalone.profilePath)) as { + daemonAuthToken: string; + }; + const health = await fetch(`http://127.0.0.1:${standalone.port}/v1/agent-device/health`, { + headers: { authorization: `Bearer ${profile.daemonAuthToken}`, connection: "close" }, + }); + const joined = await launch({ defaults: "joined" }); + + expect(health.status).toBe(200); + expect(await listens(joined.port)).toBe(false); + expect(await joined.filesystem.exists(joined.profilePath)).toBe(false); + expect((await joined.daemon.dispatch("status.get", {}, adminSession)).capabilities).toEqual([ + { name: "agent-device", state: "off" }, + ]); + }); }); diff --git a/src/agent-device/worker.ts b/src/agent-device/worker.ts index c815b5fb8..73c871e30 100644 --- a/src/agent-device/worker.ts +++ b/src/agent-device/worker.ts @@ -11,7 +11,7 @@ import { type AgentDevicePlatform, type AgentDeviceRole, } from "./host/agent-device-supervisor.js"; -import { agentDeviceFindings } from "./host/availability-findings.js"; +import { agentDeviceFindings, isAbsentByDefault } from "./host/availability-findings.js"; import { type AgentDeviceHealthProbe, NodeAgentDeviceHealthProbe } from "./host/health.js"; import { AgentDeviceHost } from "./host/host.js"; import { AgentDeviceLeaseEnd, ReleaseScopeRecord } from "./host/lease-end.js"; @@ -79,16 +79,20 @@ function agentDeviceRelayTarget( }; } -function agentDeviceCapabilitySource(parts: AgentDeviceEdgeParts): { +function agentDeviceCapabilitySource( + parts: AgentDeviceEdgeParts, + absent: () => boolean, +): { readonly name: string; readonly read: () => Promise<{ - readonly state: "available" | "unavailable"; + readonly state: "available" | "unavailable" | "off"; readonly reason?: string; }>; } { return { name: "agent-device", read: async () => { + if (absent()) return { state: "off" }; // why: a status read without a lease id is never "unreachable"; only a lease has a worker to reach. const status = (await parts.link.status()) as Exclude; return status.state === "running" @@ -139,11 +143,13 @@ export function createWorkerWith( ctx.registry, ); return { - capability: agentDeviceCapabilitySource(parts), + capability: agentDeviceCapabilitySource(parts, () => + isAbsentByDefault(supervisor.availability(), ctx.enabledByDefault), + ), findings: () => [ - ...agentDeviceFindings(supervisor.availability()), - ...agentDeviceFindings(phoneSupervisor.availability(), "phones"), + ...agentDeviceFindings(supervisor.availability(), "simulators", ctx.enabledByDefault), + ...agentDeviceFindings(phoneSupervisor.availability(), "phones", ctx.enabledByDefault), ].map(({ message, remedy }) => ({ message, remedy })), hooks: { // why: not awaited, since simlock's start never waits for agent-device, and a daemon that lost the socket race never gets here, so it reaps nothing. diff --git a/src/cli/environment.ts b/src/cli/environment.ts index c92250378..bc85c8326 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -152,7 +152,11 @@ async function isUnavailable(error: unknown): Promise { async function moduleConfigEntries(): Promise { const { optionalModules } = await import("../module-registry/index.js"); - return optionalModules.map(({ config, name }) => ({ name, ...config })); + return optionalModules.map(({ config, enabledByDefault, name }) => ({ + name, + ...config, + ...(enabledByDefault === undefined ? {} : { enabledByDefault }), + })); } async function readAdminTokenFile( diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 116b61648..3b8a9987b 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -9,35 +9,35 @@ See also: [leasing](../leasing/AGENTS.md) (lease flow, when reclaim runs), [warm ## Files -| File | Role | -| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Wiring and state** | | -| `create-core.ts`, `core-ports.ts` | `createCore`, `Core`, `CorePorts`; read ports (`CapacityReader`, `WarmPoolReader`, …) | -| `registry.ts`, `registry-rows.ts`, `registry-schema.ts` | `Registry`: the one writer of the registry tables of `state.db`; the rows, the `registry` schema owner | -| `domain.ts` | Records, specs, `transition`, `fits`, `mayBeGranted`, `sameSpec` | -| `serialized-decision.ts`, `device-operation-claims.ts` | The lock; one in-memory claim per device | -| `config.ts`, `validation.ts` | `loadConfig({ role })` (the role comes from the daemon, never a config key; a `mode` key is refused; with the optional modules' `ModuleConfigEntry` list: `capabilities.` sections, `enabled` owned here), defaults, validators, `redactConfig`, `effectiveAllowDownload` | -| `lease-request-store.ts` | Pure lease-request record helpers, shared with leasing | -| **Device verbs** | | -| `managed-device-lifecycle.ts` | `ManagedDeviceLifecycle`: every driver verb on a registered device | -| `device-provisioner.ts` | `DeviceProvisioner`: the one place a device record is created | -| `reclaim-coordinator.ts` | `ReclaimCoordinator`: wipe after a lease, spent delete, interrupted reclaim | -| `quarantine-coordinator.ts` | `QuarantineCoordinator`: entry, retry on backoff, give up | -| `nuke-service.ts`, `nuke.ts` | `NukeService` (operator reset); `Nuke` (command facade) | -| `idle-order.ts` | LRU order and eviction victim choice | -| **Background** | | -| `warm-pool/`, `capacity/` | What stays warm; limits, RAM budget, reservations (own manuals) | -| `reaper.ts`, `cleanup/`, `cleanup-executor.ts` | `CleanupReaper`, pure rules, `CleanupExecutor` | -| **Startup, health, drivers** | | -| `startup-read.ts`, `startup-converger.ts` | `readStartup`; `StartupConverger`, the device half of startup | -| `write-leftovers.ts` | `sweepWriteLeftovers`: removes dead writers' `.tmp` files and the `.staging` dirs of the device roots it is given; logs pid-less legacy ones, never deletes them | -| `doctor.ts`, `host-facts.ts` | `Doctor` findings and fixes (`service-broken` from an injected `serviceCheck`, never drift); `HostFactsReader` for status | -| `driver.ts`, `driver-catalog.ts`, `screen.ts` | `Driver`, errors, `DiskSpaceGuard`; `DriverCatalog`; `ScreenCapture`, frame tags | -| `catalog-match.ts` | Model name, class and paired runtimes against a catalog entry | -| `component-installer.ts` | `ComponentInstaller`: install, list, remove | -| `physical-enrollment.ts`, `physical-presence.ts` | `device add`/`remove`; every presence read, `latestPresence` | -| `device-root.ts`, `instance-identity.ts` | `ensureOwnedRoot`; `loadInstanceId` | -| `stable-error.ts`, `testing.ts`, `fake-driver.ts` | `stableError`; test-only wiring and `FakeDriver` | +| File | Role | +| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Wiring and state** | | +| `create-core.ts`, `core-ports.ts` | `createCore`, `Core`, `CorePorts`; read ports (`CapacityReader`, `WarmPoolReader`, …) | +| `registry.ts`, `registry-rows.ts`, `registry-schema.ts` | `Registry`: the one writer of the registry tables of `state.db`; the rows, the `registry` schema owner | +| `domain.ts` | Records, specs, `transition`, `fits`, `mayBeGranted`, `sameSpec` | +| `serialized-decision.ts`, `device-operation-claims.ts` | The lock; one in-memory claim per device | +| `config.ts`, `validation.ts` | `loadConfig({ role })`, `loadConfigWithDefaults` (also the module names whose `enabled` came from an `enabledByDefault` default) (the role comes from the daemon, never a config key; a `mode` key is refused; with the optional modules' `ModuleConfigEntry` list: `capabilities.` sections, `enabled` owned here), defaults, validators, `redactConfig`, `effectiveAllowDownload` | +| `lease-request-store.ts` | Pure lease-request record helpers, shared with leasing | +| **Device verbs** | | +| `managed-device-lifecycle.ts` | `ManagedDeviceLifecycle`: every driver verb on a registered device | +| `device-provisioner.ts` | `DeviceProvisioner`: the one place a device record is created | +| `reclaim-coordinator.ts` | `ReclaimCoordinator`: wipe after a lease, spent delete, interrupted reclaim | +| `quarantine-coordinator.ts` | `QuarantineCoordinator`: entry, retry on backoff, give up | +| `nuke-service.ts`, `nuke.ts` | `NukeService` (operator reset); `Nuke` (command facade) | +| `idle-order.ts` | LRU order and eviction victim choice | +| **Background** | | +| `warm-pool/`, `capacity/` | What stays warm; limits, RAM budget, reservations (own manuals) | +| `reaper.ts`, `cleanup/`, `cleanup-executor.ts` | `CleanupReaper`, pure rules, `CleanupExecutor` | +| **Startup, health, drivers** | | +| `startup-read.ts`, `startup-converger.ts` | `readStartup`; `StartupConverger`, the device half of startup | +| `write-leftovers.ts` | `sweepWriteLeftovers`: removes dead writers' `.tmp` files and the `.staging` dirs of the device roots it is given; logs pid-less legacy ones, never deletes them | +| `doctor.ts`, `host-facts.ts` | `Doctor` findings and fixes (`service-broken` from an injected `serviceCheck`, never drift); `HostFactsReader` for status | +| `driver.ts`, `driver-catalog.ts`, `screen.ts` | `Driver`, errors, `DiskSpaceGuard`; `DriverCatalog`; `ScreenCapture`, frame tags | +| `catalog-match.ts` | Model name, class and paired runtimes against a catalog entry | +| `component-installer.ts` | `ComponentInstaller`: install, list, remove | +| `physical-enrollment.ts`, `physical-presence.ts` | `device add`/`remove`; every presence read, `latestPresence` | +| `device-root.ts`, `instance-identity.ts` | `ensureOwnedRoot`; `loadInstanceId` | +| `stable-error.ts`, `testing.ts`, `fake-driver.ts` | `stableError`; test-only wiring and `FakeDriver` | ## Wiring diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 96165899f..84ca6ba30 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -120,7 +120,7 @@ describe("loadConfig", () => { maxBytes: 256 * 1024 * 1024, }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, - http: { enabled: false, host: "127.0.0.1", port: 4701 }, + http: { enabled: true, host: "127.0.0.1", port: 4701 }, warmPool: { enabled: true, maxConcurrentBoots: 2, @@ -1656,11 +1656,11 @@ describe("loadConfig modes (ADR 0005)", () => { }); } - it("defaults to worker mode, with HTTP off and a 24h disconnected-view retention", async () => { + it("defaults to worker mode, with HTTP on and a 24h disconnected-view retention", async () => { const config = await load({}); expect(config.mode).toBe("worker"); - expect(config.http.enabled).toBe(false); + expect(config.http.enabled).toBe(true); expect(config.gateway).toEqual({ disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000, @@ -1876,7 +1876,7 @@ describe("loadConfig modes (ADR 0005)", () => { { name: "wss URL, HTTP omitted", contents: { gateway: joined }, http: false }, { name: "standalone, HTTP true", contents: { http: { enabled: true } }, http: true }, { name: "standalone, HTTP false", contents: { http: { enabled: false } }, http: false }, - { name: "standalone, HTTP omitted", contents: {}, http: false }, + { name: "standalone, HTTP omitted", contents: {}, http: true }, { name: "gateway, HTTP omitted", contents: {}, role: "gateway", http: true }, { name: "gateway, HTTP true", diff --git a/src/core/config.ts b/src/core/config.ts index 578cd7791..c9590c757 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -44,13 +44,7 @@ import { const DEFAULT_CONFIG_PATH = "~/.simlock/config.json"; -/** - * `lease.defaultTtlMs`'s default (ADR 0004 §4): the width a request that names no `ttlMs` is - * granted. Exported because `Registry` needs the same number to migrate a lease record written - * before ADR 0004, which has no stored width of its own -- one definition, read from both - * places, rather than the same fifteen minutes spelled twice. - */ -export const DEFAULT_LEASE_TTL_MS = 15 * 60_000; +const DEFAULT_LEASE_TTL_MS = 15 * 60_000; /** `lease.maxTtlMs`'s default: the largest TTL any request or renew may ask for. */ const DEFAULT_LEASE_MAX_TTL_MS = 4 * 60 * 60_000; @@ -516,6 +510,7 @@ export interface ModuleConfigEntry { readonly validator: Validator; readonly defaults: unknown; readonly gatewayKeys: readonly string[]; + readonly enabledByDefault?: "standalone-worker"; readonly check?: (section: never, config: Config) => void; } @@ -535,7 +530,11 @@ export interface LoadConfigOptions { type Layer = Record; -export async function loadConfig({ +export async function loadConfig(options: LoadConfigOptions): Promise { + return (await loadConfigWithDefaults(options)).config; +} + +export async function loadConfigWithDefaults({ authStrategies = registeredAuthStrategies, configPath = DEFAULT_CONFIG_PATH, filesystem, @@ -544,7 +543,10 @@ export async function loadConfig({ role = "worker", systemStats, warn = () => {}, -}: LoadConfigOptions): Promise { +}: LoadConfigOptions): Promise<{ + readonly config: Config; + readonly defaulted: ReadonlySet; +}> { const fromFile = await readConfigFile(filesystem, configPath); const fromOverrides = overrides ?? {}; @@ -571,8 +573,27 @@ export async function loadConfig({ warn, ); + const layers = [fileConfig, overrideConfig]; + const standalone = + role === "worker" && !layers.some((layer) => asObject(layer["gateway"])["url"] !== undefined); + const defaulted = new Set( + modules + .filter( + (entry) => + entry.enabledByDefault === "standalone-worker" && + standalone && + !layers.some( + (layer) => + asObject(asObject(layer["capabilities"])[entry.name])["enabled"] !== undefined, + ), + ) + .map((entry) => entry.name), + ); const mergedWithoutMetrics = mergeConfig( - mergeConfig(defaultConfig(systemStats, strategy, role, modules, authStrategies), fileConfig), + mergeConfig( + defaultConfig(systemStats, strategy, role, modules, authStrategies, standalone, defaulted), + fileConfig, + ), overrideConfig, ) as unknown as Omit & { readonly metrics?: Config["metrics"] }; const merged: Config = { @@ -596,7 +617,7 @@ export async function loadConfig({ // them there would fail a start over a value nothing reads. validateGatewayMembership(merged); } - return deepFreeze(merged); + return { config: deepFreeze(merged), defaulted }; } /** @@ -885,13 +906,15 @@ function defaultConfig( role: DaemonMode, modules: readonly ModuleConfigEntry[], authStrategies: readonly AuthStrategyDefinition[], + standalone: boolean, + defaulted: ReadonlySet, ): Omit { return { mode: role, capabilities: Object.fromEntries( modules.map((entry) => [ entry.name, - { ...(entry.defaults as Record), enabled: false }, + { ...(entry.defaults as Record), enabled: defaulted.has(entry.name) }, ]), ) as Config["capabilities"], capacity: { @@ -935,11 +958,9 @@ function defaultConfig( retention: 7 * 24 * 60 * 60 * 1000, maxBytes: 256 * 1024 * 1024, }, - // ADR 0005 §2: a gateway always listens on HTTP, so that is its default rather than - // something every operator has to remember to switch on; a worker's HTTP gateway stays - // opt-in exactly as before. + // why: ADR 0005 §2 and ADR 0046 §1: a gateway and a standalone worker listen on HTTP by default; a joined worker is reached through its gateway, so its default is off. http: { - enabled: role === "gateway", + enabled: role === "gateway" || standalone, host: "127.0.0.1", port: role === "gateway" ? 4700 : 4701, ...Object.fromEntries( diff --git a/src/core/index.ts b/src/core/index.ts index 39b5253b1..bfaa2c698 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -11,6 +11,7 @@ export { type DownloadPolicy, effectiveAllowDownload, loadConfig, + loadConfigWithDefaults, type ModuleConfigEntry, REDACTED_VALUE, redactConfig, diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 1d700443c..00e4eed93 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -37,7 +37,7 @@ The role (`StartDaemonOptions.role`; the entry reads it from `--gateway` through `ComponentInstaller` → `createCore` → `createLeasing` → `core.connect` → `CleanupReaper`, `Nuke`, `TokenStore`, `AdminSecretManager` → `GatewayUplink` when `gateway.url` and `gateway.token` are both set → `DaemonServer` with `Dispatcher`. - HTTP starts only when `http.enabled`. + HTTP starts only when `http.enabled` (default on for a standalone worker, off for a joined one). - **Gateway** — instance id → `TokenStore`, `AdminSecretManager` → `FleetLeaseIndex` (requester prefix `gw::`) → `GatewayService` (uplink listener, drained workers in `state.db`) → `FleetLeaseCoordinator` → `createAlerts` when `gateway.alerts.destinations` is not empty diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 9de36e753..e299209cd 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -86,6 +86,12 @@ afterEach(async () => { ); }); +// why: a standalone worker serves HTTP and agent-device by default (ADR 0046); a test that asks for neither pins them off, and two daemons would clash on port 4701. +const STANDALONE_OFF = { + capabilities: { "agent-device": { enabled: false } }, + http: { enabled: false }, +} as const; + /** `drivers: undefined` is spelled out by a caller that wants real (module-substituted) * discovery rather than the fake driver below. */ async function start( @@ -94,6 +100,7 @@ async function start( readonly drivers?: StartDaemonOptions["drivers"] | undefined; } = {}, ) { + const { configOverrides, ...rest } = overrides; const directory = await mkdtemp(join(tmpdir(), "simlock-main-")); temporaryDirectories.push(directory); const sink = new MemoryLogSink(); @@ -108,7 +115,9 @@ async function start( hostLoadProbe: null, logger, version: "1.2.3", - ...overrides, + ...rest, + configOverrides: + overrides.role === "gateway" ? configOverrides : { ...STANDALONE_OFF, ...configOverrides }, } as StartDaemonOptions); runningDaemons.push(daemon); return { daemon, directory, sink }; @@ -297,6 +306,7 @@ describe("the version a daemon reports", () => { const clock = new FakeClock(1_000); const socketPath = join(directory, "daemon.sock"); const daemon = await startDaemon({ + configOverrides: STANDALONE_OFF, deviceDataTables: fakeDeviceDataTables, clock, dataDirectory: directory, @@ -1080,6 +1090,7 @@ describe("startDaemon wires core and leasing together", () => { const daemon = await startDaemon({ clock, + configOverrides: STANDALONE_OFF, dataDirectory: directory, deviceDataTables: fakeDeviceDataTables, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], @@ -1103,6 +1114,7 @@ describe("startDaemon wires core and leasing together", () => { const options = () => ({ clock, + configOverrides: STANDALONE_OFF, dataDirectory: directory, deviceDataTables: fakeDeviceDataTables, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], @@ -1157,6 +1169,7 @@ describe("startDaemon wires core and leasing together", () => { const options = () => ({ clock, + configOverrides: STANDALONE_OFF, dataDirectory: directory, deviceDataTables: fakeDeviceDataTables, drivers: [driver], @@ -1343,6 +1356,7 @@ describe("startDaemon startup readiness", () => { const socketPath = join(directory, "daemon.sock"); const startPromise = startDaemon({ clock, + configOverrides: STANDALONE_OFF, dataDirectory: directory, drivers: [ new FakeDriver({ @@ -1406,6 +1420,7 @@ describe("startDaemon stopped while starting", () => { const filesystem = new MemoryFilesystem(); const startPromise = startDaemon({ clock, + configOverrides: STANDALONE_OFF, dataDirectory: directory, drivers: [ new FakeDriver({ @@ -2900,7 +2915,11 @@ describe("startDaemon with the agent-device edge", () => { await filesystem.writeFileAtomic(`${packageRoot}/package.json`, '{"name":"agent-device"}'); await filesystem.writeFileAtomic(entry, ""); filesystem.defineSymlink(command, realCli); - await filesystem.writeFileAtomic(join(directory, "config.json"), JSON.stringify(config)); + // why: HTTP and agent-device are on by default for a standalone worker (ADR 0046); a test here asks for agent-device and never for HTTP, and two daemons would clash on 4701. + await filesystem.writeFileAtomic( + join(directory, "config.json"), + JSON.stringify({ http: { enabled: false }, ...(config as Record) }), + ); if (options.record !== undefined) { await filesystem.writeFileAtomic( join(directory, "agent-device-daemon.json"), @@ -3363,6 +3382,41 @@ describe("startDaemon with the agent-device edge", () => { }); }, 10_000); + const version = (stdout: string) => ({ + match: { args: [realCli, "--version"], command: process.execPath }, + result: { code: 0, stderr: "", stdout }, + }); + + // why: the simulator daemon's version answer is the row's own text when it is not the running one, and the phone daemon's follows `phones`. + function scriptedDaemons( + setup: Awaited>, + tcpProbe: FakeTcpProbe, + simulator: string, + phones: string | undefined, + ): ScriptedProcessRunner { + if (simulator === "missing") return new ScriptedProcessRunner([]); + return new ScriptedProcessRunner([ + version(simulator === "running" ? "0.21.28\n" : simulator), + { + hangs: true, + match: { args: [entry, `--simlock-home=${setup.directory}`], command: process.execPath }, + onSpawn: async () => { + await setup.filesystem.writeFileAtomic( + join(setup.directory, "agent-device", "daemon.json"), + JSON.stringify({ httpPort: 4310, pid: 2, token: "t" }), + ); + tcpProbe.startListening(4310); + }, + }, + version(phones === undefined || phones === "unstartable" ? "0.21.28\n" : phones), + ]); + } + + const findingLabel = (finding: { readonly module?: string; readonly message?: string }) => { + if (finding.module === "alpha") return "alpha"; + return finding.message?.startsWith("phone daemon: ") === true ? "phones" : "simulator"; + }; + it.each([ { name: "both daemons down: agent-device is found nowhere", @@ -3371,6 +3425,22 @@ describe("startDaemon with the agent-device edge", () => { findings: ["simulator", "phones", "alpha"], capability: "unavailable", }, + { + name: "not found, and capabilities.agent-device.enabled never set: it is on only by default", + simulator: "missing", + phones: undefined, + enabled: undefined, + findings: ["alpha"], + capability: "off", + }, + { + name: "a wrong version, and capabilities.agent-device.enabled never set", + simulator: "0.20.3\n", + phones: undefined, + enabled: undefined, + findings: ["simulator", "phones", "alpha"], + capability: "unavailable", + }, { name: "the phone daemon finds a wrong version", simulator: "running", @@ -3386,48 +3456,21 @@ describe("startDaemon with the agent-device edge", () => { capability: "available", }, ] as const)( - "lists a phone daemon finding that starts with `phone daemon: ` after the simulator daemon's and before another module's, while the capability follows the simulator daemon: $name", - async ({ capability, findings, phones, simulator }) => { + "lists a phone daemon finding that starts with `phone daemon: ` after the simulator daemon's and before another module's, while the capability follows the simulator daemon, and says nothing of a command never found while agent-device is on only by default: $name", + async ({ capability, findings, phones, simulator, ...row }) => { const setup = await setUp({ capabilities: { "agent-device": { command: simulator === "missing" ? "/opt/missing/agent-device" : command, - enabled: true, + ...("enabled" in row ? {} : { enabled: true }), }, alpha: { enabled: true }, }, }); - const version = (stdout: string) => ({ - match: { args: [realCli, "--version"], command: process.execPath }, - result: { code: 0, stderr: "", stdout }, - }); const health = new FakeAgentDeviceHealth(); health.respondWith({ rpcProtocolVersion: 2, service: "agent-device-daemon" }); const tcpProbe = new FakeTcpProbe(); - const runner = new ScriptedProcessRunner( - simulator === "missing" - ? [] - : [ - version("0.21.28\n"), - { - hangs: true, - match: { - args: [entry, `--simlock-home=${setup.directory}`], - command: process.execPath, - }, - onSpawn: async () => { - await setup.filesystem.writeFileAtomic( - join(setup.directory, "agent-device", "daemon.json"), - JSON.stringify({ httpPort: 4310, pid: 2, token: "t" }), - ); - tcpProbe.startListening(4310); - }, - }, - ...(phones === "unstartable" || phones === undefined - ? [version("0.21.28\n")] - : [version(phones)]), - ], - ); + const runner = scriptedDaemons(setup, tcpProbe, simulator, phones); const { clock, daemon } = await startEdge(setup, { agentDevice: agentDeviceModuleWith({ health }), clock: new FakeClock(1_000), @@ -3451,14 +3494,7 @@ describe("startDaemon with the agent-device edge", () => { }[]; } ).findings.filter((finding) => finding.kind === "module-unavailable"); - const labelled = async () => - (await unavailable()).map((finding) => - finding.module === "alpha" - ? "alpha" - : finding.message?.startsWith("phone daemon: ") === true - ? "phones" - : "simulator", - ); + const labelled = async () => (await unavailable()).map(findingLabel); // why: the simulator daemon's polls sleep on the fake clock, so the test advances it until the findings settle. for (let tick = 0; tick < 400; tick += 1) { if (JSON.stringify(await labelled()) === JSON.stringify(findings)) break; @@ -3552,6 +3588,7 @@ describe("startDaemon host load", () => { temporaryDirectories.push(directory); const clock = new FakeClock(1_000); const daemon = await startDaemon({ + configOverrides: STANDALONE_OFF, deviceDataTables: fakeDeviceDataTables, clock, dataDirectory: directory, @@ -3586,6 +3623,7 @@ describe("startDaemon host load", () => { const socketPath = join(directory, "daemon.sock"); const startPromise = startDaemon({ clock, + configOverrides: STANDALONE_OFF, dataDirectory: directory, drivers: [ new FakeDriver({ @@ -3737,6 +3775,7 @@ describe("startDaemon host load", () => { await expect( startDaemon({ clock, + configOverrides: STANDALONE_OFF, dataDirectory: directory, drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], deviceDataTables: fakeDeviceDataTables, @@ -3985,7 +4024,10 @@ describe("startDaemon state.db", () => { const launch = (now: number) => startDaemon({ clock: new FakeClock(now), - configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + configOverrides: { + ...STANDALONE_OFF, + http: { enabled: true, host: "127.0.0.1", port }, + }, dataDirectory: directory, deviceDataTables: fakeDeviceDataTables, drivers: [], @@ -4144,6 +4186,7 @@ describe("startDaemon version check", () => { const sink = new MemoryLogSink(); const daemon = await startDaemon({ clock, + configOverrides: overrides.role === "gateway" ? {} : STANDALONE_OFF, dataDirectory: directory, drivers: [], filesystem: new MemoryFilesystem(), @@ -4178,7 +4221,7 @@ describe("startDaemon version check", () => { await expect( startDaemon({ clock, - configOverrides: { update: { check } }, + configOverrides: { ...STANDALONE_OFF, update: { check } }, dataDirectory: directory, drivers: [], filesystem: new SecretRefusingFilesystem(), diff --git a/src/daemon/main.ts b/src/daemon/main.ts index a197e7b96..a940cb99d 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -32,7 +32,7 @@ import { DriverCatalog, HostFactsReader, createCore, - loadConfig, + loadConfigWithDefaults, latestPresence, loadInstanceId, OwnedRootError, @@ -279,12 +279,13 @@ async function composeDaemon( const socketPath = options.socketPath ?? resolveDaemonSocketPath(dataDirectory); const configWarnings: string[] = []; const moduleDefinitions = options.optionalModules ?? optionalModules; - const config = await loadConfig({ + const { config, defaulted } = await loadConfigWithDefaults({ configPath, filesystem, - modules: moduleDefinitions.map(({ config: moduleConfig, name }) => ({ + modules: moduleDefinitions.map(({ config: moduleConfig, enabledByDefault, name }) => ({ name, ...moduleConfig, + ...(enabledByDefault === undefined ? {} : { enabledByDefault }), })), ...(options.configOverrides === undefined ? {} : { overrides: options.configOverrides }), role, @@ -493,6 +494,7 @@ async function composeDaemon( let cancelPendingRequest: ((requesterId: string) => Promise) | undefined; const moduleHost = await createModuleHost({ config, + defaulted, context: { cancelPending: (requesterId) => { if (cancelPendingRequest === undefined) { diff --git a/src/daemon/optional-modules.test.ts b/src/daemon/optional-modules.test.ts index d5f52b2ad..933433877 100644 --- a/src/daemon/optional-modules.test.ts +++ b/src/daemon/optional-modules.test.ts @@ -131,7 +131,12 @@ async function prepare(options: RigOptions) { clock, configOverrides: { capabilities: Object.fromEntries((options.on ?? []).map((name) => [name, { enabled: true }])), - ...(port === undefined ? {} : { http: { enabled: true, host: "127.0.0.1", port } }), + // why: a standalone worker serves HTTP by default (ADR 0046); a rig that asks for no HTTP pins it off. + ...(port === undefined + ? options.extra?.role === "gateway" + ? {} + : { http: { enabled: false } } + : { http: { enabled: true, host: "127.0.0.1", port } }), ...options.overrides, }, dataDirectory: directory, @@ -623,7 +628,7 @@ describe("optional modules: afterSocketClaimed", () => { ) => ({ clock: new FakeClock(1_000), - configOverrides: { capabilities: { alpha: { enabled: true } } }, + configOverrides: { capabilities: { alpha: { enabled: true } }, http: { enabled: false } }, dataDirectory: directory, drivers: [ new FakeDriver({ diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index ae2732e46..e40c24382 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -166,6 +166,11 @@ export async function startWorker( directories.push(directory); const logger = new RecordingLogger(); const options: StartDaemonOptions = { + // why: a standalone worker serves HTTP and agent-device by default (ADR 0046); a relay test asks for neither. + configOverrides: { + capabilities: { "agent-device": { enabled: false } }, + http: { enabled: false }, + }, dataDirectory: directory, deviceDataTables: fakeDeviceDataTables, drivers: [ diff --git a/src/http/AGENTS.md b/src/http/AGENTS.md index 3fd45295b..2f38edcde 100644 --- a/src/http/AGENTS.md +++ b/src/http/AGENTS.md @@ -109,13 +109,13 @@ until `POST /v1/leases/{id}/renew` drains them into `notices`. `lease_lost` clea ## State and timers -| What | Default | Key | -| --------------------------- | ----------------------------------------------------- | ------------------------ | -| Listener on/off | off on a worker, on on a gateway | `http.enabled` | -| Address | `127.0.0.1`, port 4701 on a worker, 4700 on a gateway | `http.host`, `http.port` | -| SSE keepalive | 15 s | fixed, `sse.ts` | -| Long-poll cap | 60 s | fixed, `app.ts` | -| `NO_CAPACITY` `Retry-After` | 5 s | fixed, `errors.ts` | +| What | Default | Key | +| --------------------------- | --------------------------------------------------------------- | ------------------------ | +| Listener on/off | on on a gateway and a standalone worker, off on a joined worker | `http.enabled` | +| Address | `127.0.0.1`, port 4701 on a worker, 4700 on a gateway | `http.host`, `http.port` | +| SSE keepalive | 15 s | fixed, `sse.ts` | +| Long-poll cap | 60 s | fixed, `app.ts` | +| `NO_CAPACITY` `Retry-After` | 5 s | fixed, `errors.ts` | - The listener starts right after the socket claim (`onSocketClaimed`), before startup convergence. Early requests park in the dispatcher. On a gateway the worker uplink diff --git a/src/modules/AGENTS.md b/src/modules/AGENTS.md index 435e1ad45..9ac35cbcd 100644 --- a/src/modules/AGENTS.md +++ b/src/modules/AGENTS.md @@ -15,7 +15,7 @@ Imported by: `daemon/main.ts` (the factory and types); on a gateway it is handed ## Rules -- A module is on only under `capabilities..enabled`; off, nothing of it is loaded and its capability reads `off`. +- A module is on only under `capabilities..enabled`; off, nothing of it is loaded and its capability reads `off`. `enabled` defaults to false; a definition with `enabledByDefault: "standalone-worker"` gets true on a worker with no `gateway.url` when no layer sets it. The loader reports those names (`loadConfigWithDefaults`), and the host hands the module `ctx.enabledByDefault`. - Names: the capability name pattern, unique, not a core route segment, at most 16 capabilities. - Creating starts nothing. A start that fails before the socket is claimed drops created modules; after it, the normal stop runs their stop hooks. - Hooks are direct calls. `afterSocketClaimed` is not awaited; `beforeDrain` and `beforeDriversDispose` share one 30 s budget per step; a throw is logged and the step goes on. diff --git a/src/modules/host.ts b/src/modules/host.ts index 0ff6a9a63..4e784aff9 100644 --- a/src/modules/host.ts +++ b/src/modules/host.ts @@ -143,6 +143,7 @@ async function createOne( ...options.context, config: section, daemonConfig: options.config, + enabledByDefault: options.defaulted?.has(name) ?? false, logger: options.logger.child(name), name, }); diff --git a/src/modules/testing.ts b/src/modules/testing.ts index 08ad8bc50..f4403a274 100644 --- a/src/modules/testing.ts +++ b/src/modules/testing.ts @@ -175,6 +175,7 @@ export async function fakeWorkerContext(name: string, config: C): Promise bus.subscribe(event, handler) }, filesystem: new MemoryFilesystem(), diff --git a/src/modules/types.ts b/src/modules/types.ts index e3336690b..3982fe09c 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -132,6 +132,8 @@ export interface WorkerContext { readonly name: string; readonly instanceId: string; readonly config: C; + // why: true when no layer set this module's `enabled` and the loader turned it on; the module may then stay quiet about a missing tool. + readonly enabledByDefault: boolean; readonly daemonConfig: Config; readonly logger: Logger; readonly clock: Clock; @@ -246,6 +248,8 @@ export interface OptionalModuleDefinition { readonly name: string; readonly config: ModuleConfig; readonly localProfile?: ModuleLocalProfile; + // why: plain data the config loader reads without naming the module; a missing `enabled` then means on for a standalone worker (ADR 0046 §1). + readonly enabledByDefault?: "standalone-worker"; readonly http?: { readonly routes: readonly ModuleHttpRoute[] }; loadWorker(): Promise<{ createWorker(ctx: WorkerContext): WorkerModule }>; loadGateway?(): Promise<{ createGateway(ctx: GatewayContext): GatewayModule }>; @@ -308,5 +312,9 @@ export interface ModuleHostOptions { readonly config: Config; readonly logger: Logger; readonly tokens: ModuleTokens; - readonly context: Omit, "name" | "config" | "daemonConfig" | "logger">; + readonly defaulted?: ReadonlySet; + readonly context: Omit< + WorkerContext, + "name" | "config" | "daemonConfig" | "logger" | "enabledByDefault" + >; } diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index 76a25c6b2..57e1ef8bc 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -214,7 +214,7 @@ makes the next boot wipe the device once to take a new clean snapshot. | Key | Type | Default | Meaning | Applies to | | ---------------------------- | ------------------------ | ------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------- | -| `http.enabled` | boolean | `false` on a worker, `true` on a gateway | Serve the HTTP API and the web console. A gateway with `false` does not start; a worker with `gateway.url` set must be `false`. | Both | +| `http.enabled` | boolean | `true` on a gateway and on a standalone worker, `false` on a worker with `gateway.url` set | Serve the HTTP API and the web console. A gateway with `false` does not start; a worker with `gateway.url` set must be `false`. | Both | | `http.host` | string | `127.0.0.1` | Address to listen on. Simlock does no TLS: put a reverse proxy in front for HTTPS. | Both | | `http.port` | integer `1`–`65535` | `4701` on a worker, `4700` on a gateway | Port to listen on. | Both | | `http.proxyAuth` | object | not set (proxy sign-in off) | Treat a person your sign-in proxy (Cloudflare Access, for example) has signed in as an operator, with no Simlock token. Set `header`, `jwksUrl`, `issuer` and `audience` together, as one object. | Both | @@ -299,12 +299,12 @@ and delivery. ## Optional modules -Each optional module has a block under `capabilities.`. A module is off until you turn it on. +Each optional module has a block under `capabilities.`. A module is off until you turn it on, except agent-device on a standalone worker, which is on until you turn it off. A name Simlock does not know is warned about and ignored. | Key | Type | Default | Meaning | Applies to | | ------------------------------------------- | ------------------------------------ | ---------------- | ----------------------------------------------------------------------------------------------------------- | ---------- | -| `capabilities.agent-device.enabled` | boolean | `false` | On a worker: run an agent-device daemon that sees Simlock's devices, and a phone daemon beside it. On a gateway: serve agent-device and send each agent to a worker that has it. | Both | +| `capabilities.agent-device.enabled` | boolean | `true` on a standalone worker, `false` on a worker with `gateway.url` set and on a gateway | On a worker: run an agent-device daemon that sees Simlock's devices, and a phone daemon beside it. On a gateway: serve agent-device and send each agent to a worker that has it. On a standalone worker where you never set it and `agent-device` is not installed, the capability reads `off` and `simlock doctor` says nothing. | Both | | `capabilities.agent-device.command` | non-empty string | `agent-device` | The agent-device program: a name looked up on `PATH`, or a path. | Worker | | `capabilities.agent-device.leaseTtlCapMs` | integer from `5000` to `lease.maxTtlMs` | not set (no cap) | Longest TTL for leases agent-device takes through Simlock. A longer TTL is lowered to it; a lease with none gets it. | Both | | `capabilities.agent-device.ios.teamId` | non-empty string | not set | Apple developer team ID agent-device signs its iPhone runner with. Passed to the phone daemon. | Worker | diff --git a/website/src/content/docs/docs/using-devices/agent-device.mdx b/website/src/content/docs/docs/using-devices/agent-device.mdx index 1a4e7ca8e..188385abc 100644 --- a/website/src/content/docs/docs/using-devices/agent-device.mdx +++ b/website/src/content/docs/docs/using-devices/agent-device.mdx @@ -14,7 +14,7 @@ Simlock runs two agent-device daemons on each worker and watches both: one over On each worker: - agent-device 0.21.28 or later, installed so the daemon's user can run `agent-device`. Simlock never installs or updates it. -- HTTP turned on, since agents reach agent-device over HTTP. +- HTTP on, since agents reach agent-device over HTTP. A standalone worker has it on by default. On each agent's machine: @@ -29,14 +29,13 @@ The phone daemon runs `adb` without Simlock's version check, so its `adb` must c -1. On a standalone worker, turn on agent-device and HTTP. A worker that joins a gateway turns on only agent-device, and keeps HTTP off: +1. A standalone worker serves agent-device by default, with HTTP on `127.0.0.1:4701`: there is nothing to turn on. Install agent-device so the daemon's user can run it, then restart the worker (`simlock daemon stop`, then `simlock daemon start`); the worker looks for the command only when it starts. Until agent-device is installed, the worker's agent-device capability is `off` and `simlock doctor` says nothing. A worker that joins a gateway has agent-device off, and HTTP off for good; turn on only agent-device there: ```sh simlock config set capabilities.agent-device.enabled true - simlock config set http.enabled true ``` - HTTP listens on `127.0.0.1:4701` by default. For agents on other machines, set `http.host` and put a reverse proxy with TLS in front; Simlock does not do HTTPS itself (see [Configuration reference](/simlock/docs/reference/configuration)). If `agent-device` is not on the daemon's `PATH`, set `capabilities.agent-device.command` to its full path. + For agents on other machines, set `http.host` and put a reverse proxy with TLS in front; Simlock does not do HTTPS itself (see [Configuration reference](/simlock/docs/reference/configuration)). If `agent-device` is not on the daemon's `PATH`, set `capabilities.agent-device.command` to its full path. Setting `capabilities.agent-device.enabled` to `true` yourself makes a missing command show up as a `simlock doctor` finding. 2. With a gateway, turn agent-device on there too. The gateway runs no agent-device of its own; it sends each agent to a worker where agent-device is available: @@ -100,7 +99,7 @@ The URL is the worker's HTTP address, or the gateway's (port 4700 by default), f ## On the same Mac -On a standalone worker with HTTP and agent-device turned on, an agent on the same Mac, running as the same user, needs no token of its own. At each start the worker writes `agent-device-profile.json` in its data directory (`~/.simlock/` for a user session), readable only by its user. It holds the worker's agent-device URL and one agent token, labelled `agent-device on this Mac`. Connect with that file: +On a standalone worker, where HTTP and agent-device are on by default, an agent on the same Mac, running as the same user, needs no token of its own. At each start the worker writes `agent-device-profile.json` in its data directory (`~/.simlock/` for a user session), readable only by its user. It holds the worker's agent-device URL and one agent token, labelled `agent-device on this Mac`. Connect with that file: ```sh agent-device connect --remote-config ~/.simlock/agent-device-profile.json --session s1 @@ -111,7 +110,7 @@ agent-device close --session s1 Pass `--session` on every command. All local agents share the profile's one token, so they share one Simlock identity: give each agent its own `--session` name, or two agents will see each other's devices. -The worker keeps the same token across restarts, so a saved connection keeps working. If the file changes anyway (you changed `http.port`, or revoked the token with `simlock token revoke`), agent-device refuses the saved connection with `Active remote connection config changed`. Run `agent-device connect --remote-config ~/.simlock/agent-device-profile.json --session s1 --force` to refresh it. The worker removes the file and revokes the token when HTTP or agent-device is turned off. A worker that joins a gateway writes none. Do not give your own tokens the label `agent-device on this Mac`: the worker revokes them at the next start. +The worker keeps the same token across restarts, so a saved connection keeps working. If the file changes anyway (you changed `http.port`, or revoked the token with `simlock token revoke`), agent-device refuses the saved connection with `Active remote connection config changed`. Run `agent-device connect --remote-config ~/.simlock/agent-device-profile.json --session s1 --force` to refresh it. The worker removes the file and revokes the token when HTTP or agent-device is turned off (`http.enabled` or `capabilities.agent-device.enabled` set to `false`). A worker that joins a gateway writes none. Do not give your own tokens the label `agent-device on this Mac`: the worker revokes them at the next start. ## Through a gateway diff --git a/website/src/content/docs/docs/using-devices/remote-agents.mdx b/website/src/content/docs/docs/using-devices/remote-agents.mdx index 6d1895846..eaba16809 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -11,15 +11,7 @@ The `simlock` CLI talks only to the daemon on its own machine; it cannot target On the machine you connect to: -- **A standalone worker** has HTTP off by default. Turn it on, then restart the daemon. A worker that has joined a gateway cannot turn it on: its agents connect to the gateway instead. - - ```sh - simlock config set http.enabled true - simlock daemon stop - simlock daemon start - ``` - - It listens on `127.0.0.1:4701`. +- **A standalone worker** has HTTP on by default, on `127.0.0.1:4701`. A worker that has joined a gateway has it off and cannot turn it on: its agents connect to the gateway instead. - **A gateway** has HTTP on by default, on `127.0.0.1:4700`. diff --git a/website/src/content/docs/docs/worker/configuration.mdx b/website/src/content/docs/docs/worker/configuration.mdx index 1f430f301..9957eeced 100644 --- a/website/src/content/docs/docs/worker/configuration.mdx +++ b/website/src/content/docs/docs/worker/configuration.mdx @@ -89,7 +89,7 @@ The output includes secrets from the file, such as `gateway.token`. Do not paste | Goal | Key | Default | | --- | --- | --- | -| Turn on the HTTP API and the console | `http.enabled` | `false` | +| Turn off the HTTP API and the console | `http.enabled` | `true` on a standalone worker | | Choose the address and port HTTP listens on | `http.host`, `http.port` | `127.0.0.1`, `4701` | | Keep idle devices booted longer | `idle.shutdownAfterMs` | `600000` (10 min) | | Keep shut-down devices on disk longer | `idle.deleteAfterMs` | `3600000` (60 min) | @@ -107,13 +107,15 @@ The output includes secrets from the file, such as `gateway.token`. Do not paste The sections below show the common changes. Each needs a restart. -### Turn on HTTP +### Turn off HTTP + +A standalone worker serves the HTTP API and the [console](/simlock/docs/worker/console) on `127.0.0.1:4701` with no setting. Both still ask for a token. To stop it: ```sh -simlock config set http.enabled true +simlock config set http.enabled false ``` -This is what remote agents and the [console](/simlock/docs/worker/console) need. A worker that has joined a gateway (`gateway.url` is set) refuses it: set `http.enabled` to `false` there and use the gateway instead. +A worker that has joined a gateway (`gateway.url` is set) has HTTP off, and refuses `true`: use the gateway instead. Agent-device is on by default on a standalone worker too; see [agent-device](/simlock/docs/using-devices/agent-device).