From f8cda798c49342d716646fe3d7ee4d97a6f6424e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 20:16:35 +0100 Subject: [PATCH 1/3] fix(daemon): name a sandbox-denied loopback listen and point at host access A daemon whose loopback listen fails with EPERM or EACCES now exits with a typed listen-denied code. The client reports startup-listen-denied, does not retry, and its hint names the sandbox and the way out (allow agent-device in the agent's sandbox rules, or rerun with host access). Co-Authored-By: Claude Opus 5.5 --- .../daemon-client-startup-budget.test.ts | 17 ++++++++++ .../src/daemon-client-startup.ts | 27 +++++++++++---- .../src/daemon-lifecycle-errors.ts | 3 ++ .../src/daemon-registration-owner.ts | 10 +++++- .../daemon/src/server/http/daemon-runtime.ts | 5 +-- .../daemon/src/server/http/transport.test.ts | 34 +++++++++++++++++++ packages/daemon/src/server/http/transport.ts | 27 +++++++++++++-- website/docs/docs/error-reasons.md | 2 ++ 8 files changed, 114 insertions(+), 11 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts index 7d8d388652..92c9b8e62d 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts @@ -622,6 +622,23 @@ test('an unproven registration exit reports startup-exited even under a short en assert.equal(failure.details?.startupTimeoutMs, 2_000); }); +test('a listen-denied exit fails once with startup-listen-denied and a host-access hint', async () => { + const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-listen-denied-')); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { kind: 'exit', exit: { pid: 998_555, exitCode: DAEMON_STARTUP_EXIT_CODES.listenDenied } }, + { kind: 'exit', exit: { pid: 998_556, exitCode: DAEMON_STARTUP_EXIT_CODES.listenDenied } }, + ]), + ); + pause.mockImplementation(async () => { + await realPause(); + }); + const failure = await expectStartupFailure(sendToDaemon(request(paths))); + assert.equal(failure.details?.reason, 'startup-listen-denied'); + assert.match(String(failure.details?.hint), /listen EPERM or EACCES\). A sandbox/); + assert.equal(spawn.mock.calls.length, 1, 'a denied listen is not retried'); +}); + test('a startup ceiling that is not a positive integer is rejected before any daemon spawns', async () => { const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-bad-ceiling-')); for (const raw of ['0', '-5', 'abc', '12.5']) { diff --git a/packages/daemon-client/src/daemon-client-startup.ts b/packages/daemon-client/src/daemon-client-startup.ts index 19a0b983c6..9dd22b697e 100644 --- a/packages/daemon-client/src/daemon-client-startup.ts +++ b/packages/daemon-client/src/daemon-client-startup.ts @@ -77,8 +77,16 @@ const MINIMUM_DAEMON_TAKEOVER_BUDGET_MS = 5_000; const DAEMON_STARTUP_TIMEOUT_ENV = 'AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS'; +/** Agent directive: a sandboxed agent reads it to ask for host access instead of giving up. */ +const DAEMON_LISTEN_DENIED_HINT = + 'The host denied the daemon a loopback port on 127.0.0.1 (listen EPERM or EACCES). A sandbox ' + + 'around this command likely blocks local ports and simulator access. Run agent-device ' + + "outside the sandbox: allow the agent-device command in the agent's sandbox rules, or rerun it " + + 'with host access (escalated permissions).'; + type DaemonStartupFailureReason = | typeof DAEMON_UNAVAILABLE_REASONS.startupExited.reason + | typeof DAEMON_UNAVAILABLE_REASONS.startupListenDenied.reason | typeof DAEMON_UNAVAILABLE_REASONS.startupStalled.reason | typeof DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason; @@ -341,10 +349,12 @@ export async function startLocalDaemon(settings: DaemonClientSettings): Promise< ...(daemonLogTail ? { daemonLogTail } : {}), metadataState: state, hint: - reason === DAEMON_UNAVAILABLE_REASONS.startupStalled.reason || - reason === DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason - ? resolveStartupProgressHint(reason, startupTimeoutMs) - : resolveDaemonStartupHint(state, settings.paths), + effectiveReason === DAEMON_UNAVAILABLE_REASONS.startupListenDenied.reason + ? DAEMON_LISTEN_DENIED_HINT + : reason === DAEMON_UNAVAILABLE_REASONS.startupStalled.reason || + reason === DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason + ? resolveStartupProgressHint(reason, startupTimeoutMs) + : resolveDaemonStartupHint(state, settings.paths), }); } @@ -385,16 +395,21 @@ async function attemptLocalDaemonStartup( }; } const { cleanup, joined } = await retireStartupAttempt(settings, launch, deadline); + const listenDenied = + startup.kind === 'early_exit' && + startup.exit.exitCode === DAEMON_STARTUP_EXIT_CODES.listenDenied; const reason: DaemonStartupFailureReason = startup.kind === 'stalled' ? DAEMON_UNAVAILABLE_REASONS.startupStalled.reason : startup.kind === 'ceiling' ? DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason - : DAEMON_UNAVAILABLE_REASONS.startupExited.reason; + : listenDenied + ? DAEMON_UNAVAILABLE_REASONS.startupListenDenied.reason + : DAEMON_UNAVAILABLE_REASONS.startupExited.reason; const available = isRegistrationAvailable(inspectProcessLock(settings.paths.lockPath)); return { cleanup, - retry: joined && startup.kind === 'early_exit' && available, + retry: joined && startup.kind === 'early_exit' && !listenDenied && available, reason, startError: startup.kind === 'early_exit' ? describeDaemonEarlyExit(startup.exit) : undefined, daemonProcess: startup.kind === 'early_exit' ? startup.exit : { pid: launch.pid }, diff --git a/packages/daemon-client/src/daemon-lifecycle-errors.ts b/packages/daemon-client/src/daemon-lifecycle-errors.ts index e4ec1cb54d..c904d24d76 100644 --- a/packages/daemon-client/src/daemon-lifecycle-errors.ts +++ b/packages/daemon-client/src/daemon-lifecycle-errors.ts @@ -47,6 +47,9 @@ export const DAEMON_UNAVAILABLE_REASONS = { policyMismatch: { reason: 'DAEMON_POLICY_MISMATCH' }, // The daemon process ended before it registered a reachable endpoint. startupExited: { reason: 'startup-exited' }, + // The daemon process ended because the host refused its loopback listen, as a sandbox around the + // launching command does. + startupListenDenied: { reason: 'startup-listen-denied' }, // The daemon stayed registered and reachable but never reported the startup phase that follows. startupStalled: { reason: 'startup-stalled' }, // Startup passed the ceiling its own startup budget allows, so this client stopped waiting. diff --git a/packages/daemon-contracts/src/daemon-registration-owner.ts b/packages/daemon-contracts/src/daemon-registration-owner.ts index 92186a9431..5cff1e0681 100644 --- a/packages/daemon-contracts/src/daemon-registration-owner.ts +++ b/packages/daemon-contracts/src/daemon-registration-owner.ts @@ -74,7 +74,15 @@ const DAEMON_OWNERSHIP_REFUSAL_REASONS = { privateStartupUnowned: { reason: 'daemon_private_startup_unowned' }, } as const satisfies ReasonTable<'daemon lifecycle'>; -export const DAEMON_STARTUP_EXIT_CODES = Object.freeze({ busy: 75, unproven: 78 }); +/** + * The exit codes of a daemon startup that must not run. `listenDenied`: the host refused the + * loopback listen (EPERM or EACCES), as a sandbox around the launching command does. + */ +export const DAEMON_STARTUP_EXIT_CODES = Object.freeze({ + busy: 75, + listenDenied: 77, + unproven: 78, +}); export type DaemonRegistrationFields = Readonly<{ socketPort?: number; httpPort?: number; diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index 4d6e1579eb..a55aa93dfc 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -159,8 +159,9 @@ export type DaemonRuntimeController = { }; /** - * Thrown by {@link startDaemonRuntime} when the daemon must not run: its policy is unusable or - * another daemon owns the state dir. `details.exitCode` is the code the executable exits with. + * Thrown by {@link startDaemonRuntime} when the daemon must not run: its policy is unusable, + * another daemon owns the state dir, or the host denied its loopback listen. `details.exitCode` is + * the code the executable exits with. */ export function daemonStartupExitCode(error: unknown): number { const exitCode = asAppError(error).details?.exitCode; diff --git a/packages/daemon/src/server/http/transport.test.ts b/packages/daemon/src/server/http/transport.test.ts index a4261f1320..4dffb80c6d 100644 --- a/packages/daemon/src/server/http/transport.test.ts +++ b/packages/daemon/src/server/http/transport.test.ts @@ -13,6 +13,8 @@ import { } from '@agent-device/host-kit/request'; import { applicationLifecycleExecutionFromRequest } from '../../sessions/application-lifecycle-execution.ts'; import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; +import { AppError } from '@agent-device/kernel/errors'; +import { DAEMON_STARTUP_EXIT_CODES } from '@agent-device/daemon-contracts/daemon-registration-owner'; test('Provider-backed integration daemon socket transport frames requests and normalizes malformed input', async (t) => { if (await skipWhenLoopbackUnavailable(t)) { @@ -490,3 +492,35 @@ test('Provider-backed integration socket rejects malformed device pins before in await closeLoopbackServer(server); } }); + +function serverWhoseListenFails(code: string): net.Server { + const server = net.createServer(); + server.listen = (() => { + process.nextTick(() => + server.emit('error', Object.assign(new Error(`listen ${code}: 127.0.0.1`), { code })), + ); + return server; + }) as typeof server.listen; + return server; +} + +test.for(['EPERM', 'EACCES'])( + 'a %s loopback listen fails with daemon_listen_denied and the listen-denied exit code', + async (code) => { + await assert.rejects(listenNetServer(serverWhoseListenFails(code)), (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, 'daemon_listen_denied'); + assert.equal(error.details?.code, code); + assert.equal(error.details?.exitCode, DAEMON_STARTUP_EXIT_CODES.listenDenied); + return true; + }); + }, +); + +test('an EADDRINUSE loopback listen keeps its own error and no listen-denied exit code', async () => { + await assert.rejects(listenNetServer(serverWhoseListenFails('EADDRINUSE')), (error: unknown) => { + assert.ok(!(error instanceof AppError)); + assert.equal((error as NodeJS.ErrnoException).code, 'EADDRINUSE'); + return true; + }); +}); diff --git a/packages/daemon/src/server/http/transport.ts b/packages/daemon/src/server/http/transport.ts index 8755e6911e..21c48e43f0 100644 --- a/packages/daemon/src/server/http/transport.ts +++ b/packages/daemon/src/server/http/transport.ts @@ -6,6 +6,7 @@ import { createRequestCanceledError, malformedRequestDetails, normalizeError, + type ReasonTable, } from '@agent-device/kernel/errors'; import { AsyncResource } from 'node:async_hooks'; import net from 'node:net'; @@ -26,6 +27,7 @@ import { import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { consumeTextLines } from '@agent-device/host-kit/transport'; import { DAEMON_REQUEST_MAX_BYTES } from '@agent-device/contracts/daemon-http'; +import { DAEMON_STARTUP_EXIT_CODES } from '@agent-device/daemon-contracts/daemon-registration-owner'; import { serializeDaemonProgressEnvelope, @@ -230,14 +232,35 @@ export function listenHttpServer(server: HttpServer): Promise { return listenLoopbackServer(server, 'Failed to bind HTTP server'); } +const DAEMON_LISTEN_REASONS = { + // The host refused the daemon's loopback listen with EPERM or EACCES, as a sandbox around the + // launching command does; `details.code` holds the errno code. + denied: { reason: 'daemon_listen_denied' }, +} as const satisfies ReasonTable<'daemon lifecycle'>; + +const LISTEN_DENIED_CODES: ReadonlySet = new Set(['EPERM', 'EACCES']); + function listenLoopbackServer( server: net.Server | HttpServer, errorMessage: string, ): Promise { return new Promise((resolve, reject) => { - server.once('error', reject); + const onError = (error: NodeJS.ErrnoException) => { + if (!error.code || !LISTEN_DENIED_CODES.has(error.code)) { + reject(error); + return; + } + reject( + new AppError('COMMAND_FAILED', `${errorMessage}: listen ${error.code} on 127.0.0.1`, { + reason: DAEMON_LISTEN_REASONS.denied.reason, + code: error.code, + exitCode: DAEMON_STARTUP_EXIT_CODES.listenDenied, + }), + ); + }; + server.once('error', onError); server.listen(0, '127.0.0.1', () => { - server.off('error', reject); + server.off('error', onError); const address = server.address(); if (typeof address === 'object' && address?.port) { resolve(address.port); diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 4958f8ac41..6494762d22 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -573,6 +573,7 @@ These reasons can come from more than one command. | `daemon-binding-mismatch` | A client pinned to one daemon instance reached a state directory registering another one, or none it can read as an address; `details.bound` and `details.registered` hold both. | | `DAEMON_POLICY_MISMATCH` | The running daemon enforces a different daemon policy than `AGENT_DEVICE_DAEMON_POLICY` names. | | `startup-exited` | The daemon process ended before it registered a reachable endpoint. | +| `startup-listen-denied` | The daemon process ended because the host refused its loopback listen, as a sandbox around the launching command does. | | `startup-stalled` | The daemon stayed registered and reachable but never reported the startup phase that follows. | | `startup-ceiling` | Startup passed the ceiling its own startup budget allows, so this client stopped waiting. | | `daemon_binding_with_remote_base_url` | The client named both a pinned daemon instance and a daemon base URL, which answer "which daemon" two different ways. | @@ -591,6 +592,7 @@ These reasons can come from more than one command. | `daemon_exit_unconfirmed` | The stop could not confirm the daemon exited: the process stayed alive after the signal, the signal failed, or its start time or identity could not be verified. | | `repair_evidence_invalid` | The repair tombstone file exists but does not parse into a valid marker. | | `daemon_registration_refused` | Another daemon holds this state directory, or its registration could not be proven free, so this daemon did not start; `details.status` says which. | +| `daemon_listen_denied` | The host refused the daemon's loopback listen with EPERM or EACCES, as a sandbox around the launching command does; `details.code` holds the errno code. | | `daemon-clean-not-detached` | The record does not prove the process is a daemon of its own, so its process tree may be someone else's work. | ### Daemon policy From 98f5e77b4762181fc65fe657aed2dd9e7b52f430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 20:21:34 +0100 Subject: [PATCH 2/3] refactor(daemon-client): pick the startup failure hint by reason Keeps startLocalDaemon under the Fallow cognitive-complexity ceiling. Co-Authored-By: Claude Opus 5.5 --- .../src/daemon-client-startup.ts | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/packages/daemon-client/src/daemon-client-startup.ts b/packages/daemon-client/src/daemon-client-startup.ts index 9dd22b697e..ab2776a6de 100644 --- a/packages/daemon-client/src/daemon-client-startup.ts +++ b/packages/daemon-client/src/daemon-client-startup.ts @@ -348,16 +348,28 @@ export async function startLocalDaemon(settings: DaemonClientSettings): Promise< ...(phases ? { phases: describeStartupPhaseTimings(phases) } : {}), ...(daemonLogTail ? { daemonLogTail } : {}), metadataState: state, - hint: - effectiveReason === DAEMON_UNAVAILABLE_REASONS.startupListenDenied.reason - ? DAEMON_LISTEN_DENIED_HINT - : reason === DAEMON_UNAVAILABLE_REASONS.startupStalled.reason || - reason === DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason - ? resolveStartupProgressHint(reason, startupTimeoutMs) - : resolveDaemonStartupHint(state, settings.paths), + hint: resolveStartupFailureHint(effectiveReason, startupTimeoutMs, () => + resolveDaemonStartupHint(state, settings.paths), + ), }); } +function resolveStartupFailureHint( + reason: DaemonStartupFailureReason, + ceilingMs: number, + exitedHint: () => string, +): string { + switch (reason) { + case DAEMON_UNAVAILABLE_REASONS.startupListenDenied.reason: + return DAEMON_LISTEN_DENIED_HINT; + case DAEMON_UNAVAILABLE_REASONS.startupStalled.reason: + case DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason: + return resolveStartupProgressHint(reason, ceilingMs); + case DAEMON_UNAVAILABLE_REASONS.startupExited.reason: + return exitedHint(); + } +} + async function attemptLocalDaemonStartup( settings: DaemonClientSettings, deadline: number, From 97ac3f45da9967e6d9db0fd51c4f945828bb328d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 21:05:00 +0100 Subject: [PATCH 3/3] docs(help): list startup-listen-denied beside the other startup outcomes Narrows startup-exited to other causes in the help, the configuration page and the reason table, and checks the listen-denied rejection through daemonStartupExitCode. Co-Authored-By: Claude Opus 5.5 --- packages/daemon-client/src/daemon-lifecycle-errors.ts | 3 ++- packages/daemon/src/server/http/transport.test.ts | 3 ++- src/commands/schema/cli-help.ts | 2 +- website/docs/docs/configuration.md | 2 +- website/docs/docs/error-reasons.md | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/daemon-client/src/daemon-lifecycle-errors.ts b/packages/daemon-client/src/daemon-lifecycle-errors.ts index c904d24d76..1c7a13ed41 100644 --- a/packages/daemon-client/src/daemon-lifecycle-errors.ts +++ b/packages/daemon-client/src/daemon-lifecycle-errors.ts @@ -45,7 +45,8 @@ export const DAEMON_UNAVAILABLE_REASONS = { bindingMismatch: { reason: 'daemon-binding-mismatch' }, // The running daemon enforces a different daemon policy than `AGENT_DEVICE_DAEMON_POLICY` names. policyMismatch: { reason: 'DAEMON_POLICY_MISMATCH' }, - // The daemon process ended before it registered a reachable endpoint. + // The daemon process ended before it registered a reachable endpoint, for a cause other than a + // denied loopback listen. startupExited: { reason: 'startup-exited' }, // The daemon process ended because the host refused its loopback listen, as a sandbox around the // launching command does. diff --git a/packages/daemon/src/server/http/transport.test.ts b/packages/daemon/src/server/http/transport.test.ts index 4dffb80c6d..c7c04892d3 100644 --- a/packages/daemon/src/server/http/transport.test.ts +++ b/packages/daemon/src/server/http/transport.test.ts @@ -5,6 +5,7 @@ import http from 'node:http'; import net from 'node:net'; import { test } from 'vitest'; import { createSocketServer, listenHttpServer, listenNetServer } from './transport.ts'; +import { daemonStartupExitCode } from './daemon-runtime.ts'; import { DAEMON_REQUEST_MAX_BYTES } from '@agent-device/contracts/daemon-http'; import { clearRequestAbortRegistration, @@ -511,7 +512,7 @@ test.for(['EPERM', 'EACCES'])( assert.ok(error instanceof AppError); assert.equal(error.details?.reason, 'daemon_listen_denied'); assert.equal(error.details?.code, code); - assert.equal(error.details?.exitCode, DAEMON_STARTUP_EXIT_CODES.listenDenied); + assert.equal(daemonStartupExitCode(error), DAEMON_STARTUP_EXIT_CODES.listenDenied); return true; }); }, diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index f7602956df..e82b8d283c 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -418,7 +418,7 @@ Runner and daemon lifecycle (applies to simulators too): No runner read launches a session app that is not running: snapshot, wait, is, get, a reading find, and an interaction's leading reads (a gesture's viewport read, the capture that resolves a selector click/fill) answer the retriable APP_NOT_RUNNING instead of bare-launching over a launch SpringBoard still holds behind its deep-link confirmation. Only open, activate, and a command that mutates without a leading read bring a stopped app up. close keeps a healthy iOS simulator XCTest runner warm by default so the next open on that simulator (same udid in the same simulator set) skips the runner build, unless --shutdown was requested, the session was recording, or its device lease ends on close. A lease allocated with retainOnClose can keep the runner between sessions; releasing or expiring that lease stops its runner unless a session outside the lease has taken over the device. A retained runner auto-stops after an idle window (default 5 minutes); set AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS to override, or 0 to disable idle stopping. Lease release, expiry, and graceful daemon shutdown still clean up runners they own. Only a ready runner with an observed listener is retained; close retires unfinished prewarm recovery. Losing the retained listener stops that generation, and graceful daemon shutdown stops idle retained runners rather than handing them off without supervision. Each AGENT_DEVICE_STATE_DIR runs its own daemon. It self-exits after an idle window (default 5 minutes, matching the runner idle-stop default) once it has no open sessions, no in-flight requests, and no active recording; set AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS to override, or 0 to disable idle reap. - A client starting a local daemon waits while the daemon process stays alive and keeps publishing startup progress, so an overloaded host makes startup slower, not failed. It stops at a ceiling (default 120 s; set AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS to a positive integer number of milliseconds to override) and names the outcome in error details.reason: startup-exited (the process ended before registering), startup-stalled (alive, no startup progress for a fixed 60 s window the ceiling variable does not change), or startup-ceiling (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the 60 s stall window, so a ceiling set below 60 s also ends a silent own launch this way). details.phases carries the startup phase timings it observed and details.startupTimeoutMs the effective ceiling. Branch on details.reason, never on the message. The variable is read only when a client must start a daemon: a value that is not a positive integer fails with INVALID_ARGS before the daemon spawns, and a client that only attaches to or reuses a running daemon never reads it. + A client starting a local daemon waits while the daemon process stays alive and keeps publishing startup progress, so an overloaded host makes startup slower, not failed. It stops at a ceiling (default 120 s; set AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS to a positive integer number of milliseconds to override) and names the outcome in error details.reason: startup-listen-denied (the host refused the daemon's loopback listen, as a sandbox does; rerun agent-device with host access), startup-exited (the process ended before registering for another cause), startup-stalled (alive, no startup progress for a fixed 60 s window the ceiling variable does not change), or startup-ceiling (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the 60 s stall window, so a ceiling set below 60 s also ends a silent own launch this way). details.phases carries the startup phase timings it observed and details.startupTimeoutMs the effective ceiling. Branch on details.reason, never on the message. The variable is read only when a client must start a daemon: a value that is not a positive integer fails with INVALID_ARGS before the daemon spawns, and a client that only attaches to or reuses a running daemon never reads it. On iOS simulators, open prepares app accessibility before launching an app or URL. If a running app has an empty accessibility tree after an earlier XCTest session, use open --relaunch, then snapshot -i. A preparation failure is logged and does not block launch. A command that needs the shared local daemon starts it for its state dir when none runs (device status and device release --stale never contact one). When the running daemon comes from another version or build, the command replaces it only if the daemon reports no work: no in-flight request, session, repair session, or live lease (a streaming resumable upload and a host human-control hold that names no lease are not counted); otherwise it fails with details.reason daemon-busy and leaves the daemon alone. A daemon that agreed to leave is waited for up to 60 s and never signaled while it drains; one still running then fails with details.reason daemon-drain-timeout unless it answers nothing and is provably a daemon process, which is force-retired. A daemon from a release that predates this check is never replaced and fails with daemon-incompatible. End a busy or older daemon deliberately with agent-device daemon stop --state-dir . Node clients pick daemonLifecycle 'attach' (never starts or replaces a daemon; fails with daemon-not-running or daemon-incompatible) or 'managed' (the default until 0.22), and ensureDaemon() starts or replaces one explicitly. daemon stop --state-dir stops a detached daemon with process signals after verifying its identity; on non-Windows hosts it waits up to 75 s for the daemon to finish its own teardown before it forces the exit, while on Windows the stop signal force-terminates the daemon (mode forced, cleanupConfidence unknown). For a live embedded runtime, stop refuses with details.reason daemon-owner-embedded and a hint naming the host PID. Close that runtime in its host process with the handle returned by startAgentDevice(). Stop refuses live unrecognized ownership with daemon-owner-unrecognized and sends no request or signal. Stop retires an embedded or unrecognized registration when its recorded host lifetime has provably exited. Without --clean, an unreadable daemon.json fails with daemon-record-unreadable. daemon status shows host-owned or owner-not-recognized. Managed clients reuse a matching embedded runtime. Takeover, drain, and timeout recovery refuse a live embedded or unrecognized owner without a signal; a provably exited owner is retired so the state directory stays usable. Detached stop and cleanup use the lifetime and ownership from one registration read. --clean requires proven detached ownership; embedded, unrecognized and unreadable records fail with daemon-clean-not-detached because that cleanup walks the owner's whole process tree. diff --git a/website/docs/docs/configuration.md b/website/docs/docs/configuration.md index 5495b167e6..7ff26ffa31 100644 --- a/website/docs/docs/configuration.md +++ b/website/docs/docs/configuration.md @@ -143,7 +143,7 @@ Only the variables below, and those documented on command pages, are supported. | Category | Env vars | Decision | | --- | --- | --- | -| CLI defaults and config | `AGENT_DEVICE_HOME`, `AGENT_DEVICE_CONFIG`, `AGENT_DEVICE_SESSION`, `AGENT_DEVICE_PLATFORM`, `AGENT_DEVICE_SCREENSHOT_SCALE`, `AGENT_DEVICE_SESSION_LOCK`, `AGENT_DEVICE_DAEMON_BASE_URL`, `AGENT_DEVICE_DAEMON_AUTH_TOKEN`, `AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS`, `AGENT_DEVICE_CLOUD_BASE_URL` | Public. `AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS` is the ceiling (a positive integer number of milliseconds, default `120000`; any other value fails with `INVALID_ARGS` before a daemon spawns, and only when the client must start a daemon — a client that attaches to or reuses a running daemon never reads it) a client waits for a local daemon it starts to register; CLI, MCP, and Node clients share it. A live daemon is waited for while it records startup progress, so an overloaded host slows startup instead of failing it. A failed startup names the outcome in `details.reason`: `startup-exited` (the process ended before registering), `startup-stalled` (alive, no startup progress for a fixed 60 s window this variable does not change), or `startup-ceiling` (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the fixed stall window). Branch on `details.reason`, never on the message. | +| CLI defaults and config | `AGENT_DEVICE_HOME`, `AGENT_DEVICE_CONFIG`, `AGENT_DEVICE_SESSION`, `AGENT_DEVICE_PLATFORM`, `AGENT_DEVICE_SCREENSHOT_SCALE`, `AGENT_DEVICE_SESSION_LOCK`, `AGENT_DEVICE_DAEMON_BASE_URL`, `AGENT_DEVICE_DAEMON_AUTH_TOKEN`, `AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS`, `AGENT_DEVICE_CLOUD_BASE_URL` | Public. `AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS` is the ceiling (a positive integer number of milliseconds, default `120000`; any other value fails with `INVALID_ARGS` before a daemon spawns, and only when the client must start a daemon — a client that attaches to or reuses a running daemon never reads it) a client waits for a local daemon it starts to register; CLI, MCP, and Node clients share it. A live daemon is waited for while it records startup progress, so an overloaded host slows startup instead of failing it. A failed startup names the outcome in `details.reason`: `startup-listen-denied` (the host refused the daemon's loopback listen, as a sandbox does; rerun agent-device with host access), `startup-exited` (the process ended before registering for another cause), `startup-stalled` (alive, no startup progress for a fixed 60 s window this variable does not change), or `startup-ceiling` (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the fixed stall window). Branch on `details.reason`, never on the message. | | Device scoping | `AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST`, `AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET` | Public. `AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET` is read by the daemon: every iOS simulator request that names no `--ios-simulator-device-set` uses that set, so iOS physical devices are not listed, and a request naming a different path string fails with `INVALID_ARGS` (`details.reason: "ios_simulator_device_set_outside_daemon_set"`). macOS and non-iOS requests ignore it. A daemon started by the CLI inherits the CLI's value; restart the daemon after changing it. | | Android test IME | `AGENT_DEVICE_TEST_IME` | Public. Same setting as `--test-ime` / `--no-test-ime` on `open`, `test`, and `replay`; see known limitations. | | Local daemon storage | `AGENT_DEVICE_STATE_DIR` | Public. The daemon and the CLI store the daemon's record, lock, log, and recordings there, so the directory must belong to you alone: a real directory, not a symbolic link, that you own with mode `0700`, with every directory above it owned by you or root and not writable by group or other users (a shared directory that is sticky, like `/tmp`, is allowed). Every route that starts, attaches to, stops or reports on the daemon checks that first, before it reads or writes anything there. A missing directory is created at `0700` when a command starts a daemon, and is left missing when a command only reports. A directory you own that is open to the group or other users is closed to `0700` by that check, so a directory created by another program under a permissive umask, or left open by an older version, never stops the daemon. Anything else fails the check, with `details.reason: "daemon_state_root_unsafe"`, naming the directory and the step that ends it: `details.fix` runs `chmod 700` on that directory, or points `AGENT_DEVICE_STATE_DIR` at a real private directory you own, such as `$HOME/.agent-device`, when even that change is refused. For anything besides the mode bits it names that move, because a mode change cannot make a symbolic link, another owner's directory, or a directory other accounts can write private. The check reads owner and mode bits and symbolic links, so it applies on macOS and Linux. On Windows agent-device only rejects a path shape it cannot support — a network path such as `\\server\share`, a device path such as `\\.\pipe\`, or a drive-relative path such as `C:state` — because there protection between accounts is not a question of mode bits, and a missing directory is still created when a command starts a daemon. | diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 6494762d22..50bd6c9311 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -572,7 +572,7 @@ These reasons can come from more than one command. | `remote_daemon_unavailable` | The health probe that gates a remote send found no daemon to hand the request to, so `details.dispatched` is `no` and a resend is safe. | | `daemon-binding-mismatch` | A client pinned to one daemon instance reached a state directory registering another one, or none it can read as an address; `details.bound` and `details.registered` hold both. | | `DAEMON_POLICY_MISMATCH` | The running daemon enforces a different daemon policy than `AGENT_DEVICE_DAEMON_POLICY` names. | -| `startup-exited` | The daemon process ended before it registered a reachable endpoint. | +| `startup-exited` | The daemon process ended before it registered a reachable endpoint, for a cause other than a denied loopback listen. | | `startup-listen-denied` | The daemon process ended because the host refused its loopback listen, as a sandbox around the launching command does. | | `startup-stalled` | The daemon stayed registered and reachable but never reported the startup phase that follows. | | `startup-ceiling` | Startup passed the ceiling its own startup budget allows, so this client stopped waiting. |