From 1771b6c629359cab262bdada7705c8ac71866dfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 21:13:38 +0100 Subject: [PATCH 01/10] perf(daemon-client): reuse remote /health across CLI processes Each CLI call to a remote daemon is a new process, so the in-process health cache never hit and every command paid GET /health before POST /rpc. The usable /health answer now also lives in the client state directory, named by a digest of client version, base URL and token. Every RPC sent from it carries the instance preconditions, so a replaced daemon or proxy upstream still answers 409 before dispatch and the client probes again. A cached RPC that fails before it leaves the client opens the /health gate (same recovery budget and typed refusal) and is sent once more. A reply that is not the daemon's JSON-RPC clears the cache. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0006-daemon-rpc-protocol-version.md | 15 +- ...mon-client-lifecycle-remote-health.test.ts | 22 ++- .../daemon-client-remote-health-cache.test.ts | 38 +++- .../__tests__/daemon-client-transport.test.ts | 95 ++++++++- .../src/daemon-client-health-record.ts | 86 ++++++++ .../src/daemon-client-lifecycle.ts | 37 +++- .../src/daemon-client-metadata.ts | 5 + .../src/daemon-client-remote-health-cache.ts | 100 +++++++++- .../daemon-client-remote-health-recovery.ts | 9 +- .../src/daemon-client-timeout.ts | 2 +- .../src/daemon-client-transport.ts | 183 +++++++++--------- website/docs/docs/remote-proxy.md | 2 +- 12 files changed, 471 insertions(+), 123 deletions(-) create mode 100644 packages/daemon-client/src/daemon-client-health-record.ts diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index 46e27836b8..ad5a006a9d 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -9,7 +9,9 @@ Accepted - Before remote JSON-RPC requests, compare the daemon's `rpcProtocolVersion` from `/health`. - Package `version` is diagnostic only and must not be used as a compatibility gate. - Allow a missing `rpcProtocolVersion` unless a later security or protocol decision explicitly retires legacy compatibility. -- A persistent client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon. +- A client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon. +- The cache may outlive the client process in the state directory. Name the entry by a digest of the client version, base URL, and token. Do not write the token or the URL. +- If a cached RPC fails before it leaves the client, probe `/health` as on first contact. Then send the RPC once more. - Send those instance IDs as conditional headers on every cached RPC. Peers without complete instance IDs retain per-command probes. - After a stale-instance refusal, clear the cache and probe `/health` again. Retry the refused RPC once, and only if the new peer's protocol is compatible. - A peer that advertises an instance ID must continue to honor the conditional RPC headers in future versions. @@ -39,7 +41,11 @@ Package `version` is diagnostic only and must not be used as a compatibility gat A missing `rpcProtocolVersion` is treated as a legacy remote daemon. A legacy remote daemon is allowed unless a later security or protocol decision explicitly retires legacy compatibility. -A persistent client may cache a successful probe if `/health` advertises an instance ID for both the daemon endpoint and, if proxied, its upstream daemon. +A client may cache a successful probe if `/health` advertises an instance ID for both the daemon endpoint and, if proxied, its upstream daemon. +The CLI starts a new process for each command, so the cache also persists in the state directory. +Without it, each remote command pays one extra network round trip for `/health`. +The persisted entry is named by a digest of the client version, base URL, and token, and holds neither the token nor the URL. +A different token, URL, or client version reads as a miss, so a client upgrade always probes again. The client sends those IDs as conditional headers on every cached RPC. Before dispatch, a daemon refuses a stale instance with a typed HTTP 409 response. Before it forwards a request, a proxy refuses its own stale instance. @@ -47,6 +53,9 @@ The proxy passes the expected upstream instance to the daemon, which makes the s On a mismatch, the client clears the cache and probes `/health` again. The client then retries the refused RPC once, and only if the new peer's protocol is compatible. Peers without complete instance IDs retain per-command probes. +A cached RPC that fails before it leaves the client proves that nothing was dispatched. +The client then clears the cache and probes `/health` as on first contact, with the same recovery budget and typed refusal, and sends the RPC once more. +A cached RPC that fails after it was sent is not resent. The client clears the cache, so the next command probes `/health` first. A peer that advertises an instance ID must continue to honor the conditional RPC headers in future versions. The reason is that older clients may hold a cached identity across a restart. Such clients must receive a pre-dispatch refusal before they retry a mutating command. @@ -76,6 +85,8 @@ This preference does not apply if the change also affects the shared transport c It also makes proxy use brittle across frequent releases. - **Do not check compatibility.** This maximizes compatibility. However, it fails later, after the client has sent an RPC payload that a remote daemon may parse incorrectly. +- **Send `/rpc` without a probe on first contact.** This saves the round trip without a cache. + However, the client then cannot refuse an incompatible protocol before it sends the payload. - **Negotiate full schemas.** This is more precise, but it is too much machinery for the current JSON-RPC boundary. ## Consequences diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts index fedff186c2..4f81728f6f 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts @@ -9,6 +9,7 @@ import { test } from 'vitest'; import { closeLoopbackServer, listenOnLoopback, + mkdtempForTestSync, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; @@ -152,6 +153,7 @@ test('a remote press whose health probe answers 4xx is sent and is not the unava async function slowHealthyRemote(delayMs: number): Promise<{ handler: http.Server; info: { baseUrl: string; token: string; pid: number }; + stateDir: string; probes: () => number; }> { let probes = 0; @@ -165,7 +167,8 @@ async function slowHealthyRemote(delayMs: number): Promise<{ }); const port = await listenOnLoopback(handler); const info = { baseUrl: `http://127.0.0.1:${port}`, token: `probe-${port}`, pid: 0 }; - return { handler, info, probes: () => probes }; + const stateDir = mkdtempForTestSync('agent-device-remote-health-'); + return { handler, info, stateDir, probes: () => probes }; } // Each caller probes under its own bound; only a settled, usable answer is shared through the cache, @@ -174,15 +177,18 @@ test('a health caller probes on its own bound, and a settled answer is cached', if (await skipWhenLoopbackUnavailable(t)) return; const remote = await slowHealthyRemote(300); try { - const unbounded = cachedRemoteDaemonHealth(remote.info); - const bounded = await cachedRemoteDaemonHealth(remote.info, 50); + const unbounded = cachedRemoteDaemonHealth(remote.info, remote.stateDir); + const bounded = await cachedRemoteDaemonHealth(remote.info, remote.stateDir, 50); assert.equal(bounded.reachable, false); assert.equal(bounded.timedOut, true); assert.equal((await unbounded).reachable, true); assert.equal(remote.probes(), 2, 'each caller sent its own probe'); // The settled answer is cached, so a later bounded caller reads it without probing. - assert.equal((await cachedRemoteDaemonHealth(remote.info, 50)).reachable, true); + assert.equal( + (await cachedRemoteDaemonHealth(remote.info, remote.stateDir, 50)).reachable, + true, + ); assert.equal(remote.probes(), 2); } finally { await closeLoopbackServer(remote.handler); @@ -194,9 +200,13 @@ test('an aborted or budgetless health caller sends no probe', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const remote = await slowHealthyRemote(0); try { - assert.equal((await cachedRemoteDaemonHealth(remote.info, 0)).reachable, false); assert.equal( - (await cachedRemoteDaemonHealth(remote.info, undefined, AbortSignal.abort())).reachable, + (await cachedRemoteDaemonHealth(remote.info, remote.stateDir, 0)).reachable, + false, + ); + assert.equal( + (await cachedRemoteDaemonHealth(remote.info, remote.stateDir, undefined, AbortSignal.abort())) + .reachable, false, ); assert.equal(remote.probes(), 0); diff --git a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts index 5be44596db..32abef4fcb 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts @@ -1,10 +1,15 @@ import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; import { test } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; import { + cacheRemoteDaemonHealth, cachedRemoteHealth, invalidateRemoteDaemonHealth, + readCachedRemoteHealth, } from '../daemon-client-remote-health-cache.ts'; -import type { RemoteDaemonHealth } from '../daemon-client-transport.ts'; +import type { RemoteDaemonHealth } from '../daemon-client-health-record.ts'; const HEALTHY: RemoteDaemonHealth = { reachable: true, instanceId: 'remote-instance' }; @@ -35,3 +40,34 @@ test('a probe answer that lands after an invalidation is not cached', async () = }); assert.equal(probes, 1); }); + +// The state dir holds one answer named by a digest of the daemon identity. A different token or URL, +// an unusable answer, or an unreadable file reads as a miss, so the caller probes. +test('persisted health is reused only for the identity that cached it', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-health-store-'); + const file = path.join(stateDir, 'remote-daemon-health.json'); + const info = { baseUrl: 'http://remote.example.test:7777', token: 'store-test', pid: 0 }; + const other = { ...info, token: 'other-token' }; + const forget = () => invalidateRemoteDaemonHealth(info); + + cacheRemoteDaemonHealth(info, { reachable: true }, stateDir); + assert.equal(fs.existsSync(file), false, 'an answer without an instance is not persisted'); + + cacheRemoteDaemonHealth(info, { ...HEALTHY, statusCode: 200, timedOut: true }, stateDir); + forget(); + const reused = readCachedRemoteHealth(info, stateDir); + assert.equal(reused?.reachable, true); + assert.equal(reused?.instanceId, HEALTHY.instanceId); + assert.equal(reused?.statusCode, undefined, 'only the record is persisted'); + assert.equal(reused?.timedOut, undefined); + forget(); + assert.equal(readCachedRemoteHealth(other, stateDir), undefined); + + invalidateRemoteDaemonHealth(other, stateDir); + assert.equal(fs.existsSync(file), true, 'another identity leaves the entry alone'); + invalidateRemoteDaemonHealth(info, stateDir); + assert.equal(fs.existsSync(file), false); + + fs.writeFileSync(file, '{not json'); + assert.equal(readCachedRemoteHealth(info, stateDir), undefined); +}); 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 a7fa975558..d5edec307d 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -201,13 +201,14 @@ test('persistent remote client caches health and retries a refused stale instanc try { const port = await listenOnLoopback(server); const baseUrl = `http://127.0.0.1:${port}`; + const stateDir = mkdtempForTestSync('agent-device-remote-health-cache-'); const request = (token: string, url = baseUrl) => sendToDaemon( { command: 'remote-smoke', session: 'default', positionals: ['ping'], - flags: { daemonBaseUrl: url }, + flags: { daemonBaseUrl: url, stateDir }, meta: { requestId: 'request' }, }, { authToken: token }, @@ -470,13 +471,14 @@ test('proxy forwards cached upstream identity and rejects a restarted upstream b }); try { const proxyPort = await listenOnLoopback(proxy); + const stateDir = mkdtempForTestSync('agent-device-remote-proxy-health-'); const request = () => sendToDaemon( { command: 'remote-smoke', session: 'default', positionals: ['ping'], - flags: { daemonBaseUrl: `http://127.0.0.1:${proxyPort}/agent-device/` }, + flags: { daemonBaseUrl: `http://127.0.0.1:${proxyPort}/agent-device/`, stateDir }, meta: { requestId: 'request' }, }, { authToken: 'client-secret' }, @@ -665,6 +667,95 @@ test.for(['timeout', 'reset'] as const)( }, ); +/** A remote daemon that answers /health with `instanceId()` and refuses a stale instance with 409. */ +async function instanceCheckingRemote(instanceId: () => string) { + const paths: string[] = []; + const server = http.createServer((req, res) => { + paths.push(`${req.method} ${req.url}`); + res.setHeader('content-type', 'application/json'); + if (req.url?.endsWith('/health')) { + res.end( + JSON.stringify({ ok: true, service: 'agent-device-daemon', instanceId: instanceId() }), + ); + return; + } + const expected = req.headers[DAEMON_HTTP_INSTANCE_HEADER]; + if (typeof expected === 'string' && expected !== instanceId()) { + res.statusCode = 409; + res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true'); + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'request', error: { code: -32001 } })); + return; + } + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'request', result: { ok: true, data: {} } })); + }); + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const stateDir = mkdtempForTestSync('agent-device-remote-health-persisted-'); + const request = () => + sendToDaemon( + { + command: 'remote-smoke', + session: 'default', + positionals: ['ping'], + flags: { daemonBaseUrl: baseUrl, stateDir }, + meta: { requestId: 'request' }, + }, + { authToken: 'persisted-secret' }, + ); + // What a new CLI process starts with: no health cached in memory, only what the state dir holds. + const forgetInMemory = () => + invalidateRemoteDaemonHealth({ baseUrl, token: 'persisted-secret', pid: 0 }); + const cacheFile = path.join(stateDir, 'remote-daemon-health.json'); + return { server, paths, baseUrl, request, forgetInMemory, cacheFile }; +} + +// Each CLI call is a new process, so the health a first call probed is kept in the state dir and a +// later process sends straight to /rpc. The instance precondition still catches a replaced daemon. +test('a later process reuses persisted remote health and still catches a replaced daemon', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let instanceId = 'persisted-one'; + const remote = await instanceCheckingRemote(() => instanceId); + try { + assert.equal((await remote.request()).ok, true); + remote.forgetInMemory(); + assert.equal((await remote.request()).ok, true); + assert.deepEqual(remote.paths, ['GET /health', 'POST /rpc', 'POST /rpc']); + + const persisted = fs.readFileSync(remote.cacheFile, 'utf8'); + assert.equal(persisted.includes('persisted-secret'), false, 'the token is never written'); + assert.equal(persisted.includes(remote.baseUrl), false, 'the URL is never written'); + assert.equal(fs.statSync(remote.cacheFile).mode & 0o077, 0, 'only the owner reads it'); + + instanceId = 'persisted-two'; + remote.forgetInMemory(); + assert.equal((await remote.request()).ok, true); + assert.deepEqual(remote.paths.slice(3), ['POST /rpc', 'GET /health', 'POST /rpc']); + remote.forgetInMemory(); + assert.equal((await remote.request()).ok, true); + assert.deepEqual(remote.paths.slice(6), ['POST /rpc'], 'the replacement was persisted'); + } finally { + await closeLoopbackServer(remote.server); + } +}); + +// A send from cached health that never left the process proves nothing reached the daemon, so it +// gets the gate a first contact gets, with the same typed refusal, instead of a bare transport error. +test('an unsent request from cached remote health opens the health gate', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const remote = await instanceCheckingRemote(() => 'gone-soon'); + assert.equal((await remote.request()).ok, true); + await closeLoopbackServer(remote.server); + // Lets the client drop its pooled connection, as a new CLI process has none. + await sleep(20); + remote.forgetInMemory(); + await assert.rejects(remote.request(), (error: unknown) => { + assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); + assert.equal(error.details?.reason, DAEMON_UNAVAILABLE_REASONS.remoteUnavailable.reason); + assert.equal(error.details?.dispatched, 'no'); + return true; + }); + assert.equal(fs.existsSync(remote.cacheFile), false, 'the unreachable daemon is forgotten'); +}); + // A transport failure drops the cached health of a remote daemon only: a local daemon has no cached // health, so its failed request neither invalidates nor loads the remote health cache. test('a transport failure invalidates cached health for a remote daemon only', async (t) => { diff --git a/packages/daemon-client/src/daemon-client-health-record.ts b/packages/daemon-client/src/daemon-client-health-record.ts new file mode 100644 index 0000000000..4d4c8cf9e7 --- /dev/null +++ b/packages/daemon-client/src/daemon-client-health-record.ts @@ -0,0 +1,86 @@ +import type { DaemonHealthPayload } from '@agent-device/contracts/daemon-http'; +import { readDaemonCapabilities } from '@agent-device/daemon-contracts/daemon-resolution'; +import type { DaemonInfo } from './daemon-client-metadata.ts'; + +export type RemoteDaemonHealth = { + reachable: boolean; + statusCode?: number; + service?: string; + version?: string; + rpcProtocolVersion?: number; + instanceId?: string; + hostArch?: string; + capabilities?: DaemonInfo['capabilities']; + /** The daemon behind a proxy, as the proxy's health reported it. */ + upstream?: RemoteDaemonHealthLink; + /** The probe ran out of its time budget before an answer, rather than failing outright. */ + timedOut?: true; +}; + +export type RemoteDaemonHealthLink = Pick< + RemoteDaemonHealth, + 'service' | 'version' | 'rpcProtocolVersion' | 'instanceId' | 'hostArch' | 'capabilities' +>; + +type RemoteHealthRecord = Omit; + +export function readHealthPayload(body: string): RemoteHealthRecord { + try { + return readRemoteHealthRecord(JSON.parse(body)); + } catch { + return {}; + } +} + +/** The contract fields of a `/health` record, from the daemon or the cache; anything else is absent. */ +export function readRemoteHealthRecord(parsed: unknown): RemoteHealthRecord { + if (!parsed || typeof parsed !== 'object') return {}; + const record = parsed as Record; + const upstream = + record.upstream && typeof record.upstream === 'object' + ? readHealthLink(record.upstream as Record) + : undefined; + return { ...readHealthLink(record), ...(upstream ? { upstream } : {}) }; +} + +function readHealthLink(parsed: Record): RemoteDaemonHealthLink { + return { + service: isHealthService(parsed.service) ? parsed.service : undefined, + version: readHealthVersion(parsed.version), + rpcProtocolVersion: + typeof parsed.rpcProtocolVersion === 'number' ? parsed.rpcProtocolVersion : undefined, + ...(typeof parsed.instanceId === 'string' ? { instanceId: parsed.instanceId } : {}), + ...(typeof parsed.hostArch === 'string' ? { hostArch: parsed.hostArch } : {}), + ...(parsed.capabilities === undefined + ? {} + : { capabilities: readDaemonCapabilities(parsed.capabilities) }), + }; +} + +// The remote picks what /health says and agents read the refusal built from it, so only a service +// the contract names and a version-shaped string are kept; anything else reads as absent. +const HEALTH_SERVICES: Readonly> = { + 'agent-device-daemon': true, + 'agent-device-proxy': true, +}; +const HEALTH_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; +const HEALTH_VERSION_MAX_LENGTH = 64; + +function isHealthService(value: unknown): value is DaemonHealthPayload['service'] { + return typeof value === 'string' && Object.hasOwn(HEALTH_SERVICES, value); +} + +function readHealthVersion(value: unknown): string | undefined { + return typeof value === 'string' && + value.length <= HEALTH_VERSION_MAX_LENGTH && + HEALTH_VERSION.test(value) + ? value + : undefined; +} + +/** Points `info` at the daemon a `/health` answer describes: its instances and capabilities. */ +export function applyRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHealth): void { + info.remoteInstanceId = health.instanceId; + info.remoteUpstreamInstanceId = health.upstream?.instanceId; + info.capabilities = (health.upstream ?? health).capabilities; +} diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index 90de3f239f..b7db49fe33 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -31,7 +31,11 @@ import type { findUnrecoveredRepairCommitFailure } from '@agent-device/daemon-co import type { DaemonInfo } from './daemon-client-metadata.ts'; import { attachActiveSessionAddressHint } from './daemon-client-address-hints.ts'; import { isRemoteDaemon, observedDaemonIdentityOf } from './daemon-client-metadata.ts'; -import { cachedRemoteDaemonHealth } from './daemon-client-transport.ts'; +import { applyRemoteDaemonHealth } from './daemon-client-health-record.ts'; +import { + cachedRemoteDaemonHealth, + readCachedRemoteDaemonHealth, +} from './daemon-client-transport.ts'; import { assertDaemonPolicyMatches, readReusableLocalDaemon, @@ -273,10 +277,31 @@ async function ensureRemoteDaemon( pid: 0, baseUrl: settings.remoteBaseUrl, }; + const stateDir = settings.paths.baseDir; + const cached = await readCachedRemoteDaemonHealth(remoteInfo, stateDir); + if (cached) { + applyRemoteDaemonHealth(remoteInfo, cached); + remoteInfo.remoteHealthCached = true; + } else { + await openRemoteHealthGate(remoteInfo, stateDir, healthRecovery); + } + return { info: remoteInfo, startedByClient: false }; +} + +/** + * Probes a remote daemon's `/health` before anything is sent to it, re-probing a daemon that is there + * but not ready for the recovery budget, and points `info` at the daemon that answered. + */ +export async function openRemoteHealthGate( + info: DaemonInfo, + stateDir: string, + healthRecovery: RemoteHealthRecovery | undefined, +): Promise { // The command's budget starts with the first probe, which already runs under it and its signal. const deadline = performance.now() + (healthRecovery?.budgetMs ?? 0); let health = await cachedRemoteDaemonHealth( - remoteInfo, + info, + stateDir, healthRecovery?.budgetMs, healthRecovery?.signal, ); @@ -284,17 +309,15 @@ async function ensureRemoteDaemon( // Loaded on the refusal: this module is not part of what every CLI start pays for. const { recoverRemoteDaemonHealth } = await import('./daemon-client-remote-health-recovery.ts'); health = await recoverRemoteDaemonHealth({ - info: remoteInfo, + info, + stateDir, failedProbe: health, recovery: healthRecovery, deadline, hint: 'Fix or unset --daemon-base-url or AGENT_DEVICE_DAEMON_BASE_URL so the client targets a reachable daemon or the local one. If this CLI was connected with connect proxy, run agent-device disconnect to clear the saved connection and return to the local daemon.', }); } - remoteInfo.capabilities = (health.upstream ?? health).capabilities; - remoteInfo.remoteInstanceId = health.instanceId; - remoteInfo.remoteUpstreamInstanceId = health.upstream?.instanceId; - return { info: remoteInfo, startedByClient: false }; + applyRemoteDaemonHealth(info, health); } /** diff --git a/packages/daemon-client/src/daemon-client-metadata.ts b/packages/daemon-client/src/daemon-client-metadata.ts index f4eecf9f5b..6bde7e5548 100644 --- a/packages/daemon-client/src/daemon-client-metadata.ts +++ b/packages/daemon-client/src/daemon-client-metadata.ts @@ -40,6 +40,11 @@ export type DaemonInfo = { baseUrl?: string; remoteInstanceId?: string; remoteUpstreamInstanceId?: string; + /** + * The remote fields above came from a cached `/health` answer, so no probe ran for this command. A + * send that fails before it leaves this process then opens the `/health` gate and resends once. + */ + remoteHealthCached?: true; }; /** Why a daemon is not the one this client would use. `transport` means alive but not on the diff --git a/packages/daemon-client/src/daemon-client-remote-health-cache.ts b/packages/daemon-client/src/daemon-client-remote-health-cache.ts index 72c1b10334..5f9e39359b 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -1,5 +1,10 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { publishFileSync } from '@agent-device/host-kit/file'; +import { readVersion } from '@agent-device/host-kit/version'; import type { DaemonInfo } from './daemon-client-metadata.ts'; -import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; +import { readRemoteHealthRecord, type RemoteDaemonHealth } from './daemon-client-health-record.ts'; /** A settled `/health` answer for one daemon identity. Only usable answers are cached. */ type RemoteHealthCacheEntry = { @@ -13,6 +18,15 @@ let remoteHealthCache: RemoteHealthCacheEntry | undefined; /** Bumped by every invalidation, so a probe that started before one cannot cache its answer. */ let remoteHealthGeneration = 0; +/** + * The state-directory copy of the cache, so a CLI process does not pay a `/health` round trip that + * an earlier process already made. Safe to reuse because every RPC sent from it carries the cached + * instance preconditions: a replaced daemon or proxy upstream answers 409 before it dispatches, and + * the client probes again. The file names its daemon by a digest of client version, base URL and + * token, so it never holds the token or URL, and a client upgrade or token change reads as a miss. + */ +const PERSISTED_HEALTH_FILE = 'remote-daemon-health.json'; + function matchesRemoteIdentity(entry: RemoteHealthCacheEntry, info: DaemonInfo): boolean { return entry.baseUrl === info.baseUrl && entry.token === info.token && entry.pid === info.pid; } @@ -23,7 +37,64 @@ function isCacheableRemoteHealth(health: RemoteDaemonHealth): boolean { ); } -export function cacheRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHealth): void { +function persistedIdentity(info: DaemonInfo): string { + return crypto + .createHash('sha256') + .update(JSON.stringify([readVersion(), info.baseUrl ?? '', info.token, info.pid])) + .digest('hex'); +} + +function persistedHealthPath(stateDir: string): string { + return path.join(stateDir, PERSISTED_HEALTH_FILE); +} + +function readPersistedEntry(stateDir: string): { identity: unknown; health: unknown } | null { + try { + const parsed: unknown = JSON.parse(fs.readFileSync(persistedHealthPath(stateDir), 'utf8')); + return parsed && typeof parsed === 'object' + ? (parsed as { identity: unknown; health: unknown }) + : null; + } catch { + return null; + } +} + +function readPersistedHealth(info: DaemonInfo, stateDir: string): RemoteDaemonHealth | undefined { + const persisted = readPersistedEntry(stateDir); + if (!persisted || persisted.identity !== persistedIdentity(info)) return undefined; + const health: RemoteDaemonHealth = { + reachable: true, + ...readRemoteHealthRecord(persisted.health), + }; + return isCacheableRemoteHealth(health) ? health : undefined; +} + +// The cache only saves a round trip, so a state directory it cannot write or remove from leaves the +// command to the next probe rather than failing it. +function persistHealth(info: DaemonInfo, health: RemoteDaemonHealth, stateDir: string): void { + const entry = { identity: persistedIdentity(info), health: readRemoteHealthRecord(health) }; + try { + fs.mkdirSync(stateDir, { recursive: true }); + publishFileSync({ + destination: persistedHealthPath(stateDir), + contents: `${JSON.stringify(entry)}\n`, + mode: 0o600, + }); + } catch {} +} + +function removePersistedHealth(info: DaemonInfo, stateDir: string): void { + if (readPersistedEntry(stateDir)?.identity !== persistedIdentity(info)) return; + try { + fs.rmSync(persistedHealthPath(stateDir), { force: true }); + } catch {} +} + +export function cacheRemoteDaemonHealth( + info: DaemonInfo, + health: RemoteDaemonHealth, + stateDir?: string, +): void { if (!isCacheableRemoteHealth(health)) return; remoteHealthCache = { baseUrl: info.baseUrl ?? '', @@ -31,13 +102,28 @@ export function cacheRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHe pid: info.pid, health, }; + if (stateDir) persistHealth(info, health, stateDir); } -export function invalidateRemoteDaemonHealth(info: DaemonInfo): void { +export function invalidateRemoteDaemonHealth(info: DaemonInfo, stateDir?: string): void { remoteHealthGeneration += 1; if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) { remoteHealthCache = undefined; } + if (stateDir) removePersistedHealth(info, stateDir); +} + +/** The cached answer for this daemon, from this process or from `stateDir`, without probing. */ +export function readCachedRemoteHealth( + info: DaemonInfo, + stateDir?: string, +): RemoteDaemonHealth | undefined { + if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) { + return remoteHealthCache.health; + } + const persisted = stateDir ? readPersistedHealth(info, stateDir) : undefined; + if (persisted) cacheRemoteDaemonHealth(info, persisted); + return persisted; } /** @@ -47,12 +133,12 @@ export function invalidateRemoteDaemonHealth(info: DaemonInfo): void { export async function cachedRemoteHealth( info: DaemonInfo, probe: () => Promise, + stateDir?: string, ): Promise { - if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) { - return remoteHealthCache.health; - } + const cached = readCachedRemoteHealth(info, stateDir); + if (cached) return cached; const generation = remoteHealthGeneration; const health = await probe(); - if (generation === remoteHealthGeneration) cacheRemoteDaemonHealth(info, health); + if (generation === remoteHealthGeneration) cacheRemoteDaemonHealth(info, health, stateDir); return health; } diff --git a/packages/daemon-client/src/daemon-client-remote-health-recovery.ts b/packages/daemon-client/src/daemon-client-remote-health-recovery.ts index 658541eeaa..c002d5fc8c 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-recovery.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-recovery.ts @@ -1,7 +1,8 @@ import { sleep } from '@agent-device/host-kit/retry'; import type { RemoteHealthRecovery } from './daemon-client-lifecycle.ts'; import type { DaemonInfo } from './daemon-client-metadata.ts'; -import { cachedRemoteDaemonHealth, type RemoteDaemonHealth } from './daemon-client-transport.ts'; +import type { RemoteDaemonHealth } from './daemon-client-health-record.ts'; +import { cachedRemoteDaemonHealth } from './daemon-client-transport.ts'; import { remoteDaemonUnavailableError } from './daemon-lifecycle-errors.ts'; /** The pause between `/health` probes while a remote daemon is unavailable. */ @@ -26,13 +27,15 @@ function isTransientHealthFailure(health: RemoteDaemonHealth): boolean { */ export async function recoverRemoteDaemonHealth(params: { info: DaemonInfo; + /** Where a recovered answer is cached for later commands. */ + stateDir: string; failedProbe: RemoteDaemonHealth; recovery: RemoteHealthRecovery | undefined; /** When the command's budget ends, on the `performance.now()` clock: it started with the first probe. */ deadline: number; hint: string; }): Promise { - const { info, recovery, deadline, hint } = params; + const { info, stateDir, recovery, deadline, hint } = params; let attempts = 1; let probe = params.failedProbe; while (recovery && isTransientHealthFailure(probe) && !recovery.signal?.aborted) { @@ -49,7 +52,7 @@ export async function recoverRemoteDaemonHealth(params: { const probeMs = deadline - performance.now(); if (probeMs <= 0 || recovery.signal?.aborted) continue; attempts += 1; - probe = await cachedRemoteDaemonHealth(info, probeMs, recovery.signal); + probe = await cachedRemoteDaemonHealth(info, stateDir, probeMs, recovery.signal); if (probe.reachable) return probe; } throw remoteDaemonUnavailableError({ daemonBaseUrl: info.baseUrl, attempts, hint }); diff --git a/packages/daemon-client/src/daemon-client-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index 142f26019b..40ca381929 100644 --- a/packages/daemon-client/src/daemon-client-timeout.ts +++ b/packages/daemon-client/src/daemon-client-timeout.ts @@ -8,7 +8,7 @@ import type { DaemonPaths } from '@agent-device/daemon-contracts/daemon-resoluti 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'; -import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; +import type { RemoteDaemonHealth } from './daemon-client-health-record.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 diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 397cea0767..f7de17be5c 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -7,7 +7,6 @@ import { loadNodeHttpRequester, readNodeHttpResponseBody } from '@agent-device/h import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { assertScriptArtifactsCapability, - readDaemonCapabilities, type DaemonPaths, type DaemonTransportPreference, } from '@agent-device/daemon-contracts/daemon-resolution'; @@ -24,9 +23,14 @@ import { DAEMON_INSTANCE_REASONS, DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER, DAEMON_RPC_PROTOCOL_VERSION, - type DaemonHealthPayload, } from '@agent-device/contracts/daemon-http'; import { DAEMON_TRANSPORT_REASONS } from './daemon-client-transport-reasons.ts'; +import { + applyRemoteDaemonHealth, + readHealthPayload, + type RemoteDaemonHealth, + type RemoteDaemonHealthLink, +} from './daemon-client-health-record.ts'; import { buildHttpRpcPayload, handleDaemonHttpResponseBody, @@ -170,26 +174,6 @@ function daemonEndpointUnavailableError(transport: ResolvedDaemonTransport): App ); } -export type RemoteDaemonHealth = { - reachable: boolean; - statusCode?: number; - service?: string; - version?: string; - rpcProtocolVersion?: number; - instanceId?: string; - hostArch?: string; - capabilities?: DaemonInfo['capabilities']; - /** The daemon behind a proxy, as the proxy's health reported it. */ - upstream?: RemoteDaemonHealthLink; - /** The probe ran out of its time budget before an answer, rather than failing outright. */ - timedOut?: true; -}; - -type RemoteDaemonHealthLink = Pick< - RemoteDaemonHealth, - 'service' | 'version' | 'rpcProtocolVersion' | 'instanceId' | 'hostArch' | 'capabilities' ->; - export async function probeDaemonReachability( info: DaemonInfo, preference: DaemonTransportPreference, @@ -350,57 +334,6 @@ function healthProbeExpired(signal: AbortSignal, deadline: number): boolean { return signal.aborted || performance.now() >= deadline; } -function readHealthPayload(body: string): Omit { - try { - const parsed = JSON.parse(body) as { upstream?: unknown }; - const upstream = - parsed.upstream && typeof parsed.upstream === 'object' - ? readHealthLink(parsed.upstream as Record) - : undefined; - return { - ...readHealthLink(parsed as Record), - ...(upstream ? { upstream } : {}), - }; - } catch { - return {}; - } -} - -function readHealthLink(parsed: Record): RemoteDaemonHealthLink { - return { - service: isHealthService(parsed.service) ? parsed.service : undefined, - version: readHealthVersion(parsed.version), - rpcProtocolVersion: - typeof parsed.rpcProtocolVersion === 'number' ? parsed.rpcProtocolVersion : undefined, - ...(typeof parsed.instanceId === 'string' ? { instanceId: parsed.instanceId } : {}), - ...(typeof parsed.hostArch === 'string' ? { hostArch: parsed.hostArch } : {}), - ...(parsed.capabilities === undefined - ? {} - : { capabilities: readDaemonCapabilities(parsed.capabilities) }), - }; -} - -// The remote picks what /health says and agents read the refusal built from it, so only a service -// the contract names and a version-shaped string are kept; anything else reads as absent. -const HEALTH_SERVICES: Readonly> = { - 'agent-device-daemon': true, - 'agent-device-proxy': true, -}; -const HEALTH_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; -const HEALTH_VERSION_MAX_LENGTH = 64; - -function isHealthService(value: unknown): value is DaemonHealthPayload['service'] { - return typeof value === 'string' && Object.hasOwn(HEALTH_SERVICES, value); -} - -function readHealthVersion(value: unknown): string | undefined { - return typeof value === 'string' && - value.length <= HEALTH_VERSION_MAX_LENGTH && - HEALTH_VERSION.test(value) - ? value - : undefined; -} - export async function sendRequest( info: DaemonInfo, req: DaemonWireRequest, @@ -507,7 +440,19 @@ async function sendRequestWithFallback( options, ); } - if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); + if (isRemoteTransportFailure(error)) { + await invalidateRemoteDaemonHealth(info, statePaths.baseDir); + } + if (info.baseUrl && info.remoteHealthCached && isUnsentTransportFailure(error)) { + return await resendAfterRemoteHealthGate( + info, + req, + statePaths, + timeoutMs, + transport, + options, + ); + } const fallback = chooseAutoFallbackTransport(info, preference, transport); if (!fallback || !isSafeAutoTransportFallbackError(error, transport)) throw error; return await sendRequestWithTransport(info, req, statePaths, timeoutMs, fallback, options); @@ -523,7 +468,7 @@ async function retryAfterRemoteInstanceMismatch( transport: ResolvedDaemonTransport, options: SendRequestOptions, ): Promise { - await invalidateRemoteDaemonHealth(info); + await invalidateRemoteDaemonHealth(info, statePaths.baseDir); const probeTimeoutMs = remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline); const health = await readRemoteDaemonHealth(info, probeTimeoutMs, options.signal); refuseAbortedRequest(options.signal, req.meta?.requestId); @@ -537,20 +482,63 @@ async function retryAfterRemoteInstanceMismatch( const { remoteDaemonUnavailableError } = await import('./daemon-lifecycle-errors.ts'); throw remoteDaemonUnavailableError({ daemonBaseUrl: info.baseUrl, attempts: 1 }); } - info.remoteInstanceId = health.instanceId; - info.remoteUpstreamInstanceId = health.upstream?.instanceId; - info.capabilities = (health.upstream ?? health).capabilities; - (await loadRemoteHealthCache()).cacheRemoteDaemonHealth(info, health); + applyRemoteDaemonHealth(info, health); + (await loadRemoteHealthCache()).cacheRemoteDaemonHealth(info, health, statePaths.baseDir); + return await resendAfterFreshRemoteHealth(info, req, statePaths, remainingMs, transport, options); +} + +/** + * A send from a cached `/health` answer that never left this process (refused, reset, no such host) + * proves nothing reached the daemon, so it gets the gate the cache skipped: the same probe, re-probe + * budget and typed refusal as a first contact, then one resend under the command's full budget. + */ +async function resendAfterRemoteHealthGate( + info: DaemonInfo, + req: DaemonWireRequest, + statePaths: DaemonPaths, + timeoutMs: number | undefined, + transport: ResolvedDaemonTransport, + options: SendRequestOptions, +): Promise { + info.remoteHealthCached = undefined; + const { openRemoteHealthGate } = await import('./daemon-client-lifecycle.ts'); + await openRemoteHealthGate( + info, + statePaths.baseDir, + timeoutMs === undefined ? undefined : { budgetMs: timeoutMs, signal: options.signal }, + ); + refuseAbortedRequest(options.signal, req.meta?.requestId); + return await resendAfterFreshRemoteHealth(info, req, statePaths, timeoutMs, transport, options); +} + +async function resendAfterFreshRemoteHealth( + info: DaemonInfo, + req: DaemonWireRequest, + statePaths: DaemonPaths, + timeoutMs: number | undefined, + transport: ResolvedDaemonTransport, + options: SendRequestOptions, +): Promise { // A replacement daemon must still deliver the script that a remote recording asks for. if (req.meta?.scriptPublicationId) assertScriptArtifactsCapability(info.capabilities); try { - return await sendRequestWithTransport(info, req, statePaths, remainingMs, transport, options); + return await sendRequestWithTransport(info, req, statePaths, timeoutMs, transport, options); } catch (error) { - if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); + if (isRemoteTransportFailure(error)) { + await invalidateRemoteDaemonHealth(info, statePaths.baseDir); + } throw error; } } +function isUnsentTransportFailure(error: unknown): boolean { + return ( + error instanceof AppError && + error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason && + error.details.daemonRequestSent === false + ); +} + function remainingRemoteRequestTimeoutMs( req: DaemonWireRequest, timeoutMs: number | undefined, @@ -575,12 +563,15 @@ function isRemoteInstanceMismatch(error: unknown): boolean { ); } +// A reply that is not the daemon's JSON-RPC came from something else on the path, such as a gateway +// answering 5xx while the daemon is away, so the next command probes `/health` again. function isRemoteTransportFailure(error: unknown): boolean { return ( error instanceof AppError && (error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason || error.details?.reason === DAEMON_TRANSPORT_REASONS.timeout.reason || - error.details?.reason === DAEMON_TRANSPORT_REASONS.replyUnreadable.reason) + error.details?.reason === DAEMON_TRANSPORT_REASONS.replyUnreadable.reason || + error.details?.reason === DAEMON_TRANSPORT_REASONS.replyInvalid.reason) ); } @@ -640,12 +631,7 @@ function isSafeAutoTransportFallbackError( error: unknown, attempted: ResolvedDaemonTransport, ): boolean { - return ( - attempted === 'socket' && - error instanceof AppError && - error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason && - error.details.daemonRequestSent === false - ); + return attempted === 'socket' && isUnsentTransportFailure(error); } function requireDaemonTransport( @@ -971,19 +957,30 @@ async function sendHttpRequest( const loadRemoteHealthCache = () => import('./daemon-client-remote-health-cache.ts'); /** Drops a remote daemon's cached health; a local daemon has none, so its failure loads nothing. */ -async function invalidateRemoteDaemonHealth(info: DaemonInfo): Promise { +async function invalidateRemoteDaemonHealth(info: DaemonInfo, stateDir: string): Promise { if (!info.baseUrl) return; - (await loadRemoteHealthCache()).invalidateRemoteDaemonHealth(info); + (await loadRemoteHealthCache()).invalidateRemoteDaemonHealth(info, stateDir); } -/** The remote `/health` answer within this caller's bound, through the process cache. */ +/** A remote daemon's cached `/health` answer, from this process or the state directory, if any. */ +export async function readCachedRemoteDaemonHealth( + info: DaemonInfo, + stateDir: string, +): Promise { + return (await loadRemoteHealthCache()).readCachedRemoteHealth(info, stateDir); +} + +/** The remote `/health` answer within this caller's bound, through the cache. */ export async function cachedRemoteDaemonHealth( info: DaemonInfo, + stateDir: string, probeTimeoutMs?: number, callerSignal?: AbortSignal, ): Promise { const { cachedRemoteHealth } = await loadRemoteHealthCache(); - return await cachedRemoteHealth(info, () => - readRemoteDaemonHealth(info, probeTimeoutMs, callerSignal), + return await cachedRemoteHealth( + info, + () => readRemoteDaemonHealth(info, probeTimeoutMs, callerSignal), + stateDir, ); } diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 8685cee553..0628b1637d 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -361,7 +361,7 @@ for the API. ## Compatibility -Remote clients read `/health` before sending commands and compare the daemon RPC protocol version. Keep client and proxy versions close: patch-level differences usually work, and incompatible RPC protocol versions fail before any command runs. +Remote clients read `/health` before the first command to a daemon instance and compare the daemon RPC protocol version. The answer is cached in the client state directory, so later commands go straight to `/rpc` until the daemon or proxy instance changes. Keep client and proxy versions close: patch-level differences usually work, and incompatible RPC protocol versions fail before any command runs. `/health` also reports `hostArch`, the native CPU architecture of the machine serving it: the one its simulators run by default, even when Node itself runs under Rosetta. Macs report `arm64` or `x86_64`; other hosts report `x86_64` for x64 and Node's `process.arch` name otherwise (for example `arm64`). The top-level value describes the proxy's own machine, so a client behind a proxy reads `upstream.hostArch` for the host that runs the simulators, for example to build only that slice of a simulator app. Older daemons omit the field. `leaseBackends` lists the lease backends the daemon admits (`macos-app` only on a macOS host); a host checks `upstream.leaseBackends` for `macos-app` before handing out a macOS app lease, and older From 35e9b6811e93fd3560df31b27091914a2362fa88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 21:29:58 +0100 Subject: [PATCH 02/10] fix(daemon-client): harden the persisted remote health cache - Resend after an unsent cached RPC only on evidence the client's own transport recorded before the connection opened, never on reply details. The gate and resend share the command's remaining budget, and a caller abort during the gate stays request_canceled. - Read the persisted entry only from a bounded regular file the user owns that nobody else can write; links and FIFOs read as a miss. - Clear the cache on any remote 5xx. A timeout clears it only when the timeout route's probe finds the daemon gone or replaced. - Probe /health again before refusing a recording for a capability only the cached answer lacks. - Keep the /health wire declarations in transport (wire-compat), move the request guard and the health gate out of it, and drop the transport -> lifecycle import cycle. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0006-daemon-rpc-protocol-version.md | 16 +- ...mon-client-lifecycle-remote-health.test.ts | 2 +- .../daemon-client-remote-health-cache.test.ts | 85 ++- ...mon-client-transport-request-guard.test.ts | 2 +- .../__tests__/daemon-client-transport.test.ts | 119 +++- .../__tests__/index-script-capability.test.ts | 40 ++ .../src/daemon-client-health-record.ts | 86 --- .../src/daemon-client-lifecycle.ts | 49 +- .../src/daemon-client-metadata.ts | 5 - .../src/daemon-client-remote-health-cache.ts | 78 ++- .../src/daemon-client-remote-health-gate.ts | 78 +++ .../daemon-client-remote-health-recovery.ts | 11 +- .../src/daemon-client-request-guard.ts | 88 +++ .../src/daemon-client-timeout.ts | 2 +- .../src/daemon-client-transport.ts | 550 +++++++++--------- packages/daemon-client/src/index.ts | 19 +- website/docs/docs/remote-proxy.md | 2 +- 17 files changed, 780 insertions(+), 452 deletions(-) delete mode 100644 packages/daemon-client/src/daemon-client-health-record.ts create mode 100644 packages/daemon-client/src/daemon-client-remote-health-gate.ts create mode 100644 packages/daemon-client/src/daemon-client-request-guard.ts diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index ad5a006a9d..5a7041bd8e 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -11,7 +11,10 @@ Accepted - Allow a missing `rpcProtocolVersion` unless a later security or protocol decision explicitly retires legacy compatibility. - A client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon. - The cache may outlive the client process in the state directory. Name the entry by a digest of the client version, base URL, and token. Do not write the token or the URL. -- If a cached RPC fails before it leaves the client, probe `/health` as on first contact. Then send the RPC once more. +- Read a persisted entry only from a bounded regular file that the current user owns and that nobody else can write. Otherwise, probe `/health`. +- If a cached RPC fails before its connection opens, probe `/health` as on first contact, within the command's remaining budget. Then send the RPC once more. Take this evidence only from the client's own transport, never from a reply. +- Clear the cache on a remote HTTP 5xx. Do not resend the RPC. +- Before you refuse a command for a capability that only the cache lacks, probe `/health` again. - Send those instance IDs as conditional headers on every cached RPC. Peers without complete instance IDs retain per-command probes. - After a stale-instance refusal, clear the cache and probe `/health` again. Retry the refused RPC once, and only if the new peer's protocol is compatible. - A peer that advertises an instance ID must continue to honor the conditional RPC headers in future versions. @@ -53,9 +56,14 @@ The proxy passes the expected upstream instance to the daemon, which makes the s On a mismatch, the client clears the cache and probes `/health` again. The client then retries the refused RPC once, and only if the new peer's protocol is compatible. Peers without complete instance IDs retain per-command probes. -A cached RPC that fails before it leaves the client proves that nothing was dispatched. -The client then clears the cache and probes `/health` as on first contact, with the same recovery budget and typed refusal, and sends the RPC once more. -A cached RPC that fails after it was sent is not resent. The client clears the cache, so the next command probes `/health` first. +The state directory can be shared, so a persisted entry counts only when it is a bounded regular file that the current user owns and that nobody else can write. +A cached RPC whose connection never opened proves that nothing was dispatched. +Only the client's own transport supplies that evidence; a reply can carry the same error details after the command ran. +The client then clears the cache and probes `/health` as on first contact, with the recovery and typed refusal of that path, and sends the RPC once more, all within the command's remaining budget. +A cached RPC that fails after its connection opened is not resent. +A remote HTTP 5xx clears the cache, whatever its framing, because a proxy answers that way while its upstream daemon restarts. +A timeout leaves the decision to the timeout route, which clears the cache only when its `/health` probe finds the daemon gone or replaced. +A capability that only the cached answer lacks is checked against a fresh probe before the client refuses the command, because the daemon may have been upgraded. A peer that advertises an instance ID must continue to honor the conditional RPC headers in future versions. The reason is that older clients may hold a cached identity across a restart. Such clients must receive a pre-dispatch refusal before they retry a mutating command. diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts index 4f81728f6f..1c0fefc2fb 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts @@ -16,7 +16,7 @@ import { AppError } from '@agent-device/kernel/errors'; import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; import { DAEMON_UNAVAILABLE_REASONS } from '../daemon-lifecycle-errors.ts'; import { sendToDaemon } from '../index.ts'; -import { cachedRemoteDaemonHealth } from '../daemon-client-transport.ts'; +import { cachedRemoteDaemonHealth } from '../daemon-client-remote-health-gate.ts'; // A press, so the refusal states the fact a caller needs before resending a mutating command. function remotePress(baseUrl: string) { diff --git a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts index 32abef4fcb..db438a8c38 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts @@ -1,7 +1,8 @@ import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { cacheRemoteDaemonHealth, @@ -9,7 +10,16 @@ import { invalidateRemoteDaemonHealth, readCachedRemoteHealth, } from '../daemon-client-remote-health-cache.ts'; -import type { RemoteDaemonHealth } from '../daemon-client-health-record.ts'; +import { + readCachedRemoteHealthRecord, + type RemoteDaemonHealth, +} from '../daemon-client-transport.ts'; + +const clientVersion = vi.hoisted(() => ({ current: '1.0.0' })); +vi.mock('@agent-device/host-kit/version', async (importOriginal) => ({ + ...(await importOriginal()), + readVersion: () => clientVersion.current, +})); const HEALTHY: RemoteDaemonHealth = { reachable: true, instanceId: 'remote-instance' }; @@ -41,33 +51,76 @@ test('a probe answer that lands after an invalidation is not cached', async () = assert.equal(probes, 1); }); -// The state dir holds one answer named by a digest of the daemon identity. A different token or URL, -// an unusable answer, or an unreadable file reads as a miss, so the caller probes. -test('persisted health is reused only for the identity that cached it', () => { +// The state dir holds one answer named by a digest of client version, URL and token. It holds neither +// secret, and any other identity, an unusable answer or an unreadable file reads as a miss. +test('persisted health is private and reused only by the identity that cached it', () => { const stateDir = mkdtempForTestSync('agent-device-remote-health-store-'); + const store = { stateDir, readRecord: readCachedRemoteHealthRecord }; const file = path.join(stateDir, 'remote-daemon-health.json'); - const info = { baseUrl: 'http://remote.example.test:7777', token: 'store-test', pid: 0 }; - const other = { ...info, token: 'other-token' }; + const info = { baseUrl: 'http://remote.example.test:7777', token: 'store-secret', pid: 0 }; const forget = () => invalidateRemoteDaemonHealth(info); + const reuse = (identity: typeof info) => { + forget(); + return readCachedRemoteHealth(identity, store); + }; cacheRemoteDaemonHealth(info, { reachable: true }, stateDir); assert.equal(fs.existsSync(file), false, 'an answer without an instance is not persisted'); cacheRemoteDaemonHealth(info, { ...HEALTHY, statusCode: 200, timedOut: true }, stateDir); - forget(); - const reused = readCachedRemoteHealth(info, stateDir); - assert.equal(reused?.reachable, true); + const written = fs.readFileSync(file, 'utf8'); + assert.equal(written.includes('store-secret'), false, 'the token is never written'); + assert.equal(written.includes('remote.example.test'), false, 'the URL is never written'); + assert.equal(fs.statSync(file).mode & 0o777, 0o600); + const reused = reuse(info); assert.equal(reused?.instanceId, HEALTHY.instanceId); assert.equal(reused?.statusCode, undefined, 'only the record is persisted'); - assert.equal(reused?.timedOut, undefined); - forget(); - assert.equal(readCachedRemoteHealth(other, stateDir), undefined); - invalidateRemoteDaemonHealth(other, stateDir); + assert.equal(reuse({ ...info, token: 'other-token' }), undefined); + assert.equal(reuse({ ...info, baseUrl: 'http://other.example.test:7777' }), undefined); + clientVersion.current = '9.9.9'; + assert.equal(reuse(info), undefined, 'a client upgrade probes again'); + clientVersion.current = '1.0.0'; + + invalidateRemoteDaemonHealth({ ...info, token: 'other-token' }, stateDir); assert.equal(fs.existsSync(file), true, 'another identity leaves the entry alone'); invalidateRemoteDaemonHealth(info, stateDir); assert.equal(fs.existsSync(file), false); +}); + +// A shared state dir may hold an entry another user planted. Only a regular file this user owns and +// nobody else can write counts; anything else is a miss, and a FIFO does not block the read. +test.skipIf(process.platform === 'win32')('a planted persisted entry reads as a miss', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-health-planted-'); + const store = { stateDir, readRecord: readCachedRemoteHealthRecord }; + const file = path.join(stateDir, 'remote-daemon-health.json'); + const info = { baseUrl: 'http://remote.example.test:7777', token: 'planted', pid: 0 }; + cacheRemoteDaemonHealth(info, HEALTHY, stateDir); + const entry = fs.readFileSync(file); + const reuse = () => { + invalidateRemoteDaemonHealth(info); + return readCachedRemoteHealth(info, store); + }; + assert.equal( + reuse()?.instanceId, + HEALTHY.instanceId, + 'the closest negative: our own entry counts', + ); + + fs.chmodSync(file, 0o620); + assert.equal(reuse(), undefined, 'a group-writable entry'); + + const elsewhere = path.join(stateDir, 'elsewhere.json'); + fs.writeFileSync(elsewhere, entry, { mode: 0o600 }); + fs.rmSync(file); + fs.symlinkSync(elsewhere, file); + assert.equal(reuse(), undefined, 'a link'); + + fs.rmSync(file); + execFileSync('mkfifo', [file]); + assert.equal(reuse(), undefined, 'a FIFO'); - fs.writeFileSync(file, '{not json'); - assert.equal(readCachedRemoteHealth(info, stateDir), undefined); + fs.rmSync(file); + fs.writeFileSync(file, '{not json', { mode: 0o600 }); + assert.equal(reuse(), undefined, 'an unreadable entry'); }); diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport-request-guard.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-request-guard.test.ts index 2746df91ca..fea708d7ae 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport-request-guard.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport-request-guard.test.ts @@ -9,7 +9,7 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; import { isRequestCanceledError } from '@agent-device/kernel/errors'; -import { createRequestGuard } from '../daemon-client-transport.ts'; +import { createRequestGuard } from '../daemon-client-request-guard.ts'; function canceledOutcome(promise: Promise): Promise { return promise.then( 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 d5edec307d..d1dfd694c5 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -668,7 +668,12 @@ test.for(['timeout', 'reset'] as const)( ); /** A remote daemon that answers /health with `instanceId()` and refuses a stale instance with 409. */ -async function instanceCheckingRemote(instanceId: () => string) { +type RpcAnswer = { status: number; body: unknown }; + +async function instanceCheckingRemote( + instanceId: () => string, + rpcAnswer: () => RpcAnswer | undefined = () => undefined, +) { const paths: string[] = []; const server = http.createServer((req, res) => { paths.push(`${req.method} ${req.url}`); @@ -686,7 +691,12 @@ async function instanceCheckingRemote(instanceId: () => string) { res.end(JSON.stringify({ jsonrpc: '2.0', id: 'request', error: { code: -32001 } })); return; } - res.end(JSON.stringify({ jsonrpc: '2.0', id: 'request', result: { ok: true, data: {} } })); + const answer = rpcAnswer() ?? { + status: 200, + body: { jsonrpc: '2.0', id: 'request', result: { ok: true, data: {} } }, + }; + res.statusCode = answer.status; + res.end(JSON.stringify(answer.body)); }); const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; const stateDir = mkdtempForTestSync('agent-device-remote-health-persisted-'); @@ -756,6 +766,111 @@ test('an unsent request from cached remote health opens the health gate', async assert.equal(fs.existsSync(remote.cacheFile), false, 'the unreachable daemon is forgotten'); }); +// Resend evidence is only what this process saw: a daemon error that carries the transport-failure +// reason and `daemonRequestSent: false` came over the wire, so the request ran and is not resent. +test('a daemon error that claims the request was unsent is not resent', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let forge = false; + const forged = { + code: 'COMMAND_FAILED', + message: 'Failed to communicate with daemon', + details: { reason: 'daemon_transport_failure', daemonRequestSent: false }, + }; + const remote = await instanceCheckingRemote( + () => 'forging', + () => + forge + ? { + status: 200, + body: { jsonrpc: '2.0', id: 'request', error: { code: -32000, data: forged } }, + } + : undefined, + ); + try { + assert.equal((await remote.request()).ok, true); + remote.forgetInMemory(); + forge = true; + await assert.rejects(remote.request()); + assert.deepEqual(remote.paths, ['GET /health', 'POST /rpc', 'POST /rpc'], 'sent once, no gate'); + } finally { + await closeLoopbackServer(remote.server); + } +}); + +// A 5xx means the daemon or a hop before it failed, even in valid JSON-RPC framing (a proxy whose +// upstream is restarting answers that way), so the next command probes again. Nothing is resent. +test('a remote 5xx drops the persisted health without a resend', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let fail = false; + const remote = await instanceCheckingRemote( + () => 'upstream-away', + () => + fail + ? { + status: 500, + body: { jsonrpc: '2.0', id: 'request', error: { code: -32000, message: 'upstream' } }, + } + : undefined, + ); + try { + assert.equal((await remote.request()).ok, true); + fail = true; + remote.forgetInMemory(); + await assert.rejects(remote.request()); + assert.equal(fs.existsSync(remote.cacheFile), false); + fail = false; + assert.equal((await remote.request()).ok, true); + assert.deepEqual(remote.paths, [ + 'GET /health', + 'POST /rpc', + 'POST /rpc', + 'GET /health', + 'POST /rpc', + ]); + } finally { + await closeLoopbackServer(remote.server); + } +}); + +// The gate a cached answer skipped runs within what is left of the command's budget, and a caller +// abort while it runs stays the typed cancellation rather than reading as an unreachable daemon. +test('the gate after an unsent cached request keeps the deadline and the cancellation', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const closed = http.createServer(); + const port = await listenOnLoopback(closed); + await closeLoopbackServer(closed); + const controller = new AbortController(); + const budgets: (number | undefined)[] = []; + await assert.rejects( + sendRequest( + { token: 'secret', pid: 0, baseUrl: `http://127.0.0.1:${port}` }, + { token: 'secret', command: 'press', session: 'default', positionals: ['@e1'], flags: {} }, + 'http', + resolveDaemonPaths(mkdtempForTestSync('agent-device-remote-gate-abort-')), + 5_000, + { + host: createTestHostEnvironment(), + signal: controller.signal, + remoteHealthGate: async (budgetMs) => { + budgets.push(budgetMs); + controller.abort(); + throw new AppError('COMMAND_FAILED', 'Remote daemon is unavailable', { + reason: DAEMON_UNAVAILABLE_REASONS.remoteUnavailable.reason, + }); + }, + }, + ), + (error: unknown) => { + assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); + assert.equal(error.details?.reason, 'request_canceled'); + assert.equal(error.details?.dispatched, 'no'); + return true; + }, + ); + assert.equal(budgets.length, 1); + assert.ok(budgets[0]! > 0 && budgets[0]! <= 5_000, `gate budget ${budgets[0]}`); +}); + // A transport failure drops the cached health of a remote daemon only: a local daemon has no cached // health, so its failed request neither invalidates nor loads the remote health cache. test('a transport failure invalidates cached health for a remote daemon only', async (t) => { diff --git a/packages/daemon-client/src/__tests__/index-script-capability.test.ts b/packages/daemon-client/src/__tests__/index-script-capability.test.ts index 8b39250017..115d0b5dc9 100644 --- a/packages/daemon-client/src/__tests__/index-script-capability.test.ts +++ b/packages/daemon-client/src/__tests__/index-script-capability.test.ts @@ -101,3 +101,43 @@ test('a remote recording is not resent to a replacement daemon that cannot deliv await closeLoopbackServer(server); } }); + +// A cached answer can predate a daemon upgrade, so a capability it lacks is checked against a fresh +// `/health` before the recording is refused. The open is sent once, to the upgraded daemon. +test('a capability missing only from cached health is refreshed before refusal', async () => { + let upgraded = false; + const paths: string[] = []; + const server = http.createServer((req, res) => { + paths.push(`${req.method} ${req.url}`); + res.setHeader('content-type', 'application/json'); + if (req.url === '/health') { + const health = upgraded + ? { instanceId: 'upgraded', capabilities: ['script-artifacts'] } + : { instanceId: 'legacy' }; + res.end(JSON.stringify({ ok: true, ...health })); + return; + } + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'test', result: { ok: true, data: {} } })); + }); + const root = mkdtempForTestSync('script-capability-refresh-'); + try { + const daemonBaseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const stateDir = path.join(root, 'state'); + const open = (saveScript?: string) => + sendToDaemon( + { + command: 'open', + session: 'owned', + positionals: ['Demo'], + flags: { daemonBaseUrl, stateDir, ...(saveScript ? { saveScript } : {}) }, + }, + { authToken: 'test' }, + ); + await expect(open()).resolves.toMatchObject({ ok: true }); + upgraded = true; + await expect(open(path.join(root, 'journey.ad'))).resolves.toMatchObject({ ok: true }); + expect(paths).toEqual(['GET /health', 'POST /rpc', 'GET /health', 'POST /rpc']); + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon-client/src/daemon-client-health-record.ts b/packages/daemon-client/src/daemon-client-health-record.ts deleted file mode 100644 index 4d4c8cf9e7..0000000000 --- a/packages/daemon-client/src/daemon-client-health-record.ts +++ /dev/null @@ -1,86 +0,0 @@ -import type { DaemonHealthPayload } from '@agent-device/contracts/daemon-http'; -import { readDaemonCapabilities } from '@agent-device/daemon-contracts/daemon-resolution'; -import type { DaemonInfo } from './daemon-client-metadata.ts'; - -export type RemoteDaemonHealth = { - reachable: boolean; - statusCode?: number; - service?: string; - version?: string; - rpcProtocolVersion?: number; - instanceId?: string; - hostArch?: string; - capabilities?: DaemonInfo['capabilities']; - /** The daemon behind a proxy, as the proxy's health reported it. */ - upstream?: RemoteDaemonHealthLink; - /** The probe ran out of its time budget before an answer, rather than failing outright. */ - timedOut?: true; -}; - -export type RemoteDaemonHealthLink = Pick< - RemoteDaemonHealth, - 'service' | 'version' | 'rpcProtocolVersion' | 'instanceId' | 'hostArch' | 'capabilities' ->; - -type RemoteHealthRecord = Omit; - -export function readHealthPayload(body: string): RemoteHealthRecord { - try { - return readRemoteHealthRecord(JSON.parse(body)); - } catch { - return {}; - } -} - -/** The contract fields of a `/health` record, from the daemon or the cache; anything else is absent. */ -export function readRemoteHealthRecord(parsed: unknown): RemoteHealthRecord { - if (!parsed || typeof parsed !== 'object') return {}; - const record = parsed as Record; - const upstream = - record.upstream && typeof record.upstream === 'object' - ? readHealthLink(record.upstream as Record) - : undefined; - return { ...readHealthLink(record), ...(upstream ? { upstream } : {}) }; -} - -function readHealthLink(parsed: Record): RemoteDaemonHealthLink { - return { - service: isHealthService(parsed.service) ? parsed.service : undefined, - version: readHealthVersion(parsed.version), - rpcProtocolVersion: - typeof parsed.rpcProtocolVersion === 'number' ? parsed.rpcProtocolVersion : undefined, - ...(typeof parsed.instanceId === 'string' ? { instanceId: parsed.instanceId } : {}), - ...(typeof parsed.hostArch === 'string' ? { hostArch: parsed.hostArch } : {}), - ...(parsed.capabilities === undefined - ? {} - : { capabilities: readDaemonCapabilities(parsed.capabilities) }), - }; -} - -// The remote picks what /health says and agents read the refusal built from it, so only a service -// the contract names and a version-shaped string are kept; anything else reads as absent. -const HEALTH_SERVICES: Readonly> = { - 'agent-device-daemon': true, - 'agent-device-proxy': true, -}; -const HEALTH_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; -const HEALTH_VERSION_MAX_LENGTH = 64; - -function isHealthService(value: unknown): value is DaemonHealthPayload['service'] { - return typeof value === 'string' && Object.hasOwn(HEALTH_SERVICES, value); -} - -function readHealthVersion(value: unknown): string | undefined { - return typeof value === 'string' && - value.length <= HEALTH_VERSION_MAX_LENGTH && - HEALTH_VERSION.test(value) - ? value - : undefined; -} - -/** Points `info` at the daemon a `/health` answer describes: its instances and capabilities. */ -export function applyRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHealth): void { - info.remoteInstanceId = health.instanceId; - info.remoteUpstreamInstanceId = health.upstream?.instanceId; - info.capabilities = (health.upstream ?? health).capabilities; -} diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index b7db49fe33..3aa3fd940d 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -31,11 +31,11 @@ import type { findUnrecoveredRepairCommitFailure } from '@agent-device/daemon-co import type { DaemonInfo } from './daemon-client-metadata.ts'; import { attachActiveSessionAddressHint } from './daemon-client-address-hints.ts'; import { isRemoteDaemon, observedDaemonIdentityOf } from './daemon-client-metadata.ts'; -import { applyRemoteDaemonHealth } from './daemon-client-health-record.ts'; +import { applyRemoteDaemonHealth } from './daemon-client-transport.ts'; import { - cachedRemoteDaemonHealth, + openRemoteHealthGate, readCachedRemoteDaemonHealth, -} from './daemon-client-transport.ts'; +} from './daemon-client-remote-health-gate.ts'; import { assertDaemonPolicyMatches, readReusableLocalDaemon, @@ -74,6 +74,8 @@ export type DaemonTakeoverNotice = { export type EnsuredDaemon = { info: DaemonInfo; startedByClient: boolean; + /** The remote daemon's `/health` answer came from the cache, so no probe ran for this command. */ + remoteHealthCached?: true; }; /** @@ -279,45 +281,12 @@ async function ensureRemoteDaemon( }; const stateDir = settings.paths.baseDir; const cached = await readCachedRemoteDaemonHealth(remoteInfo, stateDir); - if (cached) { - applyRemoteDaemonHealth(remoteInfo, cached); - remoteInfo.remoteHealthCached = true; - } else { + if (!cached) { await openRemoteHealthGate(remoteInfo, stateDir, healthRecovery); + return { info: remoteInfo, startedByClient: false }; } - return { info: remoteInfo, startedByClient: false }; -} - -/** - * Probes a remote daemon's `/health` before anything is sent to it, re-probing a daemon that is there - * but not ready for the recovery budget, and points `info` at the daemon that answered. - */ -export async function openRemoteHealthGate( - info: DaemonInfo, - stateDir: string, - healthRecovery: RemoteHealthRecovery | undefined, -): Promise { - // The command's budget starts with the first probe, which already runs under it and its signal. - const deadline = performance.now() + (healthRecovery?.budgetMs ?? 0); - let health = await cachedRemoteDaemonHealth( - info, - stateDir, - healthRecovery?.budgetMs, - healthRecovery?.signal, - ); - if (!health.reachable) { - // Loaded on the refusal: this module is not part of what every CLI start pays for. - const { recoverRemoteDaemonHealth } = await import('./daemon-client-remote-health-recovery.ts'); - health = await recoverRemoteDaemonHealth({ - info, - stateDir, - failedProbe: health, - recovery: healthRecovery, - deadline, - hint: 'Fix or unset --daemon-base-url or AGENT_DEVICE_DAEMON_BASE_URL so the client targets a reachable daemon or the local one. If this CLI was connected with connect proxy, run agent-device disconnect to clear the saved connection and return to the local daemon.', - }); - } - applyRemoteDaemonHealth(info, health); + applyRemoteDaemonHealth(remoteInfo, cached); + return { info: remoteInfo, startedByClient: false, remoteHealthCached: true }; } /** diff --git a/packages/daemon-client/src/daemon-client-metadata.ts b/packages/daemon-client/src/daemon-client-metadata.ts index 6bde7e5548..f4eecf9f5b 100644 --- a/packages/daemon-client/src/daemon-client-metadata.ts +++ b/packages/daemon-client/src/daemon-client-metadata.ts @@ -40,11 +40,6 @@ export type DaemonInfo = { baseUrl?: string; remoteInstanceId?: string; remoteUpstreamInstanceId?: string; - /** - * The remote fields above came from a cached `/health` answer, so no probe ran for this command. A - * send that fails before it leaves this process then opens the `/health` gate and resends once. - */ - remoteHealthCached?: true; }; /** Why a daemon is not the one this client would use. `transport` means alive but not on the diff --git a/packages/daemon-client/src/daemon-client-remote-health-cache.ts b/packages/daemon-client/src/daemon-client-remote-health-cache.ts index 5f9e39359b..565287b2ec 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -1,10 +1,16 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; -import { publishFileSync } from '@agent-device/host-kit/file'; +import { openVerifiedFileForRead, publishFileSync } from '@agent-device/host-kit/file'; import { readVersion } from '@agent-device/host-kit/version'; import type { DaemonInfo } from './daemon-client-metadata.ts'; -import { readRemoteHealthRecord, type RemoteDaemonHealth } from './daemon-client-health-record.ts'; +import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; + +/** Where a cached answer persists, and the `/health` contract reader a persisted record passes. */ +type PersistedHealthStore = { + stateDir: string; + readRecord: (record: unknown) => Partial; +}; /** A settled `/health` answer for one daemon identity. Only usable answers are cached. */ type RemoteHealthCacheEntry = { @@ -26,6 +32,7 @@ let remoteHealthGeneration = 0; * token, so it never holds the token or URL, and a client upgrade or token change reads as a miss. */ const PERSISTED_HEALTH_FILE = 'remote-daemon-health.json'; +const PERSISTED_HEALTH_MAX_BYTES = 16 * 1024; function matchesRemoteIdentity(entry: RemoteHealthCacheEntry, info: DaemonInfo): boolean { return entry.baseUrl === info.baseUrl && entry.token === info.token && entry.pid === info.pid; @@ -48,31 +55,64 @@ function persistedHealthPath(stateDir: string): string { return path.join(stateDir, PERSISTED_HEALTH_FILE); } +/** + * The state directory may be shared, so the entry counts only when it is a bounded regular file this + * user owns and nobody else can write. A link, FIFO or other special file reads as a miss without + * blocking, and the caller probes `/health` instead. + */ function readPersistedEntry(stateDir: string): { identity: unknown; health: unknown } | null { try { - const parsed: unknown = JSON.parse(fs.readFileSync(persistedHealthPath(stateDir), 'utf8')); - return parsed && typeof parsed === 'object' - ? (parsed as { identity: unknown; health: unknown }) - : null; + const descriptor = openVerifiedFileForRead(persistedHealthPath(stateDir)); + if (descriptor === undefined) return null; + try { + const stats = fs.fstatSync(descriptor); + if (!isPrivateOwnedFile(stats)) return null; + const buffer = Buffer.alloc(stats.size); + const length = fs.readSync(descriptor, buffer, 0, stats.size, 0); + const parsed: unknown = JSON.parse(buffer.subarray(0, length).toString('utf8')); + return parsed && typeof parsed === 'object' + ? (parsed as { identity: unknown; health: unknown }) + : null; + } finally { + fs.closeSync(descriptor); + } } catch { return null; } } -function readPersistedHealth(info: DaemonInfo, stateDir: string): RemoteDaemonHealth | undefined { - const persisted = readPersistedEntry(stateDir); +// Windows has no POSIX owner or mode bits; its ACLs are out of scope (docs/agents/security.md). +function isPrivateOwnedFile(stats: fs.Stats): boolean { + if (!stats.isFile() || stats.size > PERSISTED_HEALTH_MAX_BYTES) return false; + const uid = process.getuid?.(); + return uid === undefined || (stats.uid === uid && (stats.mode & 0o022) === 0); +} + +function readPersistedHealth( + info: DaemonInfo, + store: PersistedHealthStore, +): RemoteDaemonHealth | undefined { + const persisted = readPersistedEntry(store.stateDir); if (!persisted || persisted.identity !== persistedIdentity(info)) return undefined; - const health: RemoteDaemonHealth = { - reachable: true, - ...readRemoteHealthRecord(persisted.health), - }; + const health: RemoteDaemonHealth = { reachable: true, ...store.readRecord(persisted.health) }; return isCacheableRemoteHealth(health) ? health : undefined; } // The cache only saves a round trip, so a state directory it cannot write or remove from leaves the // command to the next probe rather than failing it. function persistHealth(info: DaemonInfo, health: RemoteDaemonHealth, stateDir: string): void { - const entry = { identity: persistedIdentity(info), health: readRemoteHealthRecord(health) }; + const { service, version, rpcProtocolVersion, instanceId, hostArch, capabilities, upstream } = + health; + const record = { + service, + version, + rpcProtocolVersion, + instanceId, + hostArch, + capabilities, + upstream, + }; + const entry = { identity: persistedIdentity(info), health: record }; try { fs.mkdirSync(stateDir, { recursive: true }); publishFileSync({ @@ -116,12 +156,12 @@ export function invalidateRemoteDaemonHealth(info: DaemonInfo, stateDir?: string /** The cached answer for this daemon, from this process or from `stateDir`, without probing. */ export function readCachedRemoteHealth( info: DaemonInfo, - stateDir?: string, + store?: PersistedHealthStore, ): RemoteDaemonHealth | undefined { if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) { return remoteHealthCache.health; } - const persisted = stateDir ? readPersistedHealth(info, stateDir) : undefined; + const persisted = store ? readPersistedHealth(info, store) : undefined; if (persisted) cacheRemoteDaemonHealth(info, persisted); return persisted; } @@ -133,12 +173,14 @@ export function readCachedRemoteHealth( export async function cachedRemoteHealth( info: DaemonInfo, probe: () => Promise, - stateDir?: string, + store?: PersistedHealthStore, ): Promise { - const cached = readCachedRemoteHealth(info, stateDir); + const cached = readCachedRemoteHealth(info, store); if (cached) return cached; const generation = remoteHealthGeneration; const health = await probe(); - if (generation === remoteHealthGeneration) cacheRemoteDaemonHealth(info, health, stateDir); + if (generation === remoteHealthGeneration) { + cacheRemoteDaemonHealth(info, health, store?.stateDir); + } return health; } diff --git a/packages/daemon-client/src/daemon-client-remote-health-gate.ts b/packages/daemon-client/src/daemon-client-remote-health-gate.ts new file mode 100644 index 0000000000..9d71651d65 --- /dev/null +++ b/packages/daemon-client/src/daemon-client-remote-health-gate.ts @@ -0,0 +1,78 @@ +import type { DaemonInfo } from './daemon-client-metadata.ts'; +import type { RemoteHealthRecovery } from './daemon-client-lifecycle.ts'; +import { + applyRemoteDaemonHealth, + invalidateRemoteDaemonHealth, + readCachedRemoteHealthRecord, + readRemoteDaemonHealth, + type RemoteDaemonHealth, +} from './daemon-client-transport.ts'; + +// Loaded on the remote path only: a local daemon request never pays for the remote health cache. +const loadRemoteHealthCache = () => import('./daemon-client-remote-health-cache.ts'); + +/** A remote daemon's cached `/health` answer, from this process or the state directory, if any. */ +export async function readCachedRemoteDaemonHealth( + info: DaemonInfo, + stateDir: string, +): Promise { + const { readCachedRemoteHealth } = await loadRemoteHealthCache(); + return readCachedRemoteHealth(info, { stateDir, readRecord: readCachedRemoteHealthRecord }); +} + +/** The remote `/health` answer within this caller's bound, through the cache. */ +export async function cachedRemoteDaemonHealth( + info: DaemonInfo, + stateDir: string, + probeTimeoutMs?: number, + callerSignal?: AbortSignal, +): Promise { + const { cachedRemoteHealth } = await loadRemoteHealthCache(); + return await cachedRemoteHealth( + info, + () => readRemoteDaemonHealth(info, probeTimeoutMs, callerSignal), + { stateDir, readRecord: readCachedRemoteHealthRecord }, + ); +} + +/** + * Probes a remote daemon's `/health` before anything is sent to it, re-probing a daemon that is there + * but not ready for the recovery budget, and points `info` at the daemon that answered. + */ +export async function openRemoteHealthGate( + info: DaemonInfo, + stateDir: string, + healthRecovery: RemoteHealthRecovery | undefined, +): Promise { + // The command's budget starts with the first probe, which already runs under it and its signal. + const deadline = performance.now() + (healthRecovery?.budgetMs ?? 0); + let health = await cachedRemoteDaemonHealth( + info, + stateDir, + healthRecovery?.budgetMs, + healthRecovery?.signal, + ); + if (!health.reachable) { + // Loaded on the refusal: this module is not part of what every CLI start pays for. + const { recoverRemoteDaemonHealth } = await import('./daemon-client-remote-health-recovery.ts'); + health = await recoverRemoteDaemonHealth({ + info, + probe: (budgetMs, signal) => cachedRemoteDaemonHealth(info, stateDir, budgetMs, signal), + failedProbe: health, + recovery: healthRecovery, + deadline, + hint: 'Fix or unset --daemon-base-url or AGENT_DEVICE_DAEMON_BASE_URL so the client targets a reachable daemon or the local one. If this CLI was connected with connect proxy, run agent-device disconnect to clear the saved connection and return to the local daemon.', + }); + } + applyRemoteDaemonHealth(info, health); +} + +/** Drops the cached answer for this daemon, then probes it as on first contact. */ +export async function refreshRemoteDaemonHealth( + info: DaemonInfo, + stateDir: string, + healthRecovery: RemoteHealthRecovery | undefined, +): Promise { + await invalidateRemoteDaemonHealth(info, stateDir); + await openRemoteHealthGate(info, stateDir, healthRecovery); +} diff --git a/packages/daemon-client/src/daemon-client-remote-health-recovery.ts b/packages/daemon-client/src/daemon-client-remote-health-recovery.ts index c002d5fc8c..d01ab03b75 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-recovery.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-recovery.ts @@ -1,8 +1,7 @@ import { sleep } from '@agent-device/host-kit/retry'; import type { RemoteHealthRecovery } from './daemon-client-lifecycle.ts'; import type { DaemonInfo } from './daemon-client-metadata.ts'; -import type { RemoteDaemonHealth } from './daemon-client-health-record.ts'; -import { cachedRemoteDaemonHealth } from './daemon-client-transport.ts'; +import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; import { remoteDaemonUnavailableError } from './daemon-lifecycle-errors.ts'; /** The pause between `/health` probes while a remote daemon is unavailable. */ @@ -27,15 +26,15 @@ function isTransientHealthFailure(health: RemoteDaemonHealth): boolean { */ export async function recoverRemoteDaemonHealth(params: { info: DaemonInfo; - /** Where a recovered answer is cached for later commands. */ - stateDir: string; + /** Probes `/health` once within `budgetMs`. */ + probe: (budgetMs: number, signal: AbortSignal | undefined) => Promise; failedProbe: RemoteDaemonHealth; recovery: RemoteHealthRecovery | undefined; /** When the command's budget ends, on the `performance.now()` clock: it started with the first probe. */ deadline: number; hint: string; }): Promise { - const { info, stateDir, recovery, deadline, hint } = params; + const { info, recovery, deadline, hint } = params; let attempts = 1; let probe = params.failedProbe; while (recovery && isTransientHealthFailure(probe) && !recovery.signal?.aborted) { @@ -52,7 +51,7 @@ export async function recoverRemoteDaemonHealth(params: { const probeMs = deadline - performance.now(); if (probeMs <= 0 || recovery.signal?.aborted) continue; attempts += 1; - probe = await cachedRemoteDaemonHealth(info, stateDir, probeMs, recovery.signal); + probe = await params.probe(probeMs, recovery.signal); if (probe.reachable) return probe; } throw remoteDaemonUnavailableError({ daemonBaseUrl: info.baseUrl, attempts, hint }); diff --git a/packages/daemon-client/src/daemon-client-request-guard.ts b/packages/daemon-client/src/daemon-client-request-guard.ts new file mode 100644 index 0000000000..9bdddb586b --- /dev/null +++ b/packages/daemon-client/src/daemon-client-request-guard.ts @@ -0,0 +1,88 @@ +import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; + +/** + * The requester-side half of a per-call `AbortSignal` (#3178). The transport half + * (`daemon-client-transport.ts`) closes the + * request's connection (which is what makes the daemon mark the request canceled); this half + * answers for the cases a transport cannot observe: + * + * - a signal already aborted before anything is sent — nothing may leave the process, so the refusal + * carries `details.dispatched: 'no'`; + * - an abort during a phase with no connection to close, or a custom transport that ignores the + * signal — the caller's promise still settles, with `details.dispatched: 'unknown'` because the + * request may already have been written. + * + * Both reject with the typed canceled-request error (`details.reason: 'request_canceled'`) whatever + * reason the caller aborted with, so every layer dispatches on the same reason and never on the + * caller's arbitrary abort reason or on error text. An abort is never a timeout: nothing here reads + * or extends a request deadline, and no timeout path may produce this rejection. + */ + +/** + * The typed canceled-request error for a caller's own abort. The reason the caller aborted with + * survives unchanged as the cause — `AbortController.abort()` accepts any value — while the + * rejection itself dispatches on `reason: 'request_canceled'` with the delivery evidence the + * aborting layer can prove. A built-in transport rejects every abort through this, so a caller's + * arbitrary abort reason never escapes as the outcome of a daemon request. + */ +export function abortedRequestError( + signal: AbortSignal, + dispatched: 'no' | 'unknown', + requestId?: string, +): AppError { + return createRequestCanceledError({ requestId, dispatched }, signal.reason); +} + +/** + * Refuses a send attempt that starts while the caller's signal is already aborted: nothing may leave + * the process, so this never touches a connection and the refusal carries `details.dispatched: 'no'`. + */ +export function refuseAbortedRequest(signal: AbortSignal | undefined, requestId?: string): void { + if (!signal?.aborted) return; + throw abortedRequestError(signal, 'no', requestId); +} + +type RequestGuard = { + /** Refuses an already-aborted call before anything is sent. No-op without a signal. */ + refuseIfAborted(): void; + /** Settles `send`'s outcome against the signal, winning with the typed canceled error on abort. */ + guard(send: () => Promise): Promise; +}; + +const NO_REQUEST_GUARD: RequestGuard = { + refuseIfAborted: () => {}, + guard: async (send: () => Promise) => await send(), +}; + +export function createRequestGuard(params: { + signal: AbortSignal | undefined; + requestId?: string; +}): RequestGuard { + const { signal, requestId } = params; + if (!signal) return NO_REQUEST_GUARD; + return { + refuseIfAborted() { + if (signal.aborted) throw abortedRequestError(signal, 'no', requestId); + }, + guard: async (send: () => Promise): Promise => { + // Checked before `send` runs, so nothing has been dispatched yet — the honest evidence is + // 'no'. An abort listener attached to an already-aborted signal never fires, so this check is + // what keeps a late `guard` call rejecting rather than pending forever. + if (signal.aborted) throw abortedRequestError(signal, 'no', requestId); + return await new Promise((resolve, reject) => { + const onAbort = (): void => reject(abortedRequestError(signal, 'unknown', requestId)); + signal.addEventListener('abort', onAbort, { once: true }); + void send().then( + (value) => { + signal.removeEventListener('abort', onAbort); + resolve(value); + }, + (error: unknown) => { + signal.removeEventListener('abort', onAbort); + reject(error); + }, + ); + }); + }, + }; +} diff --git a/packages/daemon-client/src/daemon-client-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index 40ca381929..142f26019b 100644 --- a/packages/daemon-client/src/daemon-client-timeout.ts +++ b/packages/daemon-client/src/daemon-client-timeout.ts @@ -8,7 +8,7 @@ import type { DaemonPaths } from '@agent-device/daemon-contracts/daemon-resoluti 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'; -import type { RemoteDaemonHealth } from './daemon-client-health-record.ts'; +import type { RemoteDaemonHealth } from './daemon-client-transport.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 diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index f7de17be5c..60071933e6 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -2,11 +2,12 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import type { RequestProgressSink } from '@agent-device/contracts/progress'; import net from 'node:net'; -import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; +import { AppError } from '@agent-device/kernel/errors'; import { loadNodeHttpRequester, readNodeHttpResponseBody } from '@agent-device/host-kit/transport'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { assertScriptArtifactsCapability, + readDaemonCapabilities, type DaemonPaths, type DaemonTransportPreference, } from '@agent-device/daemon-contracts/daemon-resolution'; @@ -23,14 +24,10 @@ import { DAEMON_INSTANCE_REASONS, DAEMON_HTTP_UPSTREAM_INSTANCE_HEADER, DAEMON_RPC_PROTOCOL_VERSION, + type DaemonHealthPayload, } from '@agent-device/contracts/daemon-http'; import { DAEMON_TRANSPORT_REASONS } from './daemon-client-transport-reasons.ts'; -import { - applyRemoteDaemonHealth, - readHealthPayload, - type RemoteDaemonHealth, - type RemoteDaemonHealthLink, -} from './daemon-client-health-record.ts'; +import { abortedRequestError, refuseAbortedRequest } from './daemon-client-request-guard.ts'; import { buildHttpRpcPayload, handleDaemonHttpResponseBody, @@ -64,95 +61,10 @@ type SendRequestOptions = { * how an attach client and the quiesce request itself time out. */ timeoutRecovery?: 'retire-unresponsive' | 'none'; + /** Re-probes a daemon whose `/health` answer was cached, before an unsent request is resent. */ + remoteHealthGate?: (budgetMs: number | undefined) => Promise; }; -/** - * The requester-side half of a per-call `AbortSignal` (#3178), kept beside the transport that - * enforces it so cancellation has one owner across both halves. The transport half closes the - * request's connection (which is what makes the daemon mark the request canceled); this half - * answers for the cases a transport cannot observe: - * - * - a signal already aborted before anything is sent — nothing may leave the process, so the refusal - * carries `details.dispatched: 'no'`; - * - an abort during a phase with no connection to close, or a custom transport that ignores the - * signal — the caller's promise still settles, with `details.dispatched: 'unknown'` because the - * request may already have been written. - * - * Both reject with the typed canceled-request error (`details.reason: 'request_canceled'`) whatever - * reason the caller aborted with, so every layer dispatches on the same reason and never on the - * caller's arbitrary abort reason or on error text. An abort is never a timeout: nothing here reads - * or extends a request deadline, and no timeout path may produce this rejection. - */ - -/** - * The typed canceled-request error for a caller's own abort. The reason the caller aborted with - * survives unchanged as the cause — `AbortController.abort()` accepts any value — while the - * rejection itself dispatches on `reason: 'request_canceled'` with the delivery evidence the - * aborting layer can prove. A built-in transport rejects every abort through this, so a caller's - * arbitrary abort reason never escapes as the outcome of a daemon request. - */ -function abortedRequestError( - signal: AbortSignal, - dispatched: 'no' | 'unknown', - requestId?: string, -): AppError { - return createRequestCanceledError({ requestId, dispatched }, signal.reason); -} - -/** - * Refuses a send attempt that starts while the caller's signal is already aborted: nothing may leave - * the process, so this never touches a connection and the refusal carries `details.dispatched: 'no'`. - */ -function refuseAbortedRequest(signal: AbortSignal | undefined, requestId?: string): void { - if (!signal?.aborted) return; - throw abortedRequestError(signal, 'no', requestId); -} - -type RequestGuard = { - /** Refuses an already-aborted call before anything is sent. No-op without a signal. */ - refuseIfAborted(): void; - /** Settles `send`'s outcome against the signal, winning with the typed canceled error on abort. */ - guard(send: () => Promise): Promise; -}; - -const NO_REQUEST_GUARD: RequestGuard = { - refuseIfAborted: () => {}, - guard: async (send: () => Promise) => await send(), -}; - -export function createRequestGuard(params: { - signal: AbortSignal | undefined; - requestId?: string; -}): RequestGuard { - const { signal, requestId } = params; - if (!signal) return NO_REQUEST_GUARD; - return { - refuseIfAborted() { - if (signal.aborted) throw abortedRequestError(signal, 'no', requestId); - }, - guard: async (send: () => Promise): Promise => { - // Checked before `send` runs, so nothing has been dispatched yet — the honest evidence is - // 'no'. An abort listener attached to an already-aborted signal never fires, so this check is - // what keeps a late `guard` call rejecting rather than pending forever. - if (signal.aborted) throw abortedRequestError(signal, 'no', requestId); - return await new Promise((resolve, reject) => { - const onAbort = (): void => reject(abortedRequestError(signal, 'unknown', requestId)); - signal.addEventListener('abort', onAbort, { once: true }); - void send().then( - (value) => { - signal.removeEventListener('abort', onAbort); - resolve(value); - }, - (error: unknown) => { - signal.removeEventListener('abort', onAbort); - reject(error); - }, - ); - }); - }, - }; -} - const LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS = 500; const REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS = 3000; @@ -174,6 +86,26 @@ function daemonEndpointUnavailableError(transport: ResolvedDaemonTransport): App ); } +export type RemoteDaemonHealth = { + reachable: boolean; + statusCode?: number; + service?: string; + version?: string; + rpcProtocolVersion?: number; + instanceId?: string; + hostArch?: string; + capabilities?: DaemonInfo['capabilities']; + /** The daemon behind a proxy, as the proxy's health reported it. */ + upstream?: RemoteDaemonHealthLink; + /** The probe ran out of its time budget before an answer, rather than failing outright. */ + timedOut?: true; +}; + +type RemoteDaemonHealthLink = Pick< + RemoteDaemonHealth, + 'service' | 'version' | 'rpcProtocolVersion' | 'instanceId' | 'hostArch' | 'capabilities' +>; + export async function probeDaemonReachability( info: DaemonInfo, preference: DaemonTransportPreference, @@ -334,6 +266,57 @@ function healthProbeExpired(signal: AbortSignal, deadline: number): boolean { return signal.aborted || performance.now() >= deadline; } +function readHealthPayload(body: string): Omit { + try { + const parsed = JSON.parse(body) as { upstream?: unknown }; + const upstream = + parsed.upstream && typeof parsed.upstream === 'object' + ? readHealthLink(parsed.upstream as Record) + : undefined; + return { + ...readHealthLink(parsed as Record), + ...(upstream ? { upstream } : {}), + }; + } catch { + return {}; + } +} + +function readHealthLink(parsed: Record): RemoteDaemonHealthLink { + return { + service: isHealthService(parsed.service) ? parsed.service : undefined, + version: readHealthVersion(parsed.version), + rpcProtocolVersion: + typeof parsed.rpcProtocolVersion === 'number' ? parsed.rpcProtocolVersion : undefined, + ...(typeof parsed.instanceId === 'string' ? { instanceId: parsed.instanceId } : {}), + ...(typeof parsed.hostArch === 'string' ? { hostArch: parsed.hostArch } : {}), + ...(parsed.capabilities === undefined + ? {} + : { capabilities: readDaemonCapabilities(parsed.capabilities) }), + }; +} + +// The remote picks what /health says and agents read the refusal built from it, so only a service +// the contract names and a version-shaped string are kept; anything else reads as absent. +const HEALTH_SERVICES: Readonly> = { + 'agent-device-daemon': true, + 'agent-device-proxy': true, +}; +const HEALTH_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; +const HEALTH_VERSION_MAX_LENGTH = 64; + +function isHealthService(value: unknown): value is DaemonHealthPayload['service'] { + return typeof value === 'string' && Object.hasOwn(HEALTH_SERVICES, value); +} + +function readHealthVersion(value: unknown): string | undefined { + return typeof value === 'string' && + value.length <= HEALTH_VERSION_MAX_LENGTH && + HEALTH_VERSION.test(value) + ? value + : undefined; +} + export async function sendRequest( info: DaemonInfo, req: DaemonWireRequest, @@ -382,7 +365,13 @@ async function recoverFromTimeout( action: req.positionals?.[0], requestSent: error.details.daemonRequestSent !== false, responseStarted: error.details.remoteResponseStarted === true, - readRemoteHealth: (budgetMs) => readDaemonHttpHealth(info, budgetMs, options.signal), + readRemoteHealth: async (budgetMs) => { + const health = await readDaemonHttpHealth(info, budgetMs, options.signal); + if (!health.reachable || health.instanceId !== info.remoteInstanceId) { + await invalidateRemoteDaemonHealth(info, statePaths.baseDir); + } + return health; + }, }); } @@ -440,15 +429,22 @@ async function sendRequestWithFallback( options, ); } - if (isRemoteTransportFailure(error)) { + if (dropsCachedRemoteHealth(error)) { await invalidateRemoteDaemonHealth(info, statePaths.baseDir); } - if (info.baseUrl && info.remoteHealthCached && isUnsentTransportFailure(error)) { + if ( + info.baseUrl && + options.remoteHealthGate && + error instanceof AppError && + PROVEN_UNSENT.has(error) + ) { return await resendAfterRemoteHealthGate( + options.remoteHealthGate, info, req, statePaths, timeoutMs, + deadline, transport, options, ); @@ -488,27 +484,37 @@ async function retryAfterRemoteInstanceMismatch( } /** - * A send from a cached `/health` answer that never left this process (refused, reset, no such host) - * proves nothing reached the daemon, so it gets the gate the cache skipped: the same probe, re-probe - * budget and typed refusal as a first contact, then one resend under the command's full budget. + * Only a send whose connection never opened proves nothing reached the daemon. It gets the gate the + * cache skipped, then one resend, both within what is left of the command's budget. */ async function resendAfterRemoteHealthGate( + gate: (budgetMs: number | undefined) => Promise, info: DaemonInfo, req: DaemonWireRequest, statePaths: DaemonPaths, timeoutMs: number | undefined, + deadline: number | undefined, transport: ResolvedDaemonTransport, options: SendRequestOptions, ): Promise { - info.remoteHealthCached = undefined; - const { openRemoteHealthGate } = await import('./daemon-client-lifecycle.ts'); - await openRemoteHealthGate( + const requestId = req.meta?.requestId; + const gateBudgetMs = remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline); + try { + await gate(gateBudgetMs); + } catch (error) { + refuseAbortedRequest(options.signal, requestId); + throw error; + } + refuseAbortedRequest(options.signal, requestId); + const resendOptions = { ...options, remoteHealthGate: undefined }; + return await resendAfterFreshRemoteHealth( info, - statePaths.baseDir, - timeoutMs === undefined ? undefined : { budgetMs: timeoutMs, signal: options.signal }, + req, + statePaths, + remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline), + transport, + resendOptions, ); - refuseAbortedRequest(options.signal, req.meta?.requestId); - return await resendAfterFreshRemoteHealth(info, req, statePaths, timeoutMs, transport, options); } async function resendAfterFreshRemoteHealth( @@ -524,21 +530,23 @@ async function resendAfterFreshRemoteHealth( try { return await sendRequestWithTransport(info, req, statePaths, timeoutMs, transport, options); } catch (error) { - if (isRemoteTransportFailure(error)) { + if (dropsCachedRemoteHealth(error)) { await invalidateRemoteDaemonHealth(info, statePaths.baseDir); } throw error; } } -function isUnsentTransportFailure(error: unknown): boolean { - return ( - error instanceof AppError && - error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason && - error.details.daemonRequestSent === false - ); +/** Points `info` at the daemon a `/health` answer describes: its instances and capabilities. */ +export function applyRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHealth): void { + info.remoteInstanceId = health.instanceId; + info.remoteUpstreamInstanceId = health.upstream?.instanceId; + info.capabilities = (health.upstream ?? health).capabilities; } +/** Failures raised here before the connection opened; a daemon error can carry the same details. */ +const PROVEN_UNSENT = new WeakSet(); + function remainingRemoteRequestTimeoutMs( req: DaemonWireRequest, timeoutMs: number | undefined, @@ -563,15 +571,13 @@ function isRemoteInstanceMismatch(error: unknown): boolean { ); } -// A reply that is not the daemon's JSON-RPC came from something else on the path, such as a gateway -// answering 5xx while the daemon is away, so the next command probes `/health` again. -function isRemoteTransportFailure(error: unknown): boolean { +// A timeout is left to the timeout route, which drops the cache only when its probe shows the +// daemon gone or replaced. +function dropsCachedRemoteHealth(error: unknown): boolean { return ( error instanceof AppError && (error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason || - error.details?.reason === DAEMON_TRANSPORT_REASONS.timeout.reason || - error.details?.reason === DAEMON_TRANSPORT_REASONS.replyUnreadable.reason || - error.details?.reason === DAEMON_TRANSPORT_REASONS.replyInvalid.reason) + error.details?.reason === DAEMON_TRANSPORT_REASONS.replyUnreadable.reason) ); } @@ -631,7 +637,12 @@ function isSafeAutoTransportFallbackError( error: unknown, attempted: ResolvedDaemonTransport, ): boolean { - return attempted === 'socket' && isUnsentTransportFailure(error); + return ( + attempted === 'socket' && + error instanceof AppError && + error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason && + error.details.daemonRequestSent === false + ); } function requireDaemonTransport( @@ -816,171 +827,170 @@ async function sendHttpRequest( const transport = await loadNodeHttpRequester(rpcUrl.protocol); const callerSignal = options.signal; refuseAbortedRequest(callerSignal, req.meta?.requestId); - - return await new Promise((resolve, reject) => { - let settled = false; - // Set when the request was handed to the OS (`finish`), never for a connection that failed first. - let requestSent = false; - // Set when a 2xx progress stream opened on `/rpc`, proving the remote URL and auth token. - let responseStarted = false; - const detachCallerAbort = (): void => { - if (callerSignal) callerSignal.removeEventListener('abort', onCallerAbort); - }; - const resolveOnce = (response: DaemonResponse | PromiseLike): void => { - if (settled) return; - settled = true; - detachCallerAbort(); - resolve(response); - }; - const rejectOnce = (error: unknown): void => { - if (settled) return; - settled = true; - detachCallerAbort(); - reject(error); - }; - const handleBody = (body: string): void => { - handleDaemonHttpResponseBody(body, { - info, - req, - stateDir: statePaths.baseDir, - host: options.host, - resolve: resolveOnce, - reject: rejectOnce, - }); - }; - const request = transport.request( - { - protocol: rpcUrl.protocol, - host: rpcUrl.hostname, - port: rpcUrl.port, - method: 'POST', - path: rpcUrl.pathname + rpcUrl.search, - headers, - }, - (res) => { - if (isRemoteInstanceMismatchResponse(res.statusCode, res.headers ?? {})) { - res.resume(); - if (timeoutHandle) clearTimeout(timeoutHandle); - rejectOnce( - new AppError('COMMAND_FAILED', 'Remote daemon instance changed', { - reason: DAEMON_INSTANCE_REASONS.instanceMismatch.reason, - daemonBaseUrl: info.baseUrl, - }), - ); - return; - } - if (shouldReadDaemonProgressStream(req, res.headers?.['content-type'])) { - if (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 300) { - responseStarted = true; - } - readDaemonHttpProgressResponse(res, { - req, - onProgress: options.onProgress, - reject: rejectOnce, - clearTimeout: () => { - if (timeoutHandle) clearTimeout(timeoutHandle); - }, - handleResponseBody: handleBody, - }); - return; - } - const responseBody = readNodeHttpResponseBody(res).catch((error: unknown) => { - throw new AppError( - 'COMMAND_FAILED', - 'Failed to read daemon response', - { - requestId: req.meta?.requestId, - reason: DAEMON_TRANSPORT_REASONS.replyUnreadable.reason, - }, - error instanceof Error ? error : undefined, - ); + // A remote 5xx means the daemon or a hop before it failed, so the next command probes again. + let serverError = false; + try { + return await new Promise((resolve, reject) => { + let settled = false; + // Set once a connection opened; a reused pooled socket is already open. + let connected = false; + // Set when the request was handed to the OS (`finish`), never for a connection that failed first. + let requestSent = false; + // Set when a 2xx progress stream opened on `/rpc`, proving the remote URL and auth token. + let responseStarted = false; + const detachCallerAbort = (): void => { + if (callerSignal) callerSignal.removeEventListener('abort', onCallerAbort); + }; + const resolveOnce = (response: DaemonResponse | PromiseLike): void => { + if (settled) return; + settled = true; + detachCallerAbort(); + resolve(response); + }; + const rejectOnce = (error: unknown): void => { + if (settled) return; + settled = true; + detachCallerAbort(); + reject(error); + }; + const handleBody = (body: string): void => { + handleDaemonHttpResponseBody(body, { + info, + req, + stateDir: statePaths.baseDir, + host: options.host, + resolve: resolveOnce, + reject: rejectOnce, }); - void responseBody - .then((body) => { - if (timeoutHandle) clearTimeout(timeoutHandle); - handleBody(body); - }) - .catch((error: unknown) => { + }; + const request = transport.request( + { + protocol: rpcUrl.protocol, + host: rpcUrl.hostname, + port: rpcUrl.port, + method: 'POST', + path: rpcUrl.pathname + rpcUrl.search, + headers, + }, + (res) => { + if (info.baseUrl && (res.statusCode ?? 0) >= 500) serverError = true; + if (isRemoteInstanceMismatchResponse(res.statusCode, res.headers ?? {})) { + res.resume(); if (timeoutHandle) clearTimeout(timeoutHandle); - rejectOnce(error); - }); - }, - ); - - const remote = isRemoteDaemon(info); - const timeoutHandle = - typeof timeoutMs === 'number' - ? setTimeout(() => { rejectOnce( - requestTimeoutError(timeoutMs, req.meta?.requestId, requestSent, responseStarted), + new AppError('COMMAND_FAILED', 'Remote daemon instance changed', { + reason: DAEMON_INSTANCE_REASONS.instanceMismatch.reason, + daemonBaseUrl: info.baseUrl, + }), ); - request.destroy(); - }, timeoutMs) - : undefined; - - // Destroying the request closes this one connection, which is what makes the daemon mark the - // request canceled. The timeout timer is cleared because an abort is never a timeout: nothing - // may run the timeout's runner sweep or daemon reset after the caller canceled. The settle goes - // first so the `error` the destroy surfaces arrives after `settled` and cannot rewrite the - // typed cancellation into a transport failure. - const onCallerAbort = (): void => { - if (settled) return; - if (timeoutHandle) clearTimeout(timeoutHandle); - rejectOnce( - abortedRequestError(callerSignal!, requestSent ? 'unknown' : 'no', req.meta?.requestId), + return; + } + if (shouldReadDaemonProgressStream(req, res.headers?.['content-type'])) { + if (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 300) { + responseStarted = true; + } + readDaemonHttpProgressResponse(res, { + req, + onProgress: options.onProgress, + reject: rejectOnce, + clearTimeout: () => { + if (timeoutHandle) clearTimeout(timeoutHandle); + }, + handleResponseBody: handleBody, + }); + return; + } + const responseBody = readNodeHttpResponseBody(res).catch((error: unknown) => { + throw new AppError( + 'COMMAND_FAILED', + 'Failed to read daemon response', + { + requestId: req.meta?.requestId, + reason: DAEMON_TRANSPORT_REASONS.replyUnreadable.reason, + }, + error instanceof Error ? error : undefined, + ); + }); + void responseBody + .then((body) => { + if (timeoutHandle) clearTimeout(timeoutHandle); + handleBody(body); + }) + .catch((error: unknown) => { + if (timeoutHandle) clearTimeout(timeoutHandle); + rejectOnce(error); + }); + }, ); - request.destroy(); - }; - if (callerSignal) { - callerSignal.addEventListener('abort', onCallerAbort, { once: true }); - } - request.on('error', (err) => { - if (timeoutHandle) clearTimeout(timeoutHandle); - // `request.destroy()` surfaces an `error` after an intentional abort or timeout has already - // settled this promise. Returning before `handleTransportError` keeps that expected teardown - // from emitting a `daemon_request_socket_error` diagnostic; a genuine transport error still - // arrives before the settle and rejects. - if (settled) return; - rejectOnce(handleTransportError(err, req.meta?.requestId, remote, requestSent)); - }); + const remote = isRemoteDaemon(info); + const timeoutHandle = + typeof timeoutMs === 'number' + ? setTimeout(() => { + rejectOnce( + requestTimeoutError(timeoutMs, req.meta?.requestId, requestSent, responseStarted), + ); + request.destroy(); + }, timeoutMs) + : undefined; + + // Destroying the request closes this one connection, which is what makes the daemon mark the + // request canceled. The timeout timer is cleared because an abort is never a timeout: nothing + // may run the timeout's runner sweep or daemon reset after the caller canceled. The settle goes + // first so the `error` the destroy surfaces arrives after `settled` and cannot rewrite the + // typed cancellation into a transport failure. + const onCallerAbort = (): void => { + if (settled) return; + if (timeoutHandle) clearTimeout(timeoutHandle); + rejectOnce( + abortedRequestError(callerSignal!, requestSent ? 'unknown' : 'no', req.meta?.requestId), + ); + request.destroy(); + }; + if (callerSignal) { + callerSignal.addEventListener('abort', onCallerAbort, { once: true }); + } - request.on('finish', () => { - requestSent = true; + request.on('error', (err) => { + if (timeoutHandle) clearTimeout(timeoutHandle); + // `request.destroy()` surfaces an `error` after an intentional abort or timeout has already + // settled this promise. Returning before `handleTransportError` keeps that expected teardown + // from emitting a `daemon_request_socket_error` diagnostic; a genuine transport error still + // arrives before the settle and rejects. + if (settled) return; + const failure = handleTransportError(err, req.meta?.requestId, remote, requestSent); + if (!connected) PROVEN_UNSENT.add(failure); + rejectOnce(failure); + }); + + request.on('socket', (socket) => { + if (!socket.connecting) connected = true; + else socket.once('connect', () => (connected = true)); + }); + request.on('finish', () => { + requestSent = true; + }); + request.write(rpcPayload); + request.end(); }); - request.write(rpcPayload); - request.end(); - }); + } finally { + if (serverError) await invalidateRemoteDaemonHealth(info, statePaths.baseDir); + } } // Loaded on the remote path only: a local daemon request never pays for the remote health cache. const loadRemoteHealthCache = () => import('./daemon-client-remote-health-cache.ts'); /** Drops a remote daemon's cached health; a local daemon has none, so its failure loads nothing. */ -async function invalidateRemoteDaemonHealth(info: DaemonInfo, stateDir: string): Promise { - if (!info.baseUrl) return; - (await loadRemoteHealthCache()).invalidateRemoteDaemonHealth(info, stateDir); -} - -/** A remote daemon's cached `/health` answer, from this process or the state directory, if any. */ -export async function readCachedRemoteDaemonHealth( +export async function invalidateRemoteDaemonHealth( info: DaemonInfo, stateDir: string, -): Promise { - return (await loadRemoteHealthCache()).readCachedRemoteHealth(info, stateDir); +): Promise { + if (!info.baseUrl) return; + (await loadRemoteHealthCache()).invalidateRemoteDaemonHealth(info, stateDir); } -/** The remote `/health` answer within this caller's bound, through the cache. */ -export async function cachedRemoteDaemonHealth( - info: DaemonInfo, - stateDir: string, - probeTimeoutMs?: number, - callerSignal?: AbortSignal, -): Promise { - const { cachedRemoteHealth } = await loadRemoteHealthCache(); - return await cachedRemoteHealth( - info, - () => readRemoteDaemonHealth(info, probeTimeoutMs, callerSignal), - stateDir, - ); +/** A cached `/health` record, read with the same contract checks as a live answer. */ +export function readCachedRemoteHealthRecord(record: unknown): Partial { + return readHealthPayload(JSON.stringify(record ?? null)); } diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 0c94f60bc2..15f8fa2d5c 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -20,7 +20,8 @@ import { } from '@agent-device/remote/daemon-artifacts'; import type { DaemonClientSettings, EnsuredDaemon } from './daemon-client-lifecycle.ts'; import type { EnsuringTransportOptions } from './daemon-client-ensuring.ts'; -import { createRequestGuard, sendRequest as sendDaemonRequest } from './daemon-client-transport.ts'; +import { createRequestGuard } from './daemon-client-request-guard.ts'; +import { sendRequest as sendDaemonRequest } from './daemon-client-transport.ts'; import { isRemoteDaemon, readRegisteredDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { LocalDaemonCodeIdentity } from './daemon-launch-spec.ts'; import type { @@ -120,6 +121,17 @@ async function sendToDaemonOnHost( ); }); const info = daemon.info; + // A cached `/health` answer skipped the probe; this runs it when the command needs a fresh one. + const remoteHealthGate = daemon.remoteHealthCached + ? async (budgetMs: number | undefined) => { + const { refreshRemoteDaemonHealth } = await import('./daemon-client-remote-health-gate.ts'); + await refreshRemoteDaemonHealth( + info, + settings.paths.baseDir, + budgetMs === undefined ? undefined : { budgetMs, signal: options.signal }, + ); + } + : undefined; const preparedRemoteRequest = await cancellation.guard( async () => await protectArtifactUploadWithLeaseBeats( @@ -170,10 +182,15 @@ async function sendToDaemonOnHost( onProgress: options.onProgress, signal: options.signal, timeoutRecovery: resolveTimeoutRecovery(settings), + remoteHealthGate, }, ); if (!info.baseUrl || !request.meta?.clientArtifactPaths?.savedScript) return await send(request); + // A capability missing only from a cached answer may have arrived with a daemon upgrade. + if (remoteHealthGate && !info.capabilities?.includes('script-artifacts')) { + await cancellation.guard(() => remoteHealthGate(requestTimeoutMs)); + } return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send); }, { requestId, command: req.command }, diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 0628b1637d..59fa432360 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -361,7 +361,7 @@ for the API. ## Compatibility -Remote clients read `/health` before the first command to a daemon instance and compare the daemon RPC protocol version. The answer is cached in the client state directory, so later commands go straight to `/rpc` until the daemon or proxy instance changes. Keep client and proxy versions close: patch-level differences usually work, and incompatible RPC protocol versions fail before any command runs. +Remote clients read `/health` before the first command to a daemon instance and compare the daemon RPC protocol version. When the daemon, and the upstream daemon behind a proxy, report instance IDs, the answer is cached in the client state directory, and later commands go straight to `/rpc`. The client reads `/health` again when the daemon or proxy instance changes, after a client upgrade or token change, and after a failed call. Peers that do not report complete instance IDs get a `/health` read before every command. Keep client and proxy versions close: patch-level differences usually work, and incompatible RPC protocol versions fail before any command runs. `/health` also reports `hostArch`, the native CPU architecture of the machine serving it: the one its simulators run by default, even when Node itself runs under Rosetta. Macs report `arm64` or `x86_64`; other hosts report `x86_64` for x64 and Node's `process.arch` name otherwise (for example `arm64`). The top-level value describes the proxy's own machine, so a client behind a proxy reads `upstream.hostArch` for the host that runs the simulators, for example to build only that slice of a simulator app. Older daemons omit the field. `leaseBackends` lists the lease backends the daemon admits (`macos-app` only on a macOS host); a host checks `upstream.leaseBackends` for `macos-app` before handing out a macOS app lease, and older From 370b7bbdc5103d8b163df9bea1b71890cab44da8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 21:38:28 +0100 Subject: [PATCH 03/10] fix(daemon-client): keep the request guard in the eager closure's timeout owner The new daemon-client-request-guard.ts module made src/cli.ts, packages/client and the daemon-client entry evaluate one more module at flat weight plus new transport statements, which the eager-closure no-growth rule refuses. The guard now lives in daemon-client-timeout.ts, which every one of those entries already evaluates, beside the timeout route it must stay apart from. Co-Authored-By: Claude Opus 5.5 --- ...mon-client-transport-request-guard.test.ts | 2 +- .../src/daemon-client-request-guard.ts | 88 ------------------ .../src/daemon-client-timeout.ts | 89 ++++++++++++++++++- .../src/daemon-client-transport.ts | 7 +- packages/daemon-client/src/index.ts | 2 +- 5 files changed, 95 insertions(+), 93 deletions(-) delete mode 100644 packages/daemon-client/src/daemon-client-request-guard.ts diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport-request-guard.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-request-guard.test.ts index fea708d7ae..a329682c3e 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport-request-guard.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport-request-guard.test.ts @@ -9,7 +9,7 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; import { isRequestCanceledError } from '@agent-device/kernel/errors'; -import { createRequestGuard } from '../daemon-client-request-guard.ts'; +import { createRequestGuard } from '../daemon-client-timeout.ts'; function canceledOutcome(promise: Promise): Promise { return promise.then( diff --git a/packages/daemon-client/src/daemon-client-request-guard.ts b/packages/daemon-client/src/daemon-client-request-guard.ts deleted file mode 100644 index 9bdddb586b..0000000000 --- a/packages/daemon-client/src/daemon-client-request-guard.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; - -/** - * The requester-side half of a per-call `AbortSignal` (#3178). The transport half - * (`daemon-client-transport.ts`) closes the - * request's connection (which is what makes the daemon mark the request canceled); this half - * answers for the cases a transport cannot observe: - * - * - a signal already aborted before anything is sent — nothing may leave the process, so the refusal - * carries `details.dispatched: 'no'`; - * - an abort during a phase with no connection to close, or a custom transport that ignores the - * signal — the caller's promise still settles, with `details.dispatched: 'unknown'` because the - * request may already have been written. - * - * Both reject with the typed canceled-request error (`details.reason: 'request_canceled'`) whatever - * reason the caller aborted with, so every layer dispatches on the same reason and never on the - * caller's arbitrary abort reason or on error text. An abort is never a timeout: nothing here reads - * or extends a request deadline, and no timeout path may produce this rejection. - */ - -/** - * The typed canceled-request error for a caller's own abort. The reason the caller aborted with - * survives unchanged as the cause — `AbortController.abort()` accepts any value — while the - * rejection itself dispatches on `reason: 'request_canceled'` with the delivery evidence the - * aborting layer can prove. A built-in transport rejects every abort through this, so a caller's - * arbitrary abort reason never escapes as the outcome of a daemon request. - */ -export function abortedRequestError( - signal: AbortSignal, - dispatched: 'no' | 'unknown', - requestId?: string, -): AppError { - return createRequestCanceledError({ requestId, dispatched }, signal.reason); -} - -/** - * Refuses a send attempt that starts while the caller's signal is already aborted: nothing may leave - * the process, so this never touches a connection and the refusal carries `details.dispatched: 'no'`. - */ -export function refuseAbortedRequest(signal: AbortSignal | undefined, requestId?: string): void { - if (!signal?.aborted) return; - throw abortedRequestError(signal, 'no', requestId); -} - -type RequestGuard = { - /** Refuses an already-aborted call before anything is sent. No-op without a signal. */ - refuseIfAborted(): void; - /** Settles `send`'s outcome against the signal, winning with the typed canceled error on abort. */ - guard(send: () => Promise): Promise; -}; - -const NO_REQUEST_GUARD: RequestGuard = { - refuseIfAborted: () => {}, - guard: async (send: () => Promise) => await send(), -}; - -export function createRequestGuard(params: { - signal: AbortSignal | undefined; - requestId?: string; -}): RequestGuard { - const { signal, requestId } = params; - if (!signal) return NO_REQUEST_GUARD; - return { - refuseIfAborted() { - if (signal.aborted) throw abortedRequestError(signal, 'no', requestId); - }, - guard: async (send: () => Promise): Promise => { - // Checked before `send` runs, so nothing has been dispatched yet — the honest evidence is - // 'no'. An abort listener attached to an already-aborted signal never fires, so this check is - // what keeps a late `guard` call rejecting rather than pending forever. - if (signal.aborted) throw abortedRequestError(signal, 'no', requestId); - return await new Promise((resolve, reject) => { - const onAbort = (): void => reject(abortedRequestError(signal, 'unknown', requestId)); - signal.addEventListener('abort', onAbort, { once: true }); - void send().then( - (value) => { - signal.removeEventListener('abort', onAbort); - resolve(value); - }, - (error: unknown) => { - signal.removeEventListener('abort', onAbort); - reject(error); - }, - ); - }); - }, - }; -} diff --git a/packages/daemon-client/src/daemon-client-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index 142f26019b..47245888f2 100644 --- a/packages/daemon-client/src/daemon-client-timeout.ts +++ b/packages/daemon-client/src/daemon-client-timeout.ts @@ -1,4 +1,4 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { DAEMON_TRANSPORT_REASONS } from './daemon-client-transport-reasons.ts'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { DaemonRetirementResult } from '@agent-device/daemon-contracts/daemon-registration-owner'; @@ -456,3 +456,90 @@ function daemonWasForceKilled(retirement: DaemonRetirementResult | undefined): b const termination = retirement.termination; return termination?.status === 'exited' && termination.mode === 'forced'; } + +/** + * The requester-side half of a per-call `AbortSignal` (#3178), kept beside the timeout route so + * an abort and a timeout stay apart in one owner. The transport half closes the request's + * connection (which is what makes the daemon mark the request canceled); this half answers for the + * cases a transport cannot observe: + * + * - a signal already aborted before anything is sent — nothing may leave the process, so the refusal + * carries `details.dispatched: 'no'`; + * - an abort during a phase with no connection to close, or a custom transport that ignores the + * signal — the caller's promise still settles, with `details.dispatched: 'unknown'` because the + * request may already have been written. + * + * Both reject with the typed canceled-request error (`details.reason: 'request_canceled'`) whatever + * reason the caller aborted with, so every layer dispatches on the same reason and never on the + * caller's arbitrary abort reason or on error text. An abort is never a timeout: nothing here reads + * or extends a request deadline, and no timeout path may produce this rejection. + */ + +/** + * The typed canceled-request error for a caller's own abort. The reason the caller aborted with + * survives unchanged as the cause — `AbortController.abort()` accepts any value — while the + * rejection itself dispatches on `reason: 'request_canceled'` with the delivery evidence the + * aborting layer can prove. A built-in transport rejects every abort through this, so a caller's + * arbitrary abort reason never escapes as the outcome of a daemon request. + */ +export function abortedRequestError( + signal: AbortSignal, + dispatched: 'no' | 'unknown', + requestId?: string, +): AppError { + return createRequestCanceledError({ requestId, dispatched }, signal.reason); +} + +/** + * Refuses a send attempt that starts while the caller's signal is already aborted: nothing may leave + * the process, so this never touches a connection and the refusal carries `details.dispatched: 'no'`. + */ +export function refuseAbortedRequest(signal: AbortSignal | undefined, requestId?: string): void { + if (!signal?.aborted) return; + throw abortedRequestError(signal, 'no', requestId); +} + +type RequestGuard = { + /** Refuses an already-aborted call before anything is sent. No-op without a signal. */ + refuseIfAborted(): void; + /** Settles `send`'s outcome against the signal, winning with the typed canceled error on abort. */ + guard(send: () => Promise): Promise; +}; + +const NO_REQUEST_GUARD: RequestGuard = { + refuseIfAborted: () => {}, + guard: async (send: () => Promise) => await send(), +}; + +export function createRequestGuard(params: { + signal: AbortSignal | undefined; + requestId?: string; +}): RequestGuard { + const { signal, requestId } = params; + if (!signal) return NO_REQUEST_GUARD; + return { + refuseIfAborted() { + if (signal.aborted) throw abortedRequestError(signal, 'no', requestId); + }, + guard: async (send: () => Promise): Promise => { + // Checked before `send` runs, so nothing has been dispatched yet — the honest evidence is + // 'no'. An abort listener attached to an already-aborted signal never fires, so this check is + // what keeps a late `guard` call rejecting rather than pending forever. + if (signal.aborted) throw abortedRequestError(signal, 'no', requestId); + return await new Promise((resolve, reject) => { + const onAbort = (): void => reject(abortedRequestError(signal, 'unknown', requestId)); + signal.addEventListener('abort', onAbort, { once: true }); + void send().then( + (value) => { + signal.removeEventListener('abort', onAbort); + resolve(value); + }, + (error: unknown) => { + signal.removeEventListener('abort', onAbort); + reject(error); + }, + ); + }); + }, + }; +} diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 60071933e6..fde17adee3 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -27,14 +27,17 @@ import { type DaemonHealthPayload, } from '@agent-device/contracts/daemon-http'; import { DAEMON_TRANSPORT_REASONS } from './daemon-client-transport-reasons.ts'; -import { abortedRequestError, refuseAbortedRequest } from './daemon-client-request-guard.ts'; import { buildHttpRpcPayload, handleDaemonHttpResponseBody, incompatibleRemoteProtocolError, refuseOversizedDaemonRequest, } from './daemon-client-rpc.ts'; -import { handleRequestTimeout } from './daemon-client-timeout.ts'; +import { + abortedRequestError, + handleRequestTimeout, + refuseAbortedRequest, +} from './daemon-client-timeout.ts'; import { isRemoteDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 15f8fa2d5c..0970bd0c61 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -20,7 +20,7 @@ import { } from '@agent-device/remote/daemon-artifacts'; import type { DaemonClientSettings, EnsuredDaemon } from './daemon-client-lifecycle.ts'; import type { EnsuringTransportOptions } from './daemon-client-ensuring.ts'; -import { createRequestGuard } from './daemon-client-request-guard.ts'; +import { createRequestGuard } from './daemon-client-timeout.ts'; import { sendRequest as sendDaemonRequest } from './daemon-client-transport.ts'; import { isRemoteDaemon, readRegisteredDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { LocalDaemonCodeIdentity } from './daemon-launch-spec.ts'; From 5a21fb53106439fd9da3c61cd4c40d61a9dba340 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 21:39:33 +0100 Subject: [PATCH 04/10] fix(daemon-client): name the persisted health entry by the RPC protocol too A cached /health answer stands in for the protocol check, so its digest now includes DAEMON_RPC_PROTOCOL_VERSION beside the client version, base URL and token. A protocol change reads as a miss and the client probes. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0006-daemon-rpc-protocol-version.md | 6 +++--- .../daemon-client-remote-health-cache.test.ts | 13 +++++++++++++ .../src/daemon-client-remote-health-cache.ts | 16 +++++++++++++--- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index 5a7041bd8e..1801eeb433 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -10,7 +10,7 @@ Accepted - Package `version` is diagnostic only and must not be used as a compatibility gate. - Allow a missing `rpcProtocolVersion` unless a later security or protocol decision explicitly retires legacy compatibility. - A client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon. -- The cache may outlive the client process in the state directory. Name the entry by a digest of the client version, base URL, and token. Do not write the token or the URL. +- The cache may outlive the client process in the state directory. Name the entry by a digest of the client version, RPC protocol version, base URL, and token. Do not write the token or the URL. - Read a persisted entry only from a bounded regular file that the current user owns and that nobody else can write. Otherwise, probe `/health`. - If a cached RPC fails before its connection opens, probe `/health` as on first contact, within the command's remaining budget. Then send the RPC once more. Take this evidence only from the client's own transport, never from a reply. - Clear the cache on a remote HTTP 5xx. Do not resend the RPC. @@ -47,8 +47,8 @@ A legacy remote daemon is allowed unless a later security or protocol decision e A client may cache a successful probe if `/health` advertises an instance ID for both the daemon endpoint and, if proxied, its upstream daemon. The CLI starts a new process for each command, so the cache also persists in the state directory. Without it, each remote command pays one extra network round trip for `/health`. -The persisted entry is named by a digest of the client version, base URL, and token, and holds neither the token nor the URL. -A different token, URL, or client version reads as a miss, so a client upgrade always probes again. +The persisted entry is named by a digest of the client version, RPC protocol version, base URL, and token, and holds neither the token nor the URL. +A different token, URL, client version, or RPC protocol version reads as a miss, so a client upgrade always probes again. The client sends those IDs as conditional headers on every cached RPC. Before dispatch, a daemon refuses a stale instance with a typed HTTP 409 response. Before it forwards a request, a proxy refuses its own stale instance. diff --git a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts index db438a8c38..8fe39dd174 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts @@ -16,6 +16,16 @@ import { } from '../daemon-client-transport.ts'; const clientVersion = vi.hoisted(() => ({ current: '1.0.0' })); +const rpcProtocol = vi.hoisted(() => ({ current: 3 })); +vi.mock('@agent-device/contracts/daemon-http', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + get DAEMON_RPC_PROTOCOL_VERSION() { + return rpcProtocol.current; + }, + }; +}); vi.mock('@agent-device/host-kit/version', async (importOriginal) => ({ ...(await importOriginal()), readVersion: () => clientVersion.current, @@ -81,6 +91,9 @@ test('persisted health is private and reused only by the identity that cached it clientVersion.current = '9.9.9'; assert.equal(reuse(info), undefined, 'a client upgrade probes again'); clientVersion.current = '1.0.0'; + rpcProtocol.current = 4; + assert.equal(reuse(info), undefined, 'another RPC protocol probes again'); + rpcProtocol.current = 3; invalidateRemoteDaemonHealth({ ...info, token: 'other-token' }, stateDir); assert.equal(fs.existsSync(file), true, 'another identity leaves the entry alone'); diff --git a/packages/daemon-client/src/daemon-client-remote-health-cache.ts b/packages/daemon-client/src/daemon-client-remote-health-cache.ts index 565287b2ec..ab99431a0c 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -3,6 +3,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { openVerifiedFileForRead, publishFileSync } from '@agent-device/host-kit/file'; import { readVersion } from '@agent-device/host-kit/version'; +import { DAEMON_RPC_PROTOCOL_VERSION } from '@agent-device/contracts/daemon-http'; import type { DaemonInfo } from './daemon-client-metadata.ts'; import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; @@ -28,8 +29,9 @@ let remoteHealthGeneration = 0; * The state-directory copy of the cache, so a CLI process does not pay a `/health` round trip that * an earlier process already made. Safe to reuse because every RPC sent from it carries the cached * instance preconditions: a replaced daemon or proxy upstream answers 409 before it dispatches, and - * the client probes again. The file names its daemon by a digest of client version, base URL and - * token, so it never holds the token or URL, and a client upgrade or token change reads as a miss. + * the client probes again. The file names its daemon by a digest of client version, RPC protocol + * version, base URL and token, so it never holds the token or URL, and a client upgrade, protocol + * change or token change reads as a miss. */ const PERSISTED_HEALTH_FILE = 'remote-daemon-health.json'; const PERSISTED_HEALTH_MAX_BYTES = 16 * 1024; @@ -47,7 +49,15 @@ function isCacheableRemoteHealth(health: RemoteDaemonHealth): boolean { function persistedIdentity(info: DaemonInfo): string { return crypto .createHash('sha256') - .update(JSON.stringify([readVersion(), info.baseUrl ?? '', info.token, info.pid])) + .update( + JSON.stringify([ + readVersion(), + DAEMON_RPC_PROTOCOL_VERSION, + info.baseUrl ?? '', + info.token, + info.pid, + ]), + ) .digest('hex'); } From 1e3df974dc3c5e8a109215da4c18a0681f0d740e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 21:46:30 +0100 Subject: [PATCH 05/10] test(daemon-client): stub only the timeout seam in the abort-timeout tests The request guard now lives in daemon-client-timeout.ts, so a full mock of that module dropped refuseAbortedRequest and the guard with it. The mock now spreads the real module and replaces only handleRequestTimeout. Co-Authored-By: Claude Opus 5.5 --- .../__tests__/daemon-client-transport-abort-timeout.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport-abort-timeout.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-abort-timeout.test.ts index dcae9a7162..b2b78b6954 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport-abort-timeout.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport-abort-timeout.test.ts @@ -32,7 +32,9 @@ const { handleRequestTimeoutCalls } = vi.hoisted(() => ({ handleRequestTimeoutCalls: [] as unknown[], })); -vi.mock('../daemon-client-timeout.ts', () => ({ +// Only the timeout seam is stubbed; the request guard in the same module stays real. +vi.mock('../daemon-client-timeout.ts', async (importOriginal) => ({ + ...(await importOriginal()), handleRequestTimeout: async (params: unknown) => { handleRequestTimeoutCalls.push(params); return new AppError('COMMAND_FAILED', 'Daemon request timed out', { From 84d687842e9e4cdf0a214b71f2d46d457280ecdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 21:48:16 +0100 Subject: [PATCH 06/10] fix(daemon-client): keep one persisted health entry per daemon identity A single file held the last identity only, so a client alternating between two remote daemons missed the cache on every call. Each entry now has its own file, named by a prefix of the identity digest; the full digest inside still has to match. The read and write stay the same: verified, bounded, owner-only, atomic 0600. Stale entries are tiny and never read, so nothing evicts them. Co-Authored-By: Claude Opus 5.5 --- .../daemon-client-remote-health-cache.test.ts | 34 +++++++++++++----- .../__tests__/daemon-client-transport.test.ts | 14 +++++--- .../src/daemon-client-remote-health-cache.ts | 35 +++++++++++-------- 3 files changed, 56 insertions(+), 27 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts index 8fe39dd174..747d38d409 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts @@ -61,12 +61,20 @@ test('a probe answer that lands after an invalidation is not cached', async () = assert.equal(probes, 1); }); -// The state dir holds one answer named by a digest of client version, URL and token. It holds neither -// secret, and any other identity, an unusable answer or an unreadable file reads as a miss. +/** The persisted entries in `stateDir`, one file per daemon identity. */ +function persistedFiles(stateDir: string): string[] { + return fs + .readdirSync(stateDir) + .filter((name) => name.startsWith('remote-daemon-health-')) + .map((name) => path.join(stateDir, name)); +} + +// Each identity has its own entry, named by a digest of client version, RPC protocol, URL and token. +// No entry holds either secret, and any other identity, an unusable answer or an unreadable file +// reads as a miss. test('persisted health is private and reused only by the identity that cached it', () => { const stateDir = mkdtempForTestSync('agent-device-remote-health-store-'); const store = { stateDir, readRecord: readCachedRemoteHealthRecord }; - const file = path.join(stateDir, 'remote-daemon-health.json'); const info = { baseUrl: 'http://remote.example.test:7777', token: 'store-secret', pid: 0 }; const forget = () => invalidateRemoteDaemonHealth(info); const reuse = (identity: typeof info) => { @@ -75,9 +83,11 @@ test('persisted health is private and reused only by the identity that cached it }; cacheRemoteDaemonHealth(info, { reachable: true }, stateDir); - assert.equal(fs.existsSync(file), false, 'an answer without an instance is not persisted'); + assert.deepEqual(persistedFiles(stateDir), [], 'an answer without an instance is not persisted'); cacheRemoteDaemonHealth(info, { ...HEALTHY, statusCode: 200, timedOut: true }, stateDir); + const [file] = persistedFiles(stateDir); + assert.ok(file, 'the usable answer is persisted'); const written = fs.readFileSync(file, 'utf8'); assert.equal(written.includes('store-secret'), false, 'the token is never written'); assert.equal(written.includes('remote.example.test'), false, 'the URL is never written'); @@ -95,10 +105,17 @@ test('persisted health is private and reused only by the identity that cached it assert.equal(reuse(info), undefined, 'another RPC protocol probes again'); rpcProtocol.current = 3; - invalidateRemoteDaemonHealth({ ...info, token: 'other-token' }, stateDir); - assert.equal(fs.existsSync(file), true, 'another identity leaves the entry alone'); + // Alternating between two daemons keeps both entries. + const other = { ...info, token: 'other-token' }; + cacheRemoteDaemonHealth(other, { reachable: true, instanceId: 'other-instance' }, stateDir); + assert.equal(persistedFiles(stateDir).length, 2); + assert.equal(reuse(info)?.instanceId, HEALTHY.instanceId); + assert.equal(reuse(other)?.instanceId, 'other-instance'); + + invalidateRemoteDaemonHealth(other, stateDir); + assert.deepEqual(persistedFiles(stateDir), [file], 'another identity leaves the entry alone'); invalidateRemoteDaemonHealth(info, stateDir); - assert.equal(fs.existsSync(file), false); + assert.deepEqual(persistedFiles(stateDir), []); }); // A shared state dir may hold an entry another user planted. Only a regular file this user owns and @@ -106,9 +123,10 @@ test('persisted health is private and reused only by the identity that cached it test.skipIf(process.platform === 'win32')('a planted persisted entry reads as a miss', () => { const stateDir = mkdtempForTestSync('agent-device-remote-health-planted-'); const store = { stateDir, readRecord: readCachedRemoteHealthRecord }; - const file = path.join(stateDir, 'remote-daemon-health.json'); const info = { baseUrl: 'http://remote.example.test:7777', token: 'planted', pid: 0 }; cacheRemoteDaemonHealth(info, HEALTHY, stateDir); + const [file] = persistedFiles(stateDir); + assert.ok(file); const entry = fs.readFileSync(file); const reuse = () => { invalidateRemoteDaemonHealth(info); 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 d1dfd694c5..a51b5e0674 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -714,7 +714,11 @@ async function instanceCheckingRemote( // What a new CLI process starts with: no health cached in memory, only what the state dir holds. const forgetInMemory = () => invalidateRemoteDaemonHealth({ baseUrl, token: 'persisted-secret', pid: 0 }); - const cacheFile = path.join(stateDir, 'remote-daemon-health.json'); + // One entry per daemon identity; this remote has one identity, so at most one entry. + const cacheFile = (): string | undefined => { + const [name] = fs.readdirSync(stateDir).filter((n) => n.startsWith('remote-daemon-health-')); + return name ? path.join(stateDir, name) : undefined; + }; return { server, paths, baseUrl, request, forgetInMemory, cacheFile }; } @@ -730,10 +734,10 @@ test('a later process reuses persisted remote health and still catches a replace assert.equal((await remote.request()).ok, true); assert.deepEqual(remote.paths, ['GET /health', 'POST /rpc', 'POST /rpc']); - const persisted = fs.readFileSync(remote.cacheFile, 'utf8'); + const persisted = fs.readFileSync(remote.cacheFile()!, 'utf8'); assert.equal(persisted.includes('persisted-secret'), false, 'the token is never written'); assert.equal(persisted.includes(remote.baseUrl), false, 'the URL is never written'); - assert.equal(fs.statSync(remote.cacheFile).mode & 0o077, 0, 'only the owner reads it'); + assert.equal(fs.statSync(remote.cacheFile()!).mode & 0o077, 0, 'only the owner reads it'); instanceId = 'persisted-two'; remote.forgetInMemory(); @@ -763,7 +767,7 @@ test('an unsent request from cached remote health opens the health gate', async assert.equal(error.details?.dispatched, 'no'); return true; }); - assert.equal(fs.existsSync(remote.cacheFile), false, 'the unreachable daemon is forgotten'); + assert.equal(remote.cacheFile(), undefined, 'the unreachable daemon is forgotten'); }); // Resend evidence is only what this process saw: a daemon error that carries the transport-failure @@ -817,7 +821,7 @@ test('a remote 5xx drops the persisted health without a resend', async (t) => { fail = true; remote.forgetInMemory(); await assert.rejects(remote.request()); - assert.equal(fs.existsSync(remote.cacheFile), false); + assert.equal(remote.cacheFile(), undefined); fail = false; assert.equal((await remote.request()).ok, true); assert.deepEqual(remote.paths, [ diff --git a/packages/daemon-client/src/daemon-client-remote-health-cache.ts b/packages/daemon-client/src/daemon-client-remote-health-cache.ts index ab99431a0c..92f6d6b8f7 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -29,11 +29,11 @@ let remoteHealthGeneration = 0; * The state-directory copy of the cache, so a CLI process does not pay a `/health` round trip that * an earlier process already made. Safe to reuse because every RPC sent from it carries the cached * instance preconditions: a replaced daemon or proxy upstream answers 409 before it dispatches, and - * the client probes again. The file names its daemon by a digest of client version, RPC protocol - * version, base URL and token, so it never holds the token or URL, and a client upgrade, protocol - * change or token change reads as a miss. + * the client probes again. Each daemon identity has its own file, named by a digest of client + * version, RPC protocol version, base URL and token, so no file holds the token or URL, and a client + * upgrade, protocol change or token change reads as a miss. Stale files are tiny and never read. */ -const PERSISTED_HEALTH_FILE = 'remote-daemon-health.json'; +const PERSISTED_HEALTH_FILE_PREFIX = 'remote-daemon-health-'; const PERSISTED_HEALTH_MAX_BYTES = 16 * 1024; function matchesRemoteIdentity(entry: RemoteHealthCacheEntry, info: DaemonInfo): boolean { @@ -61,8 +61,8 @@ function persistedIdentity(info: DaemonInfo): string { .digest('hex'); } -function persistedHealthPath(stateDir: string): string { - return path.join(stateDir, PERSISTED_HEALTH_FILE); +function persistedHealthPath(stateDir: string, identity: string): string { + return path.join(stateDir, `${PERSISTED_HEALTH_FILE_PREFIX}${identity.slice(0, 16)}.json`); } /** @@ -70,9 +70,12 @@ function persistedHealthPath(stateDir: string): string { * user owns and nobody else can write. A link, FIFO or other special file reads as a miss without * blocking, and the caller probes `/health` instead. */ -function readPersistedEntry(stateDir: string): { identity: unknown; health: unknown } | null { +function readPersistedEntry( + stateDir: string, + identity: string, +): { identity: unknown; health: unknown } | null { try { - const descriptor = openVerifiedFileForRead(persistedHealthPath(stateDir)); + const descriptor = openVerifiedFileForRead(persistedHealthPath(stateDir, identity)); if (descriptor === undefined) return null; try { const stats = fs.fstatSync(descriptor); @@ -102,8 +105,10 @@ function readPersistedHealth( info: DaemonInfo, store: PersistedHealthStore, ): RemoteDaemonHealth | undefined { - const persisted = readPersistedEntry(store.stateDir); - if (!persisted || persisted.identity !== persistedIdentity(info)) return undefined; + const identity = persistedIdentity(info); + const persisted = readPersistedEntry(store.stateDir, identity); + // The file name holds a digest prefix; the full digest inside rules out a prefix collision. + if (!persisted || persisted.identity !== identity) return undefined; const health: RemoteDaemonHealth = { reachable: true, ...store.readRecord(persisted.health) }; return isCacheableRemoteHealth(health) ? health : undefined; } @@ -122,11 +127,12 @@ function persistHealth(info: DaemonInfo, health: RemoteDaemonHealth, stateDir: s capabilities, upstream, }; - const entry = { identity: persistedIdentity(info), health: record }; + const identity = persistedIdentity(info); + const entry = { identity, health: record }; try { fs.mkdirSync(stateDir, { recursive: true }); publishFileSync({ - destination: persistedHealthPath(stateDir), + destination: persistedHealthPath(stateDir, identity), contents: `${JSON.stringify(entry)}\n`, mode: 0o600, }); @@ -134,9 +140,10 @@ function persistHealth(info: DaemonInfo, health: RemoteDaemonHealth, stateDir: s } function removePersistedHealth(info: DaemonInfo, stateDir: string): void { - if (readPersistedEntry(stateDir)?.identity !== persistedIdentity(info)) return; + const identity = persistedIdentity(info); + if (readPersistedEntry(stateDir, identity)?.identity !== identity) return; try { - fs.rmSync(persistedHealthPath(stateDir), { force: true }); + fs.rmSync(persistedHealthPath(stateDir, identity), { force: true }); } catch {} } From 3dd9d765c3f8652e92a50f57a35b0f3c1a8816bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 22:16:39 +0100 Subject: [PATCH 07/10] fix(daemon-client): drop disproved saved health and resend only on transport proof - A timeout before the connection opens clears the saved entry, like a failure before connect. - An instance-mismatch resend needs a 409 with the mismatch header that the transport read, not the reason in an error body. A second refusal on the resend clears the entry. - Timeout eviction compares the upstream instance too and ignores a caller abort. - The /health gate always probes live; remote resolution reads the saved entry once and reports whether the answer was saved. - Lease heartbeats get the same single refresh and resend. - Only instance IDs and capabilities are saved, and only header-valid IDs that echo neither the token nor the URL; a proxy answer needs its upstream ID. - The transport failure and timeout builders join the abort guard in daemon-client-timeout.ts to keep the transport under its line limit. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0006-daemon-rpc-protocol-version.md | 9 +- .../daemon-client-lease-beat.test.ts | 30 +++ ...mon-client-lifecycle-remote-health.test.ts | 45 +++- .../daemon-client-remote-health-cache.test.ts | 49 ++-- .../__tests__/daemon-client-transport.test.ts | 229 ++++++++++++++++-- .../src/daemon-client-lease-beat.ts | 6 +- .../src/daemon-client-remote-health-cache.ts | 56 +++-- .../src/daemon-client-remote-health-gate.ts | 21 +- .../src/daemon-client-timeout.ts | 48 ++++ .../src/daemon-client-transport.ts | 125 ++++------ packages/daemon-client/src/index.ts | 15 +- website/docs/docs/remote-proxy.md | 2 +- 12 files changed, 479 insertions(+), 156 deletions(-) diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index 1801eeb433..1037779a66 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -12,11 +12,13 @@ Accepted - A client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon. - The cache may outlive the client process in the state directory. Name the entry by a digest of the client version, RPC protocol version, base URL, and token. Do not write the token or the URL. - Read a persisted entry only from a bounded regular file that the current user owns and that nobody else can write. Otherwise, probe `/health`. -- If a cached RPC fails before its connection opens, probe `/health` as on first contact, within the command's remaining budget. Then send the RPC once more. Take this evidence only from the client's own transport, never from a reply. +- Persist only the instance IDs and capabilities. Cache an instance ID only when it is a valid HTTP header value that does not contain the token or the URL. Cache a proxy answer only with its upstream instance ID. +- If a cached RPC fails or times out before its connection opens, clear the cache. After a failure, probe `/health` live as on first contact, within the remaining budget, then send the RPC once more. Do this for every send that carries the cached instance IDs, lease heartbeats included. Take this evidence only from the client's own transport, never from a reply. +- A forced refresh always probes `/health` live, even when the cache cannot be cleared. - Clear the cache on a remote HTTP 5xx. Do not resend the RPC. - Before you refuse a command for a capability that only the cache lacks, probe `/health` again. - Send those instance IDs as conditional headers on every cached RPC. Peers without complete instance IDs retain per-command probes. -- After a stale-instance refusal, clear the cache and probe `/health` again. Retry the refused RPC once, and only if the new peer's protocol is compatible. +- After a stale-instance refusal, clear the cache and probe `/health` again. Retry the refused RPC once, and only if the new peer's protocol is compatible. Act only on a 409 with the mismatch header that the client's transport read. Clear the cache again if the retry is refused too. - A peer that advertises an instance ID must continue to honor the conditional RPC headers in future versions. - Change `rpcProtocolVersion` only when older and newer peers cannot safely communicate over the HTTP RPC boundary for existing commands. - Do not change `rpcProtocolVersion` for additive changes. @@ -61,6 +63,9 @@ A cached RPC whose connection never opened proves that nothing was dispatched. Only the client's own transport supplies that evidence; a reply can carry the same error details after the command ran. The client then clears the cache and probes `/health` as on first contact, with the recovery and typed refusal of that path, and sends the RPC once more, all within the command's remaining budget. A cached RPC that fails after its connection opened is not resent. +A timeout before the connection opened also clears the cache; its budget is spent, so nothing is resent. +Only a 409 with the mismatch header that the client's transport read counts as a stale-instance refusal; the same reason in an error body does not. +The persisted record holds only the instance IDs and capabilities, and only header-valid IDs that echo neither the token nor the URL. A remote HTTP 5xx clears the cache, whatever its framing, because a proxy answers that way while its upstream daemon restarts. A timeout leaves the decision to the timeout route, which clears the cache only when its `/health` probe finds the daemon gone or replaced. A capability that only the cached answer lacks is checked against a fresh probe before the client refuses the command, because the daemon may have been upgraded. diff --git a/packages/daemon-client/src/__tests__/daemon-client-lease-beat.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lease-beat.test.ts index 9c57045dfd..9255a37156 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lease-beat.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lease-beat.test.ts @@ -708,6 +708,36 @@ describe('buildUploadLeaseHeartbeat', () => { assert.equal('ttlMs' in first!.params, false); }); + test('a beat from cached health that never connects re-probes once within its own budget', async () => { + // Nothing listens, so the beat provably never left. A beat relying on a cached `/health` + // answer gets the same single refresh a command gets, under the beat's own budget and signal. + const closed = net.createServer(); + const port = await listenOnLoopback(closed); + await closeLoopbackServer(closed); + const gateCalls: { budgetMs: number | undefined; signal: AbortSignal | undefined }[] = []; + const signal = new AbortController().signal; + const beat = buildUploadLeaseHeartbeat( + { baseUrl: `http://127.0.0.1:${String(port)}`, token: 'remote-token', pid: 0 }, + { ...settings, transportPreference: 'auto' }, + installRequest, + async (budgetMs, gateSignal) => { + gateCalls.push({ budgetMs, signal: gateSignal }); + throw new AppError('COMMAND_FAILED', 'Remote daemon is unavailable', { + reason: 'remote_daemon_unavailable', + }); + }, + ); + assert.ok(beat); + await assert.rejects(beat!(1_000, signal), (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, 'remote_daemon_unavailable'); + return true; + }); + assert.equal(gateCalls.length, 1); + assert.equal(gateCalls[0]!.signal, signal); + assert.ok(gateCalls[0]!.budgetMs! > 0 && gateCalls[0]!.budgetMs! <= 1_000); + }); + test('a beat that never answers dies at its budget, not at the heartbeat policy', async () => { vi.useFakeTimers(); // The daemon accepts the connection and never answers — a half-open pipe. The beat exists to diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts index 1c0fefc2fb..9338f62aeb 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts @@ -4,6 +4,7 @@ // and `details.dispatched` instead of comparing the message. import assert from 'node:assert/strict'; +import fs from 'node:fs'; import http from 'node:http'; import { test } from 'vitest'; import { @@ -16,7 +17,11 @@ import { AppError } from '@agent-device/kernel/errors'; import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; import { DAEMON_UNAVAILABLE_REASONS } from '../daemon-lifecycle-errors.ts'; import { sendToDaemon } from '../index.ts'; -import { cachedRemoteDaemonHealth } from '../daemon-client-remote-health-gate.ts'; +import { + probeRemoteDaemonHealth, + readCachedRemoteDaemonHealth, + refreshRemoteDaemonHealth, +} from '../daemon-client-remote-health-gate.ts'; // A press, so the refusal states the fact a caller needs before resending a mutating command. function remotePress(baseUrl: string) { @@ -177,16 +182,16 @@ test('a health caller probes on its own bound, and a settled answer is cached', if (await skipWhenLoopbackUnavailable(t)) return; const remote = await slowHealthyRemote(300); try { - const unbounded = cachedRemoteDaemonHealth(remote.info, remote.stateDir); - const bounded = await cachedRemoteDaemonHealth(remote.info, remote.stateDir, 50); + const unbounded = probeRemoteDaemonHealth(remote.info, remote.stateDir); + const bounded = await probeRemoteDaemonHealth(remote.info, remote.stateDir, 50); assert.equal(bounded.reachable, false); assert.equal(bounded.timedOut, true); assert.equal((await unbounded).reachable, true); assert.equal(remote.probes(), 2, 'each caller sent its own probe'); - // The settled answer is cached, so a later bounded caller reads it without probing. + // The settled answer is cached, so a later caller reads it without probing. assert.equal( - (await cachedRemoteDaemonHealth(remote.info, remote.stateDir, 50)).reachable, + (await readCachedRemoteDaemonHealth(remote.info, remote.stateDir))?.reachable, true, ); assert.equal(remote.probes(), 2); @@ -200,12 +205,9 @@ test('an aborted or budgetless health caller sends no probe', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const remote = await slowHealthyRemote(0); try { + assert.equal((await probeRemoteDaemonHealth(remote.info, remote.stateDir, 0)).reachable, false); assert.equal( - (await cachedRemoteDaemonHealth(remote.info, remote.stateDir, 0)).reachable, - false, - ); - assert.equal( - (await cachedRemoteDaemonHealth(remote.info, remote.stateDir, undefined, AbortSignal.abort())) + (await probeRemoteDaemonHealth(remote.info, remote.stateDir, undefined, AbortSignal.abort())) .reachable, false, ); @@ -214,3 +216,26 @@ test('an aborted or budgetless health caller sends no probe', async (t) => { await closeLoopbackServer(remote.handler); } }); + +// A forced refresh asks the daemon even when the saved entry cannot be removed, so it never reuses +// the answer it was asked to verify. +test.skipIf(process.platform === 'win32')( + 'a forced refresh probes live whatever is saved', + async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const remote = await slowHealthyRemote(0); + try { + await probeRemoteDaemonHealth(remote.info, remote.stateDir); + assert.equal(remote.probes(), 1); + fs.chmodSync(remote.stateDir, 0o500); + try { + await refreshRemoteDaemonHealth(remote.info, remote.stateDir, undefined); + } finally { + fs.chmodSync(remote.stateDir, 0o700); + } + assert.equal(remote.probes(), 2); + } finally { + await closeLoopbackServer(remote.handler); + } + }, +); diff --git a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts index 747d38d409..42185a26c1 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts @@ -6,7 +6,7 @@ import { test, vi } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { cacheRemoteDaemonHealth, - cachedRemoteHealth, + probedRemoteHealth, invalidateRemoteDaemonHealth, readCachedRemoteHealth, } from '../daemon-client-remote-health-cache.ts'; @@ -38,27 +38,46 @@ const HEALTHY: RemoteDaemonHealth = { reachable: true, instanceId: 'remote-insta test('a probe answer that lands after an invalidation is not cached', async () => { const info = { baseUrl: 'http://remote.example.test:7777', token: 'cache-test', pid: 0 }; let answer: (health: RemoteDaemonHealth) => void = () => {}; - const inFlight = cachedRemoteHealth( + const inFlight = probedRemoteHealth( info, () => new Promise((resolve) => (answer = resolve)), ); invalidateRemoteDaemonHealth(info); answer(HEALTHY); assert.deepEqual(await inFlight, HEALTHY); - - let probes = 0; - const next = await cachedRemoteHealth(info, async () => { - probes += 1; - return HEALTHY; - }); - assert.deepEqual(next, HEALTHY); - assert.equal(probes, 1, 'the stale answer was not cached'); + assert.equal(readCachedRemoteHealth(info), undefined, 'the stale answer was not cached'); // The closest negative: with no invalidation in flight, that usable answer is cached. - await cachedRemoteHealth(info, async () => { - probes += 1; - return HEALTHY; - }); - assert.equal(probes, 1); + await probedRemoteHealth(info, async () => HEALTHY); + assert.deepEqual(readCachedRemoteHealth(info), HEALTHY); +}); + +// Only admission metadata is kept, and only IDs a later request can send as headers without echoing +// the credential or URL. A proxy answer must name its upstream instance. +test('only usable instance IDs are cached, and a proxy needs its upstream ID', () => { + const info = { baseUrl: 'http://remote.example.test:7777', token: 'cache-secret', pid: 0 }; + const cached = (health: RemoteDaemonHealth) => { + invalidateRemoteDaemonHealth(info); + cacheRemoteDaemonHealth(info, health); + return readCachedRemoteHealth(info) !== undefined; + }; + assert.equal(cached(HEALTHY), true, 'the closest negative: a plain daemon ID'); + assert.equal(cached({ reachable: true, instanceId: 'bad\nid' }), false, 'not a header value'); + assert.equal( + cached({ reachable: true, instanceId: 'x-cache-secret' }), + false, + 'echoes the token', + ); + assert.equal( + cached({ reachable: true, instanceId: `${info.baseUrl}/x` }), + false, + 'echoes the URL', + ); + assert.equal(cached({ reachable: true, instanceId: 'p', service: 'agent-device-proxy' }), false); + assert.equal( + cached({ reachable: true, instanceId: 'p', upstream: { instanceId: 'u' } }), + true, + 'a proxy with its upstream ID', + ); }); /** The persisted entries in `stateDir`, one file per daemon identity. */ 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 a51b5e0674..3aed530197 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; import http from 'node:http'; import net from 'node:net'; import fs from 'node:fs'; @@ -217,56 +218,56 @@ test('persistent remote client caches health and retries a refused stale instanc error instanceof AppError && error.details?.remoteRpcProtocolVersion === DAEMON_RPC_PROTOCOL_VERSION + 1; - assert.equal((await request('first')).ok, true); - assert.equal((await request('first')).ok, true); + assert.equal((await request('token-one')).ok, true); + assert.equal((await request('token-one')).ok, true); assert.deepEqual(paths, ['GET /health', 'POST /rpc', 'POST /rpc']); assert.deepEqual(rpcHeaders, ['first-instance', 'first-instance']); - assert.equal((await request('second')).ok, true); + assert.equal((await request('token-two')).ok, true); assert.deepEqual(paths.slice(3), ['GET /health', 'POST /rpc']); daemonError = true; await assert.rejects( - request('second'), + request('token-two'), (error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS', ); daemonError = false; - assert.equal((await request('second')).ok, true); + assert.equal((await request('token-two')).ok, true); assert.deepEqual(paths.slice(5, 7), ['POST /rpc', 'POST /rpc']); failRpc = true; - await assert.rejects(request('second')); + await assert.rejects(request('token-two')); failRpc = false; rpcProtocolVersion = DAEMON_RPC_PROTOCOL_VERSION + 1; - await assert.rejects(request('second'), incompatible); + await assert.rejects(request('token-two'), incompatible); assert.deepEqual(paths.slice(7, 9), ['POST /rpc', 'GET /health']); rpcProtocolVersion = DAEMON_RPC_PROTOCOL_VERSION; - assert.equal((await request('second')).ok, true); + assert.equal((await request('token-two')).ok, true); assert.deepEqual(paths.slice(9, 11), ['GET /health', 'POST /rpc']); - assert.equal((await request('second', `${baseUrl}/alt`)).ok, true); + assert.equal((await request('token-two', `${baseUrl}/alt`)).ok, true); assert.deepEqual(paths.slice(11, 13), ['GET /alt/health', 'POST /alt/rpc']); instanceId = 'replacement-instance'; const beforeRestart = executed; - assert.equal((await request('second', `${baseUrl}/alt`)).ok, true); + assert.equal((await request('token-two', `${baseUrl}/alt`)).ok, true); assert.deepEqual(paths.slice(13, 16), ['POST /alt/rpc', 'GET /alt/health', 'POST /alt/rpc']); assert.equal(executed, beforeRestart + 1); assert.deepEqual(rpcHeaders.slice(-2), ['first-instance', 'replacement-instance']); - assert.equal((await request('second', `${baseUrl}/alt`)).ok, true); + assert.equal((await request('token-two', `${baseUrl}/alt`)).ok, true); assert.deepEqual(paths.slice(16, 17), ['POST /alt/rpc']); instanceId = 'incompatible-instance'; rpcProtocolVersion = DAEMON_RPC_PROTOCOL_VERSION + 1; const beforeSkew = executed; - await assert.rejects(request('second', `${baseUrl}/alt`), incompatible); + await assert.rejects(request('token-two', `${baseUrl}/alt`), incompatible); assert.deepEqual(paths.slice(17, 19), ['POST /alt/rpc', 'GET /alt/health']); assert.equal(executed, beforeSkew); legacy = true; rpcProtocolVersion = DAEMON_RPC_PROTOCOL_VERSION; - assert.equal((await request('legacy')).ok, true); - assert.equal((await request('legacy')).ok, true); + assert.equal((await request('token-legacy')).ok, true); + assert.equal((await request('token-legacy')).ok, true); assert.deepEqual(paths.slice(19), ['GET /health', 'POST /rpc', 'GET /health', 'POST /rpc']); assert.deepEqual(rpcHeaders.slice(-2), [undefined, undefined]); } finally { @@ -719,7 +720,7 @@ async function instanceCheckingRemote( const [name] = fs.readdirSync(stateDir).filter((n) => n.startsWith('remote-daemon-health-')); return name ? path.join(stateDir, name) : undefined; }; - return { server, paths, baseUrl, request, forgetInMemory, cacheFile }; + return { server, paths, baseUrl, stateDir, request, forgetInMemory, cacheFile }; } // Each CLI call is a new process, so the health a first call probed is kept in the state dir and a @@ -794,7 +795,11 @@ test('a daemon error that claims the request was unsent is not resent', async (t assert.equal((await remote.request()).ok, true); remote.forgetInMemory(); forge = true; - await assert.rejects(remote.request()); + await assert.rejects( + remote.request(), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'daemon_transport_failure', + ); assert.deepEqual(remote.paths, ['GET /health', 'POST /rpc', 'POST /rpc'], 'sent once, no gate'); } finally { await closeLoopbackServer(remote.server); @@ -820,7 +825,10 @@ test('a remote 5xx drops the persisted health without a resend', async (t) => { assert.equal((await remote.request()).ok, true); fail = true; remote.forgetInMemory(); - await assert.rejects(remote.request()); + await assert.rejects( + remote.request(), + (error: unknown) => error instanceof AppError && error.code === 'COMMAND_FAILED', + ); assert.equal(remote.cacheFile(), undefined); fail = false; assert.equal((await remote.request()).ok, true); @@ -875,6 +883,193 @@ test('the gate after an unsent cached request keeps the deadline and the cancell assert.ok(budgets[0]! > 0 && budgets[0]! <= 5_000, `gate budget ${budgets[0]}`); }); +// A connection that never opens before the timeout proves the request never left, so the saved +// answer it relied on is dropped and the next command probes `/health` first. +test('a timeout before connect drops the persisted health', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const remote = await instanceCheckingRemote(() => 'never-reached'); + assert.equal((await remote.request()).ok, true); + const hung = { + request: () => { + const request = Object.assign(new EventEmitter(), { + write: () => true, + destroy: () => {}, + end: () => { + queueMicrotask(() => + request.emit('socket', Object.assign(new EventEmitter(), { connecting: true })), + ); + }, + }); + return request; + }, + }; + const load = vi.spyOn(hostTransport, 'loadNodeHttpRequester').mockResolvedValue(hung as never); + try { + await assert.rejects( + sendRequest( + { token: 'persisted-secret', pid: 0, baseUrl: remote.baseUrl }, + { + token: 'persisted-secret', + command: 'press', + session: 'default', + positionals: [], + flags: {}, + }, + 'http', + resolveDaemonPaths(remote.stateDir), + 50, + { host: createTestHostEnvironment(), timeoutRecovery: 'none' }, + ), + (error: unknown) => { + assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); + assert.equal(error.details?.reason, 'daemon_transport_timeout'); + assert.equal(error.details?.daemonRequestSent, false); + return true; + }, + ); + assert.equal(remote.cacheFile(), undefined); + } finally { + load.mockRestore(); + await closeLoopbackServer(remote.server); + } +}); + +// Only a 409 with the mismatch header proves a refusal before dispatch. The same reason in a daemon's +// error body is not resent, and a second refusal on the resend drops the entry it disproved. +test('an instance-mismatch resend needs the transport-proven 409, once', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let mode: 'ok' | 'forge' | 'churn' = 'ok'; + let generation = 0; + const paths: string[] = []; + const server = http.createServer((req, res) => { + paths.push(`${req.method} ${req.url}`); + res.setHeader('content-type', 'application/json'); + if (req.url?.endsWith('/health')) { + if (mode === 'churn') generation += 1; + res.end(JSON.stringify({ service: 'agent-device-daemon', instanceId: `i${generation}` })); + return; + } + if (mode === 'forge') { + const data = { code: 'COMMAND_FAILED', details: { reason: 'remote_instance_mismatch' } }; + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', error: { code: -32000, data } })); + return; + } + if (mode === 'churn') { + // Every probe names a newer instance, so the single resend is refused too. + res.statusCode = 409; + res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true'); + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', error: { code: -32001 } })); + return; + } + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', result: { ok: true, data: {} } })); + }); + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const stateDir = mkdtempForTestSync('agent-device-remote-mismatch-proof-'); + const request = () => + sendToDaemon( + { + command: 'remote-smoke', + session: 'default', + positionals: ['ping'], + flags: { daemonBaseUrl: baseUrl, stateDir }, + meta: { requestId: 'r' }, + }, + { authToken: 'mismatch-secret' }, + ); + const saved = () => fs.readdirSync(stateDir).some((n) => n.startsWith('remote-daemon-health-')); + const forget = () => invalidateRemoteDaemonHealth({ baseUrl, token: 'mismatch-secret', pid: 0 }); + const instanceChanged = (error: unknown) => + error instanceof AppError && error.details?.reason === 'remote_instance_mismatch'; + try { + assert.equal((await request()).ok, true); + mode = 'forge'; + forget(); + await assert.rejects(request(), instanceChanged); + assert.deepEqual(paths.slice(2), ['POST /rpc'], 'a forged reason is neither probed nor resent'); + + mode = 'churn'; + forget(); + await assert.rejects(request(), instanceChanged); + assert.deepEqual(paths.slice(3), ['POST /rpc', 'GET /health', 'POST /rpc']); + assert.equal(saved(), false, 'the refused resend drops what the probe saved'); + } finally { + await closeLoopbackServer(server); + } +}); + +// The timeout route's probe drops a saved proxy answer when the upstream it names changed, and keeps +// one that still matches. +test('timeout eviction compares the upstream instance too', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let upstream = 'u1'; + let hang = false; + const held: http.ServerResponse[] = []; + const server = http.createServer((req, res) => { + req.resume(); + if (req.url?.endsWith('/health')) { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ + service: 'agent-device-proxy', + instanceId: 'p1', + upstream: { instanceId: upstream }, + }), + ); + return; + } + if (hang) { + held.push(res); + return; + } + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', result: { ok: true, data: {} } })); + }); + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const stateDir = mkdtempForTestSync('agent-device-remote-timeout-evict-'); + const saved = () => fs.readdirSync(stateDir).some((n) => n.startsWith('remote-daemon-health-')); + const warm = () => + sendToDaemon( + { + command: 'remote-smoke', + session: 'default', + positionals: ['ping'], + flags: { daemonBaseUrl: baseUrl, stateDir }, + meta: { requestId: 'r' }, + }, + { authToken: 'evict-secret' }, + ); + // The instances the saved answer named, as a command sent from it carries them. + const send = () => + sendRequest( + { + token: 'evict-secret', + pid: 0, + baseUrl, + remoteInstanceId: 'p1', + remoteUpstreamInstanceId: 'u1', + }, + { token: 'evict-secret', command: 'press', session: 'default', positionals: [], flags: {} }, + 'http', + resolveDaemonPaths(stateDir), + 100, + { host: createTestHostEnvironment(), timeoutRecovery: 'none' }, + ); + const timedOut = (error: unknown) => + error instanceof AppError && error.details?.reason === 'daemon_transport_timeout'; + try { + assert.equal((await warm()).ok, true); + hang = true; + await assert.rejects(send(), timedOut); + assert.equal(saved(), true, 'the closest negative: matching instances keep the entry'); + upstream = 'u2'; + await assert.rejects(send(), timedOut); + assert.equal(saved(), false); + } finally { + for (const res of held) res.destroy(); + await closeLoopbackServer(server); + } +}); + // A transport failure drops the cached health of a remote daemon only: a local daemon has no cached // health, so its failed request neither invalidates nor loads the remote health cache. test('a transport failure invalidates cached health for a remote daemon only', async (t) => { diff --git a/packages/daemon-client/src/daemon-client-lease-beat.ts b/packages/daemon-client/src/daemon-client-lease-beat.ts index 6235954061..59ca2ac3d8 100644 --- a/packages/daemon-client/src/daemon-client-lease-beat.ts +++ b/packages/daemon-client/src/daemon-client-lease-beat.ts @@ -15,7 +15,7 @@ import { } from '@agent-device/contracts/lease-scope'; import type { DaemonClientSettings } from './daemon-client-lifecycle.ts'; import { isRemoteDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; -import { sendRequest } from './daemon-client-transport.ts'; +import { sendRequest, type SendRequestOptions } from './daemon-client-transport.ts'; // The lease beat: what keeps a remote lease alive across a client-side phase the daemon never sees. // @@ -306,6 +306,7 @@ export function buildUploadLeaseHeartbeat( info: DaemonInfo, settings: DaemonClientSettings, request: Omit, + remoteHealthGate?: SendRequestOptions['remoteHealthGate'], ): ((budgetMs: number, signal: AbortSignal) => Promise) | undefined { if (!isRemoteDaemon(info)) return undefined; const leaseScope = leaseScopeFromRequest(request); @@ -328,6 +329,7 @@ export function buildUploadLeaseHeartbeat( // The beat's own budget governs; the command's heartbeat policy only ever caps it, and an // unbounded policy leaves the budget standing on its own. policyTimeoutMs === undefined ? budgetMs : Math.min(policyTimeoutMs, budgetMs), - { host: settings.host, signal }, + // A beat sent from a cached `/health` answer gets the same refresh and single resend. + { host: settings.host, signal, remoteHealthGate }, ); } diff --git a/packages/daemon-client/src/daemon-client-remote-health-cache.ts b/packages/daemon-client/src/daemon-client-remote-health-cache.ts index 92f6d6b8f7..d85b270d3c 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -40,9 +40,31 @@ function matchesRemoteIdentity(entry: RemoteHealthCacheEntry, info: DaemonInfo): return entry.baseUrl === info.baseUrl && entry.token === info.token && entry.pid === info.pid; } -function isCacheableRemoteHealth(health: RemoteDaemonHealth): boolean { +const INSTANCE_ID_MAX_LENGTH = 256; +// The characters Node accepts in a header value: an ID outside them could never be sent. +const HEADER_VALUE = /^[\t\u0020-\u007e\u0080-\u00ff]+$/; + +/** + * An instance ID a later request can carry as its precondition header: a bounded, valid header + * value that does not echo the credential or the URL this client sent to `/health`. + */ +function isUsableInstanceId(value: string | undefined, info: DaemonInfo): value is string { + return ( + typeof value === 'string' && + value.length <= INSTANCE_ID_MAX_LENGTH && + HEADER_VALUE.test(value) && + !(info.token && value.includes(info.token)) && + !(info.baseUrl && value.includes(info.baseUrl)) + ); +} + +// A proxy fences its upstream only through the upstream ID, so a proxy answer needs one. +function isCacheableRemoteHealth(health: RemoteDaemonHealth, info: DaemonInfo): boolean { + const needsUpstream = health.upstream !== undefined || health.service === 'agent-device-proxy'; return ( - health.reachable && !!health.instanceId && (!health.upstream || !!health.upstream.instanceId) + health.reachable && + isUsableInstanceId(health.instanceId, info) && + (!needsUpstream || isUsableInstanceId(health.upstream?.instanceId, info)) ); } @@ -110,22 +132,20 @@ function readPersistedHealth( // The file name holds a digest prefix; the full digest inside rules out a prefix collision. if (!persisted || persisted.identity !== identity) return undefined; const health: RemoteDaemonHealth = { reachable: true, ...store.readRecord(persisted.health) }; - return isCacheableRemoteHealth(health) ? health : undefined; + return isCacheableRemoteHealth(health, info) ? health : undefined; } // The cache only saves a round trip, so a state directory it cannot write or remove from leaves the // command to the next probe rather than failing it. function persistHealth(info: DaemonInfo, health: RemoteDaemonHealth, stateDir: string): void { - const { service, version, rpcProtocolVersion, instanceId, hostArch, capabilities, upstream } = - health; + // Only what admits a later request: the instance preconditions and the capabilities. + const { instanceId, capabilities, upstream } = health; const record = { - service, - version, - rpcProtocolVersion, instanceId, - hostArch, capabilities, - upstream, + ...(upstream + ? { upstream: { instanceId: upstream.instanceId, capabilities: upstream.capabilities } } + : {}), }; const identity = persistedIdentity(info); const entry = { identity, health: record }; @@ -152,7 +172,7 @@ export function cacheRemoteDaemonHealth( health: RemoteDaemonHealth, stateDir?: string, ): void { - if (!isCacheableRemoteHealth(health)) return; + if (!isCacheableRemoteHealth(health, info)) return; remoteHealthCache = { baseUrl: info.baseUrl ?? '', token: info.token, @@ -184,20 +204,16 @@ export function readCachedRemoteHealth( } /** - * The cached answer for this daemon, or `probe`'s, which is cached when it is usable and no - * invalidation landed while it was in flight. + * A live answer from `probe`, cached when it is usable and no invalidation landed while it was in + * flight. It never reads a cached answer, so a forced refresh always asks the daemon. */ -export async function cachedRemoteHealth( +export async function probedRemoteHealth( info: DaemonInfo, probe: () => Promise, - store?: PersistedHealthStore, + stateDir?: string, ): Promise { - const cached = readCachedRemoteHealth(info, store); - if (cached) return cached; const generation = remoteHealthGeneration; const health = await probe(); - if (generation === remoteHealthGeneration) { - cacheRemoteDaemonHealth(info, health, store?.stateDir); - } + if (generation === remoteHealthGeneration) cacheRemoteDaemonHealth(info, health, stateDir); return health; } diff --git a/packages/daemon-client/src/daemon-client-remote-health-gate.ts b/packages/daemon-client/src/daemon-client-remote-health-gate.ts index 9d71651d65..26089dc04b 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-gate.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-gate.ts @@ -20,24 +20,25 @@ export async function readCachedRemoteDaemonHealth( return readCachedRemoteHealth(info, { stateDir, readRecord: readCachedRemoteHealthRecord }); } -/** The remote `/health` answer within this caller's bound, through the cache. */ -export async function cachedRemoteDaemonHealth( +/** A live remote `/health` answer within this caller's bound, cached for later commands. */ +export async function probeRemoteDaemonHealth( info: DaemonInfo, stateDir: string, probeTimeoutMs?: number, callerSignal?: AbortSignal, ): Promise { - const { cachedRemoteHealth } = await loadRemoteHealthCache(); - return await cachedRemoteHealth( + const { probedRemoteHealth } = await loadRemoteHealthCache(); + return await probedRemoteHealth( info, () => readRemoteDaemonHealth(info, probeTimeoutMs, callerSignal), - { stateDir, readRecord: readCachedRemoteHealthRecord }, + stateDir, ); } /** - * Probes a remote daemon's `/health` before anything is sent to it, re-probing a daemon that is there - * but not ready for the recovery budget, and points `info` at the daemon that answered. + * Probes a remote daemon's `/health` live before anything is sent to it, re-probing a daemon that is + * there but not ready for the recovery budget, and points `info` at the daemon that answered. It + * never reads a saved answer, so a caller that already looked one up has made its only lookup. */ export async function openRemoteHealthGate( info: DaemonInfo, @@ -46,7 +47,7 @@ export async function openRemoteHealthGate( ): Promise { // The command's budget starts with the first probe, which already runs under it and its signal. const deadline = performance.now() + (healthRecovery?.budgetMs ?? 0); - let health = await cachedRemoteDaemonHealth( + let health = await probeRemoteDaemonHealth( info, stateDir, healthRecovery?.budgetMs, @@ -57,7 +58,7 @@ export async function openRemoteHealthGate( const { recoverRemoteDaemonHealth } = await import('./daemon-client-remote-health-recovery.ts'); health = await recoverRemoteDaemonHealth({ info, - probe: (budgetMs, signal) => cachedRemoteDaemonHealth(info, stateDir, budgetMs, signal), + probe: (budgetMs, signal) => probeRemoteDaemonHealth(info, stateDir, budgetMs, signal), failedProbe: health, recovery: healthRecovery, deadline, @@ -67,7 +68,7 @@ export async function openRemoteHealthGate( applyRemoteDaemonHealth(info, health); } -/** Drops the cached answer for this daemon, then probes it as on first contact. */ +/** Drops the cached answer for this daemon, then probes it live even when the drop failed. */ export async function refreshRemoteDaemonHealth( info: DaemonInfo, stateDir: string, diff --git a/packages/daemon-client/src/daemon-client-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index 47245888f2..d3780f4986 100644 --- a/packages/daemon-client/src/daemon-client-timeout.ts +++ b/packages/daemon-client/src/daemon-client-timeout.ts @@ -543,3 +543,51 @@ export function createRequestGuard(params: { }, }; } + +/** + * `daemonRequestSent` is required: the client discloses dispatch from it, and a producer that + * could not say would otherwise be read as sent. + */ +export function handleTransportError( + err: unknown, + requestId: string | undefined, + remote: boolean, + daemonRequestSent: boolean, +): AppError { + emitDiagnostic({ + level: 'error', + phase: 'daemon_request_socket_error', + data: { + requestId, + message: err instanceof Error ? err.message : String(err), + }, + }); + return new AppError( + 'COMMAND_FAILED', + 'Failed to communicate with daemon', + { + daemonRequestSent, + reason: DAEMON_TRANSPORT_REASONS.failure.reason, + requestId, + hint: remote + ? 'Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.' + : 'Retry command. If this persists, clean stale daemon metadata and start a fresh session.', + }, + err instanceof Error ? err : undefined, + ); +} + +export function requestTimeoutError( + timeoutMs: number, + requestId: string | undefined, + daemonRequestSent: boolean, + remoteResponseStarted?: boolean, +): AppError { + return new AppError('COMMAND_FAILED', 'Daemon request timed out', { + reason: DAEMON_TRANSPORT_REASONS.timeout.reason, + timeoutMs, + requestId, + daemonRequestSent, + ...(remoteResponseStarted ? { remoteResponseStarted: true } : {}), + }); +} diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index fde17adee3..83706ab9ba 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -4,7 +4,6 @@ import type { RequestProgressSink } from '@agent-device/contracts/progress'; import net from 'node:net'; import { AppError } from '@agent-device/kernel/errors'; import { loadNodeHttpRequester, readNodeHttpResponseBody } from '@agent-device/host-kit/transport'; -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { assertScriptArtifactsCapability, readDaemonCapabilities, @@ -36,7 +35,9 @@ import { import { abortedRequestError, handleRequestTimeout, + handleTransportError, refuseAbortedRequest, + requestTimeoutError, } from './daemon-client-timeout.ts'; import { isRemoteDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; @@ -47,7 +48,7 @@ import type { } from './daemon-client-loopback-probe.ts'; type ResolvedDaemonTransport = LoopbackTransport; -type SendRequestOptions = { +export type SendRequestOptions = { /** The host whose working directory and environment this request's client-side work reads. */ host: HostEnvironment; onProgress?: RequestProgressSink; @@ -65,7 +66,10 @@ type SendRequestOptions = { */ timeoutRecovery?: 'retire-unresponsive' | 'none'; /** Re-probes a daemon whose `/health` answer was cached, before an unsent request is resent. */ - remoteHealthGate?: (budgetMs: number | undefined) => Promise; + remoteHealthGate?: ( + budgetMs: number | undefined, + signal: AbortSignal | undefined, + ) => Promise; }; const LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS = 500; @@ -370,7 +374,11 @@ async function recoverFromTimeout( responseStarted: error.details.remoteResponseStarted === true, readRemoteHealth: async (budgetMs) => { const health = await readDaemonHttpHealth(info, budgetMs, options.signal); - if (!health.reachable || health.instanceId !== info.remoteInstanceId) { + // A caller abort proves nothing about the daemon; any other miss or changed instance does. + const replaced = + health.instanceId !== info.remoteInstanceId || + health.upstream?.instanceId !== info.remoteUpstreamInstanceId; + if (!options.signal?.aborted && (!health.reachable || replaced)) { await invalidateRemoteDaemonHealth(info, statePaths.baseDir); } return health; @@ -421,7 +429,12 @@ async function sendRequestWithFallback( try { return await sendRequestWithTransport(info, req, statePaths, timeoutMs, transport, options); } catch (error) { - if (info.baseUrl && isRemoteInstanceMismatch(error)) { + if ( + info.baseUrl && + isRemoteInstanceMismatch(error) && + error instanceof AppError && + PROVEN_STALE.has(error) + ) { return await retryAfterRemoteInstanceMismatch( info, req, @@ -435,12 +448,7 @@ async function sendRequestWithFallback( if (dropsCachedRemoteHealth(error)) { await invalidateRemoteDaemonHealth(info, statePaths.baseDir); } - if ( - info.baseUrl && - options.remoteHealthGate && - error instanceof AppError && - PROVEN_UNSENT.has(error) - ) { + if (info.baseUrl && options.remoteHealthGate && isProvenUnsentFailure(error)) { return await resendAfterRemoteHealthGate( options.remoteHealthGate, info, @@ -503,7 +511,7 @@ async function resendAfterRemoteHealthGate( const requestId = req.meta?.requestId; const gateBudgetMs = remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline); try { - await gate(gateBudgetMs); + await gate(gateBudgetMs, options.signal); } catch (error) { refuseAbortedRequest(options.signal, requestId); throw error; @@ -547,8 +555,19 @@ export function applyRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHe info.capabilities = (health.upstream ?? health).capabilities; } -/** Failures raised here before the connection opened; a daemon error can carry the same details. */ +// Evidence only this module records; a daemon error can carry the same reason and details. +/** Failures and timeouts raised here before the HTTP connection opened. */ const PROVEN_UNSENT = new WeakSet(); +/** Refusals raised here from a 409 with the instance-mismatch header. */ +const PROVEN_STALE = new WeakSet(); + +function isProvenUnsentFailure(error: unknown): boolean { + return ( + error instanceof AppError && + PROVEN_UNSENT.has(error) && + error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason + ); +} function remainingRemoteRequestTimeoutMs( req: DaemonWireRequest, @@ -574,13 +593,14 @@ function isRemoteInstanceMismatch(error: unknown): boolean { ); } -// A timeout is left to the timeout route, which drops the cache only when its probe shows the -// daemon gone or replaced. +// A sent request's timeout is left to the timeout route, which drops the cache only when its probe +// shows the daemon gone or replaced; an unsent one, or a proven stale instance, drops it here. function dropsCachedRemoteHealth(error: unknown): boolean { + if (!(error instanceof AppError)) return false; + if (PROVEN_UNSENT.has(error) || PROVEN_STALE.has(error)) return true; return ( - error instanceof AppError && - (error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason || - error.details?.reason === DAEMON_TRANSPORT_REASONS.replyUnreadable.reason) + error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason || + error.details?.reason === DAEMON_TRANSPORT_REASONS.replyUnreadable.reason ); } @@ -656,39 +676,6 @@ function requireDaemonTransport( throw daemonEndpointUnavailableError(transport); } -/** - * `daemonRequestSent` is required: the client discloses dispatch from it, and a producer that - * could not say would otherwise be read as sent. - */ -function handleTransportError( - err: unknown, - requestId: string | undefined, - remote: boolean, - daemonRequestSent: boolean, -): AppError { - emitDiagnostic({ - level: 'error', - phase: 'daemon_request_socket_error', - data: { - requestId, - message: err instanceof Error ? err.message : String(err), - }, - }); - return new AppError( - 'COMMAND_FAILED', - 'Failed to communicate with daemon', - { - daemonRequestSent, - reason: DAEMON_TRANSPORT_REASONS.failure.reason, - requestId, - hint: remote - ? 'Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.' - : 'Retry command. If this persists, clean stale daemon metadata and start a fresh session.', - }, - err instanceof Error ? err : undefined, - ); -} - async function sendSocketRequest( info: DaemonInfo, req: DaemonWireRequest, @@ -776,21 +763,6 @@ async function sendSocketRequest( }); } -function requestTimeoutError( - timeoutMs: number, - requestId: string | undefined, - daemonRequestSent: boolean, - remoteResponseStarted?: boolean, -): AppError { - return new AppError('COMMAND_FAILED', 'Daemon request timed out', { - reason: DAEMON_TRANSPORT_REASONS.timeout.reason, - timeoutMs, - requestId, - daemonRequestSent, - ...(remoteResponseStarted ? { remoteResponseStarted: true } : {}), - }); -} - function buildRemoteInstancePreconditionHeaders(info: DaemonInfo): Record { return { ...(info.remoteInstanceId ? { [DAEMON_HTTP_INSTANCE_HEADER]: info.remoteInstanceId } : {}), @@ -880,12 +852,12 @@ async function sendHttpRequest( if (isRemoteInstanceMismatchResponse(res.statusCode, res.headers ?? {})) { res.resume(); if (timeoutHandle) clearTimeout(timeoutHandle); - rejectOnce( - new AppError('COMMAND_FAILED', 'Remote daemon instance changed', { - reason: DAEMON_INSTANCE_REASONS.instanceMismatch.reason, - daemonBaseUrl: info.baseUrl, - }), - ); + const stale = new AppError('COMMAND_FAILED', 'Remote daemon instance changed', { + reason: DAEMON_INSTANCE_REASONS.instanceMismatch.reason, + daemonBaseUrl: info.baseUrl, + }); + PROVEN_STALE.add(stale); + rejectOnce(stale); return; } if (shouldReadDaemonProgressStream(req, res.headers?.['content-type'])) { @@ -930,9 +902,14 @@ async function sendHttpRequest( const timeoutHandle = typeof timeoutMs === 'number' ? setTimeout(() => { - rejectOnce( - requestTimeoutError(timeoutMs, req.meta?.requestId, requestSent, responseStarted), + const expired = requestTimeoutError( + timeoutMs, + req.meta?.requestId, + requestSent, + responseStarted, ); + if (!connected) PROVEN_UNSENT.add(expired); + rejectOnce(expired); request.destroy(); }, timeoutMs) : undefined; diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 0970bd0c61..e9540175ac 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -21,7 +21,10 @@ import { import type { DaemonClientSettings, EnsuredDaemon } from './daemon-client-lifecycle.ts'; import type { EnsuringTransportOptions } from './daemon-client-ensuring.ts'; import { createRequestGuard } from './daemon-client-timeout.ts'; -import { sendRequest as sendDaemonRequest } from './daemon-client-transport.ts'; +import { + sendRequest as sendDaemonRequest, + type SendRequestOptions, +} from './daemon-client-transport.ts'; import { isRemoteDaemon, readRegisteredDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { LocalDaemonCodeIdentity } from './daemon-launch-spec.ts'; import type { @@ -123,12 +126,12 @@ async function sendToDaemonOnHost( const info = daemon.info; // A cached `/health` answer skipped the probe; this runs it when the command needs a fresh one. const remoteHealthGate = daemon.remoteHealthCached - ? async (budgetMs: number | undefined) => { + ? async (budgetMs: number | undefined, signal: AbortSignal | undefined) => { const { refreshRemoteDaemonHealth } = await import('./daemon-client-remote-health-gate.ts'); await refreshRemoteDaemonHealth( info, settings.paths.baseDir, - budgetMs === undefined ? undefined : { budgetMs, signal: options.signal }, + budgetMs === undefined ? undefined : { budgetMs, signal }, ); } : undefined; @@ -140,6 +143,7 @@ async function sendToDaemonOnHost( requestWithoutAuthFlag, options.signal, options.onProgress, + remoteHealthGate, ), ); writeInstallInProgressNotice(requestWithoutAuthFlag.command, host.env); @@ -189,7 +193,7 @@ async function sendToDaemonOnHost( return await send(request); // A capability missing only from a cached answer may have arrived with a daemon upgrade. if (remoteHealthGate && !info.capabilities?.includes('script-artifacts')) { - await cancellation.guard(() => remoteHealthGate(requestTimeoutMs)); + await cancellation.guard(() => remoteHealthGate(requestTimeoutMs, options.signal)); } return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send); }, @@ -408,6 +412,7 @@ async function protectArtifactUploadWithLeaseBeats( request: Omit, callerSignal: AbortSignal | undefined, onProgress: DaemonTransportOptions['onProgress'], + remoteHealthGate: SendRequestOptions['remoteHealthGate'], ): Promise { const leaseScope = leaseScopeFromRequest(request); if (!isRemoteDaemon(info) || !leaseScope.leaseId) { @@ -422,7 +427,7 @@ async function protectArtifactUploadWithLeaseBeats( const { buildUploadLeaseHeartbeat, runProtectedLeaseWork } = await import('./daemon-client-lease-beat.ts'); return await runProtectedLeaseWork({ - heartbeat: buildUploadLeaseHeartbeat(info, settings, request), + heartbeat: buildUploadLeaseHeartbeat(info, settings, request, remoteHealthGate), // The upload stops for either owner of its signal: the lease beat finding the lease gone, or // the caller aborting this one call. task: (leaseSignal) => diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 59fa432360..1eb0cf408d 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -361,7 +361,7 @@ for the API. ## Compatibility -Remote clients read `/health` before the first command to a daemon instance and compare the daemon RPC protocol version. When the daemon, and the upstream daemon behind a proxy, report instance IDs, the answer is cached in the client state directory, and later commands go straight to `/rpc`. The client reads `/health` again when the daemon or proxy instance changes, after a client upgrade or token change, and after a failed call. Peers that do not report complete instance IDs get a `/health` read before every command. Keep client and proxy versions close: patch-level differences usually work, and incompatible RPC protocol versions fail before any command runs. +Remote clients read `/health` before the first command to a daemon instance and compare the daemon RPC protocol version. When the daemon, and the upstream daemon behind a proxy, report instance IDs, the answer is cached in the client state directory, and later commands go straight to `/rpc`. The client reads `/health` again when the daemon or proxy instance changes, after a client upgrade or token change, and after a connection failure, a server error, or a timeout that the daemon did not answer. Peers that do not report complete instance IDs get a `/health` read before every command. Keep client and proxy versions close: patch-level differences usually work, and incompatible RPC protocol versions fail before any command runs. `/health` also reports `hostArch`, the native CPU architecture of the machine serving it: the one its simulators run by default, even when Node itself runs under Rosetta. Macs report `arm64` or `x86_64`; other hosts report `x86_64` for x64 and Node's `process.arch` name otherwise (for example `arm64`). The top-level value describes the proxy's own machine, so a client behind a proxy reads `upstream.hostArch` for the host that runs the simulators, for example to build only that slice of a simulator app. Older daemons omit the field. `leaseBackends` lists the lease backends the daemon admits (`macos-app` only on a macOS host); a host checks `upstream.leaseBackends` for `macos-app` before handing out a macOS app lease, and older From b28065b81b840805c2cdd43743b56c2da54d33e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 22:17:47 +0100 Subject: [PATCH 08/10] test(daemon-client): move the persisted remote health cases into their own file The transport test file passed the 1000-line limit. The saved-health cases and their remote fixture move unchanged to daemon-client-transport-persisted-health.test.ts. Co-Authored-By: Claude Opus 5.5 --- ...-client-transport-persisted-health.test.ts | 430 ++++++++++++++++++ .../__tests__/daemon-client-transport.test.ts | 402 ---------------- 2 files changed, 430 insertions(+), 402 deletions(-) create mode 100644 packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts new file mode 100644 index 0000000000..8e819ee0f5 --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts @@ -0,0 +1,430 @@ +// The client keeps a remote daemon's `/health` answer in its state directory, so a later CLI process +// sends straight to `/rpc`. These cases pin when that saved answer is reused, dropped or refreshed, +// and that a resend only ever follows evidence the client's own transport recorded. + +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import { test, vi } from 'vitest'; +import * as hostTransport from '@agent-device/host-kit/transport'; +import { sleep } from '@agent-device/host-kit/retry'; +import { AppError } from '@agent-device/kernel/errors'; +import { + closeLoopbackServer, + createTestHostEnvironment, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { + DAEMON_HTTP_INSTANCE_HEADER, + DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, +} from '@agent-device/contracts/daemon-http'; +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +import { sendToDaemon } from '../index.ts'; +import { sendRequest } from '../daemon-client-transport.ts'; +import { DAEMON_UNAVAILABLE_REASONS } from '../daemon-lifecycle-errors.ts'; +import { invalidateRemoteDaemonHealth } from '../daemon-client-remote-health-cache.ts'; + +type RpcAnswer = { status: number; body: unknown }; + +async function instanceCheckingRemote( + instanceId: () => string, + rpcAnswer: () => RpcAnswer | undefined = () => undefined, +) { + const paths: string[] = []; + const server = http.createServer((req, res) => { + paths.push(`${req.method} ${req.url}`); + res.setHeader('content-type', 'application/json'); + if (req.url?.endsWith('/health')) { + res.end( + JSON.stringify({ ok: true, service: 'agent-device-daemon', instanceId: instanceId() }), + ); + return; + } + const expected = req.headers[DAEMON_HTTP_INSTANCE_HEADER]; + if (typeof expected === 'string' && expected !== instanceId()) { + res.statusCode = 409; + res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true'); + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'request', error: { code: -32001 } })); + return; + } + const answer = rpcAnswer() ?? { + status: 200, + body: { jsonrpc: '2.0', id: 'request', result: { ok: true, data: {} } }, + }; + res.statusCode = answer.status; + res.end(JSON.stringify(answer.body)); + }); + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const stateDir = mkdtempForTestSync('agent-device-remote-health-persisted-'); + const request = () => + sendToDaemon( + { + command: 'remote-smoke', + session: 'default', + positionals: ['ping'], + flags: { daemonBaseUrl: baseUrl, stateDir }, + meta: { requestId: 'request' }, + }, + { authToken: 'persisted-secret' }, + ); + // What a new CLI process starts with: no health cached in memory, only what the state dir holds. + const forgetInMemory = () => + invalidateRemoteDaemonHealth({ baseUrl, token: 'persisted-secret', pid: 0 }); + // One entry per daemon identity; this remote has one identity, so at most one entry. + const cacheFile = (): string | undefined => { + const [name] = fs.readdirSync(stateDir).filter((n) => n.startsWith('remote-daemon-health-')); + return name ? path.join(stateDir, name) : undefined; + }; + return { server, paths, baseUrl, stateDir, request, forgetInMemory, cacheFile }; +} + +// Each CLI call is a new process, so the health a first call probed is kept in the state dir and a +// later process sends straight to /rpc. The instance precondition still catches a replaced daemon. +test('a later process reuses persisted remote health and still catches a replaced daemon', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let instanceId = 'persisted-one'; + const remote = await instanceCheckingRemote(() => instanceId); + try { + assert.equal((await remote.request()).ok, true); + remote.forgetInMemory(); + assert.equal((await remote.request()).ok, true); + assert.deepEqual(remote.paths, ['GET /health', 'POST /rpc', 'POST /rpc']); + + const persisted = fs.readFileSync(remote.cacheFile()!, 'utf8'); + assert.equal(persisted.includes('persisted-secret'), false, 'the token is never written'); + assert.equal(persisted.includes(remote.baseUrl), false, 'the URL is never written'); + assert.equal(fs.statSync(remote.cacheFile()!).mode & 0o077, 0, 'only the owner reads it'); + + instanceId = 'persisted-two'; + remote.forgetInMemory(); + assert.equal((await remote.request()).ok, true); + assert.deepEqual(remote.paths.slice(3), ['POST /rpc', 'GET /health', 'POST /rpc']); + remote.forgetInMemory(); + assert.equal((await remote.request()).ok, true); + assert.deepEqual(remote.paths.slice(6), ['POST /rpc'], 'the replacement was persisted'); + } finally { + await closeLoopbackServer(remote.server); + } +}); + +// A send from cached health that never left the process proves nothing reached the daemon, so it +// gets the gate a first contact gets, with the same typed refusal, instead of a bare transport error. +test('an unsent request from cached remote health opens the health gate', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const remote = await instanceCheckingRemote(() => 'gone-soon'); + assert.equal((await remote.request()).ok, true); + await closeLoopbackServer(remote.server); + // Lets the client drop its pooled connection, as a new CLI process has none. + await sleep(20); + remote.forgetInMemory(); + await assert.rejects(remote.request(), (error: unknown) => { + assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); + assert.equal(error.details?.reason, DAEMON_UNAVAILABLE_REASONS.remoteUnavailable.reason); + assert.equal(error.details?.dispatched, 'no'); + return true; + }); + assert.equal(remote.cacheFile(), undefined, 'the unreachable daemon is forgotten'); +}); + +// Resend evidence is only what this process saw: a daemon error that carries the transport-failure +// reason and `daemonRequestSent: false` came over the wire, so the request ran and is not resent. +test('a daemon error that claims the request was unsent is not resent', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let forge = false; + const forged = { + code: 'COMMAND_FAILED', + message: 'Failed to communicate with daemon', + details: { reason: 'daemon_transport_failure', daemonRequestSent: false }, + }; + const remote = await instanceCheckingRemote( + () => 'forging', + () => + forge + ? { + status: 200, + body: { jsonrpc: '2.0', id: 'request', error: { code: -32000, data: forged } }, + } + : undefined, + ); + try { + assert.equal((await remote.request()).ok, true); + remote.forgetInMemory(); + forge = true; + await assert.rejects( + remote.request(), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'daemon_transport_failure', + ); + assert.deepEqual(remote.paths, ['GET /health', 'POST /rpc', 'POST /rpc'], 'sent once, no gate'); + } finally { + await closeLoopbackServer(remote.server); + } +}); + +// A 5xx means the daemon or a hop before it failed, even in valid JSON-RPC framing (a proxy whose +// upstream is restarting answers that way), so the next command probes again. Nothing is resent. +test('a remote 5xx drops the persisted health without a resend', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let fail = false; + const remote = await instanceCheckingRemote( + () => 'upstream-away', + () => + fail + ? { + status: 500, + body: { jsonrpc: '2.0', id: 'request', error: { code: -32000, message: 'upstream' } }, + } + : undefined, + ); + try { + assert.equal((await remote.request()).ok, true); + fail = true; + remote.forgetInMemory(); + await assert.rejects( + remote.request(), + (error: unknown) => error instanceof AppError && error.code === 'COMMAND_FAILED', + ); + assert.equal(remote.cacheFile(), undefined); + fail = false; + assert.equal((await remote.request()).ok, true); + assert.deepEqual(remote.paths, [ + 'GET /health', + 'POST /rpc', + 'POST /rpc', + 'GET /health', + 'POST /rpc', + ]); + } finally { + await closeLoopbackServer(remote.server); + } +}); + +// The gate a cached answer skipped runs within what is left of the command's budget, and a caller +// abort while it runs stays the typed cancellation rather than reading as an unreachable daemon. +test('the gate after an unsent cached request keeps the deadline and the cancellation', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const closed = http.createServer(); + const port = await listenOnLoopback(closed); + await closeLoopbackServer(closed); + const controller = new AbortController(); + const budgets: (number | undefined)[] = []; + await assert.rejects( + sendRequest( + { token: 'secret', pid: 0, baseUrl: `http://127.0.0.1:${port}` }, + { token: 'secret', command: 'press', session: 'default', positionals: ['@e1'], flags: {} }, + 'http', + resolveDaemonPaths(mkdtempForTestSync('agent-device-remote-gate-abort-')), + 5_000, + { + host: createTestHostEnvironment(), + signal: controller.signal, + remoteHealthGate: async (budgetMs) => { + budgets.push(budgetMs); + controller.abort(); + throw new AppError('COMMAND_FAILED', 'Remote daemon is unavailable', { + reason: DAEMON_UNAVAILABLE_REASONS.remoteUnavailable.reason, + }); + }, + }, + ), + (error: unknown) => { + assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); + assert.equal(error.details?.reason, 'request_canceled'); + assert.equal(error.details?.dispatched, 'no'); + return true; + }, + ); + assert.equal(budgets.length, 1); + assert.ok(budgets[0]! > 0 && budgets[0]! <= 5_000, `gate budget ${budgets[0]}`); +}); + +// A connection that never opens before the timeout proves the request never left, so the saved +// answer it relied on is dropped and the next command probes `/health` first. +test('a timeout before connect drops the persisted health', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const remote = await instanceCheckingRemote(() => 'never-reached'); + assert.equal((await remote.request()).ok, true); + const hung = { + request: () => { + const request = Object.assign(new EventEmitter(), { + write: () => true, + destroy: () => {}, + end: () => { + queueMicrotask(() => + request.emit('socket', Object.assign(new EventEmitter(), { connecting: true })), + ); + }, + }); + return request; + }, + }; + const load = vi.spyOn(hostTransport, 'loadNodeHttpRequester').mockResolvedValue(hung as never); + try { + await assert.rejects( + sendRequest( + { token: 'persisted-secret', pid: 0, baseUrl: remote.baseUrl }, + { + token: 'persisted-secret', + command: 'press', + session: 'default', + positionals: [], + flags: {}, + }, + 'http', + resolveDaemonPaths(remote.stateDir), + 50, + { host: createTestHostEnvironment(), timeoutRecovery: 'none' }, + ), + (error: unknown) => { + assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); + assert.equal(error.details?.reason, 'daemon_transport_timeout'); + assert.equal(error.details?.daemonRequestSent, false); + return true; + }, + ); + assert.equal(remote.cacheFile(), undefined); + } finally { + load.mockRestore(); + await closeLoopbackServer(remote.server); + } +}); + +// Only a 409 with the mismatch header proves a refusal before dispatch. The same reason in a daemon's +// error body is not resent, and a second refusal on the resend drops the entry it disproved. +test('an instance-mismatch resend needs the transport-proven 409, once', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let mode: 'ok' | 'forge' | 'churn' = 'ok'; + let generation = 0; + const paths: string[] = []; + const server = http.createServer((req, res) => { + paths.push(`${req.method} ${req.url}`); + res.setHeader('content-type', 'application/json'); + if (req.url?.endsWith('/health')) { + if (mode === 'churn') generation += 1; + res.end(JSON.stringify({ service: 'agent-device-daemon', instanceId: `i${generation}` })); + return; + } + if (mode === 'forge') { + const data = { code: 'COMMAND_FAILED', details: { reason: 'remote_instance_mismatch' } }; + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', error: { code: -32000, data } })); + return; + } + if (mode === 'churn') { + // Every probe names a newer instance, so the single resend is refused too. + res.statusCode = 409; + res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true'); + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', error: { code: -32001 } })); + return; + } + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', result: { ok: true, data: {} } })); + }); + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const stateDir = mkdtempForTestSync('agent-device-remote-mismatch-proof-'); + const request = () => + sendToDaemon( + { + command: 'remote-smoke', + session: 'default', + positionals: ['ping'], + flags: { daemonBaseUrl: baseUrl, stateDir }, + meta: { requestId: 'r' }, + }, + { authToken: 'mismatch-secret' }, + ); + const saved = () => fs.readdirSync(stateDir).some((n) => n.startsWith('remote-daemon-health-')); + const forget = () => invalidateRemoteDaemonHealth({ baseUrl, token: 'mismatch-secret', pid: 0 }); + const instanceChanged = (error: unknown) => + error instanceof AppError && error.details?.reason === 'remote_instance_mismatch'; + try { + assert.equal((await request()).ok, true); + mode = 'forge'; + forget(); + await assert.rejects(request(), instanceChanged); + assert.deepEqual(paths.slice(2), ['POST /rpc'], 'a forged reason is neither probed nor resent'); + + mode = 'churn'; + forget(); + await assert.rejects(request(), instanceChanged); + assert.deepEqual(paths.slice(3), ['POST /rpc', 'GET /health', 'POST /rpc']); + assert.equal(saved(), false, 'the refused resend drops what the probe saved'); + } finally { + await closeLoopbackServer(server); + } +}); + +// The timeout route's probe drops a saved proxy answer when the upstream it names changed, and keeps +// one that still matches. +test('timeout eviction compares the upstream instance too', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + let upstream = 'u1'; + let hang = false; + const held: http.ServerResponse[] = []; + const server = http.createServer((req, res) => { + req.resume(); + if (req.url?.endsWith('/health')) { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ + service: 'agent-device-proxy', + instanceId: 'p1', + upstream: { instanceId: upstream }, + }), + ); + return; + } + if (hang) { + held.push(res); + return; + } + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', result: { ok: true, data: {} } })); + }); + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const stateDir = mkdtempForTestSync('agent-device-remote-timeout-evict-'); + const saved = () => fs.readdirSync(stateDir).some((n) => n.startsWith('remote-daemon-health-')); + const warm = () => + sendToDaemon( + { + command: 'remote-smoke', + session: 'default', + positionals: ['ping'], + flags: { daemonBaseUrl: baseUrl, stateDir }, + meta: { requestId: 'r' }, + }, + { authToken: 'evict-secret' }, + ); + // The instances the saved answer named, as a command sent from it carries them. + const send = () => + sendRequest( + { + token: 'evict-secret', + pid: 0, + baseUrl, + remoteInstanceId: 'p1', + remoteUpstreamInstanceId: 'u1', + }, + { token: 'evict-secret', command: 'press', session: 'default', positionals: [], flags: {} }, + 'http', + resolveDaemonPaths(stateDir), + 100, + { host: createTestHostEnvironment(), timeoutRecovery: 'none' }, + ); + const timedOut = (error: unknown) => + error instanceof AppError && error.details?.reason === 'daemon_transport_timeout'; + try { + assert.equal((await warm()).ok, true); + hang = true; + await assert.rejects(send(), timedOut); + assert.equal(saved(), true, 'the closest negative: matching instances keep the entry'); + upstream = 'u2'; + await assert.rejects(send(), timedOut); + assert.equal(saved(), false); + } finally { + for (const res of held) res.destroy(); + await closeLoopbackServer(server); + } +}); 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 3aed530197..ed5c07fd30 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -1,5 +1,4 @@ import assert from 'node:assert/strict'; -import { EventEmitter } from 'node:events'; import http from 'node:http'; import net from 'node:net'; import fs from 'node:fs'; @@ -669,407 +668,6 @@ test.for(['timeout', 'reset'] as const)( ); /** A remote daemon that answers /health with `instanceId()` and refuses a stale instance with 409. */ -type RpcAnswer = { status: number; body: unknown }; - -async function instanceCheckingRemote( - instanceId: () => string, - rpcAnswer: () => RpcAnswer | undefined = () => undefined, -) { - const paths: string[] = []; - const server = http.createServer((req, res) => { - paths.push(`${req.method} ${req.url}`); - res.setHeader('content-type', 'application/json'); - if (req.url?.endsWith('/health')) { - res.end( - JSON.stringify({ ok: true, service: 'agent-device-daemon', instanceId: instanceId() }), - ); - return; - } - const expected = req.headers[DAEMON_HTTP_INSTANCE_HEADER]; - if (typeof expected === 'string' && expected !== instanceId()) { - res.statusCode = 409; - res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true'); - res.end(JSON.stringify({ jsonrpc: '2.0', id: 'request', error: { code: -32001 } })); - return; - } - const answer = rpcAnswer() ?? { - status: 200, - body: { jsonrpc: '2.0', id: 'request', result: { ok: true, data: {} } }, - }; - res.statusCode = answer.status; - res.end(JSON.stringify(answer.body)); - }); - const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; - const stateDir = mkdtempForTestSync('agent-device-remote-health-persisted-'); - const request = () => - sendToDaemon( - { - command: 'remote-smoke', - session: 'default', - positionals: ['ping'], - flags: { daemonBaseUrl: baseUrl, stateDir }, - meta: { requestId: 'request' }, - }, - { authToken: 'persisted-secret' }, - ); - // What a new CLI process starts with: no health cached in memory, only what the state dir holds. - const forgetInMemory = () => - invalidateRemoteDaemonHealth({ baseUrl, token: 'persisted-secret', pid: 0 }); - // One entry per daemon identity; this remote has one identity, so at most one entry. - const cacheFile = (): string | undefined => { - const [name] = fs.readdirSync(stateDir).filter((n) => n.startsWith('remote-daemon-health-')); - return name ? path.join(stateDir, name) : undefined; - }; - return { server, paths, baseUrl, stateDir, request, forgetInMemory, cacheFile }; -} - -// Each CLI call is a new process, so the health a first call probed is kept in the state dir and a -// later process sends straight to /rpc. The instance precondition still catches a replaced daemon. -test('a later process reuses persisted remote health and still catches a replaced daemon', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - let instanceId = 'persisted-one'; - const remote = await instanceCheckingRemote(() => instanceId); - try { - assert.equal((await remote.request()).ok, true); - remote.forgetInMemory(); - assert.equal((await remote.request()).ok, true); - assert.deepEqual(remote.paths, ['GET /health', 'POST /rpc', 'POST /rpc']); - - const persisted = fs.readFileSync(remote.cacheFile()!, 'utf8'); - assert.equal(persisted.includes('persisted-secret'), false, 'the token is never written'); - assert.equal(persisted.includes(remote.baseUrl), false, 'the URL is never written'); - assert.equal(fs.statSync(remote.cacheFile()!).mode & 0o077, 0, 'only the owner reads it'); - - instanceId = 'persisted-two'; - remote.forgetInMemory(); - assert.equal((await remote.request()).ok, true); - assert.deepEqual(remote.paths.slice(3), ['POST /rpc', 'GET /health', 'POST /rpc']); - remote.forgetInMemory(); - assert.equal((await remote.request()).ok, true); - assert.deepEqual(remote.paths.slice(6), ['POST /rpc'], 'the replacement was persisted'); - } finally { - await closeLoopbackServer(remote.server); - } -}); - -// A send from cached health that never left the process proves nothing reached the daemon, so it -// gets the gate a first contact gets, with the same typed refusal, instead of a bare transport error. -test('an unsent request from cached remote health opens the health gate', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - const remote = await instanceCheckingRemote(() => 'gone-soon'); - assert.equal((await remote.request()).ok, true); - await closeLoopbackServer(remote.server); - // Lets the client drop its pooled connection, as a new CLI process has none. - await sleep(20); - remote.forgetInMemory(); - await assert.rejects(remote.request(), (error: unknown) => { - assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); - assert.equal(error.details?.reason, DAEMON_UNAVAILABLE_REASONS.remoteUnavailable.reason); - assert.equal(error.details?.dispatched, 'no'); - return true; - }); - assert.equal(remote.cacheFile(), undefined, 'the unreachable daemon is forgotten'); -}); - -// Resend evidence is only what this process saw: a daemon error that carries the transport-failure -// reason and `daemonRequestSent: false` came over the wire, so the request ran and is not resent. -test('a daemon error that claims the request was unsent is not resent', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - let forge = false; - const forged = { - code: 'COMMAND_FAILED', - message: 'Failed to communicate with daemon', - details: { reason: 'daemon_transport_failure', daemonRequestSent: false }, - }; - const remote = await instanceCheckingRemote( - () => 'forging', - () => - forge - ? { - status: 200, - body: { jsonrpc: '2.0', id: 'request', error: { code: -32000, data: forged } }, - } - : undefined, - ); - try { - assert.equal((await remote.request()).ok, true); - remote.forgetInMemory(); - forge = true; - await assert.rejects( - remote.request(), - (error: unknown) => - error instanceof AppError && error.details?.reason === 'daemon_transport_failure', - ); - assert.deepEqual(remote.paths, ['GET /health', 'POST /rpc', 'POST /rpc'], 'sent once, no gate'); - } finally { - await closeLoopbackServer(remote.server); - } -}); - -// A 5xx means the daemon or a hop before it failed, even in valid JSON-RPC framing (a proxy whose -// upstream is restarting answers that way), so the next command probes again. Nothing is resent. -test('a remote 5xx drops the persisted health without a resend', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - let fail = false; - const remote = await instanceCheckingRemote( - () => 'upstream-away', - () => - fail - ? { - status: 500, - body: { jsonrpc: '2.0', id: 'request', error: { code: -32000, message: 'upstream' } }, - } - : undefined, - ); - try { - assert.equal((await remote.request()).ok, true); - fail = true; - remote.forgetInMemory(); - await assert.rejects( - remote.request(), - (error: unknown) => error instanceof AppError && error.code === 'COMMAND_FAILED', - ); - assert.equal(remote.cacheFile(), undefined); - fail = false; - assert.equal((await remote.request()).ok, true); - assert.deepEqual(remote.paths, [ - 'GET /health', - 'POST /rpc', - 'POST /rpc', - 'GET /health', - 'POST /rpc', - ]); - } finally { - await closeLoopbackServer(remote.server); - } -}); - -// The gate a cached answer skipped runs within what is left of the command's budget, and a caller -// abort while it runs stays the typed cancellation rather than reading as an unreachable daemon. -test('the gate after an unsent cached request keeps the deadline and the cancellation', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - const closed = http.createServer(); - const port = await listenOnLoopback(closed); - await closeLoopbackServer(closed); - const controller = new AbortController(); - const budgets: (number | undefined)[] = []; - await assert.rejects( - sendRequest( - { token: 'secret', pid: 0, baseUrl: `http://127.0.0.1:${port}` }, - { token: 'secret', command: 'press', session: 'default', positionals: ['@e1'], flags: {} }, - 'http', - resolveDaemonPaths(mkdtempForTestSync('agent-device-remote-gate-abort-')), - 5_000, - { - host: createTestHostEnvironment(), - signal: controller.signal, - remoteHealthGate: async (budgetMs) => { - budgets.push(budgetMs); - controller.abort(); - throw new AppError('COMMAND_FAILED', 'Remote daemon is unavailable', { - reason: DAEMON_UNAVAILABLE_REASONS.remoteUnavailable.reason, - }); - }, - }, - ), - (error: unknown) => { - assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); - assert.equal(error.details?.reason, 'request_canceled'); - assert.equal(error.details?.dispatched, 'no'); - return true; - }, - ); - assert.equal(budgets.length, 1); - assert.ok(budgets[0]! > 0 && budgets[0]! <= 5_000, `gate budget ${budgets[0]}`); -}); - -// A connection that never opens before the timeout proves the request never left, so the saved -// answer it relied on is dropped and the next command probes `/health` first. -test('a timeout before connect drops the persisted health', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - const remote = await instanceCheckingRemote(() => 'never-reached'); - assert.equal((await remote.request()).ok, true); - const hung = { - request: () => { - const request = Object.assign(new EventEmitter(), { - write: () => true, - destroy: () => {}, - end: () => { - queueMicrotask(() => - request.emit('socket', Object.assign(new EventEmitter(), { connecting: true })), - ); - }, - }); - return request; - }, - }; - const load = vi.spyOn(hostTransport, 'loadNodeHttpRequester').mockResolvedValue(hung as never); - try { - await assert.rejects( - sendRequest( - { token: 'persisted-secret', pid: 0, baseUrl: remote.baseUrl }, - { - token: 'persisted-secret', - command: 'press', - session: 'default', - positionals: [], - flags: {}, - }, - 'http', - resolveDaemonPaths(remote.stateDir), - 50, - { host: createTestHostEnvironment(), timeoutRecovery: 'none' }, - ), - (error: unknown) => { - assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); - assert.equal(error.details?.reason, 'daemon_transport_timeout'); - assert.equal(error.details?.daemonRequestSent, false); - return true; - }, - ); - assert.equal(remote.cacheFile(), undefined); - } finally { - load.mockRestore(); - await closeLoopbackServer(remote.server); - } -}); - -// Only a 409 with the mismatch header proves a refusal before dispatch. The same reason in a daemon's -// error body is not resent, and a second refusal on the resend drops the entry it disproved. -test('an instance-mismatch resend needs the transport-proven 409, once', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - let mode: 'ok' | 'forge' | 'churn' = 'ok'; - let generation = 0; - const paths: string[] = []; - const server = http.createServer((req, res) => { - paths.push(`${req.method} ${req.url}`); - res.setHeader('content-type', 'application/json'); - if (req.url?.endsWith('/health')) { - if (mode === 'churn') generation += 1; - res.end(JSON.stringify({ service: 'agent-device-daemon', instanceId: `i${generation}` })); - return; - } - if (mode === 'forge') { - const data = { code: 'COMMAND_FAILED', details: { reason: 'remote_instance_mismatch' } }; - res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', error: { code: -32000, data } })); - return; - } - if (mode === 'churn') { - // Every probe names a newer instance, so the single resend is refused too. - res.statusCode = 409; - res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true'); - res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', error: { code: -32001 } })); - return; - } - res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', result: { ok: true, data: {} } })); - }); - const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; - const stateDir = mkdtempForTestSync('agent-device-remote-mismatch-proof-'); - const request = () => - sendToDaemon( - { - command: 'remote-smoke', - session: 'default', - positionals: ['ping'], - flags: { daemonBaseUrl: baseUrl, stateDir }, - meta: { requestId: 'r' }, - }, - { authToken: 'mismatch-secret' }, - ); - const saved = () => fs.readdirSync(stateDir).some((n) => n.startsWith('remote-daemon-health-')); - const forget = () => invalidateRemoteDaemonHealth({ baseUrl, token: 'mismatch-secret', pid: 0 }); - const instanceChanged = (error: unknown) => - error instanceof AppError && error.details?.reason === 'remote_instance_mismatch'; - try { - assert.equal((await request()).ok, true); - mode = 'forge'; - forget(); - await assert.rejects(request(), instanceChanged); - assert.deepEqual(paths.slice(2), ['POST /rpc'], 'a forged reason is neither probed nor resent'); - - mode = 'churn'; - forget(); - await assert.rejects(request(), instanceChanged); - assert.deepEqual(paths.slice(3), ['POST /rpc', 'GET /health', 'POST /rpc']); - assert.equal(saved(), false, 'the refused resend drops what the probe saved'); - } finally { - await closeLoopbackServer(server); - } -}); - -// The timeout route's probe drops a saved proxy answer when the upstream it names changed, and keeps -// one that still matches. -test('timeout eviction compares the upstream instance too', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - let upstream = 'u1'; - let hang = false; - const held: http.ServerResponse[] = []; - const server = http.createServer((req, res) => { - req.resume(); - if (req.url?.endsWith('/health')) { - res.setHeader('content-type', 'application/json'); - res.end( - JSON.stringify({ - service: 'agent-device-proxy', - instanceId: 'p1', - upstream: { instanceId: upstream }, - }), - ); - return; - } - if (hang) { - held.push(res); - return; - } - res.setHeader('content-type', 'application/json'); - res.end(JSON.stringify({ jsonrpc: '2.0', id: 'r', result: { ok: true, data: {} } })); - }); - const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; - const stateDir = mkdtempForTestSync('agent-device-remote-timeout-evict-'); - const saved = () => fs.readdirSync(stateDir).some((n) => n.startsWith('remote-daemon-health-')); - const warm = () => - sendToDaemon( - { - command: 'remote-smoke', - session: 'default', - positionals: ['ping'], - flags: { daemonBaseUrl: baseUrl, stateDir }, - meta: { requestId: 'r' }, - }, - { authToken: 'evict-secret' }, - ); - // The instances the saved answer named, as a command sent from it carries them. - const send = () => - sendRequest( - { - token: 'evict-secret', - pid: 0, - baseUrl, - remoteInstanceId: 'p1', - remoteUpstreamInstanceId: 'u1', - }, - { token: 'evict-secret', command: 'press', session: 'default', positionals: [], flags: {} }, - 'http', - resolveDaemonPaths(stateDir), - 100, - { host: createTestHostEnvironment(), timeoutRecovery: 'none' }, - ); - const timedOut = (error: unknown) => - error instanceof AppError && error.details?.reason === 'daemon_transport_timeout'; - try { - assert.equal((await warm()).ok, true); - hang = true; - await assert.rejects(send(), timedOut); - assert.equal(saved(), true, 'the closest negative: matching instances keep the entry'); - upstream = 'u2'; - await assert.rejects(send(), timedOut); - assert.equal(saved(), false); - } finally { - for (const res of held) res.destroy(); - await closeLoopbackServer(server); - } -}); - // A transport failure drops the cached health of a remote daemon only: a local daemon has no cached // health, so its failed request neither invalidates nor loads the remote health cache. test('a transport failure invalidates cached health for a remote daemon only', async (t) => { From 280b4deb4300ea79a5d8e53b8a323bc69297b3ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 23:07:56 +0100 Subject: [PATCH 09/10] fix(daemon-client): type the health gate once and refuse IDs echoing the sent credential - resendAfterRemoteHealthGate takes the gate as NonNullable, so the budget and signal it is called with type-check (TS2345/TS2554 at b28065b). - An instance ID is checked against the credential as the auth header builder sends it (trimmed), before saving and when read from disk. Co-Authored-By: Claude Opus 5.5 --- .../daemon-client-remote-health-cache.test.ts | 27 +++++++++++++++++++ ...-client-transport-persisted-health.test.ts | 12 ++++----- .../src/daemon-client-remote-health-cache.ts | 9 +++++-- .../src/daemon-client-transport.ts | 2 +- 4 files changed, 40 insertions(+), 10 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts index 42185a26c1..7e4c19a981 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-remote-health-cache.test.ts @@ -137,6 +137,33 @@ test('persisted health is private and reused only by the identity that cached it assert.deepEqual(persistedFiles(stateDir), []); }); +// `/health` receives the credential trimmed, as the auth headers send it, so an ID that echoes the +// trimmed value is refused both before it is saved and when an entry on disk carries it. +test('an instance ID echoing the padded credential is neither saved nor read', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-health-padded-'); + const store = { stateDir, readRecord: readCachedRemoteHealthRecord }; + const info = { baseUrl: 'http://remote.example.test:7777', token: ' padded-secret\n', pid: 0 }; + invalidateRemoteDaemonHealth(info); + cacheRemoteDaemonHealth(info, { reachable: true, instanceId: 'id-padded-secret' }, stateDir); + assert.equal(readCachedRemoteHealth(info, store), undefined); + assert.deepEqual(persistedFiles(stateDir), [], 'nothing reaches disk'); + + cacheRemoteDaemonHealth( + info, + { reachable: true, instanceId: 'proxy', upstream: { instanceId: 'upstream' } }, + stateDir, + ); + const [file] = persistedFiles(stateDir); + assert.ok(file, 'the closest negative: IDs without the credential are saved'); + const entry = JSON.parse(fs.readFileSync(file, 'utf8')) as { + health: { upstream: { instanceId: string } }; + }; + entry.health.upstream.instanceId = 'upstream-padded-secret'; + fs.writeFileSync(file, JSON.stringify(entry), { mode: 0o600 }); + invalidateRemoteDaemonHealth(info); + assert.equal(readCachedRemoteHealth(info, store), undefined, 'an echoing upstream ID on disk'); +}); + // A shared state dir may hold an entry another user planted. Only a regular file this user owns and // nobody else can write counts; anything else is a miss, and a FIFO does not block the read. test.skipIf(process.platform === 'win32')('a planted persisted entry reads as a miss', () => { diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts index 8e819ee0f5..6d3e75c3c6 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts @@ -250,16 +250,14 @@ test('a timeout before connect drops the persisted health', async (t) => { assert.equal((await remote.request()).ok, true); const hung = { request: () => { - const request = Object.assign(new EventEmitter(), { + // A request whose socket is assigned but never connects, as against a host dropping SYNs. + const request = new EventEmitter(); + const connectingSocket = Object.assign(new EventEmitter(), { connecting: true }); + return Object.assign(request, { write: () => true, destroy: () => {}, - end: () => { - queueMicrotask(() => - request.emit('socket', Object.assign(new EventEmitter(), { connecting: true })), - ); - }, + end: () => queueMicrotask(() => request.emit('socket', connectingSocket)), }); - return request; }, }; const load = vi.spyOn(hostTransport, 'loadNodeHttpRequester').mockResolvedValue(hung as never); diff --git a/packages/daemon-client/src/daemon-client-remote-health-cache.ts b/packages/daemon-client/src/daemon-client-remote-health-cache.ts index d85b270d3c..2c6233cf9c 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -3,7 +3,10 @@ import fs from 'node:fs'; import path from 'node:path'; import { openVerifiedFileForRead, publishFileSync } from '@agent-device/host-kit/file'; import { readVersion } from '@agent-device/host-kit/version'; -import { DAEMON_RPC_PROTOCOL_VERSION } from '@agent-device/contracts/daemon-http'; +import { + buildDaemonHttpAuthHeaders, + DAEMON_RPC_PROTOCOL_VERSION, +} from '@agent-device/contracts/daemon-http'; import type { DaemonInfo } from './daemon-client-metadata.ts'; import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; @@ -49,11 +52,13 @@ const HEADER_VALUE = /^[\t\u0020-\u007e\u0080-\u00ff]+$/; * value that does not echo the credential or the URL this client sent to `/health`. */ function isUsableInstanceId(value: string | undefined, info: DaemonInfo): value is string { + // The credential as `/health` received it: the auth header builder trims it. + const sentToken = buildDaemonHttpAuthHeaders(info.token)['x-agent-device-token']; return ( typeof value === 'string' && value.length <= INSTANCE_ID_MAX_LENGTH && HEADER_VALUE.test(value) && - !(info.token && value.includes(info.token)) && + !(sentToken && value.includes(sentToken)) && !(info.baseUrl && value.includes(info.baseUrl)) ); } diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 83706ab9ba..928926cbf7 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -499,7 +499,7 @@ async function retryAfterRemoteInstanceMismatch( * cache skipped, then one resend, both within what is left of the command's budget. */ async function resendAfterRemoteHealthGate( - gate: (budgetMs: number | undefined) => Promise, + gate: NonNullable, info: DaemonInfo, req: DaemonWireRequest, statePaths: DaemonPaths, From 015189f31bb2d1fc778ff053e526439faaebe3d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 26 Nov 2026 23:08:40 +0100 Subject: [PATCH 10/10] fix(daemon-client): settle the health gate on a caller abort without a budget A command with no request timeout hands the gate no deadline, so its /health probe ran its own window after the caller aborted. The resend path now runs the gate under the request guard, which settles at once with request_canceled and dispatched: no. Co-Authored-By: Claude Opus 5.5 --- ...-client-transport-persisted-health.test.ts | 34 +++++++++++++++++++ .../src/daemon-client-transport.ts | 5 ++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts index 6d3e75c3c6..f2ccba62df 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts @@ -426,3 +426,37 @@ test('timeout eviction compares the upstream instance too', async (t) => { await closeLoopbackServer(server); } }); + +// A command with no budget gives the gate no deadline, so a caller abort must still settle the send +// at once instead of waiting out a probe that is still in flight. +test('a caller abort settles a gate that has no budget', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const closed = http.createServer(); + const port = await listenOnLoopback(closed); + await closeLoopbackServer(closed); + const controller = new AbortController(); + await assert.rejects( + sendRequest( + { token: 'secret', pid: 0, baseUrl: `http://127.0.0.1:${port}` }, + { token: 'secret', command: 'press', session: 'default', positionals: ['@e1'], flags: {} }, + 'http', + resolveDaemonPaths(mkdtempForTestSync('agent-device-remote-gate-unbounded-')), + undefined, + { + host: createTestHostEnvironment(), + signal: controller.signal, + remoteHealthGate: async (budgetMs) => { + assert.equal(budgetMs, undefined); + controller.abort(); + await new Promise(() => {}); + }, + }, + ), + (error: unknown) => { + assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); + assert.equal(error.details?.reason, 'request_canceled'); + assert.equal(error.details?.dispatched, 'no'); + return true; + }, + ); +}); diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 928926cbf7..328d5cbb31 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -34,6 +34,7 @@ import { } from './daemon-client-rpc.ts'; import { abortedRequestError, + createRequestGuard, handleRequestTimeout, handleTransportError, refuseAbortedRequest, @@ -511,7 +512,9 @@ async function resendAfterRemoteHealthGate( const requestId = req.meta?.requestId; const gateBudgetMs = remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline); try { - await gate(gateBudgetMs, options.signal); + // Settles on the caller's abort even when a probe without a budget is still in flight. + const guard = createRequestGuard({ signal: options.signal, requestId }); + await guard.guard(() => gate(gateBudgetMs, options.signal)); } catch (error) { refuseAbortedRequest(options.signal, requestId); throw error;