diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index 46e27836b8..1037779a66 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -9,9 +9,16 @@ 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, 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`. +- 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. @@ -39,7 +46,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, 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. @@ -47,6 +58,17 @@ 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. +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 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. 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 +98,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-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 fedff186c2..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,18 +4,24 @@ // 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 { closeLoopbackServer, listenOnLoopback, + mkdtempForTestSync, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; 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 { + 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) { @@ -152,6 +158,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 +172,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 +182,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 = 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. - assert.equal((await cachedRemoteDaemonHealth(remote.info, 50)).reachable, true); + // The settled answer is cached, so a later caller reads it without probing. + assert.equal( + (await readCachedRemoteDaemonHealth(remote.info, remote.stateDir))?.reachable, + true, + ); assert.equal(remote.probes(), 2); } finally { await closeLoopbackServer(remote.handler); @@ -194,9 +205,10 @@ 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 probeRemoteDaemonHealth(remote.info, remote.stateDir, 0)).reachable, false); assert.equal( - (await cachedRemoteDaemonHealth(remote.info, undefined, AbortSignal.abort())).reachable, + (await probeRemoteDaemonHealth(remote.info, remote.stateDir, undefined, AbortSignal.abort())) + .reachable, false, ); assert.equal(remote.probes(), 0); @@ -204,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 5be44596db..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 @@ -1,10 +1,35 @@ import assert from 'node:assert/strict'; -import { test } from 'vitest'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { test, vi } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; import { - cachedRemoteHealth, + cacheRemoteDaemonHealth, + probedRemoteHealth, invalidateRemoteDaemonHealth, + readCachedRemoteHealth, } from '../daemon-client-remote-health-cache.ts'; -import type { RemoteDaemonHealth } from '../daemon-client-transport.ts'; +import { + readCachedRemoteHealthRecord, + type RemoteDaemonHealth, +} 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, +})); const HEALTHY: RemoteDaemonHealth = { reachable: true, instanceId: 'remote-instance' }; @@ -13,25 +38,166 @@ 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. */ +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 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.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'); + 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(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'; + rpcProtocol.current = 4; + assert.equal(reuse(info), undefined, 'another RPC protocol probes again'); + rpcProtocol.current = 3; + + // 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.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', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-health-planted-'); + const store = { stateDir, readRecord: readCachedRemoteHealthRecord }; + 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); + 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.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-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', { 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..f2ccba62df --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-transport-persisted-health.test.ts @@ -0,0 +1,462 @@ +// 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: () => { + // 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', connectingSocket)), + }); + }, + }; + 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 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/__tests__/daemon-client-transport-request-guard.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport-request-guard.test.ts index 2746df91ca..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-transport.ts'; +import { createRequestGuard } from '../daemon-client-timeout.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 a7fa975558..ed5c07fd30 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 }, @@ -216,56 +217,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 { @@ -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,7 @@ test.for(['timeout', 'reset'] as const)( }, ); +/** A remote daemon that answers /health with `instanceId()` and refuses a stale instance with 409. */ // 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-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-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index 90de3f239f..3aa3fd940d 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-transport.ts'; +import { + openRemoteHealthGate, + readCachedRemoteDaemonHealth, +} from './daemon-client-remote-health-gate.ts'; import { assertDaemonPolicyMatches, readReusableLocalDaemon, @@ -70,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; }; /** @@ -273,28 +279,14 @@ async function ensureRemoteDaemon( pid: 0, baseUrl: settings.remoteBaseUrl, }; - // 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, - 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: remoteInfo, - 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.', - }); + const stateDir = settings.paths.baseDir; + const cached = await readCachedRemoteDaemonHealth(remoteInfo, stateDir); + if (!cached) { + await openRemoteHealthGate(remoteInfo, stateDir, healthRecovery); + return { info: remoteInfo, startedByClient: false }; } - remoteInfo.capabilities = (health.upstream ?? health).capabilities; - remoteInfo.remoteInstanceId = health.instanceId; - remoteInfo.remoteUpstreamInstanceId = health.upstream?.instanceId; - return { info: remoteInfo, startedByClient: false }; + applyRemoteDaemonHealth(remoteInfo, cached); + return { info: remoteInfo, startedByClient: false, remoteHealthCached: true }; } /** 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..2c6233cf9c 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -1,6 +1,21 @@ +import crypto from 'node:crypto'; +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 { + 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'; +/** 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 = { baseUrl: string; @@ -13,46 +28,197 @@ 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. 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_PREFIX = 'remote-daemon-health-'; +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; } -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 { + // The credential as `/health` received it: the auth header builder trims it. + const sentToken = buildDaemonHttpAuthHeaders(info.token)['x-agent-device-token']; return ( - health.reachable && !!health.instanceId && (!health.upstream || !!health.upstream.instanceId) + typeof value === 'string' && + value.length <= INSTANCE_ID_MAX_LENGTH && + HEADER_VALUE.test(value) && + !(sentToken && value.includes(sentToken)) && + !(info.baseUrl && value.includes(info.baseUrl)) ); } -export function cacheRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHealth): void { - if (!isCacheableRemoteHealth(health)) return; +// 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 && + isUsableInstanceId(health.instanceId, info) && + (!needsUpstream || isUsableInstanceId(health.upstream?.instanceId, info)) + ); +} + +function persistedIdentity(info: DaemonInfo): string { + return crypto + .createHash('sha256') + .update( + JSON.stringify([ + readVersion(), + DAEMON_RPC_PROTOCOL_VERSION, + info.baseUrl ?? '', + info.token, + info.pid, + ]), + ) + .digest('hex'); +} + +function persistedHealthPath(stateDir: string, identity: string): string { + return path.join(stateDir, `${PERSISTED_HEALTH_FILE_PREFIX}${identity.slice(0, 16)}.json`); +} + +/** + * 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: string, +): { identity: unknown; health: unknown } | null { + try { + const descriptor = openVerifiedFileForRead(persistedHealthPath(stateDir, identity)); + 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; + } +} + +// 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 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, 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 { + // Only what admits a later request: the instance preconditions and the capabilities. + const { instanceId, capabilities, upstream } = health; + const record = { + instanceId, + capabilities, + ...(upstream + ? { upstream: { instanceId: upstream.instanceId, capabilities: upstream.capabilities } } + : {}), + }; + const identity = persistedIdentity(info); + const entry = { identity, health: record }; + try { + fs.mkdirSync(stateDir, { recursive: true }); + publishFileSync({ + destination: persistedHealthPath(stateDir, identity), + contents: `${JSON.stringify(entry)}\n`, + mode: 0o600, + }); + } catch {} +} + +function removePersistedHealth(info: DaemonInfo, stateDir: string): void { + const identity = persistedIdentity(info); + if (readPersistedEntry(stateDir, identity)?.identity !== identity) return; + try { + fs.rmSync(persistedHealthPath(stateDir, identity), { force: true }); + } catch {} +} + +export function cacheRemoteDaemonHealth( + info: DaemonInfo, + health: RemoteDaemonHealth, + stateDir?: string, +): void { + if (!isCacheableRemoteHealth(health, info)) return; remoteHealthCache = { baseUrl: info.baseUrl ?? '', token: info.token, 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, + store?: PersistedHealthStore, +): RemoteDaemonHealth | undefined { + if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) { + return remoteHealthCache.health; + } + const persisted = store ? readPersistedHealth(info, store) : undefined; + if (persisted) cacheRemoteDaemonHealth(info, persisted); + return persisted; } /** - * 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, + stateDir?: string, ): Promise { - if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) { - return remoteHealthCache.health; - } 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-gate.ts b/packages/daemon-client/src/daemon-client-remote-health-gate.ts new file mode 100644 index 0000000000..26089dc04b --- /dev/null +++ b/packages/daemon-client/src/daemon-client-remote-health-gate.ts @@ -0,0 +1,79 @@ +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 }); +} + +/** 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 { probedRemoteHealth } = await loadRemoteHealthCache(); + return await probedRemoteHealth( + info, + () => readRemoteDaemonHealth(info, probeTimeoutMs, callerSignal), + stateDir, + ); +} + +/** + * 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, + 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 probeRemoteDaemonHealth( + 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) => probeRemoteDaemonHealth(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 live even when the drop failed. */ +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 658541eeaa..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,7 +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 { cachedRemoteDaemonHealth, type RemoteDaemonHealth } 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. */ @@ -26,6 +26,8 @@ function isTransientHealthFailure(health: RemoteDaemonHealth): boolean { */ export async function recoverRemoteDaemonHealth(params: { info: DaemonInfo; + /** 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. */ @@ -49,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, 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-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index 142f26019b..d3780f4986 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,138 @@ 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); + }, + ); + }); + }, + }; +} + +/** + * `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 397cea0767..328d5cbb31 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -2,9 +2,8 @@ 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, @@ -33,7 +32,14 @@ import { incompatibleRemoteProtocolError, refuseOversizedDaemonRequest, } from './daemon-client-rpc.ts'; -import { handleRequestTimeout } from './daemon-client-timeout.ts'; +import { + abortedRequestError, + createRequestGuard, + 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'; import type { @@ -43,7 +49,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; @@ -60,95 +66,13 @@ 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, + signal: AbortSignal | 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; @@ -449,7 +373,17 @@ 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); + // 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; + }, }); } @@ -496,7 +430,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, @@ -507,7 +446,21 @@ async function sendRequestWithFallback( options, ); } - if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); + if (dropsCachedRemoteHealth(error)) { + await invalidateRemoteDaemonHealth(info, statePaths.baseDir); + } + if (info.baseUrl && options.remoteHealthGate && isProvenUnsentFailure(error)) { + return await resendAfterRemoteHealthGate( + options.remoteHealthGate, + info, + req, + statePaths, + timeoutMs, + deadline, + 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 +476,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 +490,88 @@ 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); +} + +/** + * 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: NonNullable, + info: DaemonInfo, + req: DaemonWireRequest, + statePaths: DaemonPaths, + timeoutMs: number | undefined, + deadline: number | undefined, + transport: ResolvedDaemonTransport, + options: SendRequestOptions, +): Promise { + const requestId = req.meta?.requestId; + const gateBudgetMs = remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline); + try { + // 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; + } + refuseAbortedRequest(options.signal, requestId); + const resendOptions = { ...options, remoteHealthGate: undefined }; + return await resendAfterFreshRemoteHealth( + info, + req, + statePaths, + remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline), + transport, + resendOptions, + ); +} + +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 (dropsCachedRemoteHealth(error)) { + await invalidateRemoteDaemonHealth(info, statePaths.baseDir); + } throw error; } } +/** 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; +} + +// 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, timeoutMs: number | undefined, @@ -575,12 +596,14 @@ function isRemoteInstanceMismatch(error: unknown): boolean { ); } -function isRemoteTransportFailure(error: unknown): boolean { +// 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.timeout.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 +679,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 +766,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 } : {}), @@ -830,160 +805,175 @@ 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', { + // 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, + }); + }; + 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); + const stale = 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; + }); + PROVEN_STALE.add(stale); + rejectOnce(stale); + return; } - 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); - }); - }, - ); - - const remote = isRemoteDaemon(info); - const timeoutHandle = - typeof timeoutMs === 'number' - ? setTimeout(() => { - rejectOnce( - requestTimeoutError(timeoutMs, req.meta?.requestId, requestSent, responseStarted), + 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, ); - 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), + }); + 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(() => { + const expired = requestTimeoutError( + timeoutMs, + req.meta?.requestId, + requestSent, + responseStarted, + ); + if (!connected) PROVEN_UNSENT.add(expired); + rejectOnce(expired); + 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('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('finish', () => { - requestSent = true; + 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): Promise { +export 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. */ -export async function cachedRemoteDaemonHealth( - info: DaemonInfo, - probeTimeoutMs?: number, - callerSignal?: AbortSignal, -): Promise { - const { cachedRemoteHealth } = await loadRemoteHealthCache(); - return await cachedRemoteHealth(info, () => - readRemoteDaemonHealth(info, probeTimeoutMs, callerSignal), - ); +/** 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..e9540175ac 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -20,7 +20,11 @@ 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-timeout.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 { @@ -120,6 +124,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, signal: AbortSignal | undefined) => { + const { refreshRemoteDaemonHealth } = await import('./daemon-client-remote-health-gate.ts'); + await refreshRemoteDaemonHealth( + info, + settings.paths.baseDir, + budgetMs === undefined ? undefined : { budgetMs, signal }, + ); + } + : undefined; const preparedRemoteRequest = await cancellation.guard( async () => await protectArtifactUploadWithLeaseBeats( @@ -128,6 +143,7 @@ async function sendToDaemonOnHost( requestWithoutAuthFlag, options.signal, options.onProgress, + remoteHealthGate, ), ); writeInstallInProgressNotice(requestWithoutAuthFlag.command, host.env); @@ -170,10 +186,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, options.signal)); + } return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send); }, { requestId, command: req.command }, @@ -391,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) { @@ -405,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 8685cee553..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 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. 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