From 19fccace43dc3d279e3062786e3d2a678aba0a83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 10:19:48 +0100 Subject: [PATCH 1/8] fix(daemon-client): name a sandbox-denied connect and leave that daemon alone A reachability probe answered a boolean, so a loopback connect the host refused (EPERM or EACCES under a sandbox around the client) read exactly like a daemon that answers nothing. The client then judged a healthy daemon dead and tried to replace it, and reported "Daemon replacement could not be confirmed." The replacement attempt could also kill the daemon it could not reach. Probes now answer a verdict, and a refusal carried by EPERM or EACCES is a denial, not an answer about the daemon. The takeover ladder answers a new connectDenied decision for it, and every client that hears it throws details.reason daemon-connect-denied with the errno, transport, port, and daemon identity, plus the host-access hint the denied listen already used. Nothing is spawned, retired, or signaled on that answer. The probe layer moves to daemon-client-loopback-probe.ts, which owns the denial set, so the transport module stays under the lint file-size limit. --- .../daemon-client-connect-denied.test.ts | 196 ++++++++++++++++++ .../__tests__/daemon-client-transport.test.ts | 22 +- .../src/__tests__/daemon-launch-spec.test.ts | 45 +++- .../src/__tests__/index-stalled-probe.test.ts | 10 +- .../daemon-client/src/__tests__/index.test.ts | 8 +- .../daemon-client/src/daemon-client-attach.ts | 5 + .../daemon-client/src/daemon-client-ensure.ts | 9 + .../src/daemon-client-loopback-probe.ts | 75 +++++++ .../src/daemon-client-metadata.ts | 12 +- .../src/daemon-client-startup.ts | 85 ++++---- .../src/daemon-client-transport.ts | 104 +++++----- .../daemon-client/src/daemon-launch-spec.ts | 40 ++-- .../src/daemon-lifecycle-errors.ts | 39 ++++ src/commands/schema/cli-help.ts | 2 +- website/docs/docs/configuration.md | 2 +- website/docs/docs/error-reasons.md | 1 + 16 files changed, 530 insertions(+), 125 deletions(-) create mode 100644 packages/daemon-client/src/__tests__/daemon-client-connect-denied.test.ts create mode 100644 packages/daemon-client/src/daemon-client-loopback-probe.ts diff --git a/packages/daemon-client/src/__tests__/daemon-client-connect-denied.test.ts b/packages/daemon-client/src/__tests__/daemon-client-connect-denied.test.ts new file mode 100644 index 0000000000..98741c5d76 --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-connect-denied.test.ts @@ -0,0 +1,196 @@ +import assert from 'node:assert/strict'; +import EventEmitter from 'node:events'; +import fs from 'node:fs'; +import net from 'node:net'; +import { afterEach, test, vi } from 'vitest'; +import { runCmdBackground } from '@agent-device/host-kit/command'; +import { + isProcessAlive, + readProcessCommand, + readProcessStartTime, + waitForProcessExit, +} from '@agent-device/host-kit/process'; +import { AppError } from '@agent-device/kernel/errors'; +import { readVersion } from '@agent-device/host-kit/version'; +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { sendToDaemon } from '../index.ts'; +import { probeLoopbackPort } from '../daemon-client-loopback-probe.ts'; +import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; + +// A loopback connect the HOST refused (EPERM under a macOS Seatbelt sandbox around this client) is +// evidence about this client, not about the registered daemon. These cases pin that the client names +// that refusal instead of judging the daemon dead and trying to replace it. + +const DENIED_ERRNO = 'EPERM'; + +const { mockProbeAnswers, mockSpawnDaemon } = vi.hoisted(() => ({ + /** What each probe of the registered daemon answers, in order; `denied` is a host refusal. */ + mockProbeAnswers: [] as ('denied' | 'silent')[], + mockSpawnDaemon: vi.fn(), +})); + +vi.mock('../daemon-client-transport.ts', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + probeDaemonReachability: async (...args: Parameters) => { + const answer = mockProbeAnswers.shift() ?? 'silent'; + if (answer !== 'denied') return { reachable: false }; + return { + reachable: false, + denial: { errno: DENIED_ERRNO, transport: 'socket', port: args[0].port ?? 0 }, + }; + }, + }; +}); + +vi.mock('@agent-device/host-kit/command', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, runCmdDetachedMonitored: mockSpawnDaemon }; +}); + +afterEach(() => { + mockProbeAnswers.length = 0; + mockSpawnDaemon.mockReset(); +}); + +/** + * A stand-in for the daemon running OUTSIDE the sandbox: a live process whose command reads as an + * agent-device daemon, plus a registration this client wrote by hand. The client never started this + * lifetime, so an unreachable judgement lands as a retirement it may not confirm. + */ +async function withRegisteredStandIn( + t: { skip: (reason: string) => void }, + body: (input: { stateDir: string; pid: number }) => Promise, +): Promise { + if (await skipWhenLoopbackUnavailable(t)) return; + const stateDir = mkdtempForTestSync('agent-device-connect-denied-'); + const standIn = runCmdBackground(process.execPath, ['-e', 'setInterval(() => {}, 1000);'], { + stdio: 'ignore', + allowFailure: true, + captureOutput: false, + }); + void standIn.wait.catch(() => {}); + const pid = standIn.child.pid; + assert.ok(pid, 'the stand-in has a pid'); + const server = net.createServer((socket) => socket.on('error', () => {})); + try { + await new Promise((resolve) => setTimeout(resolve, 50)); + const processStartTime = readProcessStartTime(pid) ?? undefined; + const command = readProcessCommand(pid); + if (command === null || processStartTime === undefined) { + t.skip('process command/start inspection is unavailable in this environment'); + return; + } + const port = await listenOnLoopback(server); + const paths = resolveDaemonPaths(stateDir); + fs.mkdirSync(paths.baseDir, { recursive: true }); + fs.writeFileSync( + paths.infoPath, + `${JSON.stringify({ + port, + transport: 'socket', + token: 'local-secret', + pid, + version: readVersion(), + processStartTime, + codeSignature: currentDaemonCodeSignature(), + })}\n`, + 'utf8', + ); + await body({ stateDir, pid }); + } finally { + await closeLoopbackServer(server); + if (isProcessAlive(pid)) { + process.kill(pid, 'SIGKILL'); + await waitForProcessExit(pid, 1_500); + } + fs.rmSync(stateDir, { recursive: true, force: true }); + } +} + +function sendDevices(stateDir: string) { + return sendToDaemon({ + session: 'default', + command: 'devices', + positionals: [], + flags: { stateDir, daemonTransport: 'socket' }, + meta: { requestId: 'req-connect-denied' }, + }); +} + +async function rejection(pending: Promise): Promise { + let thrown: AppError | undefined; + try { + await pending; + } catch (error) { + if (!(error instanceof AppError)) throw error; + thrown = error; + } + assert.ok(thrown, 'expected the command to reject'); + return thrown; +} + +test('a connect the host refused names the sandbox and leaves the daemon running', async (t) => { + await withRegisteredStandIn(t, async ({ stateDir, pid }) => { + mockProbeAnswers.push('denied'); + + const failure = await rejection(sendDevices(stateDir)); + + assert.equal(failure.details?.reason, 'daemon-connect-denied'); + assert.equal(failure.details?.errno, DENIED_ERRNO); + assert.equal((failure.details?.daemon as { pid?: number } | undefined)?.pid, pid); + assert.match(String(failure.details?.hint), /A sandbox around this command/); + assert.match(String(failure.details?.hint), /host access/); + assert.equal(mockSpawnDaemon.mock.calls.length, 0, 'a refusal is not a dead daemon to replace'); + assert.equal(isProcessAlive(pid), true, 'the daemon outside the sandbox is not signaled'); + }); +}); + +test('a probe that goes unanswered is still judged unreachable, not denied', async (t) => { + await withRegisteredStandIn(t, async ({ stateDir, pid }) => { + mockProbeAnswers.push('silent', 'silent', 'silent', 'silent'); + + const failure = await rejection(sendDevices(stateDir)); + + // The judgement this fix replaces for a refusal: an unanswered probe keeps the old outcome, so + // the denial is a new verdict rather than a relabelled one. + assert.equal(failure.details?.reason, 'daemon_retirement_unconfirmed'); + assert.notEqual(failure.details?.errno, DENIED_ERRNO); + assert.equal(isProcessAlive(pid), true, 'a client that cannot confirm a stop signals nothing'); + }); +}); + +test.for(['EPERM', 'EACCES', 'ECONNREFUSED', 'ECONNRESET'] as const)( + 'probeLoopbackPort reports only the refused errnos as a denial (%s)', + async (code) => { + const socket = Object.assign(new EventEmitter(), { + destroy: () => {}, + setTimeout: () => socket, + }); + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((( + _options: unknown, + _listener?: () => void, + ) => { + setImmediate(() => socket.emit('error', Object.assign(new Error(code), { code }))); + return socket; + }) as unknown as typeof net.createConnection); + try { + const probe = await probeLoopbackPort(65_530, 'http', 500); + assert.deepEqual(probe, { + reachable: false, + ...(code === 'EPERM' || code === 'EACCES' + ? { denial: { errno: code, transport: 'http', port: 65_530 } } + : {}), + }); + } finally { + createConnection.mockRestore(); + } + }, +); diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts index db4361a7f6..0138e90d1a 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -23,8 +23,8 @@ import { } from '@agent-device/contracts/daemon-http'; import { sendToDaemon } from '../index.ts'; import { - canConnect, isDaemonTransportUnavailableError, + probeDaemonReachability, sendRequest, } from '../daemon-client-transport.ts'; import { DAEMON_UNAVAILABLE_REASONS } from '../daemon-lifecycle-errors.ts'; @@ -62,7 +62,13 @@ test('auto health probing reserves time for a healthy fallback when HTTP hangs', const httpPort = await listenOnLoopback(httpServer); const port = await listenOnLoopback(socketServer); assert.equal( - await canConnect({ token: 'secret', pid: 1, transport: 'http', httpPort, port }, 'auto', 120), + ( + await probeDaemonReachability( + { token: 'secret', pid: 1, transport: 'http', httpPort, port }, + 'auto', + 120, + ) + ).reachable, true, ); } finally { @@ -93,10 +99,12 @@ test('the health deadline includes requester loading and forbids a late request' try { const httpPort = await listenOnLoopback(server); let settled = false; - probing = canConnect({ token: 'secret', pid: 1, httpPort }, 'http', 40).then((reachable) => { - settled = true; - return reachable; - }); + probing = probeDaemonReachability({ token: 'secret', pid: 1, httpPort }, 'http', 40).then( + (probe) => { + settled = true; + return probe.reachable; + }, + ); await sleep(90); assert.equal(settled, true, 'loading must not extend the probe deadline'); assert.equal(await probing, false); @@ -560,7 +568,7 @@ test.for([ test('an endpoint missing for the requested transport rejects with a typed reason the classifier accepts', async () => { const socketOnly = { port: 1, token: 't', pid: 1 }; - const error = await canConnect(socketOnly, 'http').then( + const error = await probeDaemonReachability(socketOnly, 'http').then( () => undefined, (error: unknown) => error, ); diff --git a/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts b/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts index 19a0581e25..962bc9a2e7 100644 --- a/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts @@ -9,6 +9,7 @@ import { type DaemonReachability, resolveLocalDaemonCodeIdentity, } from '../daemon-launch-spec.ts'; +import type { DaemonProbeVerdict } from '../daemon-client-loopback-probe.ts'; import { isSourceCheckoutProjectRoot, readVersion } from '@agent-device/host-kit/version'; import { resetAllProcessMemosForTests } from '@agent-device/kernel/ttl-memo'; @@ -128,9 +129,9 @@ test('a version mismatch is decided without asking the client transport', async const decision = await resolveDaemonTakeover(runningDaemon({ version: '0.0.1' }), { onClientTransport: async () => { asked = true; - return false; + return silent; }, - onAnyAdvertisedTransport: async () => false, + onAnyAdvertisedTransport: async () => silent, }); assert.equal(decision.kind, 'replace'); @@ -156,6 +157,24 @@ test('a same-version daemon the client transport cannot reach is replaced', asyn ); }); +test('a same-version daemon the host refused to connect to is not judged unreachable', async () => { + useClientTree(false); + + assert.deepEqual( + await resolveDaemonTakeover(runningDaemon({ codeOrigin: 'installed' }), denied()), + { kind: 'connectDenied', denial: DENIAL }, + ); +}); + +// The refusal outranks the newer-daemon refusal: both stop the daemon being touched, and only +// `connectDenied` says the reason is this client's sandbox rather than the daemon's version. +test('a connect the host refused never reads as a newer daemon to refuse', async () => { + assert.deepEqual(await resolveDaemonTakeover(runningDaemon({ version: '999.0.0' }), denied()), { + kind: 'connectDenied', + denial: DENIAL, + }); +}); + test('a reachable daemon older than the client is replaced', async () => { assert.deepEqual(await resolveDaemonTakeover(runningDaemon({ version: '0.0.1' }), reachable()), { kind: 'replace', @@ -175,17 +194,33 @@ function useClientTree(sourceCheckout: boolean): void { } function reachable(): DaemonReachability { - return { onClientTransport: async () => true, onAnyAdvertisedTransport: async () => true }; + return { + onClientTransport: async () => answered, + onAnyAdvertisedTransport: async () => answered, + }; } function unreachable(): DaemonReachability { - return { onClientTransport: async () => false, onAnyAdvertisedTransport: async () => false }; + return { onClientTransport: async () => silent, onAnyAdvertisedTransport: async () => silent }; } function onlyOnAnotherTransport(): DaemonReachability { - return { onClientTransport: async () => false, onAnyAdvertisedTransport: async () => true }; + return { onClientTransport: async () => silent, onAnyAdvertisedTransport: async () => answered }; +} + +/** The host refused every endpoint this client tried, as its sandbox does. */ +function denied(): DaemonReachability { + return { + onClientTransport: async () => ({ reachable: false, denial: DENIAL }), + onAnyAdvertisedTransport: async () => ({ reachable: false, denial: DENIAL }), + }; } +const DENIAL = { errno: 'EPERM', transport: 'socket', port: 41_234 } as const; + +const answered: DaemonProbeVerdict = { reachable: true }; +const silent: DaemonProbeVerdict = { reachable: false }; + function runningDaemon(info: { version?: string; codeOrigin?: 'installed' | 'checkout'; diff --git a/packages/daemon-client/src/__tests__/index-stalled-probe.test.ts b/packages/daemon-client/src/__tests__/index-stalled-probe.test.ts index 39fdbe3509..e453a3c8d2 100644 --- a/packages/daemon-client/src/__tests__/index-stalled-probe.test.ts +++ b/packages/daemon-client/src/__tests__/index-stalled-probe.test.ts @@ -61,12 +61,14 @@ vi.mock('../daemon-client-transport.ts', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - canConnect: async (...args: Parameters) => { - const reachable = mockMissNextProbe.value ? false : await actual.canConnect(...args); + probeDaemonReachability: async (...args: Parameters) => { + const probe = mockMissNextProbe.value + ? { reachable: false } + : await actual.probeDaemonReachability(...args); mockMissNextProbe.value = false; - probeAnswers.push(reachable); + probeAnswers.push(probe.reachable); probedPorts.push(args[0].port); - return reachable; + return probe; }, }; }); diff --git a/packages/daemon-client/src/__tests__/index.test.ts b/packages/daemon-client/src/__tests__/index.test.ts index 8db9769cf6..0549473e2a 100644 --- a/packages/daemon-client/src/__tests__/index.test.ts +++ b/packages/daemon-client/src/__tests__/index.test.ts @@ -20,7 +20,7 @@ import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; import { computeDaemonCodeSignature } from '@agent-device/host-kit/code-signature'; import { downloadRemoteArtifact } from '@agent-device/remote/daemon-artifacts'; import { resolveDaemonStartupHint } from '../daemon-lifecycle-errors.ts'; -import { canConnectSocket } from '../daemon-client-transport.ts'; +import { probeLoopbackPort } from '../daemon-client-loopback-probe.ts'; import { DAEMON_RPC_PROTOCOL_VERSION } from '@agent-device/contracts/daemon-http'; import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { readVersion } from '@agent-device/host-kit/version'; @@ -133,7 +133,7 @@ test('startup recovery guidance retains configured paths and requires stopping e } }); -test('canConnectSocket times out stalled local daemon probes', async () => { +test('probeLoopbackPort times out stalled local daemon probes', async () => { const originalCreateConnection = net.createConnection; let timeoutMs: number | undefined; let destroyed = false; @@ -156,9 +156,9 @@ test('canConnectSocket times out stalled local daemon probes', async () => { ) => socket) as typeof net.createConnection; try { - const reachable = await canConnectSocket(65_530); + const probe = await probeLoopbackPort(65_530, 'socket'); - assert.equal(reachable, false); + assert.equal(probe.reachable, false); assert.equal(timeoutMs, 500); assert.equal(destroyed, true); } finally { diff --git a/packages/daemon-client/src/daemon-client-attach.ts b/packages/daemon-client/src/daemon-client-attach.ts index 05971463a8..30b198b084 100644 --- a/packages/daemon-client/src/daemon-client-attach.ts +++ b/packages/daemon-client/src/daemon-client-attach.ts @@ -9,6 +9,7 @@ import type { import { daemonBindingMismatchError } from './daemon-client-binding.ts'; import { DAEMON_UNAVAILABLE_REASONS, + daemonConnectDeniedError, daemonIncompatibleError, daemonNotRunningError, } from './daemon-lifecycle-errors.ts'; @@ -44,6 +45,10 @@ export async function connectToDaemon( switch (decision.kind) { case 'reuse': break; + // An attach client replaced nothing anyway; the refusal still has to name the sandbox rather than + // read as "no daemon is running". + case 'connectDenied': + throw daemonConnectDeniedError({ info, denial: decision.denial, stateDir }); case 'refuseNewer': throw await daemonIncompatibleError({ info, mismatch: 'newer', stateDir }); case 'replace': diff --git a/packages/daemon-client/src/daemon-client-ensure.ts b/packages/daemon-client/src/daemon-client-ensure.ts index ab393a4243..1efeaee7de 100644 --- a/packages/daemon-client/src/daemon-client-ensure.ts +++ b/packages/daemon-client/src/daemon-client-ensure.ts @@ -27,6 +27,7 @@ import { answersLivenessProbe } from './daemon-client-liveness-probe.ts'; import { observedDaemonIdentityOf, type DaemonInfo } from './daemon-client-metadata.ts'; import { DAEMON_UNAVAILABLE_REASONS, + daemonConnectDeniedError, daemonIdentityOf, daemonDrainTimeoutError, daemonIncompatibleError, @@ -97,6 +98,14 @@ async function ensureOnce( switch (decision.kind) { case 'reuse': return { kind: 'connected', daemon: { info, startedByClient: false }, started: false }; + // The host refused this client's connect, so the daemon's state is unknown and it is left alone: + // the refusal travels to the caller, which names the sandbox and the way out. + case 'connectDenied': + throw daemonConnectDeniedError({ + info, + denial: decision.denial, + stateDir: settings.paths.baseDir, + }); case 'refuseNewer': throw await daemonIncompatibleError({ info, diff --git a/packages/daemon-client/src/daemon-client-loopback-probe.ts b/packages/daemon-client/src/daemon-client-loopback-probe.ts new file mode 100644 index 0000000000..84d757af6a --- /dev/null +++ b/packages/daemon-client/src/daemon-client-loopback-probe.ts @@ -0,0 +1,75 @@ +import net from 'node:net'; + +/** How long one reachability probe of the local daemon's loopback endpoint may take. */ +export const LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS = 500; + +/** The errnos that say the host refused the connect itself, as a sandbox around the caller does. */ +const LOOPBACK_DENIED_CODES: ReadonlySet = new Set(['EPERM', 'EACCES']); + +/** The transport, or the endpoint family, one probe or refusal names. */ +export type LoopbackTransport = 'socket' | 'http'; + +/** + * One loopback connect this client was refused, with the endpoint it aimed at. A refusal is not an + * answer from the daemon: nothing says whether the daemon behind that port is serving. + */ +export type LoopbackConnectDenial = Readonly<{ + errno: 'EPERM' | 'EACCES'; + transport: LoopbackTransport; + port: number; +}>; + +/** + * What a reachability probe of one daemon found. `denial` is present only when nothing answered AND + * the host refused the connect, which is what a sandbox around this client does. + */ +export type DaemonProbeVerdict = Readonly<{ + reachable: boolean; + denial?: LoopbackConnectDenial; +}>; + +/** + * Whether an errno from a loopback connect says the host refused it, as a sandbox around this client + * does. A refusal is not an answer from the daemon: unlike a reset or a timeout, it says nothing about + * whether the daemon behind that port serves. + */ +export function readLoopbackConnectDenial( + errno: string | undefined, + transport: LoopbackTransport, + port: number, +): LoopbackConnectDenial | undefined { + if (!errno || !LOOPBACK_DENIED_CODES.has(errno)) return undefined; + return { errno: errno as LoopbackConnectDenial['errno'], transport, port }; +} + +/** + * One connect to one loopback port. A refusal from the host is reported as a denial: it is not an + * answer from the daemon, and it is the only reachability evidence a sandboxed client can be refused. + */ +export function probeLoopbackPort( + port: number | undefined, + transport: LoopbackTransport, + timeoutMs = LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS, +): Promise { + if (!port || timeoutMs <= 0) return Promise.resolve({ reachable: false }); + return new Promise((resolve) => { + let settled = false; + const socket = net.createConnection({ host: '127.0.0.1', port }, () => { + finish({ reachable: true }); + }); + const finish = (verdict: DaemonProbeVerdict) => { + if (settled) return; + settled = true; + socket.destroy(); + resolve(verdict); + }; + socket.setTimeout(Math.min(LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS, Math.ceil(timeoutMs))); + socket.on('timeout', () => { + finish({ reachable: false }); + }); + socket.on('error', (error: NodeJS.ErrnoException) => { + const denial = readLoopbackConnectDenial(error.code, transport, port); + finish(denial ? { reachable: false, denial } : { reachable: false }); + }); + }); +} diff --git a/packages/daemon-client/src/daemon-client-metadata.ts b/packages/daemon-client/src/daemon-client-metadata.ts index 9769143a71..f4eecf9f5b 100644 --- a/packages/daemon-client/src/daemon-client-metadata.ts +++ b/packages/daemon-client/src/daemon-client-metadata.ts @@ -1,6 +1,6 @@ import { inspectProcessLock } from '@agent-device/host-kit/file'; import { isProcessPid } from '@agent-device/host-kit/process'; - +import type { LoopbackConnectDenial } from './daemon-client-loopback-probe.ts'; import type { DaemonCodeOrigin } from '@agent-device/host-kit/code-signature'; import { admitDaemonStateRoot, @@ -42,8 +42,7 @@ export type DaemonInfo = { remoteUpstreamInstanceId?: string; }; -/** - * Why a daemon is not the one this client would use. `transport` means alive but not on the +/** Why a daemon is not the one this client would use. `transport` means alive but not on the * transport this client uses: the ladder only ever answers `unreachable` for it, and a caller that * must not kill a live daemon refines it with `observeLocalDaemon`. */ @@ -53,7 +52,12 @@ export type DaemonTakeoverCause = 'version' | 'code' | 'transport' | 'unreachabl export type DaemonTakeoverDecision = | { kind: 'reuse' } | { kind: 'replace'; reason: string; cause: DaemonTakeoverCause } - | { kind: 'refuseNewer'; daemonVersion: string; clientVersion: string }; + | { kind: 'refuseNewer'; daemonVersion: string; clientVersion: string } + /** + * The host refused this client's connect to the registered daemon, so the client cannot tell + * whether that daemon lives. Nothing is replaced, retired, or signaled on this answer. + */ + | { kind: 'connectDenied'; denial: LoopbackConnectDenial }; export type DaemonObservationSettings = { paths: DaemonPaths; diff --git a/packages/daemon-client/src/daemon-client-startup.ts b/packages/daemon-client/src/daemon-client-startup.ts index ab2776a6de..3c32cc0e5a 100644 --- a/packages/daemon-client/src/daemon-client-startup.ts +++ b/packages/daemon-client/src/daemon-client-startup.ts @@ -37,13 +37,19 @@ import { readDaemonInfo, type DaemonInfo, } from './daemon-client-metadata.ts'; -import { canConnect, isDaemonTransportUnavailableError } from './daemon-client-transport.ts'; import { + isDaemonTransportUnavailableError, + probeDaemonReachability, +} from './daemon-client-transport.ts'; +import type { DaemonProbeVerdict } from './daemon-client-loopback-probe.ts'; +import { + DAEMON_LOOPBACK_DENIED_HINT, DAEMON_UNAVAILABLE_REASONS, daemonContendedError, daemonIncompatibleError, daemonTakeoverRetirementError, daemonStopCommand, + daemonConnectDeniedError, daemonRegistrationUnprovenError, getDaemonMetadataState, resolveDaemonStartupHint, @@ -77,13 +83,6 @@ 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 @@ -121,9 +120,8 @@ export async function observeLocalDaemon( return null; const decision = await resolveDaemonTakeover(existing, { - onClientTransport: () => - canReachReusableDaemon(existing, settings.transportPreference, deadline), - onAnyAdvertisedTransport: () => canReachReusableDaemon(existing, 'auto', deadline), + onClientTransport: () => probeReusableDaemon(existing, settings.transportPreference, deadline), + onAnyAdvertisedTransport: () => probeReusableDaemon(existing, 'auto', deadline), }); return { info: existing, decision: await refineReplacement(existing, decision, options) }; } @@ -135,11 +133,10 @@ async function refineReplacement( ): Promise { if (!options.refineUnreachable || decision.kind !== 'replace') return decision; if (!isProcessAlive(info.pid)) return { ...decision, cause: 'unreachable' }; - if ( - decision.cause === 'unreachable' && - (await canReachReusableDaemon(info, 'auto', options.deadline)) - ) { - return { ...decision, cause: 'transport' }; + if (decision.cause === 'unreachable') { + const probe = await probeReusableDaemon(info, 'auto', options.deadline); + if (probe.denial) return { kind: 'connectDenied', denial: probe.denial }; + if (probe.reachable) return { ...decision, cause: 'transport' }; } return decision; } @@ -153,6 +150,14 @@ export async function readReusableLocalDaemon( if (!observed) return null; const { info: existing, decision } = observed; if (decision.kind === 'reuse') return existing; + // Ordered before the contended and newer-daemon refusals: a connect the host refused is about this + // client's sandbox, and neither re-judging the race nor replacing what it cannot see is the answer. + if (decision.kind === 'connectDenied') + throw daemonConnectDeniedError({ + info: existing, + denial: decision.denial, + stateDir: settings.paths.baseDir, + }); // Ordered before the newer-daemon refusal on purpose: a client that may not retire a contender // reports the race and lets `ensureDaemon` judge the winner again, where that refusal belongs. if (!settings.retireIncompatibleContender) throw daemonContendedError(); @@ -180,9 +185,11 @@ async function isAwaitingDaemonStartup( info: DaemonInfo, deadline: number | undefined, ): Promise { - return ( - isProcessAlive(info.pid) && !(await canConnect(info, 'auto', remainingStartupBudget(deadline))) - ); + if (!isProcessAlive(info.pid)) return false; + const probe = await probeReusableDaemonOnce(info, 'auto', deadline); + // A denied probe says nothing about the daemon, so it is not "still starting": the caller has to + // reach the takeover's connectDenied answer instead. + return !probe.reachable && !probe.denial; } export async function stopDaemonForTakeover( @@ -210,27 +217,34 @@ export async function retireDaemonForTakeover( throw daemonTakeoverRetirementError(retirement, existing, paths); } -/** A live pid is probed again before being judged unreachable; liveness is signal 0, not `ps`. */ -async function canReachReusableDaemon( +/** + * A live pid is probed again before being judged unreachable; liveness is signal 0, not `ps`. A probe + * the host refused is returned at once: the refusal comes from this client's own sandbox, so waiting + * cannot turn it into an answer. + */ +async function probeReusableDaemon( info: DaemonInfo, preference: DaemonTransportPreference, deadline?: number, -): Promise { - if (await canConnectReusableDaemon(info, preference, deadline)) return true; +): Promise { + const first = await probeReusableDaemonOnce(info, preference, deadline); + if (first.reachable || first.denial) return first; for (let retry = 1; retry <= LIVE_DAEMON_PROBE_RETRIES; retry += 1) { if (!isProcessAlive(info.pid) || (deadline !== undefined && Date.now() >= deadline)) - return false; + return first; await sleep(Math.min(LIVE_DAEMON_PROBE_RETRY_DELAY_MS, remainingStartupBudget(deadline))); - if (await canConnectReusableDaemon(info, preference, deadline)) { + const again = await probeReusableDaemonOnce(info, preference, deadline); + if (again.reachable) { emitDiagnostic({ level: 'warn', phase: 'daemon_probe_recovered', data: { pid: info.pid, retry }, }); - return true; + return again; } + if (again.denial) return again; } - return false; + return first; } /** @@ -259,15 +273,15 @@ export async function assertDaemonPolicyMatches( ); } -async function canConnectReusableDaemon( +async function probeReusableDaemonOnce( info: DaemonInfo, preference: DaemonTransportPreference, deadline?: number, -): Promise { +): Promise { try { - return await canConnect(info, preference, remainingStartupBudget(deadline)); + return await probeDaemonReachability(info, preference, remainingStartupBudget(deadline)); } catch (error) { - if (isDaemonTransportUnavailableError(error)) return false; + if (isDaemonTransportUnavailableError(error)) return { reachable: false }; throw error; } } @@ -361,7 +375,7 @@ function resolveStartupFailureHint( ): string { switch (reason) { case DAEMON_UNAVAILABLE_REASONS.startupListenDenied.reason: - return DAEMON_LISTEN_DENIED_HINT; + return DAEMON_LOOPBACK_DENIED_HINT; case DAEMON_UNAVAILABLE_REASONS.startupStalled.reason: case DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason: return resolveStartupProgressHint(reason, ceilingMs); @@ -643,13 +657,12 @@ async function readReadyLaunchedDaemon( const info = readDaemonInfo(settings.paths.infoPath); if (!info || !isLaunchedDaemon(info, launch)) return null; try { - return (await canConnect( + const probe = await probeDaemonReachability( info, settings.transportPreference, remainingStartupBudget(deadline), - )) && Date.now() < deadline - ? info - : null; + ); + return probe.reachable && Date.now() < deadline ? info : null; } catch (error) { const { cleanup, joined } = await retireStartupAttempt(settings, launch, deadline); emitDiagnostic({ diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 140e1f6f5d..5f5fc9773b 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -36,8 +36,15 @@ import { import { handleRequestTimeout } from './daemon-client-timeout.ts'; import { isRemoteDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; - -type ResolvedDaemonTransport = 'socket' | 'http'; +import { + LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS, + probeLoopbackPort, + readLoopbackConnectDenial, + type DaemonProbeVerdict, + type LoopbackTransport, +} from './daemon-client-loopback-probe.ts'; + +type ResolvedDaemonTransport = LoopbackTransport; type SendRequestOptions = { /** The host whose working directory and environment this request's client-side work reads. */ host: HostEnvironment; @@ -144,7 +151,6 @@ export function createRequestGuard(params: { }; } -const LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS = 500; const REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS = 3000; export function isDaemonTransportUnavailableError(error: unknown): boolean { @@ -185,60 +191,43 @@ type RemoteDaemonHealthLink = Pick< 'service' | 'version' | 'rpcProtocolVersion' | 'instanceId' | 'hostArch' | 'capabilities' >; -export async function canConnect( +export async function probeDaemonReachability( info: DaemonInfo, preference: DaemonTransportPreference, probeTimeoutMs?: number, -): Promise { +): Promise { const deadline = Date.now() + (probeTimeoutMs ?? Number.POSITIVE_INFINITY); const transport = chooseTransport(info, preference); const fallback = chooseAutoFallbackTransport(info, preference, transport); const firstBudget = (deadline - Date.now()) / (fallback ? 2 : 1); - if (await canConnectWithTransport(info, transport, firstBudget)) return Date.now() < deadline; - return fallback - ? (await canConnectWithTransport(info, fallback, deadline - Date.now())) && - Date.now() < deadline - : false; + const first = await probeTransportEndpoint(info, transport, firstBudget); + if (first.reachable) return { reachable: Date.now() < deadline }; + if (!fallback) return first; + const second = await probeTransportEndpoint(info, fallback, deadline - Date.now()); + if (second.reachable) return { reachable: Date.now() < deadline }; + // One refused leg is enough to withhold a death verdict: the client cannot read the other leg's + // silence as proof while the host has shown it refuses this daemon's endpoints. + return { reachable: false, denial: first.denial ?? second.denial }; } -async function canConnectWithTransport( +async function probeTransportEndpoint( info: DaemonInfo, transport: ResolvedDaemonTransport, timeoutMs: number, -): Promise { - return transport === 'http' - ? await canConnectHttp(info, timeoutMs) - : await canConnectSocket(info.port, timeoutMs); -} - -export function canConnectSocket( - port: number | undefined, - timeoutMs = LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS, -): Promise { - if (!port || timeoutMs <= 0) return Promise.resolve(false); - return new Promise((resolve) => { - let settled = false; - const socket = net.createConnection({ host: '127.0.0.1', port }, () => { - finish(true); - }); - const finish = (reachable: boolean) => { - if (settled) return; - settled = true; - socket.destroy(); - resolve(reachable); - }; - socket.setTimeout(Math.min(LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS, Math.ceil(timeoutMs))); - socket.on('timeout', () => { - finish(false); - }); - socket.on('error', () => { - finish(false); - }); - }); -} - -function canConnectHttp(info: DaemonInfo, timeoutMs: number): Promise { - return readDaemonHttpHealth(info, timeoutMs).then((health) => health.reachable); +): Promise { + if (transport === 'http') return await probeHttpEndpoint(info, timeoutMs); + return await probeLoopbackPort(info.port, 'socket', timeoutMs); +} + +async function probeHttpEndpoint(info: DaemonInfo, timeoutMs: number): Promise { + // One health request answers reachability and, through the errno it records, whether the host + // refused the connect at all. A second connect would double the probe's cost. + const health = await probeDaemonHealth(info, timeoutMs); + if (health.reachable) return { reachable: true }; + const denial = info.httpPort + ? readLoopbackConnectDenial(health.connectErrno, 'http', info.httpPort) + : undefined; + return denial ? { reachable: false, denial } : { reachable: false }; } export async function readRemoteDaemonHealth( @@ -272,11 +261,32 @@ function daemonHttpEndpoint(info: DaemonInfo, route: 'health' | 'rpc'): string | : null; } +/** + * A health probe's answer plus the errno of a connect the HOST refused, which is how a sandbox around + * this client shows up. An answer from the daemon, a refused request and a timeout all leave it + * absent. Only the reachability verdict reads it; the health shape clients and caches hold does not + * carry it. + */ +type DaemonHealthProbe = RemoteDaemonHealth & Readonly<{ connectErrno?: string }>; + async function readDaemonHttpHealth( info: DaemonInfo, probeTimeoutMs?: number, callerSignal?: AbortSignal, ): Promise { + const { connectErrno: _deny, ...health } = await probeDaemonHealth( + info, + probeTimeoutMs, + callerSignal, + ); + return health; +} + +async function probeDaemonHealth( + info: DaemonInfo, + probeTimeoutMs?: number, + callerSignal?: AbortSignal, +): Promise { const endpoint = daemonHealthEndpoint(info); if (!endpoint) return { reachable: false }; const url = new URL(endpoint); @@ -331,8 +341,8 @@ async function readDaemonHttpHealth( req.destroy(); resolve({ reachable: false, timedOut: true }); }); - req.on('error', () => { - resolve(unreachable()); + req.on('error', (error: NodeJS.ErrnoException) => { + resolve({ ...unreachable(), connectErrno: error.code }); }); req.end(); }); diff --git a/packages/daemon-client/src/daemon-launch-spec.ts b/packages/daemon-client/src/daemon-launch-spec.ts index 3280fd7fca..8586c2f9d5 100644 --- a/packages/daemon-client/src/daemon-launch-spec.ts +++ b/packages/daemon-client/src/daemon-launch-spec.ts @@ -13,6 +13,7 @@ import { computeDaemonCodeSignature, resolveDaemonCodeOrigin, } from '@agent-device/host-kit/code-signature'; +import type { DaemonProbeVerdict } from './daemon-client-loopback-probe.ts'; import type { DaemonInfo, DaemonTakeoverDecision } from './daemon-client-metadata.ts'; type DaemonLaunchSpec = { @@ -111,23 +112,28 @@ export async function resolveLocalDaemonCodeIdentity(): Promise Promise; - onAnyAdvertisedTransport: () => Promise; + onClientTransport: () => Promise; + onAnyAdvertisedTransport: () => Promise; }; /** - * One ladder decides reuse, replace, or refuse, so a daemon can never be reused and announced as - * replaced, or replaced without a reason to print. The version answers first because it is cheap - * and decides alone for the common pair of installed trees; the code identity - * (`resolveCodeIdentityMismatch`) answers next and unreachability last. + * One ladder decides reuse, replace, refuse, or "the host refused this client", so a daemon can + * never be reused and announced as replaced, or replaced without a reason to print. The version + * answers first because it is cheap and decides alone for the common pair of installed trees; the + * code identity (`resolveCodeIdentityMismatch`) answers next and unreachability last. * * A live daemon NEWER than this client is neither reused nor replaced: it was started by a * newer install that may still own live sessions, and an older binary that a package manager * hoisted onto PATH must not kill it under that install. An unreachable newer daemon is dead and - * replaced like any version mismatch. + * replaced like any version mismatch. A probe the HOST refused answers `connectDenied` on either + * branch instead: this client never saw the daemon, so it holds no evidence that the daemon is + * dead, and retiring it would end a daemon only this client's sandbox cannot reach. */ export async function resolveDaemonTakeover( info: DaemonInfo, @@ -135,12 +141,14 @@ export async function resolveDaemonTakeover( ): Promise { const clientVersion = readVersion(); if (info.version !== clientVersion) { - if ( - info.version && - isNewerVersion(info.version, clientVersion) && - (await reachability.onAnyAdvertisedTransport()) - ) { - return { kind: 'refuseNewer', daemonVersion: info.version, clientVersion }; + // Probed exactly where it was probed before: only a newer daemon's answer decides a refusal on + // its own. Where the probe is made, a connect the host refused answers `connectDenied` rather + // than a death verdict, so a newer daemon is never retired by a client that cannot see it. + if (info.version && isNewerVersion(info.version, clientVersion)) { + const advertised = await reachability.onAnyAdvertisedTransport(); + if (advertised.denial) return { kind: 'connectDenied', denial: advertised.denial }; + if (advertised.reachable) + return { kind: 'refuseNewer', daemonVersion: info.version, clientVersion }; } return { kind: 'replace', @@ -151,9 +159,9 @@ export async function resolveDaemonTakeover( const localIdentity = await resolveLocalDaemonCodeIdentity(); const codeMismatch = resolveCodeIdentityMismatch(localIdentity, info); if (codeMismatch) return { kind: 'replace', reason: codeMismatch, cause: 'code' }; - if (!(await reachability.onClientTransport())) { - return { kind: 'replace', reason: 'unreachable', cause: 'unreachable' }; - } + const probe = await reachability.onClientTransport(); + if (probe.denial) return { kind: 'connectDenied', denial: probe.denial }; + if (!probe.reachable) return { kind: 'replace', reason: 'unreachable', cause: 'unreachable' }; return { kind: 'reuse' }; } diff --git a/packages/daemon-client/src/daemon-lifecycle-errors.ts b/packages/daemon-client/src/daemon-lifecycle-errors.ts index 1c7a13ed41..3499fe6757 100644 --- a/packages/daemon-client/src/daemon-lifecycle-errors.ts +++ b/packages/daemon-client/src/daemon-lifecycle-errors.ts @@ -14,6 +14,7 @@ import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell'; import { readVersion } from '@agent-device/host-kit/version'; import type { DaemonClientSettings } from './daemon-client-lifecycle.ts'; import type { DaemonInfo, DaemonTakeoverCause } from './daemon-client-metadata.ts'; +import type { LoopbackConnectDenial } from './daemon-client-loopback-probe.ts'; import { resolveLocalDaemonCodeIdentity } from './daemon-launch-spec.ts'; // The ways an explicit lifecycle stops short of a usable daemon, as this client judges it. A busy @@ -51,6 +52,9 @@ export const DAEMON_UNAVAILABLE_REASONS = { // 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 host refused this client's loopback connect to the registered daemon, as a sandbox around it + // does; `details.daemon` names the daemon left alone. + connectDenied: { reason: 'daemon-connect-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. @@ -224,6 +228,41 @@ export function daemonBusyError( }); } +/** + * The answer to a loopback endpoint the host refused, whether the daemon's listen or a client's + * connect. One owner for both: a sandboxed agent reads it to ask for host access instead of giving up. + */ +export const DAEMON_LOOPBACK_DENIED_HINT = + 'The host denied agent-device a loopback port on 127.0.0.1 (connect or 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).'; + +/** + * The refusal when the host denied this client's connect to the registered daemon. The daemon keeps + * running: this client saw nothing of it, so it replaced, retired and signaled nothing. + */ +export function daemonConnectDeniedError(params: { + info: DaemonInfo; + denial: LoopbackConnectDenial; + stateDir: string; +}): AppError { + const { info, denial, stateDir } = params; + return new AppError( + 'COMMAND_FAILED', + `The host denied this client a connect to the daemon's loopback endpoint on 127.0.0.1:${denial.port}.`, + { + reason: DAEMON_UNAVAILABLE_REASONS.connectDenied.reason, + stateDir, + daemon: daemonIdentityOf(info), + transport: denial.transport, + port: denial.port, + errno: denial.errno, + hint: DAEMON_LOOPBACK_DENIED_HINT, + }, + ); +} + /** Refuses replacement when the record cannot prove a detached owner. */ function daemonRecordOwnerUnrecognizedError(params: { info: DaemonIdentity; diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index e82b8d283c..57e1a445d2 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-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. + 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. A sandbox around the client can also refuse the client's own connect to a daemon that runs outside it; that is not a startup outcome and needs no daemon launch. The command then fails with details.reason daemon-connect-denied, naming the errno, transport, port and daemon it could not reach. That daemon keeps running: the client replaced, retired and signaled nothing. Rerun agent-device with host access. 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 7ff26ffa31..6e8db65e9a 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-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. | +| 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. A sandbox around the client can also refuse the client's own connect to a daemon that runs outside it, which is not a startup outcome: that fails with `details.reason: daemon-connect-denied`, naming the errno, transport, port and daemon it could not reach. That daemon keeps running and nothing is replaced, retired, or signaled; rerun agent-device with host access. | | 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 692fcc8dbf..bec2695bc5 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -582,6 +582,7 @@ These reasons can come from more than one command. | `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, 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. | +| `daemon-connect-denied` | The host refused this client's loopback connect to the registered daemon, as a sandbox around it does; `details.daemon` names the daemon left alone. | | `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. | From 2b30ec42c4c4ce2882f2428780fbed3295f580bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 13:02:02 +0100 Subject: [PATCH 2/8] fix(daemon-client): leave a daemon alone on every refused connect A host-denied loopback connect (EPERM or EACCES) reached `daemon-connect-denied` only on the one ladder branch that probed. Every other path to a replacement judged the daemon from the record alone, so a client that cannot see a daemon still retired it, and a launch whose own readiness probe was refused fell into the startup cleanup that signals the launched process. The ladder now probes the advertised endpoints before ANY `replace` answer, for a version mismatch and a code mismatch alike, so `connectDenied` is the verdict wherever a replacement was about to be decided. A launch-time refusal is terminal and names the typed reason before the stalled and ceiling cleanup paths. The liveness probe classifies its legs' errnos too: a refused leg settles as a denial, so neither the drain wait, a timed-out quiesce, nor a reset-eligible timeout can retire on a connect this client was refused. The HTTP reachability leg asks on a fresh connection, and the first leg's refusal survives a late answer on the second. The probe implementation moves behind the function-scoped `await import` its one caller already uses, and `readDaemonHttpHealth` returns to the shape the wire ledger records: a probe now proves a refused connect with its own connect rather than by carrying an errno in a health payload, so no wire declaration changes. Docs name the two errnos the reason covers, and the connect-denied test is named for the module it pins. --- .../daemon-client-liveness-probe.test.ts | 58 ++++++++-- ...ent-loopback-probe-connect-denied.test.ts} | 108 +++++++++++++++--- .../src/__tests__/daemon-launch-spec.test.ts | 19 +++ .../daemon-client/src/daemon-client-ensure.ts | 24 +++- .../src/daemon-client-liveness-probe.ts | 95 +++++++++++---- .../src/daemon-client-loopback-probe.ts | 88 +++++++++++++- .../src/daemon-client-startup.ts | 19 ++- .../src/daemon-client-timeout.ts | 9 +- .../src/daemon-client-transport.ts | 78 ++++++------- .../daemon-client/src/daemon-launch-spec.ts | 24 ++-- src/commands/schema/cli-help.ts | 2 +- website/docs/docs/configuration.md | 2 +- website/docs/docs/error-reasons.md | 2 +- 13 files changed, 406 insertions(+), 122 deletions(-) rename packages/daemon-client/src/__tests__/{daemon-client-connect-denied.test.ts => daemon-client-loopback-probe-connect-denied.test.ts} (58%) diff --git a/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts b/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts index 4e1879a74f..f87a58618d 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-liveness-probe.test.ts @@ -6,9 +6,10 @@ // absolute deadline exist for) spend wall-clock, and each stays inside the unit budget. import net from 'node:net'; +import EventEmitter from 'node:events'; import http from 'node:http'; import assert from 'node:assert/strict'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; import { resolveCommandTimeoutPolicy } from '@agent-device/command-registry/registry'; @@ -73,7 +74,7 @@ test('a daemon answering /health is responsive', async (t) => { res.end('{}'); }); await withLoopback(server, async (port) => { - assert.equal(await probeDaemonResponsive(daemonInfo({ httpPort: port })), true); + assert.equal((await probeDaemonResponsive(daemonInfo({ httpPort: port }))).reachable, true); assert.deepEqual(requestedUrls, ['/health']); }); }); @@ -89,7 +90,7 @@ test('a 5xx answer is still an answer: the finding is liveness, not reachability res.end('overloaded'); }); await withLoopback(server, async (port) => { - assert.equal(await probeDaemonResponsive(daemonInfo({ httpPort: port })), true); + assert.equal((await probeDaemonResponsive(daemonInfo({ httpPort: port }))).reachable, true); }); }); @@ -110,7 +111,7 @@ test('headers alone answer: a daemon that stalls mid-body is still served', asyn await withLoopback(stallingBodyServer, async (port) => { const startedAt = Date.now(); assert.equal( - await probeDaemonResponsive(daemonInfo({ httpPort: port })), + (await probeDaemonResponsive(daemonInfo({ httpPort: port }))).reachable, true, 'a stalled body must not be read as an unresponsive daemon', ); @@ -158,7 +159,7 @@ test('the health leg rides a fresh connection, never the keep-alive pool', async request.end(); }); assert.equal(clientSockets.size, 1, 'the prime must have connected'); - assert.equal(await probeDaemonResponsive(daemonInfo({ httpPort: port })), true); + assert.equal((await probeDaemonResponsive(daemonInfo({ httpPort: port }))).reachable, true); assert.equal(probeRequests, 1, 'the health leg must actually have been asked'); assert.equal( clientSockets.size, @@ -179,7 +180,7 @@ test('a refused endpoint is negative, not a hang: the verdict arrives well insid }); await withLoopback(server, async (port) => { const startedAt = Date.now(); - assert.equal(await probeDaemonResponsive(daemonInfo({ port })), false); + assert.equal((await probeDaemonResponsive(daemonInfo({ port }))).reachable, false); assert.ok( Date.now() - startedAt < LIVENESS_PROBE_BUDGET_MS / 2, 'refusal must settle the probe immediately, not by spending the window', @@ -187,6 +188,36 @@ test('a refused endpoint is negative, not a hang: the verdict arrives well insid }); }); +// The verdict that authorizes a reset. A connect the HOST refused (EPERM or EACCES under a sandbox +// around this client) is not a missed probe: read as silence it would SIGKILL a daemon only this +// client's sandbox cannot reach, which is the same mistake #3177 removed for a live peer. +test.for(['EPERM', 'EACCES'] as const)( + 'a %s refusal is reported as a denial, not as an unresponsive daemon', + async (code) => { + const socket = Object.assign(new EventEmitter(), { + destroy: () => {}, + setEncoding: () => {}, + setTimeout: () => socket, + write: () => {}, + }); + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((( + _options: unknown, + _listener?: () => void, + ) => { + setImmediate(() => socket.emit('error', Object.assign(new Error(code), { code }))); + return socket; + }) as unknown as typeof net.createConnection); + try { + assert.deepEqual(await probeDaemonResponsive(daemonInfo({ port: 65_530 })), { + reachable: false, + denial: { errno: code, transport: 'socket', port: 65_530 }, + }); + } finally { + createConnection.mockRestore(); + } + }, +); + test('a silent HTTP leg cannot veto a live socket leg', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; // The regression the concurrent-legs design exists for: sequential probing lets the first @@ -222,7 +253,7 @@ test('a silent HTTP leg cannot veto a live socket leg', async (t) => { await withLoopback(liveSocketServer, async (port) => { const startedAt = Date.now(); assert.equal( - await probeDaemonResponsive(daemonInfo({ port, httpPort })), + (await probeDaemonResponsive(daemonInfo({ port, httpPort }))).reachable, true, 'the socket answer alone is the finding; the silent HTTP leg must not outweigh it', ); @@ -252,7 +283,11 @@ async function expectMalformedLegAnswersNotThisOne( () => null, (error: unknown) => error, ); - assert.equal(await probe, expectResponsive, `${name}: the malformed leg answers 'not this one'`); + assert.equal( + (await probe).reachable, + expectResponsive, + `${name}: the malformed leg answers 'not this one'`, + ); assert.equal(await rejection, null, `${name}: the probe never rejects on a malformed record`); } @@ -317,7 +352,7 @@ test('a slow-trickle endpoint is cut off by the absolute deadline, not extended }); await withLoopback(server, async (port) => { const startedAt = Date.now(); - assert.equal(await probeDaemonResponsive(daemonInfo({ port })), false); + assert.equal((await probeDaemonResponsive(daemonInfo({ port }))).reachable, false); const elapsedMs = Date.now() - startedAt; assert.ok( elapsedMs >= LIVENESS_PROBE_BUDGET_MS / 2 && elapsedMs <= LIVENESS_PROBE_BUDGET_MS * 1.5, @@ -340,7 +375,10 @@ test('the socket probe asks with the session-lock-exempt inventory command', asy }); }); await withLoopback(server, async (port) => { - assert.equal(await probeDaemonResponsive(daemonInfo({ port }), { session: 'worker-3' }), true); + assert.equal( + (await probeDaemonResponsive(daemonInfo({ port }), { session: 'worker-3' })).reachable, + true, + ); const asked = JSON.parse(requestLine) as { command: string; session?: string }; assert.equal(asked.command, 'session_list'); assert.equal(asked.session, 'worker-3'); diff --git a/packages/daemon-client/src/__tests__/daemon-client-connect-denied.test.ts b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts similarity index 58% rename from packages/daemon-client/src/__tests__/daemon-client-connect-denied.test.ts rename to packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts index 98741c5d76..1b431ce9cc 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-connect-denied.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts @@ -29,23 +29,32 @@ import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; const DENIED_ERRNO = 'EPERM'; +/** A host refusal to answer a probe with, naming the errno and endpoint family it refused. */ +type DeniedProbe = Readonly<{ errno: 'EPERM' | 'EACCES'; transport: 'socket' | 'http' }>; + const { mockProbeAnswers, mockSpawnDaemon } = vi.hoisted(() => ({ - /** What each probe of the registered daemon answers, in order; `denied` is a host refusal. */ - mockProbeAnswers: [] as ('denied' | 'silent')[], + /** + * What each probe of the registered daemon answers, in order: `'silent'`, or the refusal the host + * gave. `null` stands for silence so the list reads as answers, not as verdict shapes. + */ + mockProbeAnswers: [] as (DeniedProbe | null)[], mockSpawnDaemon: vi.fn(), })); +function denied(errno: DeniedProbe['errno'], transport: DeniedProbe['transport']): DeniedProbe { + return { errno, transport }; +} + vi.mock('../daemon-client-transport.ts', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, probeDaemonReachability: async (...args: Parameters) => { - const answer = mockProbeAnswers.shift() ?? 'silent'; - if (answer !== 'denied') return { reachable: false }; - return { - reachable: false, - denial: { errno: DENIED_ERRNO, transport: 'socket', port: args[0].port ?? 0 }, - }; + const answer = mockProbeAnswers.shift(); + if (!answer) return { reachable: false }; + // The port is the one this probe aimed at, as the real probe reports it. + const port = answer.transport === 'http' ? (args[0].httpPort ?? 0) : (args[0].port ?? 0); + return { reachable: false, denial: { ...answer, port } }; }, }; }); @@ -61,13 +70,16 @@ afterEach(() => { }); /** - * A stand-in for the daemon running OUTSIDE the sandbox: a live process whose command reads as an - * agent-device daemon, plus a registration this client wrote by hand. The client never started this - * lifetime, so an unreachable judgement lands as a retirement it may not confirm. + * A stand-in for the daemon running OUTSIDE the sandbox: a live process, plus a registration this + * client wrote by hand that points at loopback endpoints and this pid. The process is a plain `node + * -e` stand-in, not a daemon build: what makes it a daemon is the registration and the live pid, and + * `readProcessCommand` is read only as a skip guard for environments where process inspection is + * unavailable. The client never started this lifetime, so an unreachable judgement lands as a + * retirement it may not confirm. */ async function withRegisteredStandIn( t: { skip: (reason: string) => void }, - body: (input: { stateDir: string; pid: number }) => Promise, + body: (input: { stateDir: string; pid: number; port: number; httpPort: number }) => Promise, ): Promise { if (await skipWhenLoopbackUnavailable(t)) return; const stateDir = mkdtempForTestSync('agent-device-connect-denied-'); @@ -80,6 +92,7 @@ async function withRegisteredStandIn( const pid = standIn.child.pid; assert.ok(pid, 'the stand-in has a pid'); const server = net.createServer((socket) => socket.on('error', () => {})); + const httpServer = net.createServer((socket) => socket.on('error', () => {})); try { await new Promise((resolve) => setTimeout(resolve, 50)); const processStartTime = readProcessStartTime(pid) ?? undefined; @@ -89,13 +102,15 @@ async function withRegisteredStandIn( return; } const port = await listenOnLoopback(server); + const httpPort = await listenOnLoopback(httpServer); const paths = resolveDaemonPaths(stateDir); fs.mkdirSync(paths.baseDir, { recursive: true }); fs.writeFileSync( paths.infoPath, `${JSON.stringify({ port, - transport: 'socket', + transport: 'dual', + httpPort, token: 'local-secret', pid, version: readVersion(), @@ -104,8 +119,9 @@ async function withRegisteredStandIn( })}\n`, 'utf8', ); - await body({ stateDir, pid }); + await body({ stateDir, pid, port, httpPort }); } finally { + await closeLoopbackServer(httpServer); await closeLoopbackServer(server); if (isProcessAlive(pid)) { process.kill(pid, 'SIGKILL'); @@ -115,12 +131,12 @@ async function withRegisteredStandIn( } } -function sendDevices(stateDir: string) { +function sendDevices(stateDir: string, transport: 'socket' | 'http' = 'socket') { return sendToDaemon({ session: 'default', command: 'devices', positionals: [], - flags: { stateDir, daemonTransport: 'socket' }, + flags: { stateDir, daemonTransport: transport }, meta: { requestId: 'req-connect-denied' }, }); } @@ -139,7 +155,7 @@ async function rejection(pending: Promise): Promise { test('a connect the host refused names the sandbox and leaves the daemon running', async (t) => { await withRegisteredStandIn(t, async ({ stateDir, pid }) => { - mockProbeAnswers.push('denied'); + mockProbeAnswers.push(denied(DENIED_ERRNO, 'socket')); const failure = await rejection(sendDevices(stateDir)); @@ -153,9 +169,65 @@ test('a connect the host refused names the sandbox and leaves the daemon running }); }); +// Both endpoint families and both refused errnos have to reach the caller with the details they were +// refused with: a regression that dropped `transport` or rewrote `errno` would otherwise pass here. +// The stand-in daemon serves both endpoints, so the client probes its socket leg first and falls back +// to HTTP: an HTTP refusal therefore arrives as the SECOND leg's answer, which is the shape a real +// sandbox produces when it refuses only the family the socket leg does not cover. +test.for([ + { errno: 'EPERM', leg: 'socket' }, + { errno: 'EACCES', leg: 'socket' }, + { errno: 'EACCES', leg: 'http' }, + { errno: 'EPERM', leg: 'http' }, +] as const)( + 'a refusal of the %s endpoint with %s reports both in the reason details', + async ({ errno, leg }, t) => { + await withRegisteredStandIn(t, async ({ stateDir, pid, port, httpPort }) => { + mockProbeAnswers.push(denied(errno, leg)); + + // The client is pinned to the leg under test, so the refusal it reports is that leg's. + const failure = await rejection(sendDevices(stateDir, leg)); + + assert.equal(failure.details?.reason, 'daemon-connect-denied'); + assert.equal(failure.details?.errno, errno); + assert.equal(failure.details?.transport, leg); + assert.equal(failure.details?.port, leg === 'http' ? httpPort : port); + assert.equal((failure.details?.daemon as { pid?: number } | undefined)?.pid, pid); + assert.equal(mockSpawnDaemon.mock.calls.length, 0); + assert.equal(isProcessAlive(pid), true); + }); + }, +); + +// An attach client starts and replaces nothing anyway, so its only wrong answer would read as "no +// daemon is running" and send the caller to start one it cannot reach either. +test('an attach client told about a refusal does not report a daemon that is not running', async (t) => { + await withRegisteredStandIn(t, async ({ stateDir, pid }) => { + mockProbeAnswers.push(denied(DENIED_ERRNO, 'socket')); + + const failure = await rejection( + sendToDaemon( + { + session: 'default', + command: 'devices', + positionals: [], + flags: { stateDir, daemonTransport: 'socket' }, + meta: { requestId: 'req-attach-denied' }, + }, + { daemonLifecycle: 'attach' }, + ), + ); + + assert.equal(failure.details?.reason, 'daemon-connect-denied'); + assert.equal(failure.details?.errno, DENIED_ERRNO); + assert.equal((failure.details?.daemon as { pid?: number } | undefined)?.pid, pid); + assert.equal(isProcessAlive(pid), true, 'an attach client signals nothing either'); + }); +}); + test('a probe that goes unanswered is still judged unreachable, not denied', async (t) => { await withRegisteredStandIn(t, async ({ stateDir, pid }) => { - mockProbeAnswers.push('silent', 'silent', 'silent', 'silent'); + mockProbeAnswers.push(null, null, null, null); const failure = await rejection(sendDevices(stateDir)); diff --git a/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts b/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts index 962bc9a2e7..351ad42cb5 100644 --- a/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts @@ -166,6 +166,25 @@ test('a same-version daemon the host refused to connect to is not judged unreach ); }); +// A replacement retires a live process, so no branch of the ladder may answer it on the record alone. +// Before this, only a NEWER daemon was probed: an older or code-mismatched one was replaced without +// ever being seen, which let a client whose sandbox refuses the connect kill a healthy daemon. +test('a version mismatch the host refused to probe is a denial, not a replacement', async () => { + assert.deepEqual(await resolveDaemonTakeover(runningDaemon({ version: '0.0.1' }), denied()), { + kind: 'connectDenied', + denial: DENIAL, + }); +}); + +test('a code mismatch the host refused to probe is a denial, not a replacement', async () => { + useClientTree(false); + + assert.deepEqual( + await resolveDaemonTakeover(runningDaemon({ codeOrigin: 'checkout' }), denied()), + { kind: 'connectDenied', denial: DENIAL }, + ); +}); + // The refusal outranks the newer-daemon refusal: both stop the daemon being touched, and only // `connectDenied` says the reason is this client's sandbox rather than the daemon's version. test('a connect the host refused never reads as a newer daemon to refuse', async () => { diff --git a/packages/daemon-client/src/daemon-client-ensure.ts b/packages/daemon-client/src/daemon-client-ensure.ts index 1efeaee7de..0f1ca1f969 100644 --- a/packages/daemon-client/src/daemon-client-ensure.ts +++ b/packages/daemon-client/src/daemon-client-ensure.ts @@ -182,7 +182,17 @@ async function awaitDrainedDaemon( }); return 'left'; } - if (await answersLivenessProbe(info)) throw await daemonDrainTimeoutError(info, settings); + const liveness = await answersLivenessProbe(info); + // A connect the host refused says nothing about whether this daemon is hung, so it is not a drain + // to name: the refusal travels to the caller, which names the sandbox and the way out. + if (liveness.denial) { + throw daemonConnectDeniedError({ + info, + denial: liveness.denial, + stateDir: settings.paths.baseDir, + }); + } + if (liveness.reachable) throw await daemonDrainTimeoutError(info, settings); const retirement = await stopDaemonForTakeover(info, settings.paths, 'force'); if (retirement.status !== 'retained') return 'retired'; // Nothing was signaled because the process could not be proved to be a daemon of its own: either its @@ -214,7 +224,17 @@ async function quiesceOrRetireUnresponsive( error.details?.reason !== DAEMON_TRANSPORT_REASONS.timeout.reason ) throw error; - if (await answersLivenessProbe(info)) throw error; + const liveness = await answersLivenessProbe(info); + if (liveness.denial) { + // The refusal is the finding, not the timeout: a daemon this client cannot reach because the + // host refused the connect is never force-retired. + throw daemonConnectDeniedError({ + info, + denial: liveness.denial, + stateDir: settings.paths.baseDir, + }); + } + if (liveness.reachable) throw error; await retireDaemonForTakeover(info, settings.paths, 'force'); return 'retired'; } diff --git a/packages/daemon-client/src/daemon-client-liveness-probe.ts b/packages/daemon-client/src/daemon-client-liveness-probe.ts index b98dd2ebee..7a35600be2 100644 --- a/packages/daemon-client/src/daemon-client-liveness-probe.ts +++ b/packages/daemon-client/src/daemon-client-liveness-probe.ts @@ -5,8 +5,13 @@ import { createRequestId } from '@agent-device/host-kit/diagnostics'; import { sleep } from '@agent-device/host-kit/retry'; import { loadNodeHttpRequester, consumeTextLines } from '@agent-device/host-kit/transport'; import type { DaemonInfo } from './daemon-client-metadata.ts'; +import type { + DaemonProbeVerdict, + LoopbackConnectDenial, + LoopbackTransport, +} from './daemon-client-loopback-probe.ts'; -// The post-timeout liveness probe (#3177): the question a daemon reset may no longer assume. The +// The post-timeout liveness probe (#3177): the question that a daemon reset may no longer assume. The // daemon owns request-scoped recovery, so a reset is only justified for a daemon that answers // nothing, and it must be asked on FRESH connections — the timed-out connection is the one the // transport already tore down to cancel that request. @@ -21,17 +26,20 @@ const UNRESPONSIVE_PROBE_GAP_MS = 200; /** * The one verdict that may end a daemon for answering nothing: every probe of several missed. Each - * caller that retires on silence asks here, so the evidence is the same on every path. + * caller that retires on silence asks here, so the evidence is the same on every path. A probe the + * HOST refused stops the round at once: a refusal is not a missed probe, and repeating it cannot + * turn one into an answer about the daemon. */ export async function answersLivenessProbe( info: DaemonInfo, params: Readonly<{ session?: string }> = {}, -): Promise { +): Promise { for (let probe = 1; probe <= UNRESPONSIVE_PROBES; probe += 1) { - if (await probeDaemonResponsive(info, params)) return true; + const verdict = await probeDaemonResponsive(info, params); + if (verdict.reachable || verdict.denial) return verdict; if (probe < UNRESPONSIVE_PROBES) await sleep(UNRESPONSIVE_PROBE_GAP_MS); } - return false; + return { reachable: false }; } /** @@ -45,54 +53,91 @@ export async function answersLivenessProbe( * would outlive an idle timeout, and the negative verdict must land inside the window. A leg never * rejects: a probe that cannot ask is an endpoint that did not answer. `session` rides along so an * isolation-scoped daemon routes the probe like the request it follows. + * + * A verdict that is neither an answer nor a refusal is the only one that says the daemon served + * nothing. A connect the host refused (EPERM or EACCES under a sandbox around this client) carries + * that refusal instead, so no caller reads a daemon it cannot reach as an unresponsive one. */ export async function probeDaemonResponsive( info: DaemonInfo, params: Readonly<{ session?: string }> = {}, -): Promise { +): Promise { + // The verdict's shape and the errno that names a refusal belong to the probe module. It is loaded + // here, not at module scope: this file is a lazy path itself (`daemon-client-timeout.ts` imports it + // on a timeout) and no client entry surface pays for a verdict it only reads on a probe. + const { readLoopbackConnectDenial } = await import('./daemon-client-loopback-probe.ts'); const deadlineAtMs = Date.now() + LIVENESS_PROBE_BUDGET_MS; const legs: ProbeLeg[] = []; if (info.httpPort) legs.push(probeHttpHealth(info.httpPort, deadlineAtMs)); if (info.port) legs.push(probeSocketRpc(info.port, info.token, params.session, deadlineAtMs)); - if (legs.length === 0) return false; - return await new Promise((resolve) => { + if (legs.length === 0) return { reachable: false }; + const silent: SilentProbeLeg[] = []; + return await new Promise((resolve) => { let outstanding = legs.length; - const settle = (answered: boolean): void => { - if (answered) { + const settle = (answer: ProbeLegAnswer): void => { + if (answer.answered) { for (const leg of legs) leg.cancel(); - resolve(true); + resolve({ reachable: true }); return; } - if (--outstanding === 0) resolve(false); + silent.push(answer); + if (--outstanding > 0) return; + // Both legs answered nothing. A refusal among them withholds the unresponsive verdict: this + // client cannot read the other leg's silence as proof the daemon is hung once the host has + // shown it refuses this daemon's endpoint. Both legs are waited for rather than settled on the + // first refusal, because an answer on either one is the better finding and the deadline bounds + // the wait either way. + const denial = silent + .map((leg) => readLoopbackConnectDenial(leg.errno, leg.transport, leg.port)) + .find((verdict): verdict is LoopbackConnectDenial => verdict !== undefined); + resolve(denial ? { reachable: false, denial } : { reachable: false }); }; - for (const leg of legs) leg.answer.then(settle, () => settle(false)); + for (const leg of legs) { + leg.answer.then(settle, () => settle({ ...leg.endpoint, answered: false })); + } }); } -type ProbeLeg = Readonly<{ answer: Promise; cancel: () => void }>; +/** The endpoint family and port one liveness leg probed. */ +type ProbeEndpoint = Readonly<{ transport: LoopbackTransport; port: number }>; + +/** One leg's answer: it served, or it did not, carrying the errno that refused its connect. */ +type ProbeLegAnswer = ProbeEndpoint & Readonly<{ answered: boolean; errno?: string }>; -function createProbeLeg(deadlineAtMs: number): { +/** A leg that did not answer, kept so a refusal among them can be named at the end. */ +type SilentProbeLeg = ProbeEndpoint & Readonly<{ errno?: string }>; + +type ProbeLeg = Readonly<{ + answer: Promise; + endpoint: ProbeEndpoint; + cancel: () => void; +}>; + +function createProbeLeg( + endpoint: ProbeEndpoint, + deadlineAtMs: number, +): { leg: ProbeLeg; - settle: (answered: boolean) => void; + settle: (answered: boolean, errno?: string) => void; attach: (destroyTransport: () => void) => void; } { let settled = false; let destroy: (() => void) | undefined; - let resolveAnswer: (answered: boolean) => void = () => {}; - const answer = new Promise((resolve) => { + let resolveAnswer: (answer: ProbeLegAnswer) => void = () => {}; + const answer = new Promise((resolve) => { resolveAnswer = resolve; }); const deadlineHandle = setTimeout(() => settle(false), Math.max(1, deadlineAtMs - Date.now())); deadlineHandle.unref?.(); - function settle(answered: boolean): void { + function settle(answered: boolean, errno?: string): void { if (settled) return; settled = true; clearTimeout(deadlineHandle); destroy?.(); - resolveAnswer(answered); + resolveAnswer({ ...endpoint, answered, ...(errno === undefined ? {} : { errno }) }); } return { - leg: { answer, cancel: () => settle(false) }, + leg: { answer, endpoint, cancel: () => settle(false) }, settle, attach: (destroyTransport) => { destroy = destroyTransport; @@ -103,7 +148,7 @@ function createProbeLeg(deadlineAtMs: number): { } function probeHttpHealth(httpPort: number, deadlineAtMs: number): ProbeLeg { - const probe = createProbeLeg(deadlineAtMs); + const probe = createProbeLeg({ transport: 'http', port: httpPort }, deadlineAtMs); // This leg builds detached. Catch transport-construction errors here so they settle the probe. void (async () => { try { @@ -122,7 +167,7 @@ function probeHttpHealth(httpPort: number, deadlineAtMs: number): ProbeLeg { probe.settle(true); }, ); - request.on('error', () => probe.settle(false)); + request.on('error', (error: NodeJS.ErrnoException) => probe.settle(false, error.code)); probe.attach(() => request.destroy()); request.end(); } catch { @@ -138,7 +183,7 @@ function probeSocketRpc( session: string | undefined, deadlineAtMs: number, ): ProbeLeg { - const probe = createProbeLeg(deadlineAtMs); + const probe = createProbeLeg({ transport: 'socket', port }, deadlineAtMs); // The same malformed-record shape as the HTTP leg, and this one builds synchronously: a throw // here would escape `probeDaemonResponsive` altogether, replacing the caller's timeout error // with a crash from the recovery path and discarding the other leg's answer. @@ -163,7 +208,7 @@ function probeSocketRpc( // that it reads and answers, not that it accepted this command. if (parsed.lines.length > 0) probe.settle(true); }); - socket.on('error', () => probe.settle(false)); + socket.on('error', (error: NodeJS.ErrnoException) => probe.settle(false, error.code)); socket.on('close', () => probe.settle(false)); return probe.leg; } diff --git a/packages/daemon-client/src/daemon-client-loopback-probe.ts b/packages/daemon-client/src/daemon-client-loopback-probe.ts index 84d757af6a..b80b6672a7 100644 --- a/packages/daemon-client/src/daemon-client-loopback-probe.ts +++ b/packages/daemon-client/src/daemon-client-loopback-probe.ts @@ -1,7 +1,16 @@ import net from 'node:net'; +import { loadNodeHttpRequester } from '@agent-device/host-kit/transport'; -/** How long one reachability probe of the local daemon's loopback endpoint may take. */ -export const LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS = 500; +// One reachability probe of one daemon endpoint, and the verdict it answers with. The transport owns +// making requests; this module owns what an endpoint's silence MEANS, because a connect the HOST +// refused (EPERM or EACCES under a sandbox around this client) is evidence about this client and not +// evidence about the daemon. Nothing here is reached by a static value import: its one caller loads it +// with a function-scoped `await import` (`probeTransportEndpoint` in `daemon-client-transport.ts`), so +// no client entry surface evaluates a module for a verdict it only reads on a probe +// (`scripts/__tests__/eager-closure-budgets.ts`). + +/** How long one loopback connect may take before the probe calls it silent. */ +const LOOPBACK_CONNECT_TIMEOUT_MS = 500; /** The errnos that say the host refused the connect itself, as a sandbox around the caller does. */ const LOOPBACK_DENIED_CODES: ReadonlySet = new Set(['EPERM', 'EACCES']); @@ -28,6 +37,13 @@ export type DaemonProbeVerdict = Readonly<{ denial?: LoopbackConnectDenial; }>; +/** One HTTP reachability probe: the health endpoint to ask, the auth it needs, and its time budget. */ +export type HttpEndpointProbe = Readonly<{ + endpoint: string; + headers: Readonly>; + timeoutMs: number; +}>; + /** * Whether an errno from a loopback connect says the host refused it, as a sandbox around this client * does. A refusal is not an answer from the daemon: unlike a reset or a timeout, it says nothing about @@ -43,13 +59,13 @@ export function readLoopbackConnectDenial( } /** - * One connect to one loopback port. A refusal from the host is reported as a denial: it is not an - * answer from the daemon, and it is the only reachability evidence a sandboxed client can be refused. + * One connect to one loopback port. A refusal from the host is reported as a denial, not as an answer + * from the daemon: nothing says whether the daemon behind that port serves. */ export function probeLoopbackPort( port: number | undefined, transport: LoopbackTransport, - timeoutMs = LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS, + timeoutMs = LOOPBACK_CONNECT_TIMEOUT_MS, ): Promise { if (!port || timeoutMs <= 0) return Promise.resolve({ reachable: false }); return new Promise((resolve) => { @@ -63,7 +79,7 @@ export function probeLoopbackPort( socket.destroy(); resolve(verdict); }; - socket.setTimeout(Math.min(LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS, Math.ceil(timeoutMs))); + socket.setTimeout(Math.min(LOOPBACK_CONNECT_TIMEOUT_MS, Math.ceil(timeoutMs))); socket.on('timeout', () => { finish({ reachable: false }); }); @@ -73,3 +89,63 @@ export function probeLoopbackPort( }); }); } + +/** + * One health request to one advertised endpoint, as a reachability verdict. + * + * The request is made on a FRESH connection: `agent: false` is load-bearing, not hygiene. Since Node + * 19 the global agent keeps sockets alive, so a pooled request would ride an idle socket from an + * earlier command rather than proving that a connect to this daemon is allowed NOW — which is the only + * thing that can tell a refused endpoint from a silent one. The time budget is ABSOLUTE and covers + * loading the requester, so a late loader never opens a request the probe already gave up on. + * + * A response answers the probe. Only a connect the HOST refused to a LOOPBACK endpoint carries a + * denial: a refusal is not an answer from the daemon, and a refusal on a remote endpoint is not the + * loopback denial this verdict names. + */ +export async function probeHttpEndpoint(probe: HttpEndpointProbe): Promise { + const url = new URL(probe.endpoint); + const loopback = url.hostname === '127.0.0.1' || url.hostname === 'localhost'; + const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80); + if (probe.timeoutMs <= 0) return { reachable: false }; + const deadline = performance.now() + probe.timeoutMs; + const timeoutSignal = AbortSignal.timeout(Math.ceil(probe.timeoutMs)); + const requester = await Promise.race([ + loadNodeHttpRequester(url.protocol), + new Promise((resolve) => { + timeoutSignal.addEventListener('abort', () => resolve(null), { once: true }); + }), + ]); + if (!requester || timeoutSignal.aborted || performance.now() >= deadline) + return { reachable: false }; + return await new Promise((resolve) => { + const request = requester.request( + { + protocol: url.protocol, + host: url.hostname, + port: url.port, + path: url.pathname + url.search, + method: 'GET', + timeout: probe.timeoutMs, + agent: false, + signal: timeoutSignal, + headers: probe.headers, + }, + (response) => { + // Any status under 500 is an answer from the daemon. The body is irrelevant to reachability, + // so it is drained and dropped: an undrained response holds its socket open past the finding. + response.resume(); + resolve({ reachable: (response.statusCode ?? 500) < 500 }); + }, + ); + request.on('timeout', () => { + request.destroy(); + resolve({ reachable: false }); + }); + request.on('error', (error: NodeJS.ErrnoException) => { + const denial = loopback ? readLoopbackConnectDenial(error.code, 'http', port) : undefined; + resolve(denial ? { reachable: false, denial } : { reachable: false }); + }); + request.end(); + }); +} diff --git a/packages/daemon-client/src/daemon-client-startup.ts b/packages/daemon-client/src/daemon-client-startup.ts index 3c32cc0e5a..32e93e0937 100644 --- a/packages/daemon-client/src/daemon-client-startup.ts +++ b/packages/daemon-client/src/daemon-client-startup.ts @@ -134,6 +134,9 @@ async function refineReplacement( if (!options.refineUnreachable || decision.kind !== 'replace') return decision; if (!isProcessAlive(info.pid)) return { ...decision, cause: 'unreachable' }; if (decision.cause === 'unreachable') { + // The ladder probed the advertised endpoints before it answered `replace`. It is asked again + // here, so a refusal observed at this point still withholds the death verdict, and a live pid + // that answers now is judged a transport mismatch rather than a dead daemon. const probe = await probeReusableDaemon(info, 'auto', options.deadline); if (probe.denial) return { kind: 'connectDenied', denial: probe.denial }; if (probe.reachable) return { ...decision, cause: 'transport' }; @@ -656,13 +659,13 @@ async function readReadyLaunchedDaemon( ): Promise { const info = readDaemonInfo(settings.paths.infoPath); if (!info || !isLaunchedDaemon(info, launch)) return null; + let probe: DaemonProbeVerdict; try { - const probe = await probeDaemonReachability( + probe = await probeDaemonReachability( info, settings.transportPreference, remainingStartupBudget(deadline), ); - return probe.reachable && Date.now() < deadline ? info : null; } catch (error) { const { cleanup, joined } = await retireStartupAttempt(settings, launch, deadline); emitDiagnostic({ @@ -680,6 +683,18 @@ async function readReadyLaunchedDaemon( } throw error; } + if (probe.denial) { + // The host refused this client's connect to the daemon it launched, so readiness cannot be + // observed and the outcome is terminal. It is not a failed startup: the stalled and ceiling paths + // call `retireStartupAttempt`, which would signal a daemon this client cannot see, and a daemon + // that registered is healthy — this sandbox is not. + throw daemonConnectDeniedError({ + info, + denial: probe.denial, + stateDir: settings.paths.baseDir, + }); + } + return probe.reachable && Date.now() < deadline ? info : null; } function isLaunchedDaemon(info: DaemonInfo, launch: DaemonStartupLaunch): boolean { diff --git a/packages/daemon-client/src/daemon-client-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index c3446d99ce..4a308c3296 100644 --- a/packages/daemon-client/src/daemon-client-timeout.ts +++ b/packages/daemon-client/src/daemon-client-timeout.ts @@ -63,14 +63,16 @@ export async function handleRequestTimeout( // transport performed when this client's connection died is the recovery that request needed, // and sibling sessions survive. Only a daemon answering neither endpoint in the probe window is // the hung daemon a reset was designed for. - const probeAnswered = resetEligible + const liveness = resetEligible ? await ( await import('./daemon-client-liveness-probe.ts') ).answersLivenessProbe(info, { session, }) : undefined; - const unresponsive = probeAnswered === false; + // A probe the HOST refused is neither an answer nor an unresponsive verdict: this client holds no + // evidence about the daemon, so a reset-eligible timeout does not retire it. + const unresponsive = liveness !== undefined && !liveness.reachable && !liveness.denial; const mayRetire = unresponsive && retireUnresponsive; // Loaded only here: a timeout is the one place that needs it, and the CLI's eager closure must // not pay for it. @@ -93,7 +95,8 @@ export async function handleRequestTimeout( daemonPidForceKilled: resetDaemon ? daemonWasForceKilled(retirement) : undefined, daemonRetirement: retirement, daemonPreservedAfterTimeout: preserved || (!remote && !mayRetire), - daemonLivenessProbeAnswered: probeAnswered, + daemonLivenessProbeAnswered: liveness?.reachable, + daemonLivenessConnectDenied: liveness?.denial, daemonBaseUrl: info.baseUrl, }, }); diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 5f5fc9773b..ef20434ea5 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -36,12 +36,10 @@ import { import { handleRequestTimeout } from './daemon-client-timeout.ts'; import { isRemoteDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import { - LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS, - probeLoopbackPort, - readLoopbackConnectDenial, - type DaemonProbeVerdict, - type LoopbackTransport, +import type { + DaemonProbeVerdict, + LoopbackConnectDenial, + LoopbackTransport, } from './daemon-client-loopback-probe.ts'; type ResolvedDaemonTransport = LoopbackTransport; @@ -151,6 +149,7 @@ export function createRequestGuard(params: { }; } +const LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS = 500; const REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS = 3000; export function isDaemonTransportUnavailableError(error: unknown): boolean { @@ -204,30 +203,44 @@ export async function probeDaemonReachability( if (first.reachable) return { reachable: Date.now() < deadline }; if (!fallback) return first; const second = await probeTransportEndpoint(info, fallback, deadline - Date.now()); - if (second.reachable) return { reachable: Date.now() < deadline }; + if (second.reachable) return answeredWithinDeadline(deadline, first.denial); // One refused leg is enough to withhold a death verdict: the client cannot read the other leg's // silence as proof while the host has shown it refuses this daemon's endpoints. return { reachable: false, denial: first.denial ?? second.denial }; } +/** + * A leg that answered after the deadline is not a reachable daemon, but a refusal the other leg + * reported is still evidence this client holds. It travels with the verdict, so a late answer + * cannot turn a refused endpoint back into a dead daemon. + */ +function answeredWithinDeadline( + deadline: number, + denial?: LoopbackConnectDenial, +): DaemonProbeVerdict { + return Date.now() < deadline ? { reachable: true } : { reachable: false, denial }; +} + async function probeTransportEndpoint( info: DaemonInfo, transport: ResolvedDaemonTransport, timeoutMs: number, ): Promise { - if (transport === 'http') return await probeHttpEndpoint(info, timeoutMs); - return await probeLoopbackPort(info.port, 'socket', timeoutMs); -} - -async function probeHttpEndpoint(info: DaemonInfo, timeoutMs: number): Promise { - // One health request answers reachability and, through the errno it records, whether the host - // refused the connect at all. A second connect would double the probe's cost. - const health = await probeDaemonHealth(info, timeoutMs); - if (health.reachable) return { reachable: true }; - const denial = info.httpPort - ? readLoopbackConnectDenial(health.connectErrno, 'http', info.httpPort) - : undefined; - return denial ? { reachable: false, denial } : { reachable: false }; + // Loaded here, never at module scope: no client entry surface pays for a verdict it only reads on a + // probe (`scripts/__tests__/eager-closure-budgets.ts`). + const { probeHttpEndpoint, probeLoopbackPort } = + await import('./daemon-client-loopback-probe.ts'); + if (transport !== 'http') return await probeLoopbackPort(info.port, 'socket', timeoutMs); + const endpoint = daemonHealthEndpoint(info); + if (!endpoint) return { reachable: false }; + return await probeHttpEndpoint({ + endpoint, + headers: info.baseUrl ? buildDaemonHttpAuthHeaders(info.token) : {}, + timeoutMs: Math.min( + info.baseUrl ? REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS : LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS, + timeoutMs, + ), + }); } export async function readRemoteDaemonHealth( @@ -261,32 +274,11 @@ function daemonHttpEndpoint(info: DaemonInfo, route: 'health' | 'rpc'): string | : null; } -/** - * A health probe's answer plus the errno of a connect the HOST refused, which is how a sandbox around - * this client shows up. An answer from the daemon, a refused request and a timeout all leave it - * absent. Only the reachability verdict reads it; the health shape clients and caches hold does not - * carry it. - */ -type DaemonHealthProbe = RemoteDaemonHealth & Readonly<{ connectErrno?: string }>; - async function readDaemonHttpHealth( info: DaemonInfo, probeTimeoutMs?: number, callerSignal?: AbortSignal, ): Promise { - const { connectErrno: _deny, ...health } = await probeDaemonHealth( - info, - probeTimeoutMs, - callerSignal, - ); - return health; -} - -async function probeDaemonHealth( - info: DaemonInfo, - probeTimeoutMs?: number, - callerSignal?: AbortSignal, -): Promise { const endpoint = daemonHealthEndpoint(info); if (!endpoint) return { reachable: false }; const url = new URL(endpoint); @@ -341,8 +333,8 @@ async function probeDaemonHealth( req.destroy(); resolve({ reachable: false, timedOut: true }); }); - req.on('error', (error: NodeJS.ErrnoException) => { - resolve({ ...unreachable(), connectErrno: error.code }); + req.on('error', () => { + resolve(unreachable()); }); req.end(); }); diff --git a/packages/daemon-client/src/daemon-launch-spec.ts b/packages/daemon-client/src/daemon-launch-spec.ts index 8586c2f9d5..8ce95e1add 100644 --- a/packages/daemon-client/src/daemon-launch-spec.ts +++ b/packages/daemon-client/src/daemon-launch-spec.ts @@ -141,15 +141,15 @@ export async function resolveDaemonTakeover( ): Promise { const clientVersion = readVersion(); if (info.version !== clientVersion) { - // Probed exactly where it was probed before: only a newer daemon's answer decides a refusal on - // its own. Where the probe is made, a connect the host refused answers `connectDenied` rather - // than a death verdict, so a newer daemon is never retired by a client that cannot see it. - if (info.version && isNewerVersion(info.version, clientVersion)) { - const advertised = await reachability.onAnyAdvertisedTransport(); - if (advertised.denial) return { kind: 'connectDenied', denial: advertised.denial }; - if (advertised.reachable) - return { kind: 'refuseNewer', daemonVersion: info.version, clientVersion }; - } + // A replacement retires a live process, so no branch of the ladder answers it on the record + // alone: the advertised endpoints are probed first, and a connect the HOST refused answers + // `connectDenied` instead of a death verdict. This is where the probe used to happen only for a + // NEWER daemon; an older or mismatched one was replaced unprobed, which let a client whose + // sandbox refuses the connect kill a daemon it never saw. + const advertised = await reachability.onAnyAdvertisedTransport(); + if (advertised.denial) return { kind: 'connectDenied', denial: advertised.denial }; + if (info.version && isNewerVersion(info.version, clientVersion) && advertised.reachable) + return { kind: 'refuseNewer', daemonVersion: info.version, clientVersion }; return { kind: 'replace', reason: `version mismatch (client v${clientVersion})`, @@ -158,7 +158,11 @@ export async function resolveDaemonTakeover( } const localIdentity = await resolveLocalDaemonCodeIdentity(); const codeMismatch = resolveCodeIdentityMismatch(localIdentity, info); - if (codeMismatch) return { kind: 'replace', reason: codeMismatch, cause: 'code' }; + if (codeMismatch) { + const advertised = await reachability.onAnyAdvertisedTransport(); + if (advertised.denial) return { kind: 'connectDenied', denial: advertised.denial }; + return { kind: 'replace', reason: codeMismatch, cause: 'code' }; + } const probe = await reachability.onClientTransport(); if (probe.denial) return { kind: 'connectDenied', denial: probe.denial }; if (!probe.reachable) return { kind: 'replace', reason: 'unreachable', cause: 'unreachable' }; diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 57e1a445d2..099210df7a 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-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. A sandbox around the client can also refuse the client's own connect to a daemon that runs outside it; that is not a startup outcome and needs no daemon launch. The command then fails with details.reason daemon-connect-denied, naming the errno, transport, port and daemon it could not reach. That daemon keeps running: the client replaced, retired and signaled nothing. Rerun agent-device with host access. + 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. A sandbox around the client can also refuse the client's own connect to a daemon that runs outside it, with EPERM or EACCES; that is not a startup outcome and needs no daemon launch. The command then fails with details.reason daemon-connect-denied, naming that errno, the transport, port and daemon it could not reach. A connect refused with another errno is ordinary unreachability and is reported as such. That daemon keeps running: the client replaced, retired and signaled nothing. Rerun agent-device with host access. 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 6e8db65e9a..f90673ebbd 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-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. A sandbox around the client can also refuse the client's own connect to a daemon that runs outside it, which is not a startup outcome: that fails with `details.reason: daemon-connect-denied`, naming the errno, transport, port and daemon it could not reach. That daemon keeps running and nothing is replaced, retired, or signaled; rerun agent-device with host access. | +| 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. A sandbox around the client can also refuse the client's own connect to a daemon that runs outside it with `EPERM` or `EACCES`, which is not a startup outcome: that fails with `details.reason: daemon-connect-denied`, naming that errno, the transport, port and daemon it could not reach. A connect refused with another errno is ordinary unreachability and is reported as such. That daemon keeps running and nothing is replaced, retired, or signaled; rerun agent-device with host access. | | 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 bec2695bc5..bfdd48d2ba 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -582,7 +582,7 @@ These reasons can come from more than one command. | `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, 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. | -| `daemon-connect-denied` | The host refused this client's loopback connect to the registered daemon, as a sandbox around it does; `details.daemon` names the daemon left alone. | +| `daemon-connect-denied` | The host refused this client's loopback connect to the registered daemon with `EPERM` or `EACCES`, as a sandbox around it does; `details.daemon` names the daemon left alone. A connect that failed with another errno is ordinary unreachability. | | `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. | From 3beb513602e00f635dac618c8a830463cb0e57c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 13:25:01 +0100 Subject: [PATCH 3/8] fix(daemon-client): ask permission, not liveness, before a replacement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The guard every replacement now takes out was run through the reachability probe, and that probe is built for a different question: it sends a health request and retries with waits, so a mismatched daemon cost a takeover one request and one extra wait step it had never paid. What a retirement has to check is narrower — whether the HOST lets this client reach the registered ports at all — so it asks that directly: `readAdvertisedConnectDenial` makes one bare loopback connect per advertised port, at once, with no health request and no retries. A sandbox that blocks local ports refuses the connect itself, which is the evidence the guard needs; a busy daemon's silence stays no evidence at all. A reset-eligible timeout whose liveness probe the host refused also stops reporting a timeout. That hint promised a session the caller could not have reached, when the client's real finding is that the host refused the connect: the refusal now answers with `daemon-connect-denied` and the shared host-access hint. `handleRequestTimeout` is split at its own owners — the probe, the recovery decision, the diagnostic, and the failure — so the decision reads as one step per function and the file is back under the complexity threshold. The reason table now carries the EPERM/EACCES wording where the generated reasons page reads it, which is what made `website/docs/docs/error-reasons.md` stale. --- ...ient-loopback-probe-connect-denied.test.ts | 52 +++++- .../daemon-client-timeout-route.test.ts | 43 +++++ .../src/__tests__/daemon-launch-spec.test.ts | 36 +++- .../src/daemon-client-loopback-probe.ts | 35 ++++ .../src/daemon-client-startup.ts | 20 ++- .../src/daemon-client-timeout.ts | 167 +++++++++++++----- .../daemon-client/src/daemon-launch-spec.ts | 32 ++-- .../src/daemon-lifecycle-errors.ts | 5 +- 8 files changed, 333 insertions(+), 57 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts index 1b431ce9cc..e4a8211a7e 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts @@ -20,7 +20,7 @@ import { skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; import { sendToDaemon } from '../index.ts'; -import { probeLoopbackPort } from '../daemon-client-loopback-probe.ts'; +import { probeLoopbackPort, readAdvertisedConnectDenial } from '../daemon-client-loopback-probe.ts'; import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; // A loopback connect the HOST refused (EPERM under a macOS Seatbelt sandbox around this client) is @@ -266,3 +266,53 @@ test.for(['EPERM', 'EACCES', 'ECONNREFUSED', 'ECONNRESET'] as const)( } }, ); + +// The guard a replacement takes out is a permission question, so it must not ask anything a daemon +// could answer: no health request, and no wait step. These assertions hold it to that. +test('the pre-replacement guard asks one bare connect per advertised port and nothing else', async () => { + const connected: Array<{ port: number }> = []; + const refused = Object.assign(new EventEmitter(), { + destroy: () => {}, + setTimeout: () => refused, + }); + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((( + options: { port: number }, + _listener?: () => void, + ) => { + // Records the port only: one entry per advertised endpoint is the whole claim, and the socket port + // is asked first, so the refusal this returns names that endpoint. + connected.push({ port: options.port }); + setImmediate(() => + refused.emit('error', Object.assign(new Error('EACCES'), { code: 'EACCES' })), + ); + return refused; + }) as unknown as typeof net.createConnection); + try { + const denial = await readAdvertisedConnectDenial({ + port: 65_540, + httpPort: 65_541, + remote: false, + }); + + assert.deepEqual(denial, { errno: 'EACCES', transport: 'socket', port: 65_540 }); + assert.deepEqual(connected, [{ port: 65_540 }, { port: 65_541 }]); + } finally { + createConnection.mockRestore(); + } +}); + +// A remote registration is out of scope: a refusal to reach a remote host is not the loopback denial +// this verdict names, and connecting to it would send a request the guard has no business making. +test('the pre-replacement guard asks nothing of a remote registration', async () => { + const createConnection = vi.spyOn(net, 'createConnection').mockImplementation(() => { + throw new Error('a remote registration is not probed'); + }); + try { + assert.equal( + await readAdvertisedConnectDenial({ port: 65_540, httpPort: 65_541, remote: true }), + undefined, + ); + } finally { + createConnection.mockRestore(); + } +}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts b/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts index 320ac83e7a..6179d9c6e0 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts @@ -514,6 +514,49 @@ test('request-timeout route: an attach client leaves a daemon that answers no pr } }); +// A sandboxed client whose RPC times out AND whose probe connect the host refused holds no evidence +// about the daemon, so the timeout's own hint must not claim its session survived. The refusal is the +// finding worth reporting: it replaces the timeout's reason and carries the shared host-access hint. +// EPERM and EACCES cannot be produced by a stand-in server, so the probe seam answers with the refusal +// this client's host really gave it. +test('a timeout whose liveness probe the host refused reports the refusal, not a kept-alive session', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const daemon = await startStandIn('socket', 'refuse'); + const paths = dummyStatePaths(); + const info = await registeredOwner(paths, daemon.port, 'socket'); + const liveness = await import('../daemon-client-liveness-probe.ts'); + vi.spyOn(liveness, 'answersLivenessProbe').mockResolvedValue({ + reachable: false, + denial: { errno: 'EPERM', transport: 'socket', port: daemon.port }, + }); + try { + const error = await expectRouteError( + sendRequest( + info, + buildRequest(RESET_POLICY_COMMAND, undefined), + 'socket', + paths, + TIMEOUT_MS, + { host: createTestHostEnvironment() }, + ), + /sandbox around this command/, + ); + + assert.equal(error.details?.reason, 'daemon-connect-denied'); + assert.equal(error.details?.errno, 'EPERM'); + assert.equal(error.details?.port, daemon.port); + assert.ok( + !/kept alive|survive/i.test(String(error.details?.hint)), + 'the hint claims no session this client could not have reached', + ); + assert.equal(isProcessAlive(info.pid), true, 'a refused probe authorizes no signal'); + assert.ok(fs.existsSync(paths.infoPath), 'the registration is left in place'); + assert.ok(fs.existsSync(paths.lockPath), 'the lock is left in place'); + } finally { + await closeLoopbackServer(daemon.server); + } +}); + test('request-timeout route: the reset acts on the resolved state paths, not the request flags', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; // Path resolution happens upstream of `sendRequest`, which receives the state paths the caller diff --git a/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts b/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts index 351ad42cb5..9d61383dcb 100644 --- a/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts @@ -132,12 +132,34 @@ test('a version mismatch is decided without asking the client transport', async return silent; }, onAnyAdvertisedTransport: async () => silent, + refusedByHost: async () => undefined, }); assert.equal(decision.kind, 'replace'); assert.equal(asked, false); }); +// The guard a replacement asks for is a PERMISSION question, not a liveness one: it must be a bare +// connect, so it costs no health request, no retry and no wait step. Reaching for the reachability +// probe here would put a `/health` request and the probe's retries on every mismatched-daemon takeover. +test('the guard before a replacement asks only whether the host refuses the connect', async () => { + let probedLiveness = 0; + const decision = await resolveDaemonTakeover(runningDaemon({ version: '0.0.1' }), { + onClientTransport: async () => { + probedLiveness += 1; + return silent; + }, + onAnyAdvertisedTransport: async () => { + probedLiveness += 1; + return silent; + }, + refusedByHost: async () => undefined, + }); + + assert.equal(decision.kind, 'replace'); + assert.equal(probedLiveness, 0, 'a version mismatch is replaced without a reachability probe'); +}); + test('a newer daemon alive only on a transport the client does not prefer is still refused', async () => { assert.deepEqual( await resolveDaemonTakeover(runningDaemon({ version: '999.0.0' }), onlyOnAnotherTransport()), @@ -216,15 +238,24 @@ function reachable(): DaemonReachability { return { onClientTransport: async () => answered, onAnyAdvertisedTransport: async () => answered, + refusedByHost: async () => undefined, }; } function unreachable(): DaemonReachability { - return { onClientTransport: async () => silent, onAnyAdvertisedTransport: async () => silent }; + return { + onClientTransport: async () => silent, + onAnyAdvertisedTransport: async () => silent, + refusedByHost: async () => undefined, + }; } function onlyOnAnotherTransport(): DaemonReachability { - return { onClientTransport: async () => silent, onAnyAdvertisedTransport: async () => answered }; + return { + onClientTransport: async () => silent, + onAnyAdvertisedTransport: async () => answered, + refusedByHost: async () => undefined, + }; } /** The host refused every endpoint this client tried, as its sandbox does. */ @@ -232,6 +263,7 @@ function denied(): DaemonReachability { return { onClientTransport: async () => ({ reachable: false, denial: DENIAL }), onAnyAdvertisedTransport: async () => ({ reachable: false, denial: DENIAL }), + refusedByHost: async () => DENIAL, }; } diff --git a/packages/daemon-client/src/daemon-client-loopback-probe.ts b/packages/daemon-client/src/daemon-client-loopback-probe.ts index b80b6672a7..8c320f07e1 100644 --- a/packages/daemon-client/src/daemon-client-loopback-probe.ts +++ b/packages/daemon-client/src/daemon-client-loopback-probe.ts @@ -90,6 +90,41 @@ export function probeLoopbackPort( }); } +/** + * Whether the HOST refuses this client's connects to the endpoints one registration advertises. + * + * The question a retirement asks, and it is narrower than reachability: whether this client is allowed + * to reach that endpoint at all, not whether the daemon answers there. So each advertised port gets ONE + * bare loopback connect — no health request, no retries, no waits. A sandbox that blocks local ports + * refuses the connect itself (EPERM or EACCES), which is what this answers; a daemon that is merely busy + * or hung answers with silence, and silence is not evidence about the host. + * + * A remote registration is answered `undefined` without a connect: a refusal to reach a remote host is + * not the loopback denial this verdict names. + */ +export async function readAdvertisedConnectDenial( + advertised: Readonly<{ + port?: number; + httpPort?: number; + remote: boolean; + }>, +): Promise { + if (advertised.remote) return undefined; + const endpoints: ReadonlyArray = [ + [advertised.port, 'socket'], + [advertised.httpPort, 'http'], + ]; + // Both connects run at once: a guard a takeover waits on costs ONE connect window, not one per + // advertised port, whatever the host does to a connect it neither allows nor answers. + const verdicts = await Promise.all( + endpoints.map(([port, transport]) => (port ? probeLoopbackPort(port, transport) : undefined)), + ); + // The first refusal in endpoint order is the whole answer: this client cannot read the other + // endpoint's silence as permission to retire what it cannot see. + for (const verdict of verdicts) if (verdict?.denial) return verdict.denial; + return undefined; +} + /** * One health request to one advertised endpoint, as a reachability verdict. * diff --git a/packages/daemon-client/src/daemon-client-startup.ts b/packages/daemon-client/src/daemon-client-startup.ts index 32e93e0937..98c40deb23 100644 --- a/packages/daemon-client/src/daemon-client-startup.ts +++ b/packages/daemon-client/src/daemon-client-startup.ts @@ -41,7 +41,7 @@ import { isDaemonTransportUnavailableError, probeDaemonReachability, } from './daemon-client-transport.ts'; -import type { DaemonProbeVerdict } from './daemon-client-loopback-probe.ts'; +import type { DaemonProbeVerdict, LoopbackConnectDenial } from './daemon-client-loopback-probe.ts'; import { DAEMON_LOOPBACK_DENIED_HINT, DAEMON_UNAVAILABLE_REASONS, @@ -122,10 +122,28 @@ export async function observeLocalDaemon( const decision = await resolveDaemonTakeover(existing, { onClientTransport: () => probeReusableDaemon(existing, settings.transportPreference, deadline), onAnyAdvertisedTransport: () => probeReusableDaemon(existing, 'auto', deadline), + refusedByHost: () => readRefusedAdvertisedConnect(existing), }); return { info: existing, decision: await refineReplacement(existing, decision, options) }; } +/** + * Whether the host refuses this client's connects to the registered daemon's advertised ports — the + * guard a retirement takes out before it acts. One bare connect per advertised port, so it adds no + * health request and no wait step to a takeover. Loaded here, never at module scope: the CLI's eager + * closure must not pay for a verdict only a probe reads. + */ +async function readRefusedAdvertisedConnect( + info: DaemonInfo, +): Promise { + const { readAdvertisedConnectDenial } = await import('./daemon-client-loopback-probe.ts'); + return await readAdvertisedConnectDenial({ + port: info.port, + httpPort: info.httpPort, + remote: Boolean(info.baseUrl), + }); +} + async function refineReplacement( info: DaemonInfo, decision: DaemonTakeoverDecision, diff --git a/packages/daemon-client/src/daemon-client-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index 4a308c3296..faaf1240ff 100644 --- a/packages/daemon-client/src/daemon-client-timeout.ts +++ b/packages/daemon-client/src/daemon-client-timeout.ts @@ -7,6 +7,7 @@ import { resolveCommandTimeoutPolicy } from '@agent-device/command-registry/regi import type { DaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import type { PlatformSelector } from '@agent-device/kernel/device'; import { observedDaemonIdentityOf, type DaemonInfo } from './daemon-client-metadata.ts'; +import type { DaemonProbeVerdict } from './daemon-client-loopback-probe.ts'; // Recovery for a timed-out request is scoped to that request or to nothing. The daemon owns // request-scoped recovery (#3177): destroying the timed-out connection cancels exactly that @@ -41,46 +42,86 @@ export async function handleRequestTimeout( requestSent: boolean; }>, ): Promise { - const { - info, - statePaths, - remote, - retireUnresponsive, - timeoutMs, - requestId, - command, - platform, - session, - action, - requestSent, - } = params; + const { info, statePaths, remote, retireUnresponsive, timeoutMs, requestId, command, session } = + params; // The command's declared policy (`timeoutPolicy.onTimeout`, ADR 0008) decides whether a local // timed-out request is RESET-ELIGIBLE; the liveness probe decides whether the eligibility runs. // A remote client cannot reach the host's process table or the daemon's state dir, so a remote // timeout stays purely declarative here. const resetEligible = !remote && shouldResetDaemonAfterRequestTimeout(command); - // A daemon that answers the probe is busy or slow, not gone: the request-scoped cancel its - // transport performed when this client's connection died is the recovery that request needed, - // and sibling sessions survive. Only a daemon answering neither endpoint in the probe window is - // the hung daemon a reset was designed for. - const liveness = resetEligible - ? await ( - await import('./daemon-client-liveness-probe.ts') - ).answersLivenessProbe(info, { - session, - }) - : undefined; - // A probe the HOST refused is neither an answer nor an unresponsive verdict: this client holds no - // evidence about the daemon, so a reset-eligible timeout does not retire it. + const liveness = resetEligible ? await probeDaemonLiveness(info, session) : undefined; + const recovery = await recoverFromTimeout({ info, statePaths, liveness, retireUnresponsive }); + emitTimeoutDiagnostic({ timeoutMs, requestId, command, remote, info, liveness, recovery }); + return await timeoutFailure({ params, statePaths, liveness, recovery }); +} + +/** + * Asks the registered daemon whether it is alive, over the endpoints a reset would have retired it + * from. Loaded here and not at the module's top: a timeout is the only path that asks, and the CLI's + * eager closure must not pay for the probe. + */ +async function probeDaemonLiveness( + info: DaemonInfo, + session: string | undefined, +): Promise { + const { answersLivenessProbe } = await import('./daemon-client-liveness-probe.ts'); + return await answersLivenessProbe(info, { session }); +} + +/** What one timeout's liveness verdict authorized this caller to do about the daemon. */ +type TimeoutRecovery = Readonly<{ + /** Set when the daemon is unresponsive AND this caller may retire it. */ + mayRetire: boolean; + /** Set when the daemon answered nothing and this caller must be told to stop it by hand instead. */ + stopCommand: string | undefined; + /** The teardown this caller performed, when it performed one. */ + retirement: DaemonRetirementResult | undefined; +}>; + +/** + * A daemon that answers the probe is busy or slow, not gone: the request-scoped cancel its transport + * performed when this client's connection died is the recovery that request needed, and sibling + * sessions survive. Only a daemon answering neither endpoint in the probe window is the hung daemon a + * reset was designed for, and only a caller that owns the daemon's lifecycle may perform it. + * + * A probe the HOST refused is neither an answer nor an unresponsive verdict: this client holds no + * evidence about the daemon, so a reset-eligible timeout does not retire it. + */ +async function recoverFromTimeout( + params: Readonly<{ + info: DaemonInfo; + statePaths: DaemonPaths; + /** Absent when the command's policy declares no reset, or the client is remote. */ + liveness: DaemonProbeVerdict | undefined; + retireUnresponsive: boolean; + }>, +): Promise { + const { info, statePaths, liveness, retireUnresponsive } = params; const unresponsive = liveness !== undefined && !liveness.reachable && !liveness.denial; const mayRetire = unresponsive && retireUnresponsive; - // Loaded only here: a timeout is the one place that needs it, and the CLI's eager closure must - // not pay for it. + // Loaded only on the branch that names it: the same eager-closure rule as the probe above. const stopCommand = unresponsive && !retireUnresponsive ? (await import('./daemon-lifecycle-errors.ts')).daemonStopCommand(statePaths.baseDir) : undefined; const retirement = mayRetire ? await forceRetireDaemon(info, statePaths) : undefined; + return { mayRetire, stopCommand, retirement }; +} + +/** One diagnostic for one timed-out request: what was asked, what was found, what was done. */ +function emitTimeoutDiagnostic( + params: Readonly<{ + timeoutMs: number; + requestId: string | undefined; + command: string | undefined; + remote: boolean; + info: DaemonInfo; + liveness: DaemonProbeVerdict | undefined; + recovery: TimeoutRecovery; + }>, +): void { + const { timeoutMs, requestId, command, remote, info, liveness, recovery } = params; + const { retirement } = recovery; const resetDaemon = retirement?.status === 'retired'; const preserved = retirement?.status === 'retained' && retirement.termination?.status !== 'exited'; @@ -94,30 +135,74 @@ export async function handleRequestTimeout( daemonPidReset: resetDaemon ? info.pid : undefined, daemonPidForceKilled: resetDaemon ? daemonWasForceKilled(retirement) : undefined, daemonRetirement: retirement, - daemonPreservedAfterTimeout: preserved || (!remote && !mayRetire), + daemonPreservedAfterTimeout: preserved || (!remote && !recovery.mayRetire), daemonLivenessProbeAnswered: liveness?.reachable, daemonLivenessConnectDenied: liveness?.denial, daemonBaseUrl: info.baseUrl, }, }); +} + +/** + * The failure a timed-out request answers with. + * + * A probe the HOST refused answers `daemon-connect-denied` and not a timeout: this client learned + * nothing about the daemon, so the timeout's own hints would describe a session the caller cannot + * reach rather than the sandbox that refused the connect. The daemon is left running either way. + */ +async function timeoutFailure( + params: Readonly<{ + params: Parameters[0]; + statePaths: DaemonPaths; + liveness: DaemonProbeVerdict | undefined; + recovery: TimeoutRecovery; + }>, +): Promise { + const { params: request, statePaths, liveness, recovery } = params; + const { timeoutMs, requestId, requestSent } = request; + const { retirement } = recovery; + if (liveness?.denial) { + const { daemonConnectDeniedError } = await import('./daemon-lifecycle-errors.ts'); + return daemonConnectDeniedError({ + info: request.info, + denial: liveness.denial, + stateDir: statePaths.baseDir, + }); + } return new AppError('COMMAND_FAILED', 'Daemon request timed out', { timeoutMs, requestId, reason: DAEMON_TRANSPORT_REASONS.timeout.reason, daemonRequestSent: requestSent, ...(retirement ? { retirement, stateDir: statePaths.baseDir } : {}), - hint: - retirement?.status === 'retained' - ? `The daemon could not be safely retired. State was retained at ${statePaths.baseDir}. ${retirement.error?.hint ?? 'Read the request log and daemon.log in that directory before you retry.'}` - : resolveRequestTimeoutHint({ - remote, - resetDaemon: resetDaemon, - stopCommand, - command, - applePlatformDeclared: isAffirmativelyApplePlatform(platform), - session, - action, - }), + hint: resolveTimeoutHint({ request, recovery, stateDir: statePaths.baseDir }), + }); +} + +/** + * Either the notice that a teardown kept the daemon's state on disk, or the recovery hint for this + * request. Split from the error above so the hint's own branches stay readable. + */ +function resolveTimeoutHint( + params: Readonly<{ + request: Parameters[0]; + recovery: TimeoutRecovery; + stateDir: string; + }>, +): string { + const { request, recovery, stateDir } = params; + const { retirement } = recovery; + if (retirement?.status === 'retained') { + return `The daemon could not be safely retired. State was retained at ${stateDir}. ${retirement.error?.hint ?? 'Read the request log and daemon.log in that directory before you retry.'}`; + } + return resolveRequestTimeoutHint({ + remote: request.remote, + resetDaemon: retirement?.status === 'retired', + stopCommand: recovery.stopCommand, + command: request.command, + applePlatformDeclared: isAffirmativelyApplePlatform(request.platform), + session: request.session, + action: request.action, }); } diff --git a/packages/daemon-client/src/daemon-launch-spec.ts b/packages/daemon-client/src/daemon-launch-spec.ts index 8ce95e1add..43ae172dc9 100644 --- a/packages/daemon-client/src/daemon-launch-spec.ts +++ b/packages/daemon-client/src/daemon-launch-spec.ts @@ -13,7 +13,7 @@ import { computeDaemonCodeSignature, resolveDaemonCodeOrigin, } from '@agent-device/host-kit/code-signature'; -import type { DaemonProbeVerdict } from './daemon-client-loopback-probe.ts'; +import type { DaemonProbeVerdict, LoopbackConnectDenial } from './daemon-client-loopback-probe.ts'; import type { DaemonInfo, DaemonTakeoverDecision } from './daemon-client-metadata.ts'; type DaemonLaunchSpec = { @@ -120,6 +120,13 @@ export type DaemonReachability = { /** Asked last, only once version and code identity leave the decision to it. */ onClientTransport: () => Promise; onAnyAdvertisedTransport: () => Promise; + /** + * Asked before any answer that RETIRES the daemon: whether the host refuses this client's connects + * to its advertised ports. Cheaper than a reachability probe by design — one bare connect per + * advertised port, no health request, no retries and no waits — because the question is about this + * client's permission to reach the endpoint, not about whether the daemon answers there. + */ + refusedByHost: () => Promise; }; /** @@ -142,14 +149,19 @@ export async function resolveDaemonTakeover( const clientVersion = readVersion(); if (info.version !== clientVersion) { // A replacement retires a live process, so no branch of the ladder answers it on the record - // alone: the advertised endpoints are probed first, and a connect the HOST refused answers - // `connectDenied` instead of a death verdict. This is where the probe used to happen only for a - // NEWER daemon; an older or mismatched one was replaced unprobed, which let a client whose - // sandbox refuses the connect kill a daemon it never saw. - const advertised = await reachability.onAnyAdvertisedTransport(); - if (advertised.denial) return { kind: 'connectDenied', denial: advertised.denial }; - if (info.version && isNewerVersion(info.version, clientVersion) && advertised.reachable) + // alone: whether the host even lets this client reach the daemon's ports is asked first, and a + // refusal answers `connectDenied` instead of a death verdict. This is where the question used to + // be asked only for a NEWER daemon; an older or mismatched one was replaced unprobed, which let a + // client whose sandbox refuses the connect kill a daemon it never saw. + const refusal = await reachability.refusedByHost(); + if (refusal) return { kind: 'connectDenied', denial: refusal }; + if ( + info.version && + isNewerVersion(info.version, clientVersion) && + (await reachability.onAnyAdvertisedTransport()).reachable + ) { return { kind: 'refuseNewer', daemonVersion: info.version, clientVersion }; + } return { kind: 'replace', reason: `version mismatch (client v${clientVersion})`, @@ -159,8 +171,8 @@ export async function resolveDaemonTakeover( const localIdentity = await resolveLocalDaemonCodeIdentity(); const codeMismatch = resolveCodeIdentityMismatch(localIdentity, info); if (codeMismatch) { - const advertised = await reachability.onAnyAdvertisedTransport(); - if (advertised.denial) return { kind: 'connectDenied', denial: advertised.denial }; + const refusal = await reachability.refusedByHost(); + if (refusal) return { kind: 'connectDenied', denial: refusal }; return { kind: 'replace', reason: codeMismatch, cause: 'code' }; } const probe = await reachability.onClientTransport(); diff --git a/packages/daemon-client/src/daemon-lifecycle-errors.ts b/packages/daemon-client/src/daemon-lifecycle-errors.ts index 3499fe6757..9434d78c2d 100644 --- a/packages/daemon-client/src/daemon-lifecycle-errors.ts +++ b/packages/daemon-client/src/daemon-lifecycle-errors.ts @@ -52,8 +52,9 @@ export const DAEMON_UNAVAILABLE_REASONS = { // 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 host refused this client's loopback connect to the registered daemon, as a sandbox around it - // does; `details.daemon` names the daemon left alone. + // The host refused this client's loopback connect to the registered daemon with `EPERM` or `EACCES`, + // as a sandbox around it does; `details.daemon` names the daemon left alone. A connect that failed + // with another errno is ordinary unreachability. connectDenied: { reason: 'daemon-connect-denied' }, // The daemon stayed registered and reachable but never reported the startup phase that follows. startupStalled: { reason: 'startup-stalled' }, From f4793a243ba713e21f3a6023c198c15d6db6b308 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 13:29:02 +0100 Subject: [PATCH 4/8] fix(daemon-client): settle the probe's loader through the deadline primitive The HTTP reachability leg loaded `node:http` under a hand-rolled `Promise.race` against an abort listener, which is the third such race in this package (R88 counts two at the merge-base) and the one shape the rule exists for: a timer racing work, cleared only where the author remembered. It now waits on `settleWithin`, which clears its own timer on every settle path, and the loader's spend is taken out of the request's window so the probe's budget stays absolute across both steps. --- .../src/daemon-client-loopback-probe.ts | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/packages/daemon-client/src/daemon-client-loopback-probe.ts b/packages/daemon-client/src/daemon-client-loopback-probe.ts index 8c320f07e1..b72d113d41 100644 --- a/packages/daemon-client/src/daemon-client-loopback-probe.ts +++ b/packages/daemon-client/src/daemon-client-loopback-probe.ts @@ -1,4 +1,5 @@ import net from 'node:net'; +import { settleWithin } from '@agent-device/host-kit/settle-within'; import { loadNodeHttpRequester } from '@agent-device/host-kit/transport'; // One reachability probe of one daemon endpoint, and the verdict it answers with. The transport owns @@ -132,7 +133,9 @@ export async function readAdvertisedConnectDenial( * 19 the global agent keeps sockets alive, so a pooled request would ride an idle socket from an * earlier command rather than proving that a connect to this daemon is allowed NOW — which is the only * thing that can tell a refused endpoint from a silent one. The time budget is ABSOLUTE and covers - * loading the requester, so a late loader never opens a request the probe already gave up on. + * loading the requester, so a late loader never opens a request the probe already gave up on. That + * wait goes through `settleWithin`, the one deadline primitive: it clears its own timer on every settle + * path, so a probe that never asks a question leaves no timer behind. * * A response answers the probe. Only a connect the HOST refused to a LOOPBACK endpoint carries a * denial: a refusal is not an answer from the daemon, and a refusal on a remote endpoint is not the @@ -143,25 +146,23 @@ export async function probeHttpEndpoint(probe: HttpEndpointProbe): Promise((resolve) => { - timeoutSignal.addEventListener('abort', () => resolve(null), { once: true }); - }), - ]); - if (!requester || timeoutSignal.aborted || performance.now() >= deadline) - return { reachable: false }; + const deadlineAtMs = performance.now() + probe.timeoutMs; + const loaded = await settleWithin(() => loadNodeHttpRequester(url.protocol), probe.timeoutMs); + if (loaded.kind === 'deadline') return { reachable: false }; + // What the loader spent is gone from the request's window: the budget belongs to the probe, not to + // each step inside it. + const requestTimeoutMs = deadlineAtMs - performance.now(); + if (requestTimeoutMs <= 0) return { reachable: false }; + const timeoutSignal = AbortSignal.timeout(Math.ceil(requestTimeoutMs)); return await new Promise((resolve) => { - const request = requester.request( + const request = loaded.value.request( { protocol: url.protocol, host: url.hostname, port: url.port, path: url.pathname + url.search, method: 'GET', - timeout: probe.timeoutMs, + timeout: requestTimeoutMs, agent: false, signal: timeoutSignal, headers: probe.headers, From fdbb7fb7a40b6f141011ec89192c55b62486f6ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 14:49:50 +0100 Subject: [PATCH 5/8] fix(daemon-client): ask permission on the unreachable leg and keep dispatch visible Three follow-ups from the ready review: - The takeover's unreachable branch now asks `refusedByHost` before it answers `replace`, so a managed client pinned to a leg the daemon does not serve no longer retires a daemon it was never allowed to reach. - A denial that replaces a timed-out request's reason carries `daemonRequestSent`, and the transport's failure classifier discloses dispatch from it, so a request written before the host refused the probe is still reported as one that may have run. - Route coverage for each route that can act on a refusal: the launch-time readiness probe, the reachability probe's late fallback leg and its pooled-socket case, the quiesce-timeout route, and the drain-escalation route. Each asserts the reason and that nothing is signaled or spawned. --- .../daemon-client-ensure-drain.test.ts | 41 +++++++++ ...n-client-ensure-explicit-lifecycle.test.ts | 35 ++++++++ ...ient-loopback-probe-connect-denied.test.ts | 52 +++++++++++ .../daemon-client-timeout-route.test.ts | 5 ++ .../__tests__/daemon-client-transport.test.ts | 90 +++++++++++++++++++ .../src/__tests__/daemon-launch-spec.test.ts | 27 ++++++ .../src/daemon-client-timeout.ts | 8 +- .../src/daemon-client-transport.ts | 8 +- .../daemon-client/src/daemon-launch-spec.ts | 11 ++- .../src/daemon-lifecycle-errors.ts | 5 +- website/docs/docs/error-reasons.md | 2 +- 11 files changed, 278 insertions(+), 6 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-ensure-drain.test.ts b/packages/daemon-client/src/__tests__/daemon-client-ensure-drain.test.ts index c99f32887f..2c1a3c86e5 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-ensure-drain.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-ensure-drain.test.ts @@ -287,6 +287,47 @@ test('a daemon still running past the deadline that answers a probe is left alon } }); +// The escalation route: a daemon still running at the drain deadline that answers no probe gets force +// retired. A connect the HOST refused is not a missed probe, so this route names the sandbox instead. +test('a drain that outlives the deadline with a probe the host refused signals nothing', async (t) => { + if (!(await withLoopback(t))) return; + const { stateDir, paths } = stateDirAndPaths(); + let childPid = 0; + const drain = installVirtualDrain(() => childPid); + const stale = await startScriptedDaemon(draining, { + afterRpc: () => { + drain.begin(undefined); + void closeLoopbackServer(stale.server); + }, + }); + const { child } = await registerDaemon(paths, { + httpPort: stale.port, + version: '0.0.0-stale', + capabilities: ['quiesce'], + }); + childPid = child.pid; + const liveness = await import('../daemon-client-liveness-probe.ts'); + vi.spyOn(liveness, 'answersLivenessProbe').mockResolvedValue({ + reachable: false, + denial: { errno: 'EPERM', transport: 'socket', port: stale.port }, + }); + + try { + await assert.rejects(ensureDaemon({ stateDir, daemonTransport: 'http' }), (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, 'daemon-connect-denied'); + assert.equal(error.details?.errno, 'EPERM'); + return true; + }); + + assert.deepEqual(drain.signals, []); + assert.equal(isProcessAlive(childPid), true); + assert.equal(spawn.mock.calls.length, 0); + } finally { + drain.end(); + } +}); + test('an embedded host that outlives the deadline and answers no probe is never signaled', async (t) => { if (!(await withLoopback(t))) return; const { stateDir, paths } = stateDirAndPaths(); diff --git a/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts b/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts index 1f0711eea3..fbcf623521 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts @@ -564,6 +564,41 @@ test('ensureDaemon retires a daemon that timed out on quiesce and answers no liv } }); +// The route that force-retires a daemon which timed out on quiesce and answered no probe. A connect +// the HOST refused is not a missed probe, so this daemon is neither retired nor spawned over. +test('ensureDaemon reports a host denial instead of retiring a daemon whose quiesce timed out', async (t) => { + if (!(await withLoopback(t))) return; + const { stateDir, paths } = stateDirAndPaths(); + const stale = await startScriptedDaemon(okResult({})); + const { child } = await registerDaemon(paths, { + httpPort: stale.port, + version: '0.0.0-stale', + capabilities: ['quiesce'], + }); + vi.spyOn(transport, 'sendRequest').mockRejectedValueOnce( + new AppError('COMMAND_FAILED', 'Daemon request timed out', { + reason: 'daemon_transport_timeout', + }), + ); + const liveness = await import('../daemon-client-liveness-probe.ts'); + vi.spyOn(liveness, 'answersLivenessProbe').mockResolvedValue({ + reachable: false, + denial: { errno: 'EPERM', transport: 'socket', port: stale.port }, + }); + + try { + const error = await failureOf(ensureDaemon({ stateDir, daemonTransport: 'http' })); + + assert.equal(error.details?.reason, 'daemon-connect-denied'); + assert.equal(error.details?.errno, 'EPERM'); + assert.match(String(error.details?.hint), /A sandbox around this command/); + assert.equal(isProcessAlive(child.pid), true, 'a refused probe authorizes no signal'); + assert.equal(spawn.mock.calls.length, 0, 'a daemon this client cannot see is not replaced'); + } finally { + await closeLoopbackServer(stale.server); + } +}); + test('ensureDaemon keeps a daemon that timed out on quiesce but still answers a probe', async (t) => { if (!(await withLoopback(t))) return; const { stateDir, paths } = stateDirAndPaths(); diff --git a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts index e4a8211a7e..6ff660e93c 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts @@ -21,6 +21,10 @@ import { } from '@agent-device/test-kit'; import { sendToDaemon } from '../index.ts'; import { probeLoopbackPort, readAdvertisedConnectDenial } from '../daemon-client-loopback-probe.ts'; +import { + finishRegisteredDaemonFixture, + planRegisteredDaemonLaunches, +} from './registered-daemon-fixture.ts'; import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; // A loopback connect the HOST refused (EPERM under a macOS Seatbelt sandbox around this client) is @@ -199,6 +203,54 @@ test.for([ }, ); +// A daemon the CLIENT launched, whose registration its own startup watch then read: the readiness +// probe is the first connect after publication. When the host refuses that connect, readiness cannot +// be judged, and the stalled and ceiling routes would signal a daemon this client cannot see. The +// launch seam starts a real registration-owning child, so the client owns this lifetime. +test('a launched daemon whose readiness connect the host refused is left running', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const stateDir = mkdtempForTestSync('agent-device-launch-denied-'); + const paths = resolveDaemonPaths(stateDir); + const server = net.createServer((socket) => socket.on('error', () => {})); + const httpPort = await listenOnLoopback(server); + mockSpawnDaemon.mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths, + fields: { + httpPort, + token: 'local-secret', + version: readVersion(), + codeOrigin: 'checkout', + codeSignature: currentDaemonCodeSignature(), + }, + }, + ]), + ); + mockProbeAnswers.push(denied(DENIED_ERRNO, 'http')); + + try { + const failure = await rejection(sendDevices(stateDir, 'http')); + + assert.equal(failure.details?.reason, 'daemon-connect-denied'); + assert.equal(failure.details?.errno, DENIED_ERRNO); + assert.equal(failure.details?.transport, 'http'); + // The client is pinned to HTTP, so the readiness probe reports that leg's advertised port. + assert.equal(failure.details?.port, httpPort); + const launched = failure.details?.daemon as { pid?: number } | undefined; + assert.ok( + launched?.pid !== undefined && isProcessAlive(launched.pid), + 'the daemon the client launched keeps running', + ); + assert.ok(fs.existsSync(paths.infoPath), 'its registration is left in place'); + } finally { + await finishRegisteredDaemonFixture(stateDir); + fs.rmSync(stateDir, { recursive: true, force: true }); + await closeLoopbackServer(server); + } +}); + // An attach client starts and replaces nothing anyway, so its only wrong answer would read as "no // daemon is running" and send the caller to start one it cannot reach either. test('an attach client told about a refusal does not report a daemon that is not running', async (t) => { diff --git a/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts b/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts index 6179d9c6e0..6862b44038 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts @@ -545,6 +545,11 @@ test('a timeout whose liveness probe the host refused reports the refusal, not a assert.equal(error.details?.reason, 'daemon-connect-denied'); assert.equal(error.details?.errno, 'EPERM'); assert.equal(error.details?.port, daemon.port); + // The refusal replaces the timeout's REASON, not its facts: this request had already been written, + // so the error still says the daemon may have run it. Without `daemonRequestSent` the disclosure + // seam would call a request that dispatched `no`, and a retrying caller would run it twice. + assert.equal(error.details?.daemonRequestSent, true); + assert.equal(error.details?.dispatched, 'unknown'); assert.ok( !/kept alive|survive/i.test(String(error.details?.hint)), 'the hint claims no session this client could not have reached', diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts index 0138e90d1a..63ca0751b9 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -77,6 +77,96 @@ test('auto health probing reserves time for a healthy fallback when HTTP hangs', } }); +// Two shapes of a reachability probe that a boolean "unreachable" would report wrongly, both of which +// a caller reads before it retires a daemon: a fallback leg that answers AFTER the deadline must not +// bury the refusal the first leg already proved, and a refusal of a fresh connect must not be answered +// around by a keep-alive socket an earlier command left in the pool. +test('a fallback leg answering past the deadline still reports the first leg as a denial', async () => { + const probe = await import('../daemon-client-loopback-probe.ts'); + const denial = { errno: 'EPERM', transport: 'socket', port: 41_234 } as const; + // A clock the two legs move on, so "late" is settled rather than raced: the socket leg is refused + // at once, the HTTP leg answers, and the answer lands after the probe's deadline. + let now = 1_000; + const clock = vi.spyOn(Date, 'now').mockImplementation(() => now); + const socketLeg = vi + .spyOn(probe, 'probeLoopbackPort') + .mockResolvedValue({ reachable: false, denial }); + const httpLeg = vi.spyOn(probe, 'probeHttpEndpoint').mockImplementation(async () => { + now += 500; + return { reachable: true }; + }); + try { + assert.deepEqual( + await probeDaemonReachability( + { token: 'secret', pid: 1, transport: 'dual', port: 41_234, httpPort: 41_235 }, + 'auto', + 100, + ), + { reachable: false, denial }, + ); + } finally { + clock.mockRestore(); + socketLeg.mockRestore(); + httpLeg.mockRestore(); + } +}); + +test('a fresh connect the host refused is not answered around by a pooled socket', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + // The pool the probe must not ride, primed the way an earlier command primes it: one keep-alive + // health request whose socket returns to the global agent. Discriminator: every NEW connect is + // refused from here on, so a verdict of `reachable` could only come from the pooled socket, and a + // denial that arrives with the daemon having seen nothing but the prime is the whole claim. + if (!(await poolPrimesUnderTestAgent())) return; + const askedUrls: string[] = []; + const server = http.createServer((req, res) => { + askedUrls.push(String(req.url)); + res.end('{}'); + }); + const port = await listenOnLoopback(server); + // Prime with the SAME module object the probe loads, or the pool holds no candidate and the test + // proves nothing. + const requester = await hostTransport.loadNodeHttpRequester('http:'); + await new Promise((resolve, reject) => { + const request = requester.request( + { host: '127.0.0.1', port, path: '/health', method: 'GET' }, + (res) => { + res.resume(); + res.on('end', resolve); + }, + ); + request.on('error', reject); + request.end(); + }); + // A host that refuses a connect answers it immediately, with no round trip: the socket ends with + // the errno and never carries a request. + const connect = vi + .spyOn(net.Socket.prototype, 'connect') + .mockImplementation(function (this: net.Socket) { + this.destroy(Object.assign(new Error('EPERM'), { code: 'EPERM' })); + return this; + }); + try { + assert.deepEqual( + await probeDaemonReachability({ token: 'secret', pid: 1, httpPort: port }, 'http'), + { + reachable: false, + denial: { errno: 'EPERM', transport: 'http', port }, + }, + ); + assert.deepEqual(askedUrls, ['/health'], 'only the prime reached the daemon'); + } finally { + connect.mockRestore(); + await closeLoopbackServer(server); + } +}); + +/** Whether this Node keeps sockets alive on the global agent, which is what makes a pool exist. */ +async function poolPrimesUnderTestAgent(): Promise { + const { globalAgent } = await import('node:http'); + return Boolean((globalAgent as { keepAlive?: boolean }).keepAlive); +} + test('the health deadline includes requester loading and forbids a late request', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; let requests = 0; diff --git a/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts b/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts index 9d61383dcb..771de7df86 100644 --- a/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-launch-spec.test.ts @@ -188,6 +188,21 @@ test('a same-version daemon the host refused to connect to is not judged unreach ); }); +// The unreachable branch retires too, so it asks the same permission question even when the client's +// own transport leg answered only silence: a managed client pinned to a leg the daemon does not serve +// would otherwise replace a daemon it was never allowed to reach. +test('a daemon unreachable on the client transport but refused by the host is not replaced', async () => { + useClientTree(false); + + assert.deepEqual( + await resolveDaemonTakeover( + runningDaemon({ codeOrigin: 'installed' }), + silentButRefusedOnTheGuard(), + ), + { kind: 'connectDenied', denial: DENIAL }, + ); +}); + // A replacement retires a live process, so no branch of the ladder may answer it on the record alone. // Before this, only a NEWER daemon was probed: an older or code-mismatched one was replaced without // ever being seen, which let a client whose sandbox refuses the connect kill a healthy daemon. @@ -258,6 +273,18 @@ function onlyOnAnotherTransport(): DaemonReachability { }; } +/** + * The client's own transport answers nothing and the guard's connects are refused, while the ports + * themselves answer nothing: what a sandbox that silences one leg and refuses the other produces. + */ +function silentButRefusedOnTheGuard(): DaemonReachability { + return { + onClientTransport: async () => silent, + onAnyAdvertisedTransport: async () => silent, + refusedByHost: async () => DENIAL, + }; +} + /** The host refused every endpoint this client tried, as its sandbox does. */ function denied(): DaemonReachability { return { diff --git a/packages/daemon-client/src/daemon-client-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index faaf1240ff..14ccf4563f 100644 --- a/packages/daemon-client/src/daemon-client-timeout.ts +++ b/packages/daemon-client/src/daemon-client-timeout.ts @@ -163,11 +163,17 @@ async function timeoutFailure( const { retirement } = recovery; if (liveness?.denial) { const { daemonConnectDeniedError } = await import('./daemon-lifecycle-errors.ts'); - return daemonConnectDeniedError({ + const denied = daemonConnectDeniedError({ info: request.info, denial: liveness.denial, stateDir: statePaths.baseDir, }); + // A refusal found AFTER the request left this process replaces the timeout's REASON, not the + // timeout's facts: the daemon may still have run this request, and a caller that retries on a + // failure that dispatched nothing would run it twice. `daemonRequestSent` travels with the denial + // so the send path can disclose dispatch for it, exactly as it does for a timeout. + if (requestSent) denied.details = { ...denied.details, daemonRequestSent: true }; + return denied; } return new AppError('COMMAND_FAILED', 'Daemon request timed out', { timeoutMs, diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index ef20434ea5..1d1483e725 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -449,6 +449,10 @@ async function recoverFromTimeout( * One of the transport's own failures, with whether it happened after the request left this * process (the daemon may have run it). A lost connection or a timeout records * `daemonRequestSent`; a reply that could not be read or parsed was always sent. + * + * A `daemon-connect-denied` is usually a pre-send finding and is left alone. Only the one a timeout + * produced carries `daemonRequestSent`, and that one has to reach the disclosure seam too: the request + * was written before the host refused the probe, so the caller must still be told it may have run. */ function classifyTransportFailure( error: unknown, @@ -462,7 +466,9 @@ function classifyTransportFailure( case DAEMON_TRANSPORT_REASONS.replyInvalid.reason: return { failure: error, sent: true }; default: - return undefined; + // A refusal this module did not produce, from the timeout route, states for itself that the + // request left this process. It gets the same disclosure: the daemon may have run it. + return error.details?.daemonRequestSent === true ? { failure: error, sent: true } : undefined; } } diff --git a/packages/daemon-client/src/daemon-launch-spec.ts b/packages/daemon-client/src/daemon-launch-spec.ts index 43ae172dc9..d35b24def5 100644 --- a/packages/daemon-client/src/daemon-launch-spec.ts +++ b/packages/daemon-client/src/daemon-launch-spec.ts @@ -177,7 +177,16 @@ export async function resolveDaemonTakeover( } const probe = await reachability.onClientTransport(); if (probe.denial) return { kind: 'connectDenied', denial: probe.denial }; - if (!probe.reachable) return { kind: 'replace', reason: 'unreachable', cause: 'unreachable' }; + if (!probe.reachable) { + // A managed client retires a daemon it cannot reach on its own transport, so the permission + // question is asked here too, whatever the client's transport preference happened to try: a + // preference for an endpoint the daemon does not serve, or a sandbox that answers this leg with + // silence and would refuse the other outright, both end in a retirement of a daemon this client + // was never allowed to see. + const refusal = await reachability.refusedByHost(); + if (refusal) return { kind: 'connectDenied', denial: refusal }; + return { kind: 'replace', reason: 'unreachable', cause: 'unreachable' }; + } return { kind: 'reuse' }; } diff --git a/packages/daemon-client/src/daemon-lifecycle-errors.ts b/packages/daemon-client/src/daemon-lifecycle-errors.ts index 9434d78c2d..ad5eb8dc9d 100644 --- a/packages/daemon-client/src/daemon-lifecycle-errors.ts +++ b/packages/daemon-client/src/daemon-lifecycle-errors.ts @@ -53,8 +53,9 @@ export const DAEMON_UNAVAILABLE_REASONS = { // launching command does. startupListenDenied: { reason: 'startup-listen-denied' }, // The host refused this client's loopback connect to the registered daemon with `EPERM` or `EACCES`, - // as a sandbox around it does; `details.daemon` names the daemon left alone. A connect that failed - // with another errno is ordinary unreachability. + // as a sandbox around it does; `details.daemon` names the daemon left alone. A refusal found after a + // request was written also records `details.daemonRequestSent`, because that request may have run. A + // connect that failed with another errno is ordinary unreachability. connectDenied: { reason: 'daemon-connect-denied' }, // The daemon stayed registered and reachable but never reported the startup phase that follows. startupStalled: { reason: 'startup-stalled' }, diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index bfdd48d2ba..2399acd787 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -582,7 +582,7 @@ These reasons can come from more than one command. | `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, 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. | -| `daemon-connect-denied` | The host refused this client's loopback connect to the registered daemon with `EPERM` or `EACCES`, as a sandbox around it does; `details.daemon` names the daemon left alone. A connect that failed with another errno is ordinary unreachability. | +| `daemon-connect-denied` | The host refused this client's loopback connect to the registered daemon with `EPERM` or `EACCES`, as a sandbox around it does; `details.daemon` names the daemon left alone. A refusal found after a request was written also records `details.daemonRequestSent`, because that request may have run. A connect that failed with another errno is ordinary unreachability. | | `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. | From d93f600fdd912edd92c83d3b32d05e1d33785a91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 15:17:06 +0100 Subject: [PATCH 6/8] test(daemon-client): leave no global state from the probe-shape cases The Coverage lane runs the file's cases in a shuffled order, and two cases added for the denial shapes patched process globals: Date.now frozen to a counter, and every net.Socket connect refused. Anything still in flight from an earlier case was refused too, and a keep-alive socket left in the global agent was handed to a later case whose server the OS had just given the same port. The late-leg case now spends a real budget, the refusal is scoped to the probed port, and the primed socket is destroyed. --- .../__tests__/daemon-client-transport.test.ts | 56 +++++++++++-------- 1 file changed, 34 insertions(+), 22 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts index 63ca0751b9..f0b6b9343c 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -80,32 +80,29 @@ test('auto health probing reserves time for a healthy fallback when HTTP hangs', // Two shapes of a reachability probe that a boolean "unreachable" would report wrongly, both of which // a caller reads before it retires a daemon: a fallback leg that answers AFTER the deadline must not // bury the refusal the first leg already proved, and a refusal of a fresh connect must not be answered -// around by a keep-alive socket an earlier command left in the pool. +// around by a keep-alive socket an earlier command left in the pool. Neither case may leave global +// state behind: this file's other cases run real loopback servers on ports the OS reuses, and a frozen +// clock, a patched `connect`, or a free socket left in the global agent all reach them. test('a fallback leg answering past the deadline still reports the first leg as a denial', async () => { const probe = await import('../daemon-client-loopback-probe.ts'); const denial = { errno: 'EPERM', transport: 'socket', port: 41_234 } as const; - // A clock the two legs move on, so "late" is settled rather than raced: the socket leg is refused - // at once, the HTTP leg answers, and the answer lands after the probe's deadline. - let now = 1_000; - const clock = vi.spyOn(Date, 'now').mockImplementation(() => now); - const socketLeg = vi - .spyOn(probe, 'probeLoopbackPort') - .mockResolvedValue({ reachable: false, denial }); - const httpLeg = vi.spyOn(probe, 'probeHttpEndpoint').mockImplementation(async () => { - now += 500; - return { reachable: true }; + // "Late" is spent, not faked: the budget is 20 ms and the socket leg answers after 40 ms, so the + // deadline has provably passed by the time the fallback's answer lands. + const socketLeg = vi.spyOn(probe, 'probeLoopbackPort').mockImplementation(async () => { + await sleep(40); + return { reachable: false, denial }; }); + const httpLeg = vi.spyOn(probe, 'probeHttpEndpoint').mockResolvedValue({ reachable: true }); try { assert.deepEqual( await probeDaemonReachability( { token: 'secret', pid: 1, transport: 'dual', port: 41_234, httpPort: 41_235 }, 'auto', - 100, + 20, ), { reachable: false, denial }, ); } finally { - clock.mockRestore(); socketLeg.mockRestore(); httpLeg.mockRestore(); } @@ -115,8 +112,8 @@ test('a fresh connect the host refused is not answered around by a pooled socket if (await skipWhenLoopbackUnavailable(t)) return; // The pool the probe must not ride, primed the way an earlier command primes it: one keep-alive // health request whose socket returns to the global agent. Discriminator: every NEW connect is - // refused from here on, so a verdict of `reachable` could only come from the pooled socket, and a - // denial that arrives with the daemon having seen nothing but the prime is the whole claim. + // refused for the probe's own port, so a verdict of `reachable` could only come from the pooled + // socket, and a denial that arrives with the daemon having seen nothing but the prime is the claim. if (!(await poolPrimesUnderTestAgent())) return; const askedUrls: string[] = []; const server = http.createServer((req, res) => { @@ -127,6 +124,7 @@ test('a fresh connect the host refused is not answered around by a pooled socket // Prime with the SAME module object the probe loads, or the pool holds no candidate and the test // proves nothing. const requester = await hostTransport.loadNodeHttpRequester('http:'); + const { globalAgent } = await import('node:http'); await new Promise((resolve, reject) => { const request = requester.request( { host: '127.0.0.1', port, path: '/health', method: 'GET' }, @@ -139,13 +137,24 @@ test('a fresh connect the host refused is not answered around by a pooled socket request.end(); }); // A host that refuses a connect answers it immediately, with no round trip: the socket ends with - // the errno and never carries a request. - const connect = vi - .spyOn(net.Socket.prototype, 'connect') - .mockImplementation(function (this: net.Socket) { - this.destroy(Object.assign(new Error('EPERM'), { code: 'EPERM' })); - return this; - }); + // the errno and never carries a request. Scoped to the probed port — Node hands `connect` its + // normalized-args array and the port in it is a string — so nothing else this worker might be + // connecting is refused, and the real `connect` still runs for every other target. + const realConnect = net.Socket.prototype.connect; + const connect = vi.spyOn(net.Socket.prototype, 'connect').mockImplementation(function ( + this: net.Socket, + ...args: Parameters + ) { + const [first] = args; + const options = Array.isArray(first) ? first[0] : first; + const aimedPort = + typeof options === 'object' && options !== null && 'port' in options + ? Number((options as { port?: unknown }).port) + : Number.NaN; + if (aimedPort !== port) return realConnect.apply(this, args as never); + this.destroy(Object.assign(new Error('EPERM'), { code: 'EPERM' })); + return this; + }); try { assert.deepEqual( await probeDaemonReachability({ token: 'secret', pid: 1, httpPort: port }, 'http'), @@ -157,6 +166,9 @@ test('a fresh connect the host refused is not answered around by a pooled socket assert.deepEqual(askedUrls, ['/health'], 'only the prime reached the daemon'); } finally { connect.mockRestore(); + // The primed socket is back in the pool now, pointed at a server about to close. A later case + // that is handed this port by the OS would otherwise ride it and lose its request. + globalAgent.destroy(); await closeLoopbackServer(server); } }); From 49b48b02e1a363532a8bd4cbe1f28e7770b6f89d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 15:33:19 +0100 Subject: [PATCH 7/8] test(daemon-client): pool the refusal case's sockets, and launch it through the fixture plan Two Coverage failures on this head: The repo guard reads the launch seam as a daemon-fixture family member: its launcher mock must be a bare vi.fn() with the launch plan installed on it, and its fixture teardown must run through the shared family cleanup. The mock was built in a hoisted block instead. The pooled-socket case hung and then reported an error thrown after it completed. Two shared-state faults made that possible: it primed the process-wide agent and emptied it in teardown, so every socket another case was still using went with it, and it issued the prime without clearing the entry this endpoint already had, so a keep-alive socket a previous file had left for a port the OS just reused answered the write with nothing and the request had no bound to end the wait. The case now clears only this endpoint's pooled sockets, before and after, and the prime has its own deadline. --- ...ient-loopback-probe-connect-denied.test.ts | 27 +++++++++------- .../__tests__/daemon-client-transport.test.ts | 31 ++++++++++++++++--- 2 files changed, 41 insertions(+), 17 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts index 6ff660e93c..6a2db4e1e9 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-connect-denied.test.ts @@ -3,7 +3,7 @@ import EventEmitter from 'node:events'; import fs from 'node:fs'; import net from 'node:net'; import { afterEach, test, vi } from 'vitest'; -import { runCmdBackground } from '@agent-device/host-kit/command'; +import { runCmdBackground, runCmdDetachedMonitored } from '@agent-device/host-kit/command'; import { isProcessAlive, readProcessCommand, @@ -23,6 +23,7 @@ import { sendToDaemon } from '../index.ts'; import { probeLoopbackPort, readAdvertisedConnectDenial } from '../daemon-client-loopback-probe.ts'; import { finishRegisteredDaemonFixture, + finishRegisteredDaemonFixtures, planRegisteredDaemonLaunches, } from './registered-daemon-fixture.ts'; import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; @@ -36,13 +37,12 @@ const DENIED_ERRNO = 'EPERM'; /** A host refusal to answer a probe with, naming the errno and endpoint family it refused. */ type DeniedProbe = Readonly<{ errno: 'EPERM' | 'EACCES'; transport: 'socket' | 'http' }>; -const { mockProbeAnswers, mockSpawnDaemon } = vi.hoisted(() => ({ +const { mockProbeAnswers } = vi.hoisted(() => ({ /** * What each probe of the registered daemon answers, in order: `'silent'`, or the refusal the host * gave. `null` stands for silence so the list reads as answers, not as verdict shapes. */ mockProbeAnswers: [] as (DeniedProbe | null)[], - mockSpawnDaemon: vi.fn(), })); function denied(errno: DeniedProbe['errno'], transport: DeniedProbe['transport']): DeniedProbe { @@ -63,14 +63,17 @@ vi.mock('../daemon-client-transport.ts', async (importOriginal) => { }; }); -vi.mock('@agent-device/host-kit/command', async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, runCmdDetachedMonitored: mockSpawnDaemon }; -}); +vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({ + ...(await importOriginal()), + runCmdDetachedMonitored: vi.fn(), +})); + +const spawnDaemon = vi.mocked(runCmdDetachedMonitored); -afterEach(() => { +afterEach(async () => { mockProbeAnswers.length = 0; - mockSpawnDaemon.mockReset(); + spawnDaemon.mockReset(); + await finishRegisteredDaemonFixtures(); }); /** @@ -168,7 +171,7 @@ test('a connect the host refused names the sandbox and leaves the daemon running assert.equal((failure.details?.daemon as { pid?: number } | undefined)?.pid, pid); assert.match(String(failure.details?.hint), /A sandbox around this command/); assert.match(String(failure.details?.hint), /host access/); - assert.equal(mockSpawnDaemon.mock.calls.length, 0, 'a refusal is not a dead daemon to replace'); + assert.equal(spawnDaemon.mock.calls.length, 0, 'a refusal is not a dead daemon to replace'); assert.equal(isProcessAlive(pid), true, 'the daemon outside the sandbox is not signaled'); }); }); @@ -197,7 +200,7 @@ test.for([ assert.equal(failure.details?.transport, leg); assert.equal(failure.details?.port, leg === 'http' ? httpPort : port); assert.equal((failure.details?.daemon as { pid?: number } | undefined)?.pid, pid); - assert.equal(mockSpawnDaemon.mock.calls.length, 0); + assert.equal(spawnDaemon.mock.calls.length, 0); assert.equal(isProcessAlive(pid), true); }); }, @@ -213,7 +216,7 @@ test('a launched daemon whose readiness connect the host refused is left running const paths = resolveDaemonPaths(stateDir); const server = net.createServer((socket) => socket.on('error', () => {})); const httpPort = await listenOnLoopback(server); - mockSpawnDaemon.mockImplementation( + spawnDaemon.mockImplementation( planRegisteredDaemonLaunches([ { kind: 'registered', diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts index f0b6b9343c..0df32bf6dd 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -121,18 +121,27 @@ test('a fresh connect the host refused is not answered around by a pooled socket res.end('{}'); }); const port = await listenOnLoopback(server); + // The agent is shared with every other case in this file and with every file this worker reuses, + // and the OS hands loopback ports out again, so the pool may already hold a socket for THIS port + // from a server that is gone. Riding one would write the prime to a peer that never answers, so + // this endpoint's pooled sockets go before the prime, and again after it. + const { globalAgent } = await import('node:http'); + destroyPooledSockets(globalAgent, port); // Prime with the SAME module object the probe loads, or the pool holds no candidate and the test - // proves nothing. + // proves nothing. The prime is bounded so a pool this case does not control cannot hold the case + // open to the test budget. const requester = await hostTransport.loadNodeHttpRequester('http:'); - const { globalAgent } = await import('node:http'); await new Promise((resolve, reject) => { const request = requester.request( - { host: '127.0.0.1', port, path: '/health', method: 'GET' }, + { host: '127.0.0.1', port, path: '/health', method: 'GET', timeout: 2_000 }, (res) => { res.resume(); res.on('end', resolve); }, ); + request.on('timeout', () => { + request.destroy(new Error(`the prime reached no daemon on port ${port}`)); + }); request.on('error', reject); request.end(); }); @@ -167,12 +176,24 @@ test('a fresh connect the host refused is not answered around by a pooled socket } finally { connect.mockRestore(); // The primed socket is back in the pool now, pointed at a server about to close. A later case - // that is handed this port by the OS would otherwise ride it and lose its request. - globalAgent.destroy(); + // that is handed this port by the OS would otherwise ride it and lose its request. Only this + // endpoint's pooled sockets go: the agent is shared with every other case in this file. + destroyPooledSockets(globalAgent, port); await closeLoopbackServer(server); } }); +/** Drops the keep-alive sockets the pool holds for one loopback port, and only those. */ +function destroyPooledSockets(agent: http.Agent, port: number): void { + // Node types the pool as read-only, and this is the one place a test has to empty it. + const free = agent.freeSockets as Record; + for (const [key, sockets] of Object.entries(free)) { + if (!key.endsWith(`:${port}:`)) continue; + for (const socket of sockets ?? []) socket.destroy(); + delete free[key]; + } +} + /** Whether this Node keeps sockets alive on the global agent, which is what makes a pool exist. */ async function poolPrimesUnderTestAgent(): Promise { const { globalAgent } = await import('node:http'); From 411ad6e5ccace0a65ca92c9b5745ea8099688071 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 15:45:27 +0100 Subject: [PATCH 8/8] test(daemon-client): give the pooled-socket probe case a file of its own The case refused every connect made while its patch was installed, and a worker runs the cases of one file in one process: a connect another case was still waiting on was refused too, and the errno surfaced as an unhandled error once that case had finished. Vitest gives every file a worker, so the patch now reaches only this case. The refusal also lands later. Destroying a socket synchronously inside its connect reports a closed socket rather than the errno, and it fires before the requester has a listener on the socket. The real connect runs, so the socket has its handle, and the errno arrives on the next turn, when the request owns it. The case pins that the prime really did leave an idle socket in the pool, so the verdict cannot come from an empty pool, and it drops only this endpoint's pooled sockets. --- ...lient-loopback-probe-pooled-socket.test.ts | 121 ++++++++++++++++++ .../__tests__/daemon-client-transport.test.ts | 101 +-------------- 2 files changed, 124 insertions(+), 98 deletions(-) create mode 100644 packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts diff --git a/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts new file mode 100644 index 0000000000..1996a2ff99 --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-loopback-probe-pooled-socket.test.ts @@ -0,0 +1,121 @@ +import assert from 'node:assert/strict'; +import http from 'node:http'; +import net from 'node:net'; +import { afterEach, test, vi, type Mock } from 'vitest'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import * as hostTransport from '@agent-device/host-kit/transport'; +import { probeDaemonReachability } from '../daemon-client-transport.ts'; + +// A reachability probe must not be answered around by a keep-alive socket an earlier command left in +// the pool: a caller reads this verdict before it retires a daemon, and a pooled socket proves only +// that SOME connect was allowed at SOME point, not that one is allowed NOW. +// +// This case owns a file because it patches `Socket.prototype.connect` for every socket made while the +// patch is on and leans on the process-wide keep-alive pool. Vitest gives each file a worker of its +// own, so the refusal cannot reach a case elsewhere that is mid-request on a shared socket, and +// `afterEach` hands the prototype back before this file runs anything else. + +let server: http.Server | undefined; +let connect: Mock | undefined; +const askedUrls: string[] = []; + +afterEach(async () => { + connect?.mockRestore(); + connect = undefined; + askedUrls.length = 0; + if (server) await closeLoopbackServer(server); + server = undefined; +}); + +test('a fresh connect the host refused is not answered around by a pooled socket', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + server = http.createServer((req, res) => { + askedUrls.push(String(req.url)); + res.end('{}'); + }); + const port = await listenOnLoopback(server); + // The pool may still hold a socket for THIS port from a server this worker already closed, and the + // OS hands loopback ports out again. Riding one would write the prime to a peer that never answers, + // so this endpoint's pooled sockets go first. + destroyPooledSockets(http.globalAgent, port); + + // Prime the pool the way an earlier command primes it: one health request whose socket returns to + // the agent. It goes through the SAME module object the probe loads, or no candidate lands in the + // pool and the case proves nothing. The request is bounded so a pool this case does not control + // cannot hold it open to the test budget. + const requester = await hostTransport.loadNodeHttpRequester('http:'); + await new Promise((resolve, reject) => { + const request = requester.request( + { host: '127.0.0.1', port, path: '/health', method: 'GET', timeout: 2_000 }, + (res) => { + res.resume(); + res.on('end', resolve); + }, + ); + request.on('timeout', () => { + request.destroy(new Error(`the prime reached no daemon on port ${port}`)); + }); + request.on('error', reject); + request.end(); + }); + // A pool that took nothing in would leave the probe with nothing to ride, and a `reachable: false` + // verdict would then mean nothing. + assert.ok( + freeSocketCountFor(http.globalAgent, port) > 0, + 'the prime left a keep-alive socket in the pool for this endpoint', + ); + + // A host that refuses a connect answers it immediately, with no round trip: the socket ends with + // the errno and carries no request. The connect is the real one, so the socket has a handle and the + // errno reaches the requester — destroying a socket that never connected reports only a closed + // socket. The refusal lands on a later turn, after the requester has put its listener on it. + const realConnect = net.Socket.prototype.connect; + connect = vi.spyOn(net.Socket.prototype, 'connect').mockImplementation(function ( + this: net.Socket, + ...args: Parameters + ) { + const socket = realConnect.apply(this, args as never) as net.Socket; + setImmediate(() => socket.destroy(Object.assign(new Error('EPERM'), { code: 'EPERM' }))); + return socket; + }); + + assert.deepEqual( + await probeDaemonReachability({ token: 'secret', pid: 1, httpPort: port }, 'http'), + { reachable: false, denial: { errno: 'EPERM', transport: 'http', port } }, + ); + assert.deepEqual(askedUrls, ['/health'], 'only the prime reached the daemon'); + + // The primed socket is back in the pool now, pointed at a server about to close. Drop this + // endpoint's entry so nothing downstream rides it. + destroyPooledSockets(http.globalAgent, port); +}); + +/** Drops the keep-alive sockets the pool holds for one loopback port, and only those. */ +function destroyPooledSockets(agent: http.Agent, port: number): void { + // Node types the pool as read-only, and this is the one place a test has to empty it. + const free = agent.freeSockets as Record; + for (const [key, sockets] of Object.entries(free)) { + if (!isPooledEndpointForPort(key, port)) continue; + for (const socket of sockets ?? []) socket.destroy(); + delete free[key]; + } +} + +/** How many idle keep-alive sockets the pool holds for one loopback port. */ +function freeSocketCountFor(agent: http.Agent, port: number): number { + return Object.entries(agent.freeSockets).reduce( + (total, [key, sockets]) => + isPooledEndpointForPort(key, port) ? total + (sockets?.length ?? 0) : total, + 0, + ); +} + +/** The agent keys sockets by `host:port:`; the port is the field before the trailing colon. */ +function isPooledEndpointForPort(key: string, port: number): boolean { + const [, pooledPort] = key.split(':'); + return Number(pooledPort) === port; +} diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts index 0df32bf6dd..a7fa975558 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -77,12 +77,9 @@ test('auto health probing reserves time for a healthy fallback when HTTP hangs', } }); -// Two shapes of a reachability probe that a boolean "unreachable" would report wrongly, both of which -// a caller reads before it retires a daemon: a fallback leg that answers AFTER the deadline must not -// bury the refusal the first leg already proved, and a refusal of a fresh connect must not be answered -// around by a keep-alive socket an earlier command left in the pool. Neither case may leave global -// state behind: this file's other cases run real loopback servers on ports the OS reuses, and a frozen -// clock, a patched `connect`, or a free socket left in the global agent all reach them. +// A reachability probe shape that a boolean "unreachable" would report wrongly, and that a caller +// reads before it retires a daemon: a fallback leg that answers AFTER the deadline must not bury the +// refusal the first leg already proved. test('a fallback leg answering past the deadline still reports the first leg as a denial', async () => { const probe = await import('../daemon-client-loopback-probe.ts'); const denial = { errno: 'EPERM', transport: 'socket', port: 41_234 } as const; @@ -108,98 +105,6 @@ test('a fallback leg answering past the deadline still reports the first leg as } }); -test('a fresh connect the host refused is not answered around by a pooled socket', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - // The pool the probe must not ride, primed the way an earlier command primes it: one keep-alive - // health request whose socket returns to the global agent. Discriminator: every NEW connect is - // refused for the probe's own port, so a verdict of `reachable` could only come from the pooled - // socket, and a denial that arrives with the daemon having seen nothing but the prime is the claim. - if (!(await poolPrimesUnderTestAgent())) return; - const askedUrls: string[] = []; - const server = http.createServer((req, res) => { - askedUrls.push(String(req.url)); - res.end('{}'); - }); - const port = await listenOnLoopback(server); - // The agent is shared with every other case in this file and with every file this worker reuses, - // and the OS hands loopback ports out again, so the pool may already hold a socket for THIS port - // from a server that is gone. Riding one would write the prime to a peer that never answers, so - // this endpoint's pooled sockets go before the prime, and again after it. - const { globalAgent } = await import('node:http'); - destroyPooledSockets(globalAgent, port); - // Prime with the SAME module object the probe loads, or the pool holds no candidate and the test - // proves nothing. The prime is bounded so a pool this case does not control cannot hold the case - // open to the test budget. - const requester = await hostTransport.loadNodeHttpRequester('http:'); - await new Promise((resolve, reject) => { - const request = requester.request( - { host: '127.0.0.1', port, path: '/health', method: 'GET', timeout: 2_000 }, - (res) => { - res.resume(); - res.on('end', resolve); - }, - ); - request.on('timeout', () => { - request.destroy(new Error(`the prime reached no daemon on port ${port}`)); - }); - request.on('error', reject); - request.end(); - }); - // A host that refuses a connect answers it immediately, with no round trip: the socket ends with - // the errno and never carries a request. Scoped to the probed port — Node hands `connect` its - // normalized-args array and the port in it is a string — so nothing else this worker might be - // connecting is refused, and the real `connect` still runs for every other target. - const realConnect = net.Socket.prototype.connect; - const connect = vi.spyOn(net.Socket.prototype, 'connect').mockImplementation(function ( - this: net.Socket, - ...args: Parameters - ) { - const [first] = args; - const options = Array.isArray(first) ? first[0] : first; - const aimedPort = - typeof options === 'object' && options !== null && 'port' in options - ? Number((options as { port?: unknown }).port) - : Number.NaN; - if (aimedPort !== port) return realConnect.apply(this, args as never); - this.destroy(Object.assign(new Error('EPERM'), { code: 'EPERM' })); - return this; - }); - try { - assert.deepEqual( - await probeDaemonReachability({ token: 'secret', pid: 1, httpPort: port }, 'http'), - { - reachable: false, - denial: { errno: 'EPERM', transport: 'http', port }, - }, - ); - assert.deepEqual(askedUrls, ['/health'], 'only the prime reached the daemon'); - } finally { - connect.mockRestore(); - // The primed socket is back in the pool now, pointed at a server about to close. A later case - // that is handed this port by the OS would otherwise ride it and lose its request. Only this - // endpoint's pooled sockets go: the agent is shared with every other case in this file. - destroyPooledSockets(globalAgent, port); - await closeLoopbackServer(server); - } -}); - -/** Drops the keep-alive sockets the pool holds for one loopback port, and only those. */ -function destroyPooledSockets(agent: http.Agent, port: number): void { - // Node types the pool as read-only, and this is the one place a test has to empty it. - const free = agent.freeSockets as Record; - for (const [key, sockets] of Object.entries(free)) { - if (!key.endsWith(`:${port}:`)) continue; - for (const socket of sockets ?? []) socket.destroy(); - delete free[key]; - } -} - -/** Whether this Node keeps sockets alive on the global agent, which is what makes a pool exist. */ -async function poolPrimesUnderTestAgent(): Promise { - const { globalAgent } = await import('node:http'); - return Boolean((globalAgent as { keepAlive?: boolean }).keepAlive); -} - test('the health deadline includes requester loading and forbids a late request', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; let requests = 0;