From 14da43fcbc5499868e1729d1b3a559c60c185beb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 08:33:44 +0100 Subject: [PATCH 01/10] perf(daemon-client): send opted-in standalone remote commands as one checked RPC A connection with daemonRpc: checked (profile field, --daemon-rpc, or AGENT_DEVICE_DAEMON_RPC) sends standalone commands on POST /rpc/checked with no /health probe first. connect accepts the field only when every link advertises checked-rpc. Installs keep health-first and the instance fences. A route miss fails typed with dispatched unknown and is never resent; refusals keep today's upgrade message. Only a connection that never opened is acted on: refused fails at once, a connect timeout runs the existing /health recovery loop and sends once. Without the field the client path is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/flag-definitions-connection.ts | 12 + packages/command-registry/src/flag-groups.ts | 1 + packages/command-surface/src/command-flags.ts | 1 + packages/contracts/src/cli-flags.ts | 2 + packages/contracts/src/client-connection.ts | 1 + packages/contracts/src/daemon-http.ts | 5 + packages/contracts/src/facades/remote.ts | 2 + .../contracts/src/remote-config-fields.ts | 10 + ...lient-checked-rpc-connect-recovery.test.ts | 122 +++++++++ .../daemon-client-checked-rpc.test.ts | 250 ++++++++++++++++++ .../src/daemon-client-checked-rpc.ts | 242 +++++++++++++++++ .../src/daemon-client-lifecycle.ts | 44 ++- .../src/daemon-client-metadata.ts | 2 + .../src/daemon-client-remote-resend.ts | 126 +++++++++ .../src/daemon-client-transport.ts | 144 +++++----- .../src/daemon-lifecycle-errors.ts | 4 + packages/daemon-client/src/index.ts | 16 +- packages/remote/src/remote-config-schema.ts | 2 + .../remote/src/session-script-destination.ts | 28 +- scripts/integration-progress-model.ts | 1 + src/cli.ts | 1 + src/cli/commands/connection.ts | 14 + test/wire-compat/ledger.json | 40 ++- test/wire-compat/surface.ts | 13 + website/docs/docs/configuration.md | 1 + website/docs/docs/remote-proxy.md | 17 ++ 26 files changed, 994 insertions(+), 107 deletions(-) create mode 100644 packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts create mode 100644 packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts create mode 100644 packages/daemon-client/src/daemon-client-checked-rpc.ts create mode 100644 packages/daemon-client/src/daemon-client-remote-resend.ts diff --git a/packages/command-registry/src/flag-definitions-connection.ts b/packages/command-registry/src/flag-definitions-connection.ts index 0012f2acab..247ffbf745 100644 --- a/packages/command-registry/src/flag-definitions-connection.ts +++ b/packages/command-registry/src/flag-definitions-connection.ts @@ -1,5 +1,6 @@ import { LEASE_BACKENDS } from '@agent-device/kernel/contracts'; import { + DAEMON_RPC_MODES, PROVIDER_DEVICE_ORIENTATIONS, PROVIDER_DEVICE_TYPES, } from '@agent-device/contracts/remote'; @@ -74,6 +75,17 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ projectConfig: false, recorded: false, }, + { + key: 'daemonRpc', + names: ['--daemon-rpc'], + type: 'enum', + enumValues: DAEMON_RPC_MODES, + usageLabel: '--daemon-rpc health|checked', + usageDescription: + 'Remote command RPC: health probes /health first; checked sends one request the remote checks itself', + projectConfig: false, + recorded: false, + }, { key: 'proxyHost', names: ['--host'], diff --git a/packages/command-registry/src/flag-groups.ts b/packages/command-registry/src/flag-groups.ts index b07bb93950..ef960345f5 100644 --- a/packages/command-registry/src/flag-groups.ts +++ b/packages/command-registry/src/flag-groups.ts @@ -76,6 +76,7 @@ export const COMMON_COMMAND_SUPPORTED_FLAG_KEYS = flagKeys( 'daemonAuthToken', 'daemonTransport', 'daemonServerMode', + 'daemonRpc', 'tenant', 'sessionIsolation', 'runId', diff --git a/packages/command-surface/src/command-flags.ts b/packages/command-surface/src/command-flags.ts index fc2be6a74f..62fd6fe045 100644 --- a/packages/command-surface/src/command-flags.ts +++ b/packages/command-surface/src/command-flags.ts @@ -23,6 +23,7 @@ function buildFlags(options: InternalRequestOptions): CommandFlags { daemonBaseUrl: options.daemonBaseUrl, daemonTransport: options.daemonTransport, daemonServerMode: options.daemonServerMode, + daemonRpc: options.daemonRpc, ...leaseScopeToCommandFlags(leaseScope), provider: options.provider, providerSessionId: options.providerSessionId, diff --git a/packages/contracts/src/cli-flags.ts b/packages/contracts/src/cli-flags.ts index 018cbb0fbe..595b8520d5 100644 --- a/packages/contracts/src/cli-flags.ts +++ b/packages/contracts/src/cli-flags.ts @@ -16,6 +16,7 @@ import type { } from '@agent-device/kernel/contracts'; import type { CloudProviderProfileFields, + DaemonRpcMode, RemoteConfigMetroOptions, } from './remote-config-fields.ts'; import type { ScreenshotRequestFlags } from './screenshot.ts'; @@ -40,6 +41,7 @@ export type CliFlags = CloudProviderProfileFields & daemonAuthToken?: string; daemonTransport?: DaemonTransportPreference; daemonServerMode?: DaemonServerMode; + daemonRpc?: DaemonRpcMode; proxyHost?: string; proxyPort?: number; publicOrigin?: string; diff --git a/packages/contracts/src/client-connection.ts b/packages/contracts/src/client-connection.ts index 96bb4a55c9..fe4fd84df7 100644 --- a/packages/contracts/src/client-connection.ts +++ b/packages/contracts/src/client-connection.ts @@ -144,6 +144,7 @@ export type AgentDeviceRequestOverrides = Pick< | 'daemonAuthToken' | 'daemonTransport' | 'daemonServerMode' + | 'daemonRpc' | 'tenant' | 'sessionIsolation' | 'runId' diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index f53d09aaf2..a92753be7a 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -180,6 +180,11 @@ const DAEMON_CHECKED_RPC_REASONS = { // The daemon or proxy speaks a different RPC protocol from the caller. After authentication, // `details.service`, `details.version` and `details.rpcProtocolVersion` name the side that refused. protocolMismatch: { reason: 'remote_rpc_protocol_mismatch' }, + // The connection sets `daemonRpc: checked`, but the remote does not serve checked RPC: `connect` + // found no `checked-rpc` capability in its `/health`, or a command got the route answered as + // unknown. A command is never resent, because an ingress may have answered for one that ran. + // Update the remote daemon or proxy, or remove `daemonRpc` from the connection. + routeUnsupported: { reason: 'remote_checked_rpc_unsupported' }, } as const satisfies ReasonTable<'remote connection'>; /** diff --git a/packages/contracts/src/facades/remote.ts b/packages/contracts/src/facades/remote.ts index a90c19472d..820d3c79b6 100644 --- a/packages/contracts/src/facades/remote.ts +++ b/packages/contracts/src/facades/remote.ts @@ -16,6 +16,7 @@ export type { ProviderConnectionVerification, } from '../provider-connection.ts'; export { + DAEMON_RPC_MODES, PROVIDER_DEVICE_ORIENTATIONS, PROVIDER_DEVICE_TYPES, PROVIDER_PROFILE_FIELD_FLAG_ALIASES, @@ -23,6 +24,7 @@ export { } from '../remote-config-fields.ts'; export type { CloudProviderProfileFields, + DaemonRpcMode, ProviderDeviceOrientation, ProviderDeviceType, RemoteConfigMetroOptions, diff --git a/packages/contracts/src/remote-config-fields.ts b/packages/contracts/src/remote-config-fields.ts index 5a35acc074..63b1efe095 100644 --- a/packages/contracts/src/remote-config-fields.ts +++ b/packages/contracts/src/remote-config-fields.ts @@ -25,6 +25,15 @@ export type ProviderDeviceOrientation = (typeof PROVIDER_DEVICE_ORIENTATIONS)[nu export const PROVIDER_DEVICE_TYPES = ['real', 'virtual'] as const; export type ProviderDeviceType = (typeof PROVIDER_DEVICE_TYPES)[number]; +/** + * How a client sends a remote command. `health` reads `/health` before each command RPC. `checked` + * sends a standalone command on the checked RPC route, where the server refuses protocol skew + * itself, so the command takes one round trip. Only a remote endpoint that advertises `checked-rpc` + * accepts it. + */ +export const DAEMON_RPC_MODES = ['health', 'checked'] as const; +export type DaemonRpcMode = (typeof DAEMON_RPC_MODES)[number]; + export type CloudProviderProfileFields = { providerApp?: string; providerOsVersion?: string; @@ -130,6 +139,7 @@ export type RemoteConnectionProfileFields = { daemonAuthToken?: string; daemonTransport?: DaemonTransportPreference; daemonServerMode?: DaemonServerMode; + daemonRpc?: DaemonRpcMode; tenant?: string; sessionIsolation?: SessionIsolationMode; runId?: string; diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts new file mode 100644 index 0000000000..0a2eb2b3b2 --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts @@ -0,0 +1,122 @@ +// A checked call whose connection never opens is this client's own proof that nothing left. On fake +// time: the first POST never connects, so the connect timer fires, the `/health` loop runs, and the +// command is sent once more. `http.request` is replaced, so no real socket is involved. + +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { EventEmitter } from 'node:events'; +import { afterEach, test, vi } from 'vitest'; +import { sendToDaemon } from '../index.ts'; + +type Call = { method: string; path: string; at: number }; + +function fakeResponse(): EventEmitter { + return Object.assign(new EventEmitter(), { + statusCode: 200, + headers: { 'content-type': 'application/json' }, + resume: () => {}, + setEncoding: () => {}, + }); +} + +/** The first checked POST hangs before its socket connects; everything after it answers. */ +function firstConnectHangs(): Call[] { + const calls: Call[] = []; + vi.spyOn(http, 'request').mockImplementation((( + options: { method?: string; path?: string }, + callback: (res: EventEmitter) => void, + ) => { + const call = { + method: options.method ?? 'GET', + path: options.path ?? '', + at: performance.now(), + }; + calls.push(call); + const hangs = + calls.filter((seen) => seen.method === 'POST').length === 1 && call.method === 'POST'; + const req = Object.assign(new EventEmitter(), { + write: () => {}, + destroy: () => {}, + end: () => { + if (hangs) { + process.nextTick(() => + req.emit('socket', Object.assign(new EventEmitter(), { connecting: true })), + ); + return; + } + const body = + call.method === 'GET' + ? JSON.stringify({ ok: true, service: 'agent-device-daemon', rpcProtocolVersion: 3 }) + : JSON.stringify({ + jsonrpc: '2.0', + id: 'x', + result: { ok: true, data: { sent: true } }, + }); + const res = fakeResponse(); + process.nextTick(() => { + callback(res); + res.emit('data', body); + res.emit('end'); + }); + }, + }); + return req; + }) as unknown as typeof http.request); + return calls; +} + +/** Advances fake time to the next timer once real work has gone quiet. Returns the stop. */ +function driveFakeTime(): () => Promise { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); + let driving = true; + const drive = (async () => { + while (driving) { + for (let turn = 0; turn < 20; turn += 1) { + await new Promise((resolve) => setImmediate(resolve)); + } + if (vi.getTimerCount() > 0) await vi.advanceTimersToNextTimerAsync(); + } + })(); + return async () => { + driving = false; + await drive; + }; +} + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +test('a checked connect timeout runs the /health loop, then sends exactly once more', async () => { + const calls = firstConnectHangs(); + const stopDriving = driveFakeTime(); + try { + const response = await sendToDaemon( + { + session: 'default', + command: 'session', + positionals: ['list'], + flags: { + daemonBaseUrl: 'http://remote-mac.example.test:7777/agent-device', + daemonRpc: 'checked', + }, + }, + { authToken: 'remote-secret' }, + ); + + assert.equal(response.ok, true); + assert.deepEqual( + calls.map(({ method, path }) => `${method} ${path}`), + [ + 'POST /agent-device/rpc/checked', + 'GET /agent-device/health', + 'POST /agent-device/rpc/checked', + ], + ); + // The connect timer is the `/health` probe's own 3 s limit; the loop then waits its 1 s interval. + assert.ok((calls[1]?.at ?? 0) - (calls[0]?.at ?? 0) >= 4_000); + } finally { + await stopDriving(); + } +}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts new file mode 100644 index 0000000000..e7d51941c6 --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts @@ -0,0 +1,250 @@ +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, + DAEMON_RPC_PROTOCOL_VERSION, +} from '@agent-device/contracts/daemon-http'; +import { assertRemoteServesCheckedRpc, sendToDaemon } from '../index.ts'; + +type Seen = { method: string; url: string; protocol: string | undefined }; +type Answer = { status?: number; headers?: Record; body: string }; + +const OK_ANSWER: Answer = { + body: JSON.stringify({ jsonrpc: '2.0', id: 'test', result: { ok: true, data: {} } }), +}; + +/** A remote daemon that records every request and answers RPCs with `answer`. */ +async function remoteDaemon(answer: Answer = OK_ANSWER) { + const seen: Seen[] = []; + const server = http.createServer((req, res) => { + const protocol = req.headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER]; + seen.push({ + method: req.method ?? '', + url: req.url ?? '', + protocol: typeof protocol === 'string' ? protocol : undefined, + }); + req.resume(); + req.on('end', () => { + if (req.url === '/health') { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ ok: true, service: 'agent-device-daemon', rpcProtocolVersion: 3 }), + ); + return; + } + res.statusCode = answer.status ?? 200; + for (const [name, value] of Object.entries(answer.headers ?? {})) res.setHeader(name, value); + res.end(answer.body); + }); + }); + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + return { seen, baseUrl, close: () => closeLoopbackServer(server) }; +} + +function sessionList(baseUrl: string, flags: Record = {}) { + return { + session: 'default', + command: 'session', + positionals: ['list'], + flags: { daemonBaseUrl: baseUrl, ...flags }, + }; +} + +const routes = (seen: Seen[]) => seen.map(({ method, url }) => `${method} ${url}`); + +test('without daemonRpc a remote command probes /health first, exactly as before', async () => { + const daemon = await remoteDaemon(); + try { + await expect(sendToDaemon(sessionList(daemon.baseUrl))).resolves.toMatchObject({ ok: true }); + expect(routes(daemon.seen)).toEqual(['GET /health', 'POST /rpc']); + expect(daemon.seen[1]?.protocol).toBeUndefined(); + } finally { + await daemon.close(); + } +}); + +test('with daemonRpc checked a standalone command takes one checked request', async () => { + const daemon = await remoteDaemon(); + try { + await expect( + sendToDaemon(sessionList(daemon.baseUrl, { daemonRpc: 'checked' })), + ).resolves.toMatchObject({ ok: true }); + expect(routes(daemon.seen)).toEqual(['POST /rpc/checked']); + expect(daemon.seen[0]?.protocol).toBe(String(DAEMON_RPC_PROTOCOL_VERSION)); + } finally { + await daemon.close(); + } +}); + +test('a leased command under checked RPC sends no lease beat ahead of its one request', async () => { + const daemon = await remoteDaemon(); + try { + await sendToDaemon(sessionList(daemon.baseUrl, { daemonRpc: 'checked', leaseId: 'lease-1' })); + expect(routes(daemon.seen)).toEqual(['POST /rpc/checked']); + } finally { + await daemon.close(); + } +}); + +test('an install keeps the /health probe and /rpc even when checked RPC is on', async () => { + const daemon = await remoteDaemon(); + try { + await sendToDaemon({ + session: 'default', + command: 'install', + positionals: ['com.example.app', 'remote:/tmp/app.apk'], + flags: { daemonBaseUrl: daemon.baseUrl, daemonRpc: 'checked', platform: 'android' }, + }); + expect(routes(daemon.seen)).toEqual(['GET /health', 'POST /rpc']); + } finally { + await daemon.close(); + } +}); + +test('a route miss under checked RPC fails typed and is never resent', async () => { + const daemon = await remoteDaemon({ status: 404, body: 'Not found' }); + try { + await expect( + sendToDaemon(sessionList(daemon.baseUrl, { daemonRpc: 'checked' })), + ).rejects.toMatchObject({ + details: { reason: 'remote_checked_rpc_unsupported', dispatched: 'unknown' }, + }); + expect(routes(daemon.seen)).toEqual(['POST /rpc/checked']); + } finally { + await daemon.close(); + } +}); + +test('a JSON-RPC 404 under checked RPC is the daemon answer, not a route miss', async () => { + const daemon = await remoteDaemon({ + status: 404, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'test', + error: { + code: -32000, + message: 'gone', + data: { code: 'SESSION_NOT_FOUND', message: 'gone' }, + }, + }), + }); + try { + await expect( + sendToDaemon(sessionList(daemon.baseUrl, { daemonRpc: 'checked' })), + ).rejects.toMatchObject({ code: 'SESSION_NOT_FOUND' }); + } finally { + await daemon.close(); + } +}); + +test('an upstream protocol refusal keeps the upgrade message and names the daemon behind the proxy', async () => { + const daemon = await remoteDaemon({ + status: 409, + headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'upstream-protocol-mismatch' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'test', + error: { + code: -32001, + message: 'skew', + data: { + details: { service: 'agent-device-daemon', version: '9.0.0', rpcProtocolVersion: 99 }, + }, + }, + }), + }); + try { + const error = await sendToDaemon(sessionList(daemon.baseUrl, { daemonRpc: 'checked' })).catch( + (error: unknown) => error, + ); + expect(error).toMatchObject({ + message: expect.stringContaining( + 'the agent-device-daemon behind agent-device-proxy runs 9.0.0 (RPC protocol 99)', + ), + details: { upgradeSide: 'client-and-proxy', remoteRpcProtocolVersion: 99, dispatched: 'no' }, + }); + expect(routes(daemon.seen)).toEqual(['POST /rpc/checked']); + } finally { + await daemon.close(); + } +}); + +test('a script-artifacts refusal is not dispatched and removes the publication record', async () => { + const daemon = await remoteDaemon({ + status: 409, + headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'script-artifacts' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 'test', error: { code: -32001, message: 'no' } }), + }); + const root = mkdtempForTestSync('checked-script-'); + const stateDir = path.join(root, 'state'); + try { + await expect( + sendToDaemon({ + command: 'open', + session: 'owned', + positionals: ['Demo'], + flags: { + daemonBaseUrl: daemon.baseUrl, + daemonRpc: 'checked', + saveScript: path.join(root, 'journey.ad'), + stateDir, + }, + }), + ).rejects.toMatchObject({ + details: { reason: 'remote_script_artifacts_unsupported', dispatched: 'no' }, + }); + const records = path.join(stateDir, 'remote-connections', 'session-scripts'); + expect(fs.existsSync(records) ? fs.readdirSync(records) : []).toEqual([]); + } finally { + await daemon.close(); + } +}); + +test('a refused connection under checked RPC fails at once as an unavailable remote', async () => { + const daemon = await remoteDaemon(); + const { baseUrl } = daemon; + await daemon.close(); + await expect(sendToDaemon(sessionList(baseUrl, { daemonRpc: 'checked' }))).rejects.toMatchObject({ + details: { reason: 'remote_daemon_unavailable', dispatched: 'no', attempts: 1 }, + }); +}); + +test.each([ + { name: 'a daemon without the capability', health: {}, served: false }, + { name: 'a daemon with it', health: { capabilities: ['checked-rpc'] }, served: true }, + { + name: 'a proxy whose daemon lacks it', + health: { capabilities: ['checked-rpc'], upstream: { capabilities: [] } }, + served: false, + }, + { + name: 'a proxy whose daemon has it', + health: { capabilities: ['checked-rpc'], upstream: { capabilities: ['checked-rpc'] } }, + served: true, + }, +])( + 'connect accepts daemonRpc checked only when $name advertises checked-rpc', + async ({ health, served }) => { + const server = http.createServer((_req, res) => { + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ ok: true, ...health })); + }); + try { + const verdict = assertRemoteServesCheckedRpc({ + baseUrl: `http://127.0.0.1:${await listenOnLoopback(server)}`, + token: undefined, + }); + if (served) await expect(verdict).resolves.toBeUndefined(); + else + await expect(verdict).rejects.toMatchObject({ + details: { reason: 'remote_checked_rpc_unsupported', dispatched: 'no' }, + }); + } finally { + await closeLoopbackServer(server); + } + }, +); diff --git a/packages/daemon-client/src/daemon-client-checked-rpc.ts b/packages/daemon-client/src/daemon-client-checked-rpc.ts new file mode 100644 index 0000000000..ee041301d0 --- /dev/null +++ b/packages/daemon-client/src/daemon-client-checked-rpc.ts @@ -0,0 +1,242 @@ +// The client half of the checked RPC route (ADR 0006): what a refusal or an unknown-route answer +// means for the caller, and the `connect` check that the remote serves the route at all. Loaded only +// on those paths, so a command that gets its answer never pays for it. +import type { IncomingMessage } from 'node:http'; +import type { Socket } from 'node:net'; +import { AppError, discloseUnclassifiedDispatch } from '@agent-device/kernel/errors'; +import { isRecord } from '@agent-device/kernel/record'; +import { + DAEMON_CHECKED_RPC_REASONS, + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_REFUSALS, +} from '@agent-device/contracts/daemon-http'; +import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; +import type { DaemonInfo } from './daemon-client-metadata.ts'; +import { incompatibleRemoteProtocolError } from './daemon-client-rpc.ts'; +import { readHealthLink, readRemoteDaemonHealth } from './daemon-client-transport.ts'; +import { remoteDaemonUnavailableError } from './daemon-lifecycle-errors.ts'; + +/** The most of a refusal body the client reads: its metadata is a few short fields. */ +const REFUSAL_BODY_MAX_BYTES = 64 * 1024; +/** The most of a 404 body the client reads to tell a daemon's JSON-RPC answer from a route miss. */ +const NOT_FOUND_BODY_MAX_BYTES = 1024 * 1024; + +const UNSUPPORTED_HINT = + 'The remote daemon or proxy does not serve checked RPC. Update it, or remove daemonRpc from the connection profile (or pass --daemon-rpc health).'; + +/** + * A checked call's connection never opened: refused, or not open within the `/health` probe's time. + * Only this client can know it, so it is the one evidence that nothing was sent. Client-internal: + * the resend module turns it into the outcome the caller sees. + */ +export class CheckedRpcConnectFailure extends Error { + readonly timedOut: boolean; + constructor(timedOut: boolean) { + super(timedOut ? 'Checked RPC connect timed out' : 'Checked RPC connect failed'); + this.timedOut = timedOut; + } +} + +/** + * Watches whether a checked call's connection opens (TLS included) within `timeoutMs`, and calls + * `onTimeout` when it does not. Before it opens, nothing can have been sent. + */ +export function watchCheckedRpcConnect( + request: { on(event: 'socket', listener: (socket: Socket) => void): unknown }, + timeoutMs: number, + onTimeout: () => void, +): { + unconnected(): boolean; + failure(timedOut: boolean): CheckedRpcConnectFailure; + stop(): void; +} { + let connected = false; + const timer = setTimeout(() => { + if (!connected) onTimeout(); + }, timeoutMs); + const onConnected = (): void => { + connected = true; + clearTimeout(timer); + }; + request.on('socket', (socket) => { + if (!socket.connecting) onConnected(); + else socket.once('encrypted' in socket ? 'secureConnect' : 'connect', onConnected); + }); + return { + unconnected: () => !connected, + failure: (timedOut) => new CheckedRpcConnectFailure(timedOut), + stop: () => clearTimeout(timer), + }; +} + +/** A checked call's 404, or its 409 that names the refusing precondition. */ +export function isCheckedRpcOutcomeResponse( + statusCode: number | undefined, + headers: Record, +): boolean { + return ( + statusCode === 404 || + (statusCode === 409 && typeof headers[DAEMON_HTTP_REFUSAL_HEADER] === 'string') + ); +} + +/** + * What a checked call's 404 or refusal 409 means. `answer` is a JSON-RPC body the daemon wrote, which the + * caller reads like any other answer. `refused` is final: nothing is resent. + */ +type CheckedRpcOutcome = + | { kind: 'answer'; body: string } + | { kind: 'refused'; error: AppError }; + +/** + * Reads a checked call's 404, or its 409 that carries a refusal header. That 409 is a refusal made + * before dispatch. A 404 whose body is not a JSON-RPC answer is a route this remote does not serve; an + * ingress may still have answered for a command that ran, so the request is never resent. + */ +export async function readCheckedRpcOutcome( + res: IncomingMessage, + info: DaemonInfo, +): Promise { + const notFound = res.statusCode === 404; + const body = await readBoundedBody( + res, + notFound ? NOT_FOUND_BODY_MAX_BYTES : REFUSAL_BODY_MAX_BYTES, + ); + if (notFound) { + return body !== undefined && isJsonRpcAnswer(body) + ? { kind: 'answer', body } + : { kind: 'refused', error: checkedRpcUnsupportedError(info, 'unknown') }; + } + return { + kind: 'refused', + error: checkedRpcRefusalError(String(res.headers[DAEMON_HTTP_REFUSAL_HEADER]), body, info), + }; +} + +function checkedRpcRefusalError( + refusal: string, + body: string | undefined, + info: DaemonInfo, +): AppError { + switch (refusal) { + case DAEMON_HTTP_REFUSALS.protocolMismatch: + case DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch: + return discloseUnclassifiedDispatch(protocolMismatchError(refusal, body, info), 'no'); + case DAEMON_HTTP_REFUSALS.scriptArtifacts: + return discloseUnclassifiedDispatch(scriptArtifactsError(), 'no'); + default: + return new AppError( + 'COMMAND_FAILED', + 'The remote refused the checked RPC call because it named no RPC protocol', + { + reason: DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason, + dispatched: 'no', + daemonBaseUrl: info.baseUrl, + hint: 'An ingress between this client and the remote removes the x-agent-device-rpc-protocol header. Fix that ingress, or remove daemonRpc from the connection profile.', + }, + ); + } +} + +/** Today's upgrade message, built from the refusing side's bounded and validated metadata. */ +function protocolMismatchError( + refusal: string, + body: string | undefined, + info: DaemonInfo, +): AppError { + const link = readHealthLink(readRefusalDetails(body)); + const behindProxy = refusal === DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch; + if (typeof link.rpcProtocolVersion === 'number' && Number.isInteger(link.rpcProtocolVersion)) { + return incompatibleRemoteProtocolError( + info.baseUrl ?? '', + { ...link, rpcProtocolVersion: link.rpcProtocolVersion }, + behindProxy ? { service: 'agent-device-proxy' } : undefined, + ); + } + return new AppError('COMMAND_FAILED', 'Remote daemon RPC protocol is incompatible', { + reason: DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason, + daemonBaseUrl: info.baseUrl, + hint: 'Upgrade agent-device so this client and the remote speak the same RPC protocol.', + }); +} + +function scriptArtifactsError(): AppError { + try { + assertScriptArtifactsCapability(undefined); + } catch (error) { + if (error instanceof AppError) return error; + } + throw new Error('assertScriptArtifactsCapability accepted no capabilities'); +} + +/** The typed failure when the remote does not serve checked RPC. A command is never resent. */ +function checkedRpcUnsupportedError(info: DaemonInfo, dispatched: 'no' | 'unknown'): AppError { + return new AppError('COMMAND_FAILED', 'The remote does not serve checked RPC', { + reason: DAEMON_CHECKED_RPC_REASONS.routeUnsupported.reason, + dispatched, + daemonBaseUrl: info.baseUrl, + hint: UNSUPPORTED_HINT, + }); +} + +/** + * Refuses `daemonRpc: checked` at `connect` unless every link the command RPC crosses advertises the + * `checked-rpc` capability: the endpoint, and the daemon behind it when the endpoint is a proxy. + */ +export async function assertRemoteServesCheckedRpc(params: { + baseUrl: string; + token: string | undefined; +}): Promise { + const info: DaemonInfo = { token: params.token ?? '', pid: 0, baseUrl: params.baseUrl }; + const health = await readRemoteDaemonHealth(info); + if (!health.reachable) { + throw remoteDaemonUnavailableError({ daemonBaseUrl: params.baseUrl, attempts: 1 }); + } + if (health.checkedRpc && (!health.upstream || health.upstream.checkedRpc)) return; + throw checkedRpcUnsupportedError(info, 'no'); +} + +function readRefusalDetails(body: string | undefined): Record { + if (body === undefined) return {}; + try { + const parsed: unknown = JSON.parse(body); + const details = + isRecord(parsed) && isRecord(parsed.error) && isRecord(parsed.error.data) + ? parsed.error.data.details + : undefined; + return isRecord(details) ? details : {}; + } catch { + return {}; + } +} + +function isJsonRpcAnswer(body: string): boolean { + try { + const parsed: unknown = JSON.parse(body); + return ( + isRecord(parsed) && parsed.jsonrpc === '2.0' && ('result' in parsed || 'error' in parsed) + ); + } catch { + return false; + } +} + +/** The body, or `undefined` when it passes `maxBytes` or the stream fails before its end. */ +function readBoundedBody(res: IncomingMessage, maxBytes: number): Promise { + return new Promise((resolve) => { + const chunks: Buffer[] = []; + let bytes = 0; + res.on('data', (chunk: Buffer) => { + bytes += chunk.byteLength; + if (bytes > maxBytes) { + res.destroy(); + resolve(undefined); + return; + } + chunks.push(chunk); + }); + res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + res.on('error', () => resolve(undefined)); + res.on('aborted', () => resolve(undefined)); + }); +} diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index 75ec4ac853..3f77b2e85c 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -24,8 +24,12 @@ import { type DaemonServerMode, type DaemonTransportPreference, } from '@agent-device/daemon-contracts/daemon-resolution'; -import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; -import { DAEMON_CLIENT_CONFIG_REASONS } from './daemon-lifecycle-errors.ts'; +import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; +import type { DaemonRpcMode } from '@agent-device/contracts/remote'; +import { + DAEMON_CLIENT_CONFIG_REASONS, + REMOTE_DAEMON_UNREACHABLE_HINT, +} from './daemon-lifecycle-errors.ts'; import type { findUnrecoveredRepairCommitFailure } from '@agent-device/daemon-contracts/session-repair-tombstone'; import type { DaemonInfo } from './daemon-client-metadata.ts'; @@ -56,6 +60,11 @@ export type DaemonClientSettings = { ownedStateDir?: OwnedReplayStateDir; remoteBaseUrl?: string; remoteAuthToken?: string; + /** + * The request goes on the checked RPC route without a `/health` probe: its connection sets + * `daemonRpc: checked`, and the request has no remote side effect before its command RPC. + */ + remoteCheckedRpc?: true; /** See {@link DaemonBinding}. Present on a client that is pinned to one daemon instance. */ daemonBinding?: DaemonBinding; }; @@ -128,10 +137,26 @@ export function resolveClientSettings( ownedStateDir, remoteBaseUrl: remote.remoteBaseUrl, remoteAuthToken: remote.authToken, + ...(remote.remoteBaseUrl && remote.daemonRpc === 'checked' && isStandaloneRemoteRequest(req) + ? { remoteCheckedRpc: true as const } + : {}), ...(daemonBinding ? { daemonBinding } : {}), }; } +/** + * Whether a remote request reaches the daemon with nothing before its command RPC. An install may + * upload an artifact, under lease beats, before its RPC, so it keeps the `/health` probe and the + * instance headers that pin that RPC to the daemon holding the upload. + */ +function isStandaloneRemoteRequest(req: Omit): boolean { + return ( + req.command !== PUBLIC_COMMANDS.install && + req.command !== PUBLIC_COMMANDS.reinstall && + req.command !== INTERNAL_COMMANDS.installSource + ); +} + /** * The local daemon a request would use, in the terms `ensureDaemon` takes, or `undefined` when the * request has no shared local daemon to ensure: a remote connection has none, and a one-shot replay @@ -192,12 +217,20 @@ function resolveRemoteClientSettings( rawBaseUrl: string | undefined; remoteBaseUrl?: string; authToken?: string; + daemonRpc: DaemonRpcMode; } { const rawBaseUrl = req.flags?.daemonBaseUrl ?? env.AGENT_DEVICE_DAEMON_BASE_URL; const remoteBaseUrl = resolveRemoteDaemonBaseUrl(rawBaseUrl); const authToken = suppliedAuthToken ?? env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; validateRemoteDaemonTrust(remoteBaseUrl, authToken); - return { rawBaseUrl, remoteBaseUrl, authToken }; + const daemonRpc = resolveDaemonRpcMode(req.flags?.daemonRpc ?? env.AGENT_DEVICE_DAEMON_RPC); + return { rawBaseUrl, remoteBaseUrl, authToken, daemonRpc }; +} + +function resolveDaemonRpcMode(raw: string | undefined): DaemonRpcMode { + if (raw === undefined || raw === '') return 'health'; + if (raw === 'health' || raw === 'checked') return raw; + throw new AppError('INVALID_ARGS', 'daemonRpc must be health or checked', { daemonRpc: raw }); } function resolveTransportClientSettings( @@ -285,6 +318,9 @@ async function ensureRemoteDaemon( pid: 0, baseUrl: settings.remoteBaseUrl, }; + // The checked route makes the server refuse what `/health` would have: no probe goes first. + if (settings.remoteCheckedRpc) + return { info: { ...remoteInfo, checkedRpc: true }, startedByClient: false }; // 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( @@ -300,7 +336,7 @@ async function ensureRemoteDaemon( 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.', + hint: REMOTE_DAEMON_UNREACHABLE_HINT, }); } remoteInfo.capabilities = (health.upstream ?? health).capabilities; diff --git a/packages/daemon-client/src/daemon-client-metadata.ts b/packages/daemon-client/src/daemon-client-metadata.ts index f4eecf9f5b..25f8b415d4 100644 --- a/packages/daemon-client/src/daemon-client-metadata.ts +++ b/packages/daemon-client/src/daemon-client-metadata.ts @@ -40,6 +40,8 @@ export type DaemonInfo = { baseUrl?: string; remoteInstanceId?: string; remoteUpstreamInstanceId?: string; + /** Requests go on the checked RPC route, and no `/health` probe preceded them. */ + checkedRpc?: true; }; /** Why a daemon is not the one this client would use. `transport` means alive but not on the diff --git a/packages/daemon-client/src/daemon-client-remote-resend.ts b/packages/daemon-client/src/daemon-client-remote-resend.ts new file mode 100644 index 0000000000..b3b0bbdc6a --- /dev/null +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -0,0 +1,126 @@ +// The only ways a remote command is sent a second time. Each trigger is evidence that the first send +// never dispatched: a typed pre-dispatch instance refusal on `/rpc` (ADR 0006), or, on the checked +// route, this client's own proof that the connection never opened. Nothing a response says on the +// checked route triggers a resend. Loaded only on those failures. +import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { + assertScriptArtifactsCapability, + type DaemonPaths, +} from '@agent-device/daemon-contracts/daemon-resolution'; +import type { DaemonInfo } from './daemon-client-metadata.ts'; +import { CheckedRpcConnectFailure } from './daemon-client-checked-rpc.ts'; +import { cacheRemoteDaemonHealth } from './daemon-client-remote-health-cache.ts'; +import { recoverRemoteDaemonHealth } from './daemon-client-remote-health-recovery.ts'; +import { + invalidateRemoteDaemonHealth, + isRemoteTransportFailure, + readRemoteDaemonHealth, + refuseAbortedRequest, + REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS, + requestTimeoutError, + sendRequestWithTransport, + type ResolvedDaemonTransport, + type SendRequestOptions, +} from './daemon-client-transport.ts'; +import { + REMOTE_DAEMON_UNREACHABLE_HINT, + remoteDaemonUnavailableError, +} from './daemon-lifecycle-errors.ts'; + +/** One failed send: what was sent, where, and the command's budget on the `performance.now()` clock. */ +type FailedSend = { + info: DaemonInfo; + req: DaemonWireRequest; + statePaths: DaemonPaths; + timeoutMs: number | undefined; + deadline: number | undefined; + transport: ResolvedDaemonTransport; + options: SendRequestOptions; +}; + +/** + * Answers a failed checked call. Only a connection that never opened is acted on. A refused one fails + * at once, as a refused `/health` probe does. A connect that timed out runs the `/health` recovery + * loop within the command's budget, then sends once with the full send budget. Every other failure + * is the caller's answer. + */ +export async function sendCheckedRpcAfterConnectFailure( + error: unknown, + failed: FailedSend, +): Promise { + const { info, req, statePaths, timeoutMs, deadline, options } = failed; + if (!(error instanceof CheckedRpcConnectFailure)) { + if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); + throw error; + } + if (!error.timedOut) { + throw remoteDaemonUnavailableError({ + daemonBaseUrl: info.baseUrl, + attempts: 1, + hint: REMOTE_DAEMON_UNREACHABLE_HINT, + }); + } + await recoverRemoteDaemonHealth({ + info, + failedProbe: { reachable: false, timedOut: true }, + recovery: timeoutMs === undefined ? undefined : { budgetMs: timeoutMs, signal: options.signal }, + deadline: deadline ?? performance.now(), + hint: REMOTE_DAEMON_UNREACHABLE_HINT, + }); + refuseAbortedRequest(options.signal, req.meta?.requestId); + const { trackCheckedConnect: _once, ...resend } = options; + return await sendRequestWithTransport(info, req, statePaths, timeoutMs, 'http', resend); +} + +/** + * Resends a `/rpc` call once after a stale-instance refusal (ADR 0006), and only to a replacement + * whose protocol is compatible and that is answered within what is left of the command's budget. + */ +export async function retryAfterRemoteInstanceMismatch( + failed: FailedSend, +): Promise { + const { info, req, statePaths, timeoutMs, deadline, transport, options } = failed; + await invalidateRemoteDaemonHealth(info); + const probeTimeoutMs = remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline); + const health = await readRemoteDaemonHealth(info, probeTimeoutMs, options.signal); + refuseAbortedRequest(options.signal, req.meta?.requestId); + const remainingMs = remainingRemoteRequestTimeoutMs( + req, + timeoutMs, + deadline, + health.timedOut ? probeTimeoutMs : undefined, + ); + if (!health.reachable) { + throw remoteDaemonUnavailableError({ daemonBaseUrl: info.baseUrl, attempts: 1 }); + } + info.remoteInstanceId = health.instanceId; + info.remoteUpstreamInstanceId = health.upstream?.instanceId; + info.capabilities = (health.upstream ?? health).capabilities; + cacheRemoteDaemonHealth(info, health); + // 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); + } catch (error) { + if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); + throw error; + } +} + +function remainingRemoteRequestTimeoutMs( + req: DaemonWireRequest, + timeoutMs: number | undefined, + deadline: number | undefined, + timedOutProbeMs?: number, +): number | undefined { + if (deadline === undefined || timeoutMs === undefined) return undefined; + const remainingMs = deadline - performance.now(); + // A probe capped by the request can expire before the monotonic clock catches up to its timer. + if ( + remainingMs > 0 && + (timedOutProbeMs === undefined || timedOutProbeMs > REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS) + ) + return remainingMs; + throw requestTimeoutError(timeoutMs, req.meta?.requestId, false); +} diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 397cea0767..2bdd3d9489 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -6,7 +6,6 @@ import { AppError, createRequestCanceledError } from '@agent-device/kernel/error import { loadNodeHttpRequester, readNodeHttpResponseBody } from '@agent-device/host-kit/transport'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { - assertScriptArtifactsCapability, readDaemonCapabilities, type DaemonPaths, type DaemonTransportPreference, @@ -19,6 +18,9 @@ import { import { buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, + DAEMON_HTTP_CHECKED_RPC_CAPABILITY, + DAEMON_HTTP_CHECKED_RPC_ROUTE, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, DAEMON_HTTP_INSTANCE_HEADER, DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, DAEMON_INSTANCE_REASONS, @@ -42,8 +44,8 @@ import type { LoopbackTransport, } from './daemon-client-loopback-probe.ts'; -type ResolvedDaemonTransport = LoopbackTransport; -type SendRequestOptions = { +export type ResolvedDaemonTransport = LoopbackTransport; +export type SendRequestOptions = { /** The host whose working directory and environment this request's client-side work reads. */ host: HostEnvironment; onProgress?: RequestProgressSink; @@ -60,6 +62,8 @@ type SendRequestOptions = { * how an attach client and the quiesce request itself time out. */ timeoutRecovery?: 'retire-unresponsive' | 'none'; + /** A checked call's connect that fails or stalls rejects as a `CheckedRpcConnectFailure`. */ + trackCheckedConnect?: true; }; /** @@ -99,7 +103,7 @@ function abortedRequestError( * 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 { +export function refuseAbortedRequest(signal: AbortSignal | undefined, requestId?: string): void { if (!signal?.aborted) return; throw abortedRequestError(signal, 'no', requestId); } @@ -150,7 +154,7 @@ export function createRequestGuard(params: { } const LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS = 500; -const REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS = 3000; +export const REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS = 3000; export function isDaemonTransportUnavailableError(error: unknown): boolean { return ( @@ -179,15 +183,17 @@ export type RemoteDaemonHealth = { instanceId?: string; hostArch?: string; capabilities?: DaemonInfo['capabilities']; + /** This link serves the checked RPC route. */ + checkedRpc?: true; /** The daemon behind a proxy, as the proxy's health reported it. */ upstream?: RemoteDaemonHealthLink; /** The probe ran out of its time budget before an answer, rather than failing outright. */ timedOut?: true; }; -type RemoteDaemonHealthLink = Pick< +type RemoteDaemonHealthLink = Omit< RemoteDaemonHealth, - 'service' | 'version' | 'rpcProtocolVersion' | 'instanceId' | 'hostArch' | 'capabilities' + 'reachable' | 'statusCode' | 'upstream' | 'timedOut' >; export async function probeDaemonReachability( @@ -266,7 +272,7 @@ function daemonHealthEndpoint(info: DaemonInfo): string | null { return daemonHttpEndpoint(info, 'health'); } -function daemonHttpEndpoint(info: DaemonInfo, route: 'health' | 'rpc'): string | null { +function daemonHttpEndpoint(info: DaemonInfo, route: string): string | null { return info.baseUrl ? buildDaemonHttpUrl(info.baseUrl, route) : info.httpPort @@ -366,7 +372,7 @@ function readHealthPayload(body: string): Omit): RemoteDaemonHealthLink { +export function readHealthLink(parsed: Record): RemoteDaemonHealthLink { return { service: isHealthService(parsed.service) ? parsed.service : undefined, version: readHealthVersion(parsed.version), @@ -377,6 +383,10 @@ function readHealthLink(parsed: Record): RemoteDaemonHealthLink ...(parsed.capabilities === undefined ? {} : { capabilities: readDaemonCapabilities(parsed.capabilities) }), + ...(Array.isArray(parsed.capabilities) && + parsed.capabilities.includes(DAEMON_HTTP_CHECKED_RPC_CAPABILITY) + ? { checkedRpc: true as const } + : {}), }; } @@ -494,18 +504,21 @@ async function sendRequestWithFallback( // that begins after the abort must not send either — every attempt starts behind this check. refuseAbortedRequest(options.signal, req.meta?.requestId); try { - return await sendRequestWithTransport(info, req, statePaths, timeoutMs, transport, options); + return await sendRequestWithTransport(info, req, statePaths, timeoutMs, transport, { + ...options, + trackCheckedConnect: info.checkedRpc, + }); } catch (error) { + const attempt = { info, req, statePaths, timeoutMs, deadline, transport, options }; + // Loaded only on these failures: the two remote resend rules live in one module. + if (info.checkedRpc) { + const { sendCheckedRpcAfterConnectFailure } = + await import('./daemon-client-remote-resend.ts'); + return await sendCheckedRpcAfterConnectFailure(error, attempt); + } if (info.baseUrl && isRemoteInstanceMismatch(error)) { - return await retryAfterRemoteInstanceMismatch( - info, - req, - statePaths, - timeoutMs, - deadline, - transport, - options, - ); + const { retryAfterRemoteInstanceMismatch } = await import('./daemon-client-remote-resend.ts'); + return await retryAfterRemoteInstanceMismatch(attempt); } if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); const fallback = chooseAutoFallbackTransport(info, preference, transport); @@ -514,60 +527,6 @@ async function sendRequestWithFallback( } } -async function retryAfterRemoteInstanceMismatch( - info: DaemonInfo, - req: DaemonWireRequest, - statePaths: DaemonPaths, - timeoutMs: number | undefined, - deadline: number | undefined, - transport: ResolvedDaemonTransport, - options: SendRequestOptions, -): Promise { - await invalidateRemoteDaemonHealth(info); - const probeTimeoutMs = remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline); - const health = await readRemoteDaemonHealth(info, probeTimeoutMs, options.signal); - refuseAbortedRequest(options.signal, req.meta?.requestId); - const remainingMs = remainingRemoteRequestTimeoutMs( - req, - timeoutMs, - deadline, - health.timedOut ? probeTimeoutMs : undefined, - ); - if (!health.reachable) { - 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); - // 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); - } catch (error) { - if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); - throw error; - } -} - -function remainingRemoteRequestTimeoutMs( - req: DaemonWireRequest, - timeoutMs: number | undefined, - deadline: number | undefined, - timedOutProbeMs?: number, -): number | undefined { - if (deadline === undefined || timeoutMs === undefined) return undefined; - const remainingMs = deadline - performance.now(); - // A probe capped by the request can expire before the monotonic clock catches up to its timer. - if ( - remainingMs > 0 && - (timedOutProbeMs === undefined || timedOutProbeMs > REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS) - ) - return remainingMs; - throw requestTimeoutError(timeoutMs, req.meta?.requestId, false); -} - function isRemoteInstanceMismatch(error: unknown): boolean { return ( error instanceof AppError && @@ -575,7 +534,7 @@ function isRemoteInstanceMismatch(error: unknown): boolean { ); } -function isRemoteTransportFailure(error: unknown): boolean { +export function isRemoteTransportFailure(error: unknown): boolean { return ( error instanceof AppError && (error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason || @@ -584,7 +543,7 @@ function isRemoteTransportFailure(error: unknown): boolean { ); } -async function sendRequestWithTransport( +export async function sendRequestWithTransport( info: DaemonInfo, req: DaemonWireRequest, statePaths: DaemonPaths, @@ -776,7 +735,7 @@ async function sendSocketRequest( }); } -function requestTimeoutError( +export function requestTimeoutError( timeoutMs: number, requestId: string | undefined, daemonRequestSent: boolean, @@ -814,7 +773,8 @@ async function sendHttpRequest( timeoutMs: number | undefined, options: SendRequestOptions, ): Promise { - const rpcEndpoint = daemonHttpEndpoint(info, 'rpc'); + const checked = info.baseUrl !== undefined && info.checkedRpc === true; + const rpcEndpoint = daemonHttpEndpoint(info, checked ? DAEMON_HTTP_CHECKED_RPC_ROUTE : 'rpc'); if (!rpcEndpoint) throw daemonEndpointUnavailableError('http'); const rpcUrl = new URL(rpcEndpoint); const rpcPayload = JSON.stringify(buildHttpRpcPayload(req, { includeTokenParam: !info.baseUrl })); @@ -827,6 +787,8 @@ async function sendHttpRequest( Object.assign(headers, buildDaemonHttpAuthHeaders(info.token)); Object.assign(headers, buildRemoteInstancePreconditionHeaders(info)); } + if (checked) headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER] = String(DAEMON_RPC_PROTOCOL_VERSION); + const checkedRpc = checked ? await import('./daemon-client-checked-rpc.ts') : undefined; const transport = await loadNodeHttpRequester(rpcUrl.protocol); const callerSignal = options.signal; refuseAbortedRequest(callerSignal, req.meta?.requestId); @@ -837,8 +799,10 @@ async function sendHttpRequest( let requestSent = false; // Set when a 2xx progress stream opened on `/rpc`, proving the remote URL and auth token. let responseStarted = false; + let connectWatch: ReturnType['watchCheckedRpcConnect']>; const detachCallerAbort = (): void => { if (callerSignal) callerSignal.removeEventListener('abort', onCallerAbort); + connectWatch?.stop(); }; const resolveOnce = (response: DaemonResponse | PromiseLike): void => { if (settled) return; @@ -872,7 +836,16 @@ async function sendHttpRequest( headers, }, (res) => { - if (isRemoteInstanceMismatchResponse(res.statusCode, res.headers ?? {})) { + if (checkedRpc?.isCheckedRpcOutcomeResponse(res.statusCode, res.headers ?? {})) { + void checkedRpc.readCheckedRpcOutcome(res, info).then((outcome) => { + if (timeoutHandle) clearTimeout(timeoutHandle); + if (outcome.kind === 'answer') handleBody(outcome.body); + else rejectOnce(outcome.error); + }, rejectOnce); + return; + } + // The checked route sends no instance headers, so a mismatch answer there is never resent. + if (!checked && isRemoteInstanceMismatchResponse(res.statusCode, res.headers ?? {})) { res.resume(); if (timeoutHandle) clearTimeout(timeoutHandle); rejectOnce( @@ -956,9 +929,22 @@ async function sendHttpRequest( // from emitting a `daemon_request_socket_error` diagnostic; a genuine transport error still // arrives before the settle and rejects. if (settled) return; + if (connectWatch?.unconnected()) return rejectOnce(connectWatch.failure(false)); rejectOnce(handleTransportError(err, req.meta?.requestId, remote, requestSent)); }); + if (options.trackCheckedConnect && checkedRpc) { + connectWatch = checkedRpc.watchCheckedRpcConnect( + request, + REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS, + () => { + if (timeoutHandle) clearTimeout(timeoutHandle); + rejectOnce(connectWatch?.failure(true)); + request.destroy(); + }, + ); + } + request.on('finish', () => { requestSent = true; }); @@ -971,7 +957,7 @@ async function sendHttpRequest( const loadRemoteHealthCache = () => import('./daemon-client-remote-health-cache.ts'); /** Drops a remote daemon's cached health; a local daemon has none, so its failure loads nothing. */ -async function invalidateRemoteDaemonHealth(info: DaemonInfo): Promise { +export async function invalidateRemoteDaemonHealth(info: DaemonInfo): Promise { if (!info.baseUrl) return; (await loadRemoteHealthCache()).invalidateRemoteDaemonHealth(info); } diff --git a/packages/daemon-client/src/daemon-lifecycle-errors.ts b/packages/daemon-client/src/daemon-lifecycle-errors.ts index 867c87efd5..88d7c4ba40 100644 --- a/packages/daemon-client/src/daemon-lifecycle-errors.ts +++ b/packages/daemon-client/src/daemon-lifecycle-errors.ts @@ -111,6 +111,10 @@ export function daemonStopCommand(stateDir: string): string { * one when it re-probed within the command's budget. `healthRecoveryBudgetMs` is present only when * that budget ran out, which tells a spent budget from a single failed probe. */ +/** What a caller does about a remote daemon that answers nothing. */ +export const REMOTE_DAEMON_UNREACHABLE_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.'; + export function remoteDaemonUnavailableError(params: { daemonBaseUrl: string | undefined; attempts: number; diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 0c94f60bc2..237e3a9c25 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -393,7 +393,8 @@ async function protectArtifactUploadWithLeaseBeats( onProgress: DaemonTransportOptions['onProgress'], ): Promise { const leaseScope = leaseScopeFromRequest(request); - if (!isRemoteDaemon(info) || !leaseScope.leaseId) { + // A checked request uploads nothing (`remoteCheckedRpc`), so it has no phase for a beat to cover. + if (!isRemoteDaemon(info) || !leaseScope.leaseId || settings.remoteCheckedRpc) { return await prepareRemoteRequestArtifacts( request, info, @@ -459,6 +460,19 @@ export async function resolveLocalDaemonCodeIdentity(): Promise { + const { assertRemoteServesCheckedRpc: assert } = await import('./daemon-client-checked-rpc.ts'); + await assert(params); +} + /** The managed local HTTP daemon `agent-device proxy` forwards to, started if none is usable. */ export async function ensureProxyUpstreamDaemon( options: ProxyUpstreamDaemonOptions, diff --git a/packages/remote/src/remote-config-schema.ts b/packages/remote/src/remote-config-schema.ts index 517a0931d2..f2bbcd25e9 100644 --- a/packages/remote/src/remote-config-schema.ts +++ b/packages/remote/src/remote-config-schema.ts @@ -1,4 +1,5 @@ import { + DAEMON_RPC_MODES, PROVIDER_DEVICE_ORIENTATIONS, PROVIDER_DEVICE_TYPES, type RemoteConfigProfile, @@ -37,6 +38,7 @@ export const REMOTE_CONFIG_FIELD_SPECS = [ { key: 'daemonAuthToken', type: 'string' }, { key: 'daemonTransport', type: 'enum', enumValues: ['auto', 'socket', 'http'] }, { key: 'daemonServerMode', type: 'enum', enumValues: ['socket', 'http', 'dual'] }, + { key: 'daemonRpc', type: 'enum', enumValues: DAEMON_RPC_MODES }, { key: 'tenant', type: 'string' }, { key: 'sessionIsolation', type: 'enum', enumValues: ['none', 'tenant'] }, { key: 'runId', type: 'string' }, diff --git a/packages/remote/src/session-script-destination.ts b/packages/remote/src/session-script-destination.ts index 97f5c9b735..aee8386f13 100644 --- a/packages/remote/src/session-script-destination.ts +++ b/packages/remote/src/session-script-destination.ts @@ -7,7 +7,7 @@ import type { ScriptDeliveryReceipt, } from '@agent-device/kernel/contracts'; import { readScriptDeliveryReceipt } from '@agent-device/kernel/contracts'; -import type { DaemonError } from '@agent-device/kernel/errors'; +import { AppError, type DaemonError } from '@agent-device/kernel/errors'; import { readResponseWarnings } from '@agent-device/kernel/success-text'; import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; @@ -21,14 +21,19 @@ import { } from './script-publication-record.ts'; import { publishScriptVersion } from './script-version-publisher.ts'; -type RemoteEndpoint = DaemonArtifactEndpoint & { capabilities?: readonly string[] }; +type RemoteEndpoint = DaemonArtifactEndpoint & { + capabilities?: readonly string[]; + /** The open goes on the checked RPC route, where the daemon checks its own capability. */ + checkedRpc?: true; +}; /** * Sends a remote `open --save-script`. Before the open leaves, the client mints a publication ID * and records the caller destination and the `--force` grant under it. The serialized request * carries the ID and omits the destination. A daemon answer that does not name the ID removes the - * record. A failed open may still have armed the recording, so it keeps the record. A record that - * outlives its open stays inert: only artifacts of its own ID match it. + * record, and so does a failure that proves nothing was dispatched. Any other failed open may still + * have armed the recording, so it keeps the record. A record that outlives its open stays inert: + * only artifacts of its own ID match it. */ export async function sendRemoteScriptOpen( info: RemoteEndpoint, @@ -36,18 +41,23 @@ export async function sendRemoteScriptOpen( stateDir: string, send: (req: DaemonWireRequest) => Promise, ): Promise { - assertScriptArtifactsCapability(info.capabilities); + if (!info.checkedRpc) assertScriptArtifactsCapability(info.capabilities); const { savedScript: destination, ...clientArtifactPaths } = req.meta?.clientArtifactPaths ?? {}; if (!info.baseUrl || !destination) throw new Error('A remote script open needs a destination.'); const publicationId = crypto.randomUUID(); const file = recordPath(stateDir, info.baseUrl, req, publicationId); await createRecord(file, { destination, force: req.flags?.force === true, revision: 0 }); const meta = { ...req.meta, clientArtifactPaths, scriptPublicationId: publicationId }; - const response = await send({ ...req, meta }); - if (!response.ok || response.data?.scriptPublicationId !== publicationId) { - // A record that cannot be removed stays inert, so the open's own outcome is reported. - await withRecordLock(file, async () => removeRecord(file)).catch(() => {}); + // A record that cannot be removed stays inert, so the open's own outcome is reported. + const discard = () => withRecordLock(file, async () => removeRecord(file)).catch(() => {}); + let response: DaemonResponse; + try { + response = await send({ ...req, meta }); + } catch (error) { + if (error instanceof AppError && error.details?.dispatched === 'no') await discard(); + throw error; } + if (!response.ok || response.data?.scriptPublicationId !== publicationId) await discard(); return response; } diff --git a/scripts/integration-progress-model.ts b/scripts/integration-progress-model.ts index 12c9c0e883..f90806f777 100644 --- a/scripts/integration-progress-model.ts +++ b/scripts/integration-progress-model.ts @@ -246,6 +246,7 @@ function summarizeProviderScenarioFlagExclusions() { 'daemonAuthToken', 'daemonTransport', 'daemonServerMode', + 'daemonRpc', 'remote', 'tenant', 'sessionIsolation', diff --git a/src/cli.ts b/src/cli.ts index b467d1b5c7..36f6a36834 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -538,6 +538,7 @@ function buildClientConfig(ctx: CliRunContext): AgentDeviceClientConfig { daemonAuthToken: currentFlags.daemonAuthToken, daemonTransport: currentFlags.daemonTransport, daemonServerMode: currentFlags.daemonServerMode, + daemonRpc: currentFlags.daemonRpc, tenant: currentFlags.tenant, sessionIsolation: currentFlags.sessionIsolation, runId: currentFlags.runId, diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 1dc4c60a47..a8f7c833cc 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -83,6 +83,7 @@ export const connectCommand: ClientCommandHandler = async ({ host, ); const scope = readRequiredConnectScope(connectFlags, connectionMetadata); + await assertCheckedRpcServed(connectFlags, host); const context = resolveConnectContext({ stateDir, flags: connectFlags, @@ -124,6 +125,19 @@ export const connectCommand: ClientCommandHandler = async ({ return true; }; +/** + * `daemonRpc: checked` skips the `/health` probe on later commands, so `connect` accepts it only + * when every link of the remote advertises `checked-rpc`. + */ +async function assertCheckedRpcServed(flags: CliFlags, host: HostEnvironment): Promise { + if (flags.daemonRpc !== 'checked' || !flags.daemonBaseUrl) return; + const { assertRemoteServesCheckedRpc } = await import('@agent-device/daemon-client'); + await assertRemoteServesCheckedRpc({ + baseUrl: flags.daemonBaseUrl, + token: flags.daemonAuthToken ?? host.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN, + }); +} + function assertConnectProviderUsage(provider: ConnectProvider | undefined, flags: CliFlags): void { if (!provider || !flags.remoteConfig) return; throw new AppError( diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 29bfc82186..967e982c48 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -68,11 +68,11 @@ "packages/daemon-client/src/daemon-client-transport.ts#HEALTH_SERVICES": "sha256:3e9d09c1e78adf1d537aa22053e2dee7d35a33d37942721701476a0c06dff52b", "packages/daemon-client/src/daemon-client-transport.ts#HEALTH_VERSION": "sha256:8dd8e36dc936523cf38bba3ed3737a6199431c35b7ce04e1441aaa2c8a186993", "packages/daemon-client/src/daemon-client-transport.ts#HEALTH_VERSION_MAX_LENGTH": "sha256:0357d7c75ccb6fefe7ec901c7937bc795a2e66c4082c90fed27b4baf10c16416", - "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth": "sha256:1ff542dadff6d92233c464b7d09052d809f36186bb60acdb572c48bfc1eb5c1f", - "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink": "sha256:96a79a8ff5a078916ee7bffed1d9624d0ba9c0dcbd8e2c55f9abf37fccfef744", + "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth": "sha256:5bd9f31964e3b83b410f1e918b71c2423a5dc7e0fe6e0c4b4b8bcd4edda77c65", + "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink": "sha256:10dd49f8b54da8f469718c43ed84f5ac95c32c581345534a4b952db3d24a27b6", "packages/daemon-client/src/daemon-client-transport.ts#isHealthService": "sha256:ffd2c774e0efca5e5d2b01f9d37fe9b76aaf5e7569e07d9208fe667473771c10", "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:6ce1f9be1e6a977130d0875003ac22da2de5e90b514a3b22b30b9347e63d81c7", - "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink": "sha256:c4f638b4df43f572e105b6f8df578fe90ebf64cb56002e4d029a109bdbc167d1", + "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink": "sha256:feda23773be1f57ca93711e17c7ad45d344a3f65a2f4f1be15a8f0d3e1315abd", "packages/daemon-client/src/daemon-client-transport.ts#readHealthPayload": "sha256:4e85ffc3e35e02379c393e9312344757e003cf1f0ad9eb8d1f77d90c81c861f1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthVersion": "sha256:856bd74aa8b2f205b6b30855755f16391015bffc1b6a323f618b51c26e749bfd", "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:bf9ca0ecb9dc00f18d0bf4acab30d544d680246b8cdacbc50f684db182b6f23b", @@ -248,15 +248,22 @@ "packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18", "packages/remote/src/script-version-publisher.ts#publishScriptVersion": "sha256:b37b9391d20f535ca9c0858f92ed37943297c7acbf1fb10f8cad5cd5b53423eb", "packages/remote/src/script-version-publisher.ts#PublishOutcome": "sha256:a4ae6fc3298d3c560719591372edddbfa83ce749f4cf3f3e2ed1d8369313bd2d", - "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:73eca35dba88bfe0e933ea877a0ca953fbbe5c5ddca5896ed5fbac7f459ecd6c", - "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:9c48e8e0ee14a25b85ebd930243fd263134836b35ecda55fb927919911263c15", + "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:c5b86a1d785db435cda62b56412006ba80f86f4f886c15cc84f8d03a3230ac1f", + "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:2fbcaa03bc0675fef8d19fd0a163d5d01a2162031745a41ff5c1db8a982cc2b6", "packages/daemon/src/server/upload-http.ts#authorizeUpload": "sha256:69ee5039c7eadbe0f96cdf57bcd947b16cdc815671ba4c966ace93ad353cc740", "packages/remote/src/daemon-artifacts.ts#FetchRemoteArtifactParams": "sha256:f90ae571961d6147a09973791178d369dfb8550990a1e0ebf120e97336540824", "packages/remote/src/daemon-artifacts.ts#fetchRemoteArtifact": "sha256:871f675d744dfa2bbf50237ac14b7f8957f973b126b774f4011da65573c8548f", "packages/remote/src/artifact-download.ts#RemoteArtifactRequest": "sha256:6cce66499f34bb18139917df592e554395936964025089024d6c6f67e4fa4b98", "packages/remote/src/artifact-download.ts#RemoteArtifactFetch": "sha256:e83939ec48a66917df9ec84becf53b6ca3c8115cfdada10731046381ac9e32c1", "packages/remote/src/artifact-download.ts#fetchRemoteArtifactFromUrl": "sha256:de6e71abdc758f760beffba0dc260473f88a8c60b13540b9c14d39f1a3d5e3a1", - "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:cafb5fd5838819719b2fac62c5e108276dd800a58b4614462d138cf1ed2f7d6e" + "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:cafb5fd5838819719b2fac62c5e108276dd800a58b4614462d138cf1ed2f7d6e", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#isCheckedRpcOutcomeResponse": "sha256:75fb9f3444a3f8f4a762811ba7cbe02d92a39ed4e55483ea0cf7f029e5720a3e", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#CheckedRpcOutcome": "sha256:965cd834c6dfb581db6cee46323bfd1c0b639749b4873454bb82ace8d9456f07", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#readCheckedRpcOutcome": "sha256:db0f4a1285d19036f7fbd4385b7b898b521b8b76e62c2d5e7f4e369ce0c81ad6", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#checkedRpcRefusalError": "sha256:1cadc96a26d64d8cd072cb4542680d1f4f797bc748fa4994b060e0d97cddecbd", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#protocolMismatchError": "sha256:f86912368af04fc263ad858f15e8bc67efa68be472e3d5e575e7b47addc357d4", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#readRefusalDetails": "sha256:41309e8fe57616e93848c93b36e8fb665a737f87d013243c6f6f1949e9f87215", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#isJsonRpcAnswer": "sha256:ecbf4226264fe3d3b551f89a075729df477e5c3b183dc2a761123c7229f4fe99" }, "compatibleChanges": [ { @@ -386,18 +393,18 @@ }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth", - "digest": "sha256:1ff542dadff6d92233c464b7d09052d809f36186bb60acdb572c48bfc1eb5c1f", - "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. A restart retry must tell a probe that ran out of time from one that failed, so the client can report the RPC deadline instead of 'Remote daemon is unavailable'. `timedOut` is client-local: the prober sets it on its own timeout and abort paths and never reads it from a /health payload. The health request and the accepted payload fields are unchanged, so a released daemon or proxy is probed and parsed exactly as before. #4511 adds optional parsed capabilities. A released daemon or proxy that sends none parses as before and only loses remote --save-script, which the client refuses before any RPC." + "digest": "sha256:5bd9f31964e3b83b410f1e918b71c2423a5dc7e0fe6e0c4b4b8bcd4edda77c65", + "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. A restart retry must tell a probe that ran out of time from one that failed, so the client can report the RPC deadline instead of 'Remote daemon is unavailable'. `timedOut` is client-local: the prober sets it on its own timeout and abort paths and never reads it from a /health payload. The health request and the accepted payload fields are unchanged, so a released daemon or proxy is probed and parsed exactly as before. #4511 adds optional parsed capabilities. A released daemon or proxy that sends none parses as before and only loses remote --save-script, which the client refuses before any RPC. The checked RPC route (ADR 0006) adds an optional checkedRpc flag, read from the checked-rpc entry of the released capabilities list; a peer that does not list it reads as not serving the route." }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink", - "digest": "sha256:96a79a8ff5a078916ee7bffed1d9624d0ba9c0dcbd8e2c55f9abf37fccfef744", - "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. #4511 adds optional capabilities to the parsed link; a link without them parses exactly as before." + "digest": "sha256:10dd49f8b54da8f469718c43ed84f5ac95c32c581345534a4b952db3d24a27b6", + "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. #4511 adds optional capabilities to the parsed link; a link without them parses exactly as before. The checked RPC route (ADR 0006) adds an optional checkedRpc flag, read from the checked-rpc entry of the released capabilities list; a peer that does not list it reads as not serving the route." }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink", - "digest": "sha256:c4f638b4df43f572e105b6f8df578fe90ebf64cb56002e4d029a109bdbc167d1", - "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. #4511 reads an optional capabilities array and omits the field when a peer does not send one, so a released payload parses to the same object. The service and version now reach error messages, so readHealthLink keeps a service only when it is one the DaemonHealthPayload contract names and a version only when it is version-shaped and at most 64 characters; anything else reads as absent. Released daemons and proxies report exactly those, so their payloads parse unchanged, and the /health request is unchanged." + "digest": "sha256:feda23773be1f57ca93711e17c7ad45d344a3f65a2f4f1be15a8f0d3e1315abd", + "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. #4511 reads an optional capabilities array and omits the field when a peer does not send one, so a released payload parses to the same object. The service and version now reach error messages, so readHealthLink keeps a service only when it is one the DaemonHealthPayload contract names and a version only when it is version-shaped and at most 64 characters; anything else reads as absent. Released daemons and proxies report exactly those, so their payloads parse unchanged, and the /health request is unchanged. The checked RPC route (ADR 0006) adds an optional checkedRpc flag, read from the checked-rpc entry of the released capabilities list; a peer that does not list it reads as not serving the route. Every released field is read as before." }, { "declaration": "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_HEADER", @@ -666,8 +673,8 @@ }, { "declaration": "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen", - "digest": "sha256:73eca35dba88bfe0e933ea877a0ca953fbbe5c5ddca5896ed5fbac7f459ecd6c", - "rationale": "Removes the unanswered open's record through the record owner instead of a direct unlink. The request still carries meta.scriptPublicationId and omits the caller path, and the response is read for the same scriptPublicationId field." + "digest": "sha256:c5b86a1d785db435cda62b56412006ba80f86f4f886c15cc84f8d03a3230ac1f", + "rationale": "Removes the unanswered open's record through the record owner instead of a direct unlink. The request still carries meta.scriptPublicationId and omits the caller path, and the response is read for the same scriptPublicationId field. A checked open skips the client-side capability check, because the daemon checks the same requirement from scriptPublicationId, and a failure that proves nothing was dispatched removes the record. The request and response fields are unchanged." }, { "declaration": "packages/remote/src/script-version-publisher.ts#PublishOutcome", @@ -688,6 +695,11 @@ "declaration": "packages/daemon-contracts/src/daemon-resolution.ts#DAEMON_CAPABILITIES", "digest": "sha256:4ff6eba594b923a1d8f46a5856c42132b7ecd3a63d40f26c42972e06cb5a0a04", "rationale": "Adds the checked-rpc capability (ADR 0006). readDaemonCapabilities filters to known names, so a released client drops it, and a released daemon never lists it; a client treats an absent capability as cannot-do. The existing quiesce and script-artifacts entries are unchanged." + }, + { + "declaration": "packages/remote/src/session-script-destination.ts#RemoteEndpoint", + "digest": "sha256:2fbcaa03bc0675fef8d19fd0a163d5d01a2162031745a41ff5c1db8a982cc2b6", + "rationale": "Adds the client-local checkedRpc flag, set when the open goes on the checked RPC route. Nothing on the wire reads it; the open request and its response fields are unchanged." } ] } diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 46299c3625..f6bc74fe74 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -60,6 +60,7 @@ const PROGRESS_PROTOCOL = 'packages/daemon-contracts/src/request-progress-protoc const CLIENT_RPC = 'packages/daemon-client/src/daemon-client-rpc.ts'; const CLIENT_PROGRESS = 'packages/daemon-client/src/daemon-client-progress.ts'; const CLIENT_TRANSPORT = 'packages/daemon-client/src/daemon-client-transport.ts'; +const CLIENT_CHECKED_RPC = 'packages/daemon-client/src/daemon-client-checked-rpc.ts'; const DAEMON_PROXY = 'packages/proxy/src/daemon-proxy.ts'; const PROXY_CHECKED_RPC = 'packages/proxy/src/checked-rpc-admission.ts'; const UPLOAD_CLIENT = 'packages/remote/src/upload-client.ts'; @@ -130,6 +131,18 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'readUpstreamRefusalDetails', 'UPSTREAM_REFUSAL_MAX_BYTES', ), + // Consumer side of the checked route: which answers the client reads as a refusal, and the + // refusal metadata it validates before it names who must upgrade. + ...from( + CLIENT_CHECKED_RPC, + 'isCheckedRpcOutcomeResponse', + 'CheckedRpcOutcome', + 'readCheckedRpcOutcome', + 'checkedRpcRefusalError', + 'protocolMismatchError', + 'readRefusalDetails', + 'isJsonRpcAnswer', + ), ...from( DAEMON_PROXY, 'refuseStaleProxyInstance', diff --git a/website/docs/docs/configuration.md b/website/docs/docs/configuration.md index f90673ebbd..33dd511207 100644 --- a/website/docs/docs/configuration.md +++ b/website/docs/docs/configuration.md @@ -83,6 +83,7 @@ explicit config: - `daemonAuthToken` - `daemonTransport` - `daemonServerMode` +- `daemonRpc` (see [Send each command in one round trip](/docs/remote-proxy#send-each-command-in-one-round-trip)) - `tenant` - `sessionIsolation` - `runId` diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 89f43c3074..fe5408c029 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -363,6 +363,23 @@ for the API. 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. +### Send each command in one round trip + +By default every command makes two requests: `GET /health`, then `POST /rpc`. Add `"daemonRpc": "checked"` to the connection profile to send most commands as one `POST /rpc/checked` instead. The proxy and the daemon behind it then check the RPC protocol themselves, after the token, and refuse a mismatch with the same upgrade message before anything runs. + +```json +{ + "daemonBaseUrl": "https://example.trycloudflare.com/agent-device", + "daemonRpc": "checked" +} +``` + +`connect` accepts the field only when the proxy and its daemon both list `checked-rpc` in `capabilities` on `/health`. `--daemon-rpc checked` and `AGENT_DEVICE_DAEMON_RPC=checked` set it for one command or shell; `--daemon-rpc health` turns it off. + +- `install` and `reinstall` still read `/health` first, because they can upload an app before the command runs. +- If the remote stops serving the route, for example after a rollback, commands fail with `reason: "remote_checked_rpc_unsupported"` and `dispatched: "unknown"`. The client never resends them. Update the proxy and daemon, or remove `daemonRpc`. +- Set it only when everything between you and the proxy forwards `/rpc/checked` and its `x-agent-device-rpc-protocol` header unchanged. + `/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 daemons omit it. From d4ef6447fb10abda8f516042f159ff0f4cd9b2dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 08:36:40 +0100 Subject: [PATCH 02/10] style(daemon-client): format checked RPC module Co-Authored-By: Claude Opus 5.5 --- packages/daemon-client/src/daemon-client-checked-rpc.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/daemon-client/src/daemon-client-checked-rpc.ts b/packages/daemon-client/src/daemon-client-checked-rpc.ts index ee041301d0..141eea052a 100644 --- a/packages/daemon-client/src/daemon-client-checked-rpc.ts +++ b/packages/daemon-client/src/daemon-client-checked-rpc.ts @@ -84,9 +84,7 @@ export function isCheckedRpcOutcomeResponse( * What a checked call's 404 or refusal 409 means. `answer` is a JSON-RPC body the daemon wrote, which the * caller reads like any other answer. `refused` is final: nothing is resent. */ -type CheckedRpcOutcome = - | { kind: 'answer'; body: string } - | { kind: 'refused'; error: AppError }; +type CheckedRpcOutcome = { kind: 'answer'; body: string } | { kind: 'refused'; error: AppError }; /** * Reads a checked call's 404, or its 409 that carries a refusal header. That 409 is a refusal made From b04fb41bcff0143323a4982f35b900a561be04b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 09:03:45 +0100 Subject: [PATCH 03/10] fix(daemon-client): validate the checked RPC opt-in once and keep lease flows fenced - Only connect enables checked RPC: daemonRpc is a remote-config profile field with no flag or environment variable, recorded in the connection after every link proves checked-rpc; a proxy must prove its upstream. The connect probe goes through the client's URL and trust validation. - A command that allocates or renews its lease first, and the lease calls themselves, go health-first with the instance fences. - Checked connect recovery decides on fresh /health probes, and an abort during it rejects with the typed cancellation. - A protocol refusal keeps its typed reason and the refusing side; an unknown refusal value is an unreadable reply, never resent. - Script-record cleanup on proven non-dispatch applies to checked opens only. The resend rules take transport powers as a port, so the lazily loaded modules import nothing back. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0006-daemon-rpc-protocol-version.md | 8 ++ .../src/flag-definitions-connection.ts | 12 -- packages/command-registry/src/flag-groups.ts | 1 - packages/contracts/src/cli-flags.ts | 1 + packages/contracts/src/client-connection.ts | 1 - .../contracts/src/remote-config-fields.ts | 4 +- ...lient-checked-rpc-connect-recovery.test.ts | 91 +++++++++--- .../daemon-client-checked-rpc.test.ts | 120 +++++++++++----- .../src/daemon-client-checked-rpc.ts | 105 ++++++++------ .../src/daemon-client-lifecycle.ts | 3 +- .../daemon-client-remote-health-recovery.ts | 6 +- .../src/daemon-client-remote-resend.ts | 129 +++++++++--------- .../src/daemon-client-transport.ts | 74 ++++++---- .../src/daemon-lifecycle-errors.ts | 8 +- packages/daemon-client/src/index.ts | 43 ++++-- packages/remote/src/remote-config-schema.ts | 13 +- .../remote/src/remote-connection-state.ts | 7 +- .../remote/src/session-script-destination.ts | 8 +- scripts/integration-progress-model.ts | 1 - src/cli.ts | 15 +- .../commands/connection-lease-transaction.ts | 6 +- .../connection-runtime-checked-rpc.test.ts | 78 +++++++++++ src/cli/commands/connection-runtime.ts | 7 +- src/cli/commands/connection.ts | 21 ++- test/wire-compat/ledger.json | 33 ++--- test/wire-compat/surface.ts | 1 + website/docs/docs/configuration.md | 1 - website/docs/docs/error-reasons.md | 1 + website/docs/docs/remote-proxy.md | 10 +- 29 files changed, 545 insertions(+), 263 deletions(-) create mode 100644 src/cli/commands/connection-runtime-checked-rpc.test.ts diff --git a/docs/adr/0006-daemon-rpc-protocol-version.md b/docs/adr/0006-daemon-rpc-protocol-version.md index fe98175677..cc1944a04c 100644 --- a/docs/adr/0006-daemon-rpc-protocol-version.md +++ b/docs/adr/0006-daemon-rpc-protocol-version.md @@ -8,6 +8,7 @@ Accepted - Before remote JSON-RPC requests, compare the daemon's `rpcProtocolVersion` from `/health`, or send them on the checked route, where the server makes that comparison. - The checked route reaches its authentication verdict exactly as `/rpc` does, then refuses protocol skew before dispatch, with HTTP 409 and a typed `x-agent-device-refusal` header. +- A client uses the checked route only when `connect` recorded it for the connection. It never resends a checked call on a response, and never falls back to `/rpc` after one. - 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. @@ -92,6 +93,12 @@ A daemon that serves `checked-rpc` also serves `script-artifacts`, so the route The route, not a header, is what makes the check safe. Released daemons and proxies answer an unknown route with 404 before dispatch, and they ignore unknown headers on `/rpc`. +A 404 is still not proof of non-dispatch, because a gateway can answer for a command that ran. +So a client does not discover the route. +`connect` records `daemonRpc: "checked"` from the remote-config profile only when `/health` advertises `checked-rpc` on the endpoint and, for a proxy, on its `upstream`. +With it recorded, a 404 that is not a JSON-RPC answer fails with `remote_checked_rpc_unsupported` and `dispatched: 'unknown'`, and the client does not resend. +A flow with remote side effects before its command keeps the `/health` probe and the instance headers for every call: an upload, and a lease allocate or heartbeat. +Only a connect that never opened is evidence that nothing left: a refused one fails at once, and a timed-out one runs fresh `/health` probes within the command's budget, then sends once. ## Alternatives Considered @@ -102,6 +109,7 @@ Released daemons and proxies answer an unknown route with 404 before dispatch, a - **Negotiate full schemas.** This is more precise, but it is too much machinery for the current JSON-RPC boundary. - **Persist the `/health` answer in the client state directory (#5134).** It saves the probe across CLI processes, but it adds a local trust boundary and cache rules, and a rollback to a daemon that ignores instance headers would dispatch on a stale view. - **Send the protocol as a header on `/rpc`.** Released daemons ignore unknown headers and dispatch anyway. +- **Fall back to `/health` and `/rpc` after a 404 on the checked route.** A 404 can come after dispatch, so the fallback could run a command twice. ## Consequences diff --git a/packages/command-registry/src/flag-definitions-connection.ts b/packages/command-registry/src/flag-definitions-connection.ts index 247ffbf745..0012f2acab 100644 --- a/packages/command-registry/src/flag-definitions-connection.ts +++ b/packages/command-registry/src/flag-definitions-connection.ts @@ -1,6 +1,5 @@ import { LEASE_BACKENDS } from '@agent-device/kernel/contracts'; import { - DAEMON_RPC_MODES, PROVIDER_DEVICE_ORIENTATIONS, PROVIDER_DEVICE_TYPES, } from '@agent-device/contracts/remote'; @@ -75,17 +74,6 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ projectConfig: false, recorded: false, }, - { - key: 'daemonRpc', - names: ['--daemon-rpc'], - type: 'enum', - enumValues: DAEMON_RPC_MODES, - usageLabel: '--daemon-rpc health|checked', - usageDescription: - 'Remote command RPC: health probes /health first; checked sends one request the remote checks itself', - projectConfig: false, - recorded: false, - }, { key: 'proxyHost', names: ['--host'], diff --git a/packages/command-registry/src/flag-groups.ts b/packages/command-registry/src/flag-groups.ts index ef960345f5..b07bb93950 100644 --- a/packages/command-registry/src/flag-groups.ts +++ b/packages/command-registry/src/flag-groups.ts @@ -76,7 +76,6 @@ export const COMMON_COMMAND_SUPPORTED_FLAG_KEYS = flagKeys( 'daemonAuthToken', 'daemonTransport', 'daemonServerMode', - 'daemonRpc', 'tenant', 'sessionIsolation', 'runId', diff --git a/packages/contracts/src/cli-flags.ts b/packages/contracts/src/cli-flags.ts index 595b8520d5..62d352cb8a 100644 --- a/packages/contracts/src/cli-flags.ts +++ b/packages/contracts/src/cli-flags.ts @@ -41,6 +41,7 @@ export type CliFlags = CloudProviderProfileFields & daemonAuthToken?: string; daemonTransport?: DaemonTransportPreference; daemonServerMode?: DaemonServerMode; + /** No CLI token: the connection `connect` recorded sets it. */ daemonRpc?: DaemonRpcMode; proxyHost?: string; proxyPort?: number; diff --git a/packages/contracts/src/client-connection.ts b/packages/contracts/src/client-connection.ts index fe4fd84df7..96bb4a55c9 100644 --- a/packages/contracts/src/client-connection.ts +++ b/packages/contracts/src/client-connection.ts @@ -144,7 +144,6 @@ export type AgentDeviceRequestOverrides = Pick< | 'daemonAuthToken' | 'daemonTransport' | 'daemonServerMode' - | 'daemonRpc' | 'tenant' | 'sessionIsolation' | 'runId' diff --git a/packages/contracts/src/remote-config-fields.ts b/packages/contracts/src/remote-config-fields.ts index 63b1efe095..de36674512 100644 --- a/packages/contracts/src/remote-config-fields.ts +++ b/packages/contracts/src/remote-config-fields.ts @@ -28,8 +28,8 @@ export type ProviderDeviceType = (typeof PROVIDER_DEVICE_TYPES)[number]; /** * How a client sends a remote command. `health` reads `/health` before each command RPC. `checked` * sends a standalone command on the checked RPC route, where the server refuses protocol skew - * itself, so the command takes one round trip. Only a remote endpoint that advertises `checked-rpc` - * accepts it. + * itself, so the command takes one round trip. Only the remote-config profile sets it, and + * `connect` records it only when every link of the remote advertises `checked-rpc`. */ export const DAEMON_RPC_MODES = ['health', 'checked'] as const; export type DaemonRpcMode = (typeof DAEMON_RPC_MODES)[number]; diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts index 0a2eb2b3b2..209542eeee 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts @@ -6,6 +6,7 @@ import assert from 'node:assert/strict'; import http from 'node:http'; import { EventEmitter } from 'node:events'; import { afterEach, test, vi } from 'vitest'; +import { isRequestCanceledError } from '@agent-device/kernel/errors'; import { sendToDaemon } from '../index.ts'; type Call = { method: string; path: string; at: number }; @@ -19,8 +20,11 @@ function fakeResponse(): EventEmitter { }); } -/** The first checked POST hangs before its socket connects; everything after it answers. */ -function firstConnectHangs(): Call[] { +/** + * The first checked POST hangs before its socket connects. `/health` answers with `healthStatus` + * (and an instance ID, so a usable answer is cached); every other request answers. + */ +function firstCheckedConnectHangs(healthStatus = 200): Call[] { const calls: Call[] = []; vi.spyOn(http, 'request').mockImplementation((( options: { method?: string; path?: string }, @@ -31,9 +35,9 @@ function firstConnectHangs(): Call[] { path: options.path ?? '', at: performance.now(), }; + const checked = call.path.endsWith('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/rpc/checked'); + const hangs = checked && !calls.some((seen) => seen.path.endsWith('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/rpc/checked')); calls.push(call); - const hangs = - calls.filter((seen) => seen.method === 'POST').length === 1 && call.method === 'POST'; const req = Object.assign(new EventEmitter(), { write: () => {}, destroy: () => {}, @@ -46,13 +50,20 @@ function firstConnectHangs(): Call[] { } const body = call.method === 'GET' - ? JSON.stringify({ ok: true, service: 'agent-device-daemon', rpcProtocolVersion: 3 }) + ? JSON.stringify({ + ok: true, + service: 'agent-device-daemon', + rpcProtocolVersion: 3, + instanceId: 'daemon-1', + }) : JSON.stringify({ jsonrpc: '2.0', id: 'x', result: { ok: true, data: { sent: true } }, }); - const res = fakeResponse(); + const res = Object.assign(fakeResponse(), { + statusCode: call.method === 'GET' ? healthStatus : 200, + }); process.nextTick(() => { callback(res); res.emit('data', body); @@ -83,27 +94,27 @@ function driveFakeTime(): () => Promise { }; } +const BASE_URL = 'http://remote-mac.example.test:7777/agent-device'; + +function sessionList(daemonRpc?: 'checked') { + return { + session: 'default', + command: 'session', + positionals: ['list'], + flags: { daemonBaseUrl: BASE_URL, ...(daemonRpc ? { daemonRpc } : {}) }, + }; +} + afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); }); test('a checked connect timeout runs the /health loop, then sends exactly once more', async () => { - const calls = firstConnectHangs(); + const calls = firstCheckedConnectHangs(); const stopDriving = driveFakeTime(); try { - const response = await sendToDaemon( - { - session: 'default', - command: 'session', - positionals: ['list'], - flags: { - daemonBaseUrl: 'http://remote-mac.example.test:7777/agent-device', - daemonRpc: 'checked', - }, - }, - { authToken: 'remote-secret' }, - ); + const response = await sendToDaemon(sessionList('checked'), { authToken: 'remote-secret' }); assert.equal(response.ok, true); assert.deepEqual( @@ -120,3 +131,45 @@ test('a checked connect timeout runs the /health loop, then sends exactly once m await stopDriving(); } }); + +test('a cached /health answer never stands in for the recovery probe after a checked connect timeout', async () => { + const calls = firstCheckedConnectHangs(); + const stopDriving = driveFakeTime(); + try { + // A health-first command in this process caches a usable `/health` answer. + await sendToDaemon(sessionList(), { authToken: 'remote-secret' }); + calls.length = 0; + const response = await sendToDaemon(sessionList('checked'), { authToken: 'remote-secret' }); + + assert.equal(response.ok, true); + assert.deepEqual( + calls.map(({ method, path }) => `${method} ${path}`), + [ + 'POST /agent-device/rpc/checked', + 'GET /agent-device/health', + 'POST /agent-device/rpc/checked', + ], + ); + } finally { + await stopDriving(); + } +}); + +test('an abort during checked connect recovery rejects with the typed cancellation', async () => { + firstCheckedConnectHangs(503); + const stopDriving = driveFakeTime(); + const controller = new AbortController(); + setTimeout(() => controller.abort(), 6_000); + try { + const outcome = await sendToDaemon(sessionList('checked'), { + authToken: 'remote-secret', + signal: controller.signal, + }).then( + () => undefined, + (error: unknown) => error, + ); + assert.ok(isRequestCanceledError(outcome), `unexpected outcome: ${String(outcome)}`); + } finally { + await stopDriving(); + } +}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts index e7d51941c6..15b912a96e 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts @@ -1,8 +1,13 @@ import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; -import { expect, test } from 'vitest'; -import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { expect, test, vi } from 'vitest'; +import { + closeLoopbackServer, + createTestHostEnvironment, + listenOnLoopback, + mkdtempForTestSync, +} from '@agent-device/test-kit'; import { DAEMON_HTTP_REFUSAL_HEADER, DAEMON_HTTP_RPC_PROTOCOL_HEADER, @@ -141,7 +146,7 @@ test('a JSON-RPC 404 under checked RPC is the daemon answer, not a route miss', } }); -test('an upstream protocol refusal keeps the upgrade message and names the daemon behind the proxy', async () => { +test('an upstream protocol refusal keeps the upgrade message, the typed reason and the refusing side', async () => { const daemon = await remoteDaemon({ status: 409, headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'upstream-protocol-mismatch' }, @@ -165,7 +170,14 @@ test('an upstream protocol refusal keeps the upgrade message and names the daemo message: expect.stringContaining( 'the agent-device-daemon behind agent-device-proxy runs 9.0.0 (RPC protocol 99)', ), - details: { upgradeSide: 'client-and-proxy', remoteRpcProtocolVersion: 99, dispatched: 'no' }, + details: { + reason: 'remote_rpc_protocol_mismatch', + service: 'agent-device-daemon', + version: '9.0.0', + rpcProtocolVersion: 99, + upgradeSide: 'client-and-proxy', + dispatched: 'no', + }, }); expect(routes(daemon.seen)).toEqual(['POST /rpc/checked']); } finally { @@ -173,37 +185,47 @@ test('an upstream protocol refusal keeps the upgrade message and names the daemo } }); -test('a script-artifacts refusal is not dispatched and removes the publication record', async () => { +test('a refusal value this build does not know is an unreadable reply, never a protocol mismatch', async () => { const daemon = await remoteDaemon({ status: 409, - headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'script-artifacts' }, + headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'future-precondition' }, body: JSON.stringify({ jsonrpc: '2.0', id: 'test', error: { code: -32001, message: 'no' } }), }); - const root = mkdtempForTestSync('checked-script-'); - const stateDir = path.join(root, 'state'); try { - await expect( - sendToDaemon({ - command: 'open', - session: 'owned', - positionals: ['Demo'], - flags: { - daemonBaseUrl: daemon.baseUrl, - daemonRpc: 'checked', - saveScript: path.join(root, 'journey.ad'), - stateDir, - }, - }), - ).rejects.toMatchObject({ - details: { reason: 'remote_script_artifacts_unsupported', dispatched: 'no' }, - }); - const records = path.join(stateDir, 'remote-connections', 'session-scripts'); - expect(fs.existsSync(records) ? fs.readdirSync(records) : []).toEqual([]); + const error = await sendToDaemon(sessionList(daemon.baseUrl, { daemonRpc: 'checked' })).catch( + (error: unknown) => error, + ); + expect(error).toMatchObject({ details: { reason: 'daemon_response_invalid' } }); + expect(error).not.toMatchObject({ details: { dispatched: 'no' } }); + expect(routes(daemon.seen)).toEqual(['POST /rpc/checked']); } finally { await daemon.close(); } }); +test('a checked open proven undispatched removes its publication record', async () => { + const daemon = await remoteDaemon(); + const { baseUrl } = daemon; + await daemon.close(); + const root = mkdtempForTestSync('checked-script-'); + const stateDir = path.join(root, 'state'); + await expect( + sendToDaemon({ + command: 'open', + session: 'owned', + positionals: ['Demo'], + flags: { + daemonBaseUrl: baseUrl, + daemonRpc: 'checked', + saveScript: path.join(root, 'journey.ad'), + stateDir, + }, + }), + ).rejects.toMatchObject({ details: { reason: 'remote_daemon_unavailable', dispatched: 'no' } }); + const records = path.join(stateDir, 'remote-connections', 'session-scripts'); + expect(fs.existsSync(records) ? fs.readdirSync(records) : []).toEqual([]); +}); + test('a refused connection under checked RPC fails at once as an unavailable remote', async () => { const daemon = await remoteDaemon(); const { baseUrl } = daemon; @@ -218,26 +240,39 @@ test.each([ { name: 'a daemon with it', health: { capabilities: ['checked-rpc'] }, served: true }, { name: 'a proxy whose daemon lacks it', - health: { capabilities: ['checked-rpc'], upstream: { capabilities: [] } }, + health: { + service: 'agent-device-proxy', + capabilities: ['checked-rpc'], + upstream: { capabilities: [] }, + }, + served: false, + }, + { + name: 'a proxy that reports no daemon behind it', + health: { service: 'agent-device-proxy', capabilities: ['checked-rpc'], upstream: null }, served: false, }, { name: 'a proxy whose daemon has it', - health: { capabilities: ['checked-rpc'], upstream: { capabilities: ['checked-rpc'] } }, + health: { + service: 'agent-device-proxy', + capabilities: ['checked-rpc'], + upstream: { capabilities: ['checked-rpc'] }, + }, served: true, }, ])( - 'connect accepts daemonRpc checked only when $name advertises checked-rpc', + 'assertRemoteServesCheckedRpc accepts only when $name proves checked-rpc on every link', async ({ health, served }) => { const server = http.createServer((_req, res) => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ ok: true, ...health })); }); try { - const verdict = assertRemoteServesCheckedRpc({ - baseUrl: `http://127.0.0.1:${await listenOnLoopback(server)}`, - token: undefined, - }); + const verdict = assertRemoteServesCheckedRpc( + { daemonBaseUrl: `http://127.0.0.1:${await listenOnLoopback(server)}` }, + createTestHostEnvironment(), + ); if (served) await expect(verdict).resolves.toBeUndefined(); else await expect(verdict).rejects.toMatchObject({ @@ -248,3 +283,24 @@ test.each([ } }, ); + +test('the connect probe is refused by remote trust validation before any request leaves', async () => { + const requests = vi.spyOn(http, 'request'); + try { + await expect( + assertRemoteServesCheckedRpc( + { daemonBaseUrl: 'http://remote-mac.example.test:7777/agent-device' }, + createTestHostEnvironment(), + ), + ).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + await expect( + assertRemoteServesCheckedRpc( + { daemonBaseUrl: 'ftp://remote-mac.example.test/agent-device', daemonAuthToken: 'secret' }, + createTestHostEnvironment(), + ), + ).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + expect(requests).not.toHaveBeenCalled(); + } finally { + requests.mockRestore(); + } +}); diff --git a/packages/daemon-client/src/daemon-client-checked-rpc.ts b/packages/daemon-client/src/daemon-client-checked-rpc.ts index 141eea052a..8e85f48b37 100644 --- a/packages/daemon-client/src/daemon-client-checked-rpc.ts +++ b/packages/daemon-client/src/daemon-client-checked-rpc.ts @@ -3,17 +3,18 @@ // on those paths, so a command that gets its answer never pays for it. import type { IncomingMessage } from 'node:http'; import type { Socket } from 'node:net'; -import { AppError, discloseUnclassifiedDispatch } from '@agent-device/kernel/errors'; +import { AppError } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { DAEMON_CHECKED_RPC_REASONS, + DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_REFUSAL_HEADER, DAEMON_HTTP_REFUSALS, } from '@agent-device/contracts/daemon-http'; -import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; +import { DAEMON_TRANSPORT_REASONS } from './daemon-client-transport-reasons.ts'; import type { DaemonInfo } from './daemon-client-metadata.ts'; import { incompatibleRemoteProtocolError } from './daemon-client-rpc.ts'; -import { readHealthLink, readRemoteDaemonHealth } from './daemon-client-transport.ts'; +import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; import { remoteDaemonUnavailableError } from './daemon-lifecycle-errors.ts'; /** The most of a refusal body the client reads: its metadata is a few short fields. */ @@ -22,7 +23,12 @@ const REFUSAL_BODY_MAX_BYTES = 64 * 1024; const NOT_FOUND_BODY_MAX_BYTES = 1024 * 1024; const UNSUPPORTED_HINT = - 'The remote daemon or proxy does not serve checked RPC. Update it, or remove daemonRpc from the connection profile (or pass --daemon-rpc health).'; + 'The remote daemon or proxy does not serve checked RPC. Update it, or remove daemonRpc from the remote-config profile and run agent-device connect --force.'; + +/** The transport's validated `/health` link reader, which refusal metadata goes through too. */ +type ReadHealthLink = ( + parsed: Record, +) => Pick; /** * A checked call's connection never opened: refused, or not open within the `/health` probe's time. @@ -94,6 +100,7 @@ type CheckedRpcOutcome = { kind: 'answer'; body: string } | { kind: 'refused'; e export async function readCheckedRpcOutcome( res: IncomingMessage, info: DaemonInfo, + readLink: ReadHealthLink, ): Promise { const notFound = res.statusCode === 404; const body = await readBoundedBody( @@ -107,7 +114,12 @@ export async function readCheckedRpcOutcome( } return { kind: 'refused', - error: checkedRpcRefusalError(String(res.headers[DAEMON_HTTP_REFUSAL_HEADER]), body, info), + error: checkedRpcRefusalError( + String(res.headers[DAEMON_HTTP_REFUSAL_HEADER]), + body, + info, + readLink, + ), }; } @@ -115,14 +127,13 @@ function checkedRpcRefusalError( refusal: string, body: string | undefined, info: DaemonInfo, + readLink: ReadHealthLink, ): AppError { switch (refusal) { case DAEMON_HTTP_REFUSALS.protocolMismatch: case DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch: - return discloseUnclassifiedDispatch(protocolMismatchError(refusal, body, info), 'no'); - case DAEMON_HTTP_REFUSALS.scriptArtifacts: - return discloseUnclassifiedDispatch(scriptArtifactsError(), 'no'); - default: + return protocolMismatchError(refusal, body, info, readLink); + case DAEMON_HTTP_REFUSALS.protocolMissing: return new AppError( 'COMMAND_FAILED', 'The remote refused the checked RPC call because it named no RPC protocol', @@ -133,38 +144,54 @@ function checkedRpcRefusalError( hint: 'An ingress between this client and the remote removes the x-agent-device-rpc-protocol header. Fix that ingress, or remove daemonRpc from the connection profile.', }, ); + default: + // A refusal this build does not know proves nothing about dispatch: the reply is unreadable, + // and the transport discloses it like any reply it cannot read. It is never resent. + return new AppError('COMMAND_FAILED', 'Invalid daemon RPC response', { + reason: DAEMON_TRANSPORT_REASONS.replyInvalid.reason, + refusal, + daemonBaseUrl: info.baseUrl, + }); } } -/** Today's upgrade message, built from the refusing side's bounded and validated metadata. */ +/** + * Today's upgrade message, with the typed reason and the refusing side's bounded, validated + * `service`, `version` and `rpcProtocolVersion`. A refusal without them, which a daemon sends a call + * it could not authenticate, keeps the reason alone. + */ function protocolMismatchError( refusal: string, body: string | undefined, info: DaemonInfo, + readLink: ReadHealthLink, ): AppError { - const link = readHealthLink(readRefusalDetails(body)); - const behindProxy = refusal === DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch; - if (typeof link.rpcProtocolVersion === 'number' && Number.isInteger(link.rpcProtocolVersion)) { - return incompatibleRemoteProtocolError( - info.baseUrl ?? '', - { ...link, rpcProtocolVersion: link.rpcProtocolVersion }, - behindProxy ? { service: 'agent-device-proxy' } : undefined, - ); - } - return new AppError('COMMAND_FAILED', 'Remote daemon RPC protocol is incompatible', { + const link = readLink(readRefusalDetails(body)); + const typed = { reason: DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason, - daemonBaseUrl: info.baseUrl, - hint: 'Upgrade agent-device so this client and the remote speak the same RPC protocol.', - }); -} - -function scriptArtifactsError(): AppError { - try { - assertScriptArtifactsCapability(undefined); - } catch (error) { - if (error instanceof AppError) return error; + dispatched: 'no' as const, + }; + if (typeof link.rpcProtocolVersion !== 'number' || !Number.isInteger(link.rpcProtocolVersion)) { + return new AppError('COMMAND_FAILED', 'Remote daemon RPC protocol is incompatible', { + ...typed, + daemonBaseUrl: info.baseUrl, + hint: 'Upgrade agent-device so this client and the remote speak the same RPC protocol.', + }); } - throw new Error('assertScriptArtifactsCapability accepted no capabilities'); + const upgrade = incompatibleRemoteProtocolError( + info.baseUrl ?? '', + { ...link, rpcProtocolVersion: link.rpcProtocolVersion }, + refusal === DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch + ? { service: 'agent-device-proxy' } + : undefined, + ); + return new AppError(upgrade.code, upgrade.message, { + ...upgrade.details, + ...typed, + service: link.service, + version: link.version, + rpcProtocolVersion: link.rpcProtocolVersion, + }); } /** The typed failure when the remote does not serve checked RPC. A command is never resent. */ @@ -179,18 +206,16 @@ function checkedRpcUnsupportedError(info: DaemonInfo, dispatched: 'no' | 'unknow /** * Refuses `daemonRpc: checked` at `connect` unless every link the command RPC crosses advertises the - * `checked-rpc` capability: the endpoint, and the daemon behind it when the endpoint is a proxy. + * `checked-rpc` capability in `health`. A proxy proves its daemon only through `upstream`: one with no readable + * `upstream` is refused, never taken for a direct daemon. */ -export async function assertRemoteServesCheckedRpc(params: { - baseUrl: string; - token: string | undefined; -}): Promise { - const info: DaemonInfo = { token: params.token ?? '', pid: 0, baseUrl: params.baseUrl }; - const health = await readRemoteDaemonHealth(info); +export function assertHealthServesCheckedRpc(health: RemoteDaemonHealth, info: DaemonInfo): void { if (!health.reachable) { - throw remoteDaemonUnavailableError({ daemonBaseUrl: params.baseUrl, attempts: 1 }); + throw remoteDaemonUnavailableError({ daemonBaseUrl: info.baseUrl, attempts: 1 }); } - if (health.checkedRpc && (!health.upstream || health.upstream.checkedRpc)) return; + const links = health.service === 'agent-device-proxy' ? [health, health.upstream] : [health]; + if (links.every((link) => link?.capabilities?.includes(DAEMON_HTTP_CHECKED_RPC_CAPABILITY))) + return; throw checkedRpcUnsupportedError(info, 'no'); } diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index 3f77b2e85c..93280f4628 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -223,7 +223,7 @@ function resolveRemoteClientSettings( const remoteBaseUrl = resolveRemoteDaemonBaseUrl(rawBaseUrl); const authToken = suppliedAuthToken ?? env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; validateRemoteDaemonTrust(remoteBaseUrl, authToken); - const daemonRpc = resolveDaemonRpcMode(req.flags?.daemonRpc ?? env.AGENT_DEVICE_DAEMON_RPC); + const daemonRpc = resolveDaemonRpcMode(req.flags?.daemonRpc); return { rawBaseUrl, remoteBaseUrl, authToken, daemonRpc }; } @@ -337,6 +337,7 @@ async function ensureRemoteDaemon( recovery: healthRecovery, deadline, hint: REMOTE_DAEMON_UNREACHABLE_HINT, + probe: async (probeMs, signal) => await cachedRemoteDaemonHealth(remoteInfo, probeMs, signal), }); } remoteInfo.capabilities = (health.upstream ?? health).capabilities; 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..6d0d5a33cf 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. */ @@ -31,6 +31,8 @@ export async function recoverRemoteDaemonHealth(params: { /** When the command's budget ends, on the `performance.now()` clock: it started with the first probe. */ deadline: number; hint: string; + /** One `/health` probe within `probeTimeoutMs`. */ + probe: (probeTimeoutMs: number, signal: AbortSignal | undefined) => Promise; }): Promise { const { info, recovery, deadline, hint } = params; let attempts = 1; @@ -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-remote-resend.ts b/packages/daemon-client/src/daemon-client-remote-resend.ts index b3b0bbdc6a..d5518526bd 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -1,76 +1,86 @@ // The only ways a remote command is sent a second time. Each trigger is evidence that the first send // never dispatched: a typed pre-dispatch instance refusal on `/rpc` (ADR 0006), or, on the checked // route, this client's own proof that the connection never opened. Nothing a response says on the -// checked route triggers a resend. Loaded only on those failures. -import type { DaemonWireRequest } from '@agent-device/contracts/command'; +// checked route triggers a resend. Loaded only on those failures; the transport hands in what it +// owns, so this module never imports it back. import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { - assertScriptArtifactsCapability, - type DaemonPaths, -} from '@agent-device/daemon-contracts/daemon-resolution'; +import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; import type { DaemonInfo } from './daemon-client-metadata.ts'; import { CheckedRpcConnectFailure } from './daemon-client-checked-rpc.ts'; import { cacheRemoteDaemonHealth } from './daemon-client-remote-health-cache.ts'; import { recoverRemoteDaemonHealth } from './daemon-client-remote-health-recovery.ts'; -import { - invalidateRemoteDaemonHealth, - isRemoteTransportFailure, - readRemoteDaemonHealth, - refuseAbortedRequest, - REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS, - requestTimeoutError, - sendRequestWithTransport, - type ResolvedDaemonTransport, - type SendRequestOptions, -} from './daemon-client-transport.ts'; +import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; import { REMOTE_DAEMON_UNREACHABLE_HINT, remoteDaemonUnavailableError, } from './daemon-lifecycle-errors.ts'; -/** One failed send: what was sent, where, and the command's budget on the `performance.now()` clock. */ -type FailedSend = { +/** The transport's side of one failed send: how to probe, resend and refuse for that request. */ +export type RemoteResendPort = { info: DaemonInfo; - req: DaemonWireRequest; - statePaths: DaemonPaths; + /** The command's budget and its end on the `performance.now()` clock, when it has one. */ timeoutMs: number | undefined; deadline: number | undefined; - transport: ResolvedDaemonTransport; - options: SendRequestOptions; + signal: AbortSignal | undefined; + /** Sends the request once more, with `timeoutMs` as its budget. */ + resend(timeoutMs: number | undefined): Promise; + /** A live `/health` read that refuses a skewed protocol. */ + readHealth(probeTimeoutMs: number | undefined): Promise; + /** A `/health` read through the process cache, as the recovery loop probes. */ + probeHealth(probeTimeoutMs: number, signal: AbortSignal | undefined): Promise; + invalidateHealth(): Promise; + /** Throws the typed cancellation when the caller has aborted. */ + refuseIfAborted(): void; + /** The timeout refusal for a budget spent before anything was resent. */ + budgetSpent(): Error; + /** Whether a failure is a transport failure that makes the cached health stale. */ + isTransportFailure(error: unknown): boolean; + /** The `/health` probe's own time limit. */ + healthProbeTimeoutMs: number; }; /** * Answers a failed checked call. Only a connection that never opened is acted on. A refused one fails * at once, as a refused `/health` probe does. A connect that timed out runs the `/health` recovery - * loop within the command's budget, then sends once with the full send budget. Every other failure - * is the caller's answer. + * loop on fresh probes within the command's budget, then sends once with the full send budget. Every + * other failure is the caller's answer. */ export async function sendCheckedRpcAfterConnectFailure( error: unknown, - failed: FailedSend, + port: RemoteResendPort, ): Promise { - const { info, req, statePaths, timeoutMs, deadline, options } = failed; if (!(error instanceof CheckedRpcConnectFailure)) { - if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); + if (port.isTransportFailure(error)) await port.invalidateHealth(); throw error; } + // A cached `/health` answer predates this failure, so recovery decides on fresh probes only. + await port.invalidateHealth(); if (!error.timedOut) { throw remoteDaemonUnavailableError({ - daemonBaseUrl: info.baseUrl, + daemonBaseUrl: port.info.baseUrl, attempts: 1, hint: REMOTE_DAEMON_UNREACHABLE_HINT, }); } - await recoverRemoteDaemonHealth({ - info, - failedProbe: { reachable: false, timedOut: true }, - recovery: timeoutMs === undefined ? undefined : { budgetMs: timeoutMs, signal: options.signal }, - deadline: deadline ?? performance.now(), - hint: REMOTE_DAEMON_UNREACHABLE_HINT, - }); - refuseAbortedRequest(options.signal, req.meta?.requestId); - const { trackCheckedConnect: _once, ...resend } = options; - return await sendRequestWithTransport(info, req, statePaths, timeoutMs, 'http', resend); + try { + await recoverRemoteDaemonHealth({ + info: port.info, + failedProbe: { reachable: false, timedOut: true }, + recovery: + port.timeoutMs === undefined + ? undefined + : { budgetMs: port.timeoutMs, signal: port.signal }, + deadline: port.deadline ?? performance.now(), + hint: REMOTE_DAEMON_UNREACHABLE_HINT, + probe: port.probeHealth, + }); + } catch (recoveryError) { + // The caller's abort ends the recovery, and the caller hears its own typed cancellation. + port.refuseIfAborted(); + throw recoveryError; + } + port.refuseIfAborted(); + return await port.resend(port.timeoutMs); } /** @@ -78,19 +88,15 @@ export async function sendCheckedRpcAfterConnectFailure( * whose protocol is compatible and that is answered within what is left of the command's budget. */ export async function retryAfterRemoteInstanceMismatch( - failed: FailedSend, + port: RemoteResendPort, + scriptPublicationId: string | undefined, ): Promise { - const { info, req, statePaths, timeoutMs, deadline, transport, options } = failed; - await invalidateRemoteDaemonHealth(info); - const probeTimeoutMs = remainingRemoteRequestTimeoutMs(req, timeoutMs, deadline); - const health = await readRemoteDaemonHealth(info, probeTimeoutMs, options.signal); - refuseAbortedRequest(options.signal, req.meta?.requestId); - const remainingMs = remainingRemoteRequestTimeoutMs( - req, - timeoutMs, - deadline, - health.timedOut ? probeTimeoutMs : undefined, - ); + const { info } = port; + await port.invalidateHealth(); + const probeTimeoutMs = remainingBudgetMs(port); + const health = await port.readHealth(probeTimeoutMs); + port.refuseIfAborted(); + const remainingMs = remainingBudgetMs(port, health.timedOut ? probeTimeoutMs : undefined); if (!health.reachable) { throw remoteDaemonUnavailableError({ daemonBaseUrl: info.baseUrl, attempts: 1 }); } @@ -99,28 +105,23 @@ export async function retryAfterRemoteInstanceMismatch( info.capabilities = (health.upstream ?? health).capabilities; cacheRemoteDaemonHealth(info, health); // A replacement daemon must still deliver the script that a remote recording asks for. - if (req.meta?.scriptPublicationId) assertScriptArtifactsCapability(info.capabilities); + if (scriptPublicationId) assertScriptArtifactsCapability(info.capabilities); try { - return await sendRequestWithTransport(info, req, statePaths, remainingMs, transport, options); + return await port.resend(remainingMs); } catch (error) { - if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); + if (port.isTransportFailure(error)) await port.invalidateHealth(); throw error; } } -function remainingRemoteRequestTimeoutMs( - req: DaemonWireRequest, - timeoutMs: number | undefined, - deadline: number | undefined, - timedOutProbeMs?: number, -): number | undefined { - if (deadline === undefined || timeoutMs === undefined) return undefined; - const remainingMs = deadline - performance.now(); +function remainingBudgetMs(port: RemoteResendPort, timedOutProbeMs?: number): number | undefined { + if (port.deadline === undefined || port.timeoutMs === undefined) return undefined; + const remainingMs = port.deadline - performance.now(); // A probe capped by the request can expire before the monotonic clock catches up to its timer. if ( remainingMs > 0 && - (timedOutProbeMs === undefined || timedOutProbeMs > REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS) + (timedOutProbeMs === undefined || timedOutProbeMs > port.healthProbeTimeoutMs) ) return remainingMs; - throw requestTimeoutError(timeoutMs, req.meta?.requestId, false); + throw port.budgetSpent(); } diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 2bdd3d9489..465fa23f33 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -18,7 +18,6 @@ import { import { buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, - DAEMON_HTTP_CHECKED_RPC_CAPABILITY, DAEMON_HTTP_CHECKED_RPC_ROUTE, DAEMON_HTTP_RPC_PROTOCOL_HEADER, DAEMON_HTTP_INSTANCE_HEADER, @@ -38,14 +37,15 @@ import { import { handleRequestTimeout } from './daemon-client-timeout.ts'; import { isRemoteDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { RemoteResendPort } from './daemon-client-remote-resend.ts'; import type { DaemonProbeVerdict, LoopbackConnectDenial, LoopbackTransport, } from './daemon-client-loopback-probe.ts'; -export type ResolvedDaemonTransport = LoopbackTransport; -export type SendRequestOptions = { +type ResolvedDaemonTransport = LoopbackTransport; +type SendRequestOptions = { /** The host whose working directory and environment this request's client-side work reads. */ host: HostEnvironment; onProgress?: RequestProgressSink; @@ -103,7 +103,7 @@ function abortedRequestError( * 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 { +function refuseAbortedRequest(signal: AbortSignal | undefined, requestId?: string): void { if (!signal?.aborted) return; throw abortedRequestError(signal, 'no', requestId); } @@ -154,7 +154,7 @@ export function createRequestGuard(params: { } const LOCAL_DAEMON_HEALTHCHECK_TIMEOUT_MS = 500; -export const REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS = 3000; +const REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS = 3000; export function isDaemonTransportUnavailableError(error: unknown): boolean { return ( @@ -183,17 +183,15 @@ export type RemoteDaemonHealth = { instanceId?: string; hostArch?: string; capabilities?: DaemonInfo['capabilities']; - /** This link serves the checked RPC route. */ - checkedRpc?: true; /** The daemon behind a proxy, as the proxy's health reported it. */ upstream?: RemoteDaemonHealthLink; /** The probe ran out of its time budget before an answer, rather than failing outright. */ timedOut?: true; }; -type RemoteDaemonHealthLink = Omit< +type RemoteDaemonHealthLink = Pick< RemoteDaemonHealth, - 'reachable' | 'statusCode' | 'upstream' | 'timedOut' + 'service' | 'version' | 'rpcProtocolVersion' | 'instanceId' | 'hostArch' | 'capabilities' >; export async function probeDaemonReachability( @@ -372,7 +370,7 @@ function readHealthPayload(body: string): Omit): RemoteDaemonHealthLink { +function readHealthLink(parsed: Record): RemoteDaemonHealthLink { return { service: isHealthService(parsed.service) ? parsed.service : undefined, version: readHealthVersion(parsed.version), @@ -383,10 +381,6 @@ export function readHealthLink(parsed: Record): RemoteDaemonHea ...(parsed.capabilities === undefined ? {} : { capabilities: readDaemonCapabilities(parsed.capabilities) }), - ...(Array.isArray(parsed.capabilities) && - parsed.capabilities.includes(DAEMON_HTTP_CHECKED_RPC_CAPABILITY) - ? { checkedRpc: true as const } - : {}), }; } @@ -509,16 +503,13 @@ async function sendRequestWithFallback( trackCheckedConnect: info.checkedRpc, }); } catch (error) { - const attempt = { info, req, statePaths, timeoutMs, deadline, transport, options }; // Loaded only on these failures: the two remote resend rules live in one module. - if (info.checkedRpc) { - const { sendCheckedRpcAfterConnectFailure } = - await import('./daemon-client-remote-resend.ts'); - return await sendCheckedRpcAfterConnectFailure(error, attempt); - } - if (info.baseUrl && isRemoteInstanceMismatch(error)) { - const { retryAfterRemoteInstanceMismatch } = await import('./daemon-client-remote-resend.ts'); - return await retryAfterRemoteInstanceMismatch(attempt); + if (info.checkedRpc || (info.baseUrl && isRemoteInstanceMismatch(error))) { + const resend = await import('./daemon-client-remote-resend.ts'); + const port = remoteResendPort(info, req, statePaths, transport, timeoutMs, deadline, options); + return info.checkedRpc + ? await resend.sendCheckedRpcAfterConnectFailure(error, port) + : await resend.retryAfterRemoteInstanceMismatch(port, req.meta?.scriptPublicationId); } if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); const fallback = chooseAutoFallbackTransport(info, preference, transport); @@ -527,6 +518,33 @@ async function sendRequestWithFallback( } } +/** What the resend rules may do for one failed request: every transport power they use, bound to it. */ +function remoteResendPort( + info: DaemonInfo, + req: DaemonWireRequest, + statePaths: DaemonPaths, + transport: ResolvedDaemonTransport, + timeoutMs: number | undefined, + deadline: number | undefined, + options: SendRequestOptions, +): RemoteResendPort { + return { + info, + timeoutMs, + deadline, + signal: options.signal, + resend: async (budgetMs) => + await sendRequestWithTransport(info, req, statePaths, budgetMs, transport, options), + readHealth: async (probeMs) => await readRemoteDaemonHealth(info, probeMs, options.signal), + probeHealth: async (probeMs, signal) => await cachedRemoteDaemonHealth(info, probeMs, signal), + invalidateHealth: async () => await invalidateRemoteDaemonHealth(info), + refuseIfAborted: () => refuseAbortedRequest(options.signal, req.meta?.requestId), + budgetSpent: () => requestTimeoutError(timeoutMs ?? 0, req.meta?.requestId, false), + isTransportFailure: isRemoteTransportFailure, + healthProbeTimeoutMs: REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS, + }; +} + function isRemoteInstanceMismatch(error: unknown): boolean { return ( error instanceof AppError && @@ -534,7 +552,7 @@ function isRemoteInstanceMismatch(error: unknown): boolean { ); } -export function isRemoteTransportFailure(error: unknown): boolean { +function isRemoteTransportFailure(error: unknown): boolean { return ( error instanceof AppError && (error.details?.reason === DAEMON_TRANSPORT_REASONS.failure.reason || @@ -543,7 +561,7 @@ export function isRemoteTransportFailure(error: unknown): boolean { ); } -export async function sendRequestWithTransport( +async function sendRequestWithTransport( info: DaemonInfo, req: DaemonWireRequest, statePaths: DaemonPaths, @@ -735,7 +753,7 @@ async function sendSocketRequest( }); } -export function requestTimeoutError( +function requestTimeoutError( timeoutMs: number, requestId: string | undefined, daemonRequestSent: boolean, @@ -837,7 +855,7 @@ async function sendHttpRequest( }, (res) => { if (checkedRpc?.isCheckedRpcOutcomeResponse(res.statusCode, res.headers ?? {})) { - void checkedRpc.readCheckedRpcOutcome(res, info).then((outcome) => { + void checkedRpc.readCheckedRpcOutcome(res, info, readHealthLink).then((outcome) => { if (timeoutHandle) clearTimeout(timeoutHandle); if (outcome.kind === 'answer') handleBody(outcome.body); else rejectOnce(outcome.error); @@ -957,7 +975,7 @@ async function sendHttpRequest( const loadRemoteHealthCache = () => import('./daemon-client-remote-health-cache.ts'); /** Drops a remote daemon's cached health; a local daemon has none, so its failure loads nothing. */ -export async function invalidateRemoteDaemonHealth(info: DaemonInfo): Promise { +async function invalidateRemoteDaemonHealth(info: DaemonInfo): Promise { if (!info.baseUrl) return; (await loadRemoteHealthCache()).invalidateRemoteDaemonHealth(info); } diff --git a/packages/daemon-client/src/daemon-lifecycle-errors.ts b/packages/daemon-client/src/daemon-lifecycle-errors.ts index 88d7c4ba40..47da5c9018 100644 --- a/packages/daemon-client/src/daemon-lifecycle-errors.ts +++ b/packages/daemon-client/src/daemon-lifecycle-errors.ts @@ -111,10 +111,6 @@ export function daemonStopCommand(stateDir: string): string { * one when it re-probed within the command's budget. `healthRecoveryBudgetMs` is present only when * that budget ran out, which tells a spent budget from a single failed probe. */ -/** What a caller does about a remote daemon that answers nothing. */ -export const REMOTE_DAEMON_UNREACHABLE_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.'; - export function remoteDaemonUnavailableError(params: { daemonBaseUrl: string | undefined; attempts: number; @@ -132,6 +128,10 @@ export function remoteDaemonUnavailableError(params: { }); } +/** What a caller does about a remote daemon that answers nothing. */ +export const REMOTE_DAEMON_UNREACHABLE_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.'; + /** A daemon won a startup race that this caller may not settle by retiring it. */ export function daemonContendedError(): AppError { return new AppError( diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 237e3a9c25..94f5727f60 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, + readRemoteDaemonHealth, + sendRequest as sendDaemonRequest, +} from './daemon-client-transport.ts'; import { isRemoteDaemon, readRegisteredDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { LocalDaemonCodeIdentity } from './daemon-launch-spec.ts'; import type { @@ -461,16 +465,35 @@ export async function resolveLocalDaemonCodeIdentity(): Promise { - const { assertRemoteServesCheckedRpc: assert } = await import('./daemon-client-checked-rpc.ts'); - await assert(params); +export async function assertRemoteServesCheckedRpc( + flags: Pick & { daemonAuthToken?: string }, + host: HostEnvironment, +): Promise { + const [{ resolveClientSettings }, { assertHealthServesCheckedRpc }] = await Promise.all([ + import('./daemon-client-lifecycle.ts'), + import('./daemon-client-checked-rpc.ts'), + ]); + const settings = resolveClientSettings( + { + session: 'default', + command: 'connect', + positionals: [], + flags: { daemonBaseUrl: flags.daemonBaseUrl }, + }, + flags.daemonAuthToken, + host, + ); + if (!settings.remoteBaseUrl) return; + const info: DaemonInfo = { + token: settings.remoteAuthToken ?? '', + pid: 0, + baseUrl: settings.remoteBaseUrl, + }; + assertHealthServesCheckedRpc(await readRemoteDaemonHealth(info), info); } /** The managed local HTTP daemon `agent-device proxy` forwards to, started if none is usable. */ diff --git a/packages/remote/src/remote-config-schema.ts b/packages/remote/src/remote-config-schema.ts index f2bbcd25e9..eb8926bf36 100644 --- a/packages/remote/src/remote-config-schema.ts +++ b/packages/remote/src/remote-config-schema.ts @@ -38,7 +38,6 @@ export const REMOTE_CONFIG_FIELD_SPECS = [ { key: 'daemonAuthToken', type: 'string' }, { key: 'daemonTransport', type: 'enum', enumValues: ['auto', 'socket', 'http'] }, { key: 'daemonServerMode', type: 'enum', enumValues: ['socket', 'http', 'dual'] }, - { key: 'daemonRpc', type: 'enum', enumValues: DAEMON_RPC_MODES }, { key: 'tenant', type: 'string' }, { key: 'sessionIsolation', type: 'enum', enumValues: ['none', 'tenant'] }, { key: 'runId', type: 'string' }, @@ -115,9 +114,21 @@ const REMOTE_CONFIG_LEASE_FIELD_SPECS = [ { key: 'clientId', type: 'string', env: false }, ] as const satisfies readonly RemoteConfigFieldSpec[]; +/** + * Profile-only: no flag or environment variable sets it. `connect` checks the remote serves checked + * RPC before it records the mode in the connection, and commands read it from there. + */ +const REMOTE_CONFIG_DAEMON_RPC_FIELD_SPEC = { + key: 'daemonRpc', + type: 'enum', + enumValues: DAEMON_RPC_MODES, + env: false, +} as const satisfies RemoteConfigFieldSpec; + export const REMOTE_CONFIG_PROFILE_FIELD_SPECS = [ ...REMOTE_CONFIG_FIELD_SPECS, ...REMOTE_CONFIG_LEASE_FIELD_SPECS, + REMOTE_CONFIG_DAEMON_RPC_FIELD_SPEC, ] as const satisfies readonly RemoteConfigFieldSpec[]; const remoteConfigFieldSpecByKey = new Map( diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index 2ca43e968b..b94d5a43d7 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -41,6 +41,8 @@ export type RemoteConnectionState = { baseUrl?: string; transport?: CliFlags['daemonTransport']; serverMode?: CliFlags['daemonServerMode']; + /** Set only by `connect`, after every link of the remote advertised `checked-rpc`. */ + rpc?: 'checked'; }; tenant: string; runId: string; @@ -395,13 +397,14 @@ export function writeRemoteConnectionState(options: { export function buildRemoteConnectionDaemonState( flags: Pick< CliFlags, - 'daemonBaseUrl' | 'daemonAuthToken' | 'daemonTransport' | 'daemonServerMode' + 'daemonBaseUrl' | 'daemonAuthToken' | 'daemonTransport' | 'daemonServerMode' | 'daemonRpc' >, ): RemoteConnectionState['daemon'] { return { baseUrl: sanitizeDaemonBaseUrl(flags.daemonBaseUrl), transport: flags.daemonTransport, serverMode: flags.daemonServerMode, + ...(flags.daemonRpc === 'checked' ? { rpc: 'checked' as const } : {}), }; } @@ -546,6 +549,8 @@ function remoteConnectionDefaults( daemonAuthToken: profile.daemonAuthToken, daemonTransport: state.daemon?.transport ?? profile.daemonTransport, daemonServerMode: state.daemon?.serverMode ?? profile.daemonServerMode, + // Only the mode `connect` checked; the profile's own value is never read here. + daemonRpc: state.daemon?.rpc, ...leaseScopeToCommandFlags(leaseScope), sessionIsolation: 'tenant', session: state.session, diff --git a/packages/remote/src/session-script-destination.ts b/packages/remote/src/session-script-destination.ts index aee8386f13..412623a227 100644 --- a/packages/remote/src/session-script-destination.ts +++ b/packages/remote/src/session-script-destination.ts @@ -31,8 +31,8 @@ type RemoteEndpoint = DaemonArtifactEndpoint & { * Sends a remote `open --save-script`. Before the open leaves, the client mints a publication ID * and records the caller destination and the `--force` grant under it. The serialized request * carries the ID and omits the destination. A daemon answer that does not name the ID removes the - * record, and so does a failure that proves nothing was dispatched. Any other failed open may still - * have armed the recording, so it keeps the record. A record that outlives its open stays inert: + * record, and so does a checked open's failure that proves nothing was dispatched. Any other + * failed open may still have armed the recording, so it keeps the record. A record that outlives its open stays inert: * only artifacts of its own ID match it. */ export async function sendRemoteScriptOpen( @@ -54,7 +54,9 @@ export async function sendRemoteScriptOpen( try { response = await send({ ...req, meta }); } catch (error) { - if (error instanceof AppError && error.details?.dispatched === 'no') await discard(); + if (info.checkedRpc && error instanceof AppError && error.details?.dispatched === 'no') { + await discard(); + } throw error; } if (!response.ok || response.data?.scriptPublicationId !== publicationId) await discard(); diff --git a/scripts/integration-progress-model.ts b/scripts/integration-progress-model.ts index f90806f777..12c9c0e883 100644 --- a/scripts/integration-progress-model.ts +++ b/scripts/integration-progress-model.ts @@ -246,7 +246,6 @@ function summarizeProviderScenarioFlagExclusions() { 'daemonAuthToken', 'daemonTransport', 'daemonServerMode', - 'daemonRpc', 'remote', 'tenant', 'sessionIsolation', diff --git a/src/cli.ts b/src/cli.ts index 36f6a36834..4b2538374c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -490,11 +490,16 @@ async function resolveRemoteContext( } if (ctx.effectiveFlags.remoteConfig && shouldMaterializeRemoteConnection(ctx.command)) { - const materializationClient = createAgentDeviceClient(buildClientConfig(ctx), { - host: ctx.host, - devicePin: ctx.devicePin, - transport: createClientDaemonTransport(transport), - }); + // Lease allocate and heartbeat calls act on the remote before the command, so they go + // health-first with the instance fences, never on the checked route. + const materializationClient = createAgentDeviceClient( + { ...buildClientConfig(ctx), daemonRpc: undefined }, + { + host: ctx.host, + devicePin: ctx.devicePin, + transport: createClientDaemonTransport(transport), + }, + ); const { materializeRemoteConnectionForCommand } = await import('./cli/commands/connection-runtime.ts'); const materialized = await materializeRemoteConnectionForCommand({ diff --git a/src/cli/commands/connection-lease-transaction.ts b/src/cli/commands/connection-lease-transaction.ts index 626730bb81..77bb277cb6 100644 --- a/src/cli/commands/connection-lease-transaction.ts +++ b/src/cli/commands/connection-lease-transaction.ts @@ -121,7 +121,7 @@ export async function acquireConnectionLease(options: { nextFlags: CliFlags; positionals?: string[]; leaseLedger: LeaseLedger; -}): Promise<{ state: RemoteConnectionState; changed: boolean }> { +}): Promise<{ state: RemoteConnectionState; changed: boolean; leasePrepared: boolean }> { const { command, client, state, nextFlags, leaseLedger } = options; const deferredAppSelection = connectionProviderCapabilities( state.leaseProvider, @@ -151,7 +151,9 @@ export async function acquireConnectionLease(options: { platform: carriedConnectionPlatform(state.session, nextState, nextFlags), }; nextFlags.platform = nextState.platform; - return { state: nextState, changed }; + // An allocate or heartbeat just ran on the remote, so the command that uses the lease must reach + // the same daemon: the caller sends it health-first, with the instance fences. + return { state: nextState, changed, leasePrepared: leasePolicy.shouldAllocate(command) }; } /** diff --git a/src/cli/commands/connection-runtime-checked-rpc.test.ts b/src/cli/commands/connection-runtime-checked-rpc.test.ts new file mode 100644 index 0000000000..00b418e43d --- /dev/null +++ b/src/cli/commands/connection-runtime-checked-rpc.test.ts @@ -0,0 +1,78 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { test } from 'vitest'; +import type { AgentDeviceClient } from '@agent-device/command-surface'; +import { createTestHostEnvironment } from '@agent-device/test-kit'; +import { + connectionWorkspace, + seedConnectionState, +} from '../../__tests__/remote-connection.fixtures.ts'; +import { materializeRemoteConnectionForCommand } from './connection-runtime.ts'; + +/** A connection `connect` recorded with checked RPC, holding one android lease. */ +function checkedConnection() { + const { stateDir, remoteConfigPath } = connectionWorkspace('agent-device-checked-lease-'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ daemonBaseUrl: 'http://127.0.0.1:9', daemonRpc: 'checked' }), + ); + seedConnectionState({ + stateDir, + state: { + session: 'checked', + remoteConfigPath, + tenant: 'tenant-a', + runId: 'run-a', + daemon: { baseUrl: 'http://127.0.0.1:9', transport: 'http', rpc: 'checked' }, + leaseId: 'lease-1', + leaseBackend: 'android-instance', + platform: 'android', + }, + }); + const heartbeats: unknown[] = []; + const client = { + leases: { + heartbeat: async (request: { leaseId: string }) => { + heartbeats.push(request); + return { + leaseId: request.leaseId, + tenantId: 'tenant-a', + runId: 'run-a', + backend: 'android-instance', + }; + }, + }, + } as unknown as AgentDeviceClient; + const materialize = (command: string) => + materializeRemoteConnectionForCommand({ + host: createTestHostEnvironment(), + command, + client, + flags: { + json: true, + help: false, + version: false, + stateDir, + session: 'checked', + remoteConfig: remoteConfigPath, + daemonBaseUrl: 'http://127.0.0.1:9', + daemonRpc: 'checked', + platform: 'android', + }, + }); + return { materialize, heartbeats }; +} + +test('a command that renews its lease first goes health-first, fenced to the same daemon', async () => { + const connection = checkedConnection(); + const materialized = await connection.materialize('snapshot'); + assert.equal(connection.heartbeats.length, 1); + assert.equal(materialized.flags.daemonRpc, undefined); +}); + +test('a command that prepares no lease keeps checked RPC', async () => { + const connection = checkedConnection(); + const materialized = await connection.materialize('session'); + assert.equal(connection.heartbeats.length, 0); + assert.equal(materialized.flags.daemonRpc, 'checked'); +}); diff --git a/src/cli/commands/connection-runtime.ts b/src/cli/commands/connection-runtime.ts index 0c687dc05c..c6ac8d528d 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -97,6 +97,7 @@ export async function materializeRemoteConnectionForCommand(options: { let nextRuntime = selectCompatibleRuntime(state.runtime, nextFlags.platform) ?? options.runtime; let nextState = state; let changed = !existingState; + let leasePrepared = false; // Unknown creation evidence permits discard before binding, but only confirmed creation permits // rollback after a later failure. A committed session record takes over either lease. @@ -112,6 +113,7 @@ export async function materializeRemoteConnectionForCommand(options: { }); nextState = acquired.state; changed = changed || acquired.changed; + leasePrepared = acquired.leasePrepared; const runtimePreparation = await prepareRuntimeForCommand({ command, @@ -147,6 +149,8 @@ export async function materializeRemoteConnectionForCommand(options: { leaseBackend: nextState.leaseBackend, platform: nextState.platform ?? nextFlags.platform, target: nextState.target ?? nextFlags.target, + // A command that follows a lease allocate or heartbeat goes health-first, fenced to that daemon. + ...(leasePrepared ? { daemonRpc: undefined } : {}), }, runtime: nextRuntime, connection: buildRemoteConnectionRequestMetadata(nextState), @@ -231,7 +235,8 @@ function createRemoteConnectionStateFromFlags( session, remoteConfigPath, remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), - daemon: buildRemoteConnectionDaemonState(flags), + // Only `connect` records checked RPC, after it checks the remote serves it. + daemon: buildRemoteConnectionDaemonState({ ...flags, daemonRpc: undefined }), tenant: flags.tenant, runId, leaseId: flags.leaseId, diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index a8f7c833cc..2604675315 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -126,16 +126,13 @@ export const connectCommand: ClientCommandHandler = async ({ }; /** - * `daemonRpc: checked` skips the `/health` probe on later commands, so `connect` accepts it only + * `daemonRpc: checked` skips the `/health` probe on later commands, so `connect` records it only * when every link of the remote advertises `checked-rpc`. */ async function assertCheckedRpcServed(flags: CliFlags, host: HostEnvironment): Promise { - if (flags.daemonRpc !== 'checked' || !flags.daemonBaseUrl) return; + if (flags.daemonRpc !== 'checked') return; const { assertRemoteServesCheckedRpc } = await import('@agent-device/daemon-client'); - await assertRemoteServesCheckedRpc({ - baseUrl: flags.daemonBaseUrl, - token: flags.daemonAuthToken ?? host.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN, - }); + await assertRemoteServesCheckedRpc(flags, host); } function assertConnectProviderUsage(provider: ConnectProvider | undefined, flags: CliFlags): void { @@ -334,18 +331,20 @@ function scopeConnectProfile( cwd: host.cwd, env: host.env, }).profile; + // The profile is the only source of `daemonRpc`; `connect` checks it before recording it. + const resolvedFlags = { ...resolved.flags, daemonRpc: profile.daemonRpc }; if (!flags.remoteConfig || flags.session === undefined) { - return { flags: resolved.flags, connection: buildRemoteConnectionRequestMetadata(profile) }; + return { flags: resolvedFlags, connection: buildRemoteConnectionRequestMetadata(profile) }; } const scope = sessionLeaseScope( - { ...profile, leaseId: resolved.flags.leaseId, runId: profile.runId }, + { ...profile, leaseId: resolvedFlags.leaseId, runId: profile.runId }, flags.session, ); return { flags: - resolved.flags.runId === profile.runId - ? { ...resolved.flags, runId: scope.runId } - : resolved.flags, + resolvedFlags.runId === profile.runId + ? { ...resolvedFlags, runId: scope.runId } + : resolvedFlags, connection: buildRemoteConnectionRequestMetadata({ ...profile, clientId: scope.clientId }), }; } diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 967e982c48..34e27621fa 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -68,11 +68,11 @@ "packages/daemon-client/src/daemon-client-transport.ts#HEALTH_SERVICES": "sha256:3e9d09c1e78adf1d537aa22053e2dee7d35a33d37942721701476a0c06dff52b", "packages/daemon-client/src/daemon-client-transport.ts#HEALTH_VERSION": "sha256:8dd8e36dc936523cf38bba3ed3737a6199431c35b7ce04e1441aaa2c8a186993", "packages/daemon-client/src/daemon-client-transport.ts#HEALTH_VERSION_MAX_LENGTH": "sha256:0357d7c75ccb6fefe7ec901c7937bc795a2e66c4082c90fed27b4baf10c16416", - "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth": "sha256:5bd9f31964e3b83b410f1e918b71c2423a5dc7e0fe6e0c4b4b8bcd4edda77c65", - "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink": "sha256:10dd49f8b54da8f469718c43ed84f5ac95c32c581345534a4b952db3d24a27b6", + "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth": "sha256:1ff542dadff6d92233c464b7d09052d809f36186bb60acdb572c48bfc1eb5c1f", + "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink": "sha256:96a79a8ff5a078916ee7bffed1d9624d0ba9c0dcbd8e2c55f9abf37fccfef744", "packages/daemon-client/src/daemon-client-transport.ts#isHealthService": "sha256:ffd2c774e0efca5e5d2b01f9d37fe9b76aaf5e7569e07d9208fe667473771c10", "packages/daemon-client/src/daemon-client-transport.ts#readDaemonHttpHealth": "sha256:6ce1f9be1e6a977130d0875003ac22da2de5e90b514a3b22b30b9347e63d81c7", - "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink": "sha256:feda23773be1f57ca93711e17c7ad45d344a3f65a2f4f1be15a8f0d3e1315abd", + "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink": "sha256:c4f638b4df43f572e105b6f8df578fe90ebf64cb56002e4d029a109bdbc167d1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthPayload": "sha256:4e85ffc3e35e02379c393e9312344757e003cf1f0ad9eb8d1f77d90c81c861f1", "packages/daemon-client/src/daemon-client-transport.ts#readHealthVersion": "sha256:856bd74aa8b2f205b6b30855755f16391015bffc1b6a323f618b51c26e749bfd", "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:bf9ca0ecb9dc00f18d0bf4acab30d544d680246b8cdacbc50f684db182b6f23b", @@ -248,7 +248,7 @@ "packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18", "packages/remote/src/script-version-publisher.ts#publishScriptVersion": "sha256:b37b9391d20f535ca9c0858f92ed37943297c7acbf1fb10f8cad5cd5b53423eb", "packages/remote/src/script-version-publisher.ts#PublishOutcome": "sha256:a4ae6fc3298d3c560719591372edddbfa83ce749f4cf3f3e2ed1d8369313bd2d", - "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:c5b86a1d785db435cda62b56412006ba80f86f4f886c15cc84f8d03a3230ac1f", + "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:7cdb0d65cdc72e12c88a05a837f20097fa76034fd00e82fa4a10da78be4fb7f4", "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:2fbcaa03bc0675fef8d19fd0a163d5d01a2162031745a41ff5c1db8a982cc2b6", "packages/daemon/src/server/upload-http.ts#authorizeUpload": "sha256:69ee5039c7eadbe0f96cdf57bcd947b16cdc815671ba4c966ace93ad353cc740", "packages/remote/src/daemon-artifacts.ts#FetchRemoteArtifactParams": "sha256:f90ae571961d6147a09973791178d369dfb8550990a1e0ebf120e97336540824", @@ -258,10 +258,11 @@ "packages/remote/src/artifact-download.ts#fetchRemoteArtifactFromUrl": "sha256:de6e71abdc758f760beffba0dc260473f88a8c60b13540b9c14d39f1a3d5e3a1", "packages/remote/src/artifact-download.ts#requestRemoteArtifact": "sha256:cafb5fd5838819719b2fac62c5e108276dd800a58b4614462d138cf1ed2f7d6e", "packages/daemon-client/src/daemon-client-checked-rpc.ts#isCheckedRpcOutcomeResponse": "sha256:75fb9f3444a3f8f4a762811ba7cbe02d92a39ed4e55483ea0cf7f029e5720a3e", - "packages/daemon-client/src/daemon-client-checked-rpc.ts#CheckedRpcOutcome": "sha256:965cd834c6dfb581db6cee46323bfd1c0b639749b4873454bb82ace8d9456f07", - "packages/daemon-client/src/daemon-client-checked-rpc.ts#readCheckedRpcOutcome": "sha256:db0f4a1285d19036f7fbd4385b7b898b521b8b76e62c2d5e7f4e369ce0c81ad6", - "packages/daemon-client/src/daemon-client-checked-rpc.ts#checkedRpcRefusalError": "sha256:1cadc96a26d64d8cd072cb4542680d1f4f797bc748fa4994b060e0d97cddecbd", - "packages/daemon-client/src/daemon-client-checked-rpc.ts#protocolMismatchError": "sha256:f86912368af04fc263ad858f15e8bc67efa68be472e3d5e575e7b47addc357d4", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#CheckedRpcOutcome": "sha256:8aa7e58307417460bb54938f6bbbd340254e14ffbbaf2093272996909592f7be", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#ReadHealthLink": "sha256:86a9e6f1ebdaecca3ddaa16081c221321c01c684b70197961ecd71a3f54a464f", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#readCheckedRpcOutcome": "sha256:95c2757f5ad08d488b2e373af65d22422f1953b40f079fd56c2f3e7655a6589d", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#checkedRpcRefusalError": "sha256:30cbda341fa43b02e0121b0520c6a9dab6dd7aff2f99974ecbe49b7661dbad93", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#protocolMismatchError": "sha256:e56950b0227f839d70db1af54887270dc571ed4ac3593cc37b158bef133b0912", "packages/daemon-client/src/daemon-client-checked-rpc.ts#readRefusalDetails": "sha256:41309e8fe57616e93848c93b36e8fb665a737f87d013243c6f6f1949e9f87215", "packages/daemon-client/src/daemon-client-checked-rpc.ts#isJsonRpcAnswer": "sha256:ecbf4226264fe3d3b551f89a075729df477e5c3b183dc2a761123c7229f4fe99" }, @@ -393,18 +394,18 @@ }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealth", - "digest": "sha256:5bd9f31964e3b83b410f1e918b71c2423a5dc7e0fe6e0c4b4b8bcd4edda77c65", - "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. A restart retry must tell a probe that ran out of time from one that failed, so the client can report the RPC deadline instead of 'Remote daemon is unavailable'. `timedOut` is client-local: the prober sets it on its own timeout and abort paths and never reads it from a /health payload. The health request and the accepted payload fields are unchanged, so a released daemon or proxy is probed and parsed exactly as before. #4511 adds optional parsed capabilities. A released daemon or proxy that sends none parses as before and only loses remote --save-script, which the client refuses before any RPC. The checked RPC route (ADR 0006) adds an optional checkedRpc flag, read from the checked-rpc entry of the released capabilities list; a peer that does not list it reads as not serving the route." + "digest": "sha256:1ff542dadff6d92233c464b7d09052d809f36186bb60acdb572c48bfc1eb5c1f", + "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. A restart retry must tell a probe that ran out of time from one that failed, so the client can report the RPC deadline instead of 'Remote daemon is unavailable'. `timedOut` is client-local: the prober sets it on its own timeout and abort paths and never reads it from a /health payload. The health request and the accepted payload fields are unchanged, so a released daemon or proxy is probed and parsed exactly as before. #4511 adds optional parsed capabilities. A released daemon or proxy that sends none parses as before and only loses remote --save-script, which the client refuses before any RPC." }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#RemoteDaemonHealthLink", - "digest": "sha256:10dd49f8b54da8f469718c43ed84f5ac95c32c581345534a4b952db3d24a27b6", - "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. #4511 adds optional capabilities to the parsed link; a link without them parses exactly as before. The checked RPC route (ADR 0006) adds an optional checkedRpc flag, read from the checked-rpc entry of the released capabilities list; a peer that does not list it reads as not serving the route." + "digest": "sha256:96a79a8ff5a078916ee7bffed1d9624d0ba9c0dcbd8e2c55f9abf37fccfef744", + "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. #4511 adds optional capabilities to the parsed link; a link without them parses exactly as before." }, { "declaration": "packages/daemon-client/src/daemon-client-transport.ts#readHealthLink", - "digest": "sha256:feda23773be1f57ca93711e17c7ad45d344a3f65a2f4f1be15a8f0d3e1315abd", - "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. #4511 reads an optional capabilities array and omits the field when a peer does not send one, so a released payload parses to the same object. The service and version now reach error messages, so readHealthLink keeps a service only when it is one the DaemonHealthPayload contract names and a version only when it is version-shaped and at most 64 characters; anything else reads as absent. Released daemons and proxies report exactly those, so their payloads parse unchanged, and the /health request is unchanged. The checked RPC route (ADR 0006) adds an optional checkedRpc flag, read from the checked-rpc entry of the released capabilities list; a peer that does not list it reads as not serving the route. Every released field is read as before." + "digest": "sha256:c4f638b4df43f572e105b6f8df578fe90ebf64cb56002e4d029a109bdbc167d1", + "rationale": "#2650 adds an optional daemon instance ID to health metadata or reads it when present, #3047 adds an optional hostArch the same way, and #3229 adds an optional leaseBackends list the same way. Older peers ignore the added fields, and new clients keep probing legacy peers that send neither; existing fields and RPC envelopes are unchanged. #4511 reads an optional capabilities array and omits the field when a peer does not send one, so a released payload parses to the same object. The service and version now reach error messages, so readHealthLink keeps a service only when it is one the DaemonHealthPayload contract names and a version only when it is version-shaped and at most 64 characters; anything else reads as absent. Released daemons and proxies report exactly those, so their payloads parse unchanged, and the /health request is unchanged." }, { "declaration": "packages/contracts/src/daemon-http.ts#DAEMON_HTTP_INSTANCE_HEADER", @@ -673,8 +674,8 @@ }, { "declaration": "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen", - "digest": "sha256:c5b86a1d785db435cda62b56412006ba80f86f4f886c15cc84f8d03a3230ac1f", - "rationale": "Removes the unanswered open's record through the record owner instead of a direct unlink. The request still carries meta.scriptPublicationId and omits the caller path, and the response is read for the same scriptPublicationId field. A checked open skips the client-side capability check, because the daemon checks the same requirement from scriptPublicationId, and a failure that proves nothing was dispatched removes the record. The request and response fields are unchanged." + "digest": "sha256:7cdb0d65cdc72e12c88a05a837f20097fa76034fd00e82fa4a10da78be4fb7f4", + "rationale": "Removes the unanswered open's record through the record owner instead of a direct unlink. The request still carries meta.scriptPublicationId and omits the caller path, and the response is read for the same scriptPublicationId field. A checked open skips the client-side capability check, because every daemon that serves checked-rpc serves script-artifacts, and a checked open proven undispatched removes its record. The request and response fields are unchanged." }, { "declaration": "packages/remote/src/script-version-publisher.ts#PublishOutcome", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index f6bc74fe74..dac3bd6416 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -137,6 +137,7 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ CLIENT_CHECKED_RPC, 'isCheckedRpcOutcomeResponse', 'CheckedRpcOutcome', + 'ReadHealthLink', 'readCheckedRpcOutcome', 'checkedRpcRefusalError', 'protocolMismatchError', diff --git a/website/docs/docs/configuration.md b/website/docs/docs/configuration.md index 33dd511207..f90673ebbd 100644 --- a/website/docs/docs/configuration.md +++ b/website/docs/docs/configuration.md @@ -83,7 +83,6 @@ explicit config: - `daemonAuthToken` - `daemonTransport` - `daemonServerMode` -- `daemonRpc` (see [Send each command in one round trip](/docs/remote-proxy#send-each-command-in-one-round-trip)) - `tenant` - `sessionIsolation` - `runId` diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 2bfcc12e69..24790ac6fe 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -900,6 +900,7 @@ These reasons can come from more than one command. | `remote_instance_mismatch` | The daemon or proxy behind the remote URL was replaced since the client last read its health, so it refused a request addressed to the earlier instance. The client refreshes health and resends at most once; this reaches the caller when that resend is refused too. | | `remote_rpc_protocol_missing` | The checked RPC call named no RPC protocol. An intermediary that strips request headers causes this. | | `remote_rpc_protocol_mismatch` | The daemon or proxy speaks a different RPC protocol from the caller. After authentication, `details.service`, `details.version` and `details.rpcProtocolVersion` name the side that refused. | +| `remote_checked_rpc_unsupported` | The connection sets `daemonRpc: checked`, but the remote does not serve checked RPC: `connect` found no `checked-rpc` capability in its `/health`, or a command got the route answered as unknown. A command is never resent, because an ingress may have answered for one that ran. Update the remote daemon or proxy, or remove `daemonRpc` from the connection. | | `REMOTE_SESSION_REQUIRED` | A command on a leased remote connection, or one that would lease one, named no session. | | `CONNECTION_DEVICE_CONFLICT` | The connection is bound to another device, or its lease was allocated by another device spec; `details.keys` names the disagreeing keys, and is present only for a device-spec mismatch. | | `CONNECTION_PLATFORM_CONFLICT` | The connection is bound to another platform, or the request names one its lease backend does not rent. | diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index fe5408c029..ed4aa30c8e 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -363,9 +363,9 @@ for the API. 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. -### Send each command in one round trip +### Send standalone commands in one round trip -By default every command makes two requests: `GET /health`, then `POST /rpc`. Add `"daemonRpc": "checked"` to the connection profile to send most commands as one `POST /rpc/checked` instead. The proxy and the daemon behind it then check the RPC protocol themselves, after the token, and refuse a mismatch with the same upgrade message before anything runs. +Without the field, a command's dispatch makes two requests: `GET /health`, then `POST /rpc`. Uploads, artifact downloads, and lease calls are separate. Add `"daemonRpc": "checked"` to the remote-config profile to send that dispatch as one `POST /rpc/checked` instead. The proxy and the daemon behind it then check the RPC protocol themselves, after authentication, and refuse a mismatch with the same upgrade message before anything runs. ```json { @@ -374,10 +374,10 @@ By default every command makes two requests: `GET /health`, then `POST /rpc`. Ad } ``` -`connect` accepts the field only when the proxy and its daemon both list `checked-rpc` in `capabilities` on `/health`. `--daemon-rpc checked` and `AGENT_DEVICE_DAEMON_RPC=checked` set it for one command or shell; `--daemon-rpc health` turns it off. +Only `connect` turns the field on, and only when the proxy, and the daemon behind it, list `checked-rpc` in `capabilities` on `/health`. Otherwise `connect` fails with `reason: "remote_checked_rpc_unsupported"` and `dispatched: "no"`. No flag or environment variable turns it on. -- `install` and `reinstall` still read `/health` first, because they can upload an app before the command runs. -- If the remote stops serving the route, for example after a rollback, commands fail with `reason: "remote_checked_rpc_unsupported"` and `dispatched: "unknown"`. The client never resends them. Update the proxy and daemon, or remove `daemonRpc`. +- A command that allocates or renews its lease first, and `install` or `reinstall`, still read `/health` first. Their command must reach the daemon that holds the lease or the upload. +- If the remote stops serving the route later, for example after a rollback, commands fail with `reason: "remote_checked_rpc_unsupported"` and `dispatched: "unknown"`. The client never resends them. Update the proxy and daemon, or remove `daemonRpc` and run `connect --force`. - Set it only when everything between you and the proxy forwards `/rpc/checked` and its `x-agent-device-rpc-protocol` header unchanged. `/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 From c91747afb36a9592ad32acf36efb36edcaeadca9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 09:11:42 +0100 Subject: [PATCH 04/10] fix(daemon-client): declare the resend port below the transport and the resend rules The transport type-imported RemoteResendPort from the resend module, which closed a 9-file type cycle through the checked-RPC, recovery and lifecycle modules (R9/R10). The port and the health facts it reads now live in daemon-client-remote-resend-port.ts, which imports neither side. The SDK daemonRpc field documents that setting it is an explicit opt-in the server enforces. Co-Authored-By: Claude Opus 5.5 --- .../contracts/src/remote-config-fields.ts | 6 +++ .../src/daemon-client-remote-resend-port.ts | 38 +++++++++++++++++++ .../src/daemon-client-remote-resend.ts | 29 +------------- .../src/daemon-client-transport.ts | 2 +- 4 files changed, 47 insertions(+), 28 deletions(-) create mode 100644 packages/daemon-client/src/daemon-client-remote-resend-port.ts diff --git a/packages/contracts/src/remote-config-fields.ts b/packages/contracts/src/remote-config-fields.ts index de36674512..269efa4b82 100644 --- a/packages/contracts/src/remote-config-fields.ts +++ b/packages/contracts/src/remote-config-fields.ts @@ -139,6 +139,12 @@ export type RemoteConnectionProfileFields = { daemonAuthToken?: string; daemonTransport?: DaemonTransportPreference; daemonServerMode?: DaemonServerMode; + /** + * How a remote command is sent; see `DaemonRpcMode`. The CLI sets it only from the connection + * `connect` recorded. An SDK caller that sets `checked` opts in explicitly: a remote that does not + * serve the checked route answers 404, which fails typed (`remote_checked_rpc_unsupported`) and + * is never resent. + */ daemonRpc?: DaemonRpcMode; tenant?: string; sessionIsolation?: SessionIsolationMode; diff --git a/packages/daemon-client/src/daemon-client-remote-resend-port.ts b/packages/daemon-client/src/daemon-client-remote-resend-port.ts new file mode 100644 index 0000000000..fb61db65c3 --- /dev/null +++ b/packages/daemon-client/src/daemon-client-remote-resend-port.ts @@ -0,0 +1,38 @@ +// The seam between the transport and the remote resend rules. Declared below both, so neither +// imports the other's types and the two stay readable in isolation. +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import type { DaemonCapability } from '@agent-device/daemon-contracts/daemon-resolution'; +import type { DaemonInfo } from './daemon-client-metadata.ts'; + +/** The `/health` facts the resend rules read; the transport's health answer has this shape. */ +export type RemoteResendHealth = { + reachable: boolean; + timedOut?: true; + instanceId?: string; + capabilities?: readonly DaemonCapability[]; + upstream?: { instanceId?: string; capabilities?: readonly DaemonCapability[] }; +}; + +/** The transport's side of one failed send: how to probe, resend and refuse for that request. */ +export type RemoteResendPort = { + info: DaemonInfo; + /** The command's budget and its end on the `performance.now()` clock, when it has one. */ + timeoutMs: number | undefined; + deadline: number | undefined; + signal: AbortSignal | undefined; + /** Sends the request once more, with `timeoutMs` as its budget. */ + resend(timeoutMs: number | undefined): Promise; + /** A live `/health` read that refuses a skewed protocol. */ + readHealth(probeTimeoutMs: number | undefined): Promise; + /** A `/health` read through the process cache, as the recovery loop probes. */ + probeHealth(probeTimeoutMs: number, signal: AbortSignal | undefined): Promise; + invalidateHealth(): Promise; + /** Throws the typed cancellation when the caller has aborted. */ + refuseIfAborted(): void; + /** The timeout refusal for a budget spent before anything was resent. */ + budgetSpent(): Error; + /** Whether a failure is a transport failure that makes the cached health stale. */ + isTransportFailure(error: unknown): boolean; + /** The `/health` probe's own time limit. */ + healthProbeTimeoutMs: number; +}; diff --git a/packages/daemon-client/src/daemon-client-remote-resend.ts b/packages/daemon-client/src/daemon-client-remote-resend.ts index d5518526bd..9f33de2741 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -2,43 +2,18 @@ // never dispatched: a typed pre-dispatch instance refusal on `/rpc` (ADR 0006), or, on the checked // route, this client's own proof that the connection never opened. Nothing a response says on the // checked route triggers a resend. Loaded only on those failures; the transport hands in what it -// owns, so this module never imports it back. +// owns as a `RemoteResendPort`, declared below both in `daemon-client-remote-resend-port.ts`. import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; -import type { DaemonInfo } from './daemon-client-metadata.ts'; import { CheckedRpcConnectFailure } from './daemon-client-checked-rpc.ts'; import { cacheRemoteDaemonHealth } from './daemon-client-remote-health-cache.ts'; import { recoverRemoteDaemonHealth } from './daemon-client-remote-health-recovery.ts'; -import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; +import type { RemoteResendPort } from './daemon-client-remote-resend-port.ts'; import { REMOTE_DAEMON_UNREACHABLE_HINT, remoteDaemonUnavailableError, } from './daemon-lifecycle-errors.ts'; -/** The transport's side of one failed send: how to probe, resend and refuse for that request. */ -export type RemoteResendPort = { - info: DaemonInfo; - /** The command's budget and its end on the `performance.now()` clock, when it has one. */ - timeoutMs: number | undefined; - deadline: number | undefined; - signal: AbortSignal | undefined; - /** Sends the request once more, with `timeoutMs` as its budget. */ - resend(timeoutMs: number | undefined): Promise; - /** A live `/health` read that refuses a skewed protocol. */ - readHealth(probeTimeoutMs: number | undefined): Promise; - /** A `/health` read through the process cache, as the recovery loop probes. */ - probeHealth(probeTimeoutMs: number, signal: AbortSignal | undefined): Promise; - invalidateHealth(): Promise; - /** Throws the typed cancellation when the caller has aborted. */ - refuseIfAborted(): void; - /** The timeout refusal for a budget spent before anything was resent. */ - budgetSpent(): Error; - /** Whether a failure is a transport failure that makes the cached health stale. */ - isTransportFailure(error: unknown): boolean; - /** The `/health` probe's own time limit. */ - healthProbeTimeoutMs: number; -}; - /** * Answers a failed checked call. Only a connection that never opened is acted on. A refused one fails * at once, as a refused `/health` probe does. A connect that timed out runs the `/health` recovery diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 465fa23f33..a6bff3dd3b 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -37,7 +37,7 @@ import { import { handleRequestTimeout } from './daemon-client-timeout.ts'; import { isRemoteDaemon, type DaemonInfo } from './daemon-client-metadata.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import type { RemoteResendPort } from './daemon-client-remote-resend.ts'; +import type { RemoteResendPort } from './daemon-client-remote-resend-port.ts'; import type { DaemonProbeVerdict, LoopbackConnectDenial, From 6305c29cd1e288a18b24494cda3cfd62f47ca325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 09:29:10 +0100 Subject: [PATCH 05/10] fix(daemon-client): bind checked RPC to the validated endpoint and probe live in recovery - The recorded checked mode holds only for the base URL connect validated; a command that names another endpoint goes health-first. - Checked connect recovery probes /health through the live reader, so a concurrent call that refills the cache never stands in for its probe. Co-Authored-By: Claude Opus 5.5 --- ...lient-checked-rpc-connect-recovery.test.ts | 24 ++++++++ .../src/daemon-client-remote-resend-port.ts | 2 +- .../src/daemon-client-transport.ts | 3 +- .../remote/src/remote-connection-state.ts | 12 ++++ src/__tests__/cli-run-transport.test.ts | 56 +++++++++++++++++++ src/cli.ts | 6 +- 6 files changed, 100 insertions(+), 3 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts index 209542eeee..0dcf58400e 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts @@ -173,3 +173,27 @@ test('an abort during checked connect recovery rejects with the typed cancellati await stopDriving(); } }); + +test('a concurrent call that refills the health cache during recovery never stands in for its probe', async () => { + const calls = firstCheckedConnectHangs(); + const stopDriving = driveFakeTime(); + // Lands after the connect timeout (3 s) and before the recovery probe (4 s). + const concurrent = new Promise((resolve) => { + setTimeout(() => { + void sendToDaemon(sessionList(), { authToken: 'remote-secret' }).then(() => resolve()); + }, 3_500); + }); + try { + const response = await sendToDaemon(sessionList('checked'), { authToken: 'remote-secret' }); + await concurrent; + + assert.equal(response.ok, true); + const routes = calls.map(({ method, path }) => `${method} ${path}`); + const resend = routes.lastIndexOf('POST /agent-device/rpc/checked'); + const probes = routes.slice(1, resend).filter((route) => route === 'GET /agent-device/health'); + // One probe is the concurrent call's own; the recovery made a live one of its own. + assert.equal(probes.length, 2, routes.join(', ')); + } finally { + await stopDriving(); + } +}); diff --git a/packages/daemon-client/src/daemon-client-remote-resend-port.ts b/packages/daemon-client/src/daemon-client-remote-resend-port.ts index fb61db65c3..ca3a534278 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend-port.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend-port.ts @@ -24,7 +24,7 @@ export type RemoteResendPort = { resend(timeoutMs: number | undefined): Promise; /** A live `/health` read that refuses a skewed protocol. */ readHealth(probeTimeoutMs: number | undefined): Promise; - /** A `/health` read through the process cache, as the recovery loop probes. */ + /** A live `/health` read for the recovery loop; never the process cache. */ probeHealth(probeTimeoutMs: number, signal: AbortSignal | undefined): Promise; invalidateHealth(): Promise; /** Throws the typed cancellation when the caller has aborted. */ diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index a6bff3dd3b..854fa92983 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -536,7 +536,8 @@ function remoteResendPort( resend: async (budgetMs) => await sendRequestWithTransport(info, req, statePaths, budgetMs, transport, options), readHealth: async (probeMs) => await readRemoteDaemonHealth(info, probeMs, options.signal), - probeHealth: async (probeMs, signal) => await cachedRemoteDaemonHealth(info, probeMs, signal), + // Live reads only: another call may refill the cache while recovery waits. + probeHealth: async (probeMs, signal) => await readRemoteDaemonHealth(info, probeMs, signal), invalidateHealth: async () => await invalidateRemoteDaemonHealth(info), refuseIfAborted: () => refuseAbortedRequest(options.signal, req.meta?.requestId), budgetSpent: () => requestTimeoutError(timeoutMs ?? 0, req.meta?.requestId, false), diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index b94d5a43d7..2580b674a3 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -394,6 +394,18 @@ export function writeRemoteConnectionState(options: { writeJsonFile(activeConnectionStatePath(options.stateDir), { session: options.state.session }); } +/** + * Checked RPC holds only for the base URL `connect` validated. A command that names another + * endpoint goes health-first, because nothing checked that endpoint serves the route. + */ +export function bindCheckedRpcToValidatedEndpoint( + flags: CliFlags, + defaults: Partial, +): CliFlags { + if (flags.daemonRpc !== 'checked' || flags.daemonBaseUrl === defaults.daemonBaseUrl) return flags; + return { ...flags, daemonRpc: undefined }; +} + export function buildRemoteConnectionDaemonState( flags: Pick< CliFlags, diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index 37e229b3e2..d078671065 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -84,3 +84,59 @@ test('a CLI run builds one transport, shared by the remote-materialization clien fs.rmSync(root, { recursive: true, force: true }); } }); + +test('checked RPC holds only for the base URL connect validated; another endpoint goes health-first', async () => { + const { root, home, project } = makeTempWorkspace(); + const stateDir = path.join(root, 'state'); + const remoteConfig = path.join(project, 'remote.json'); + fs.writeFileSync(remoteConfig, JSON.stringify({ daemonRpc: 'checked' }), 'utf8'); + const now = new Date().toISOString(); + writeRemoteConnectionState({ + stateDir, + state: { + version: 1, + session: 'checked-endpoint', + remoteConfigPath: remoteConfig, + remoteConfigHash: hashRemoteConfigFile(remoteConfig), + daemon: { baseUrl: 'http://127.0.0.1:7001', transport: 'http', rpc: 'checked' }, + tenant: 'tenant', + runId: 'run-checked', + connectedAt: now, + updatedAt: now, + }, + }); + const sent: Array<{ daemonBaseUrl?: string; daemonRpc?: string }> = []; + const transportForHost = vi.fn(() => async (req: Omit) => { + sent.push({ daemonBaseUrl: req.flags?.daemonBaseUrl, daemonRpc: req.flags?.daemonRpc }); + return { ok: true, data: { sessions: [] } } satisfies DaemonResponse; + }); + const host = { env: { HOME: home, PATH: process.env.PATH }, cwd: project }; + vi.spyOn(process, 'exit').mockImplementation((() => { + throw new ProcessExit(); + }) as never); + vi.spyOn(process.stdout, 'write').mockReturnValue(true); + vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const run = async (extra: string[]) => + await runCli( + [ + 'session', + 'list', + '--session', + 'checked-endpoint', + '--state-dir', + stateDir, + '--json', + ...extra, + ], + { sendToDaemon: vi.fn(), transportForHost }, + host, + ); + + await run([]); + await run(['--daemon-base-url', 'http://127.0.0.1:7002']); + + assert.deepEqual(sent, [ + { daemonBaseUrl: 'http://127.0.0.1:7001', daemonRpc: 'checked' }, + { daemonBaseUrl: 'http://127.0.0.1:7002', daemonRpc: undefined }, + ]); +}); diff --git a/src/cli.ts b/src/cli.ts index 4b2538374c..2ac7230983 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -59,6 +59,7 @@ import { claimRemoteConnectionDefaults, remoteSessionRequiredError, resolveRemoteConnectionDefaults, + bindCheckedRpcToValidatedEndpoint, type RemoteConnectionRequestMetadata, } from '@agent-device/remote/remote-connection-state'; import { resolveRemoteAuthForCli } from './cli/auth-session.ts'; @@ -425,7 +426,10 @@ async function resolveRunContextOrExit( remoteConfig: flags.remoteConfig, }); const effectiveFlags = connectionDefaults - ? mergeConnectionFlags(flags, connectionDefaults.flags, explicitFlagKeys) + ? bindCheckedRpcToValidatedEndpoint( + mergeConnectionFlags(flags, connectionDefaults.flags, explicitFlagKeys), + connectionDefaults.flags, + ) : flags; return { ...base, From b9971017f71b699851038c4590f786db0897d917 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 09:37:55 +0100 Subject: [PATCH 06/10] fix(daemon-client): record checked RPC only with the base URL connect probed connect now records the sanitized URL it probed (checkedRpcBaseUrl) in place of a bare mode, and checked RPC applies only when a command's effective endpoint, from its flags or the environment, sanitizes to that URL. A connection with no probed URL, such as a direct-provider one, never applies checked mode to a URL that arrives later. Equivalent spellings (host case, default port, trailing slash) keep checked mode through the existing URL sanitizer. Co-Authored-By: Claude Opus 5.5 --- .../daemon-client-checked-rpc.test.ts | 6 +- packages/daemon-client/src/index.ts | 8 ++- .../remote/src/remote-connection-state.ts | 32 ++++++---- src/__tests__/cli-run-transport.test.ts | 62 ++++++++++++++++++- src/cli.ts | 3 +- .../connection-runtime-checked-rpc.test.ts | 6 +- src/cli/commands/connection-runtime.ts | 3 +- src/cli/commands/connection.ts | 27 ++++++-- 8 files changed, 119 insertions(+), 28 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts index 15b912a96e..e86e9be5ee 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts @@ -269,11 +269,13 @@ test.each([ res.end(JSON.stringify({ ok: true, ...health })); }); try { + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; const verdict = assertRemoteServesCheckedRpc( - { daemonBaseUrl: `http://127.0.0.1:${await listenOnLoopback(server)}` }, + { daemonBaseUrl: baseUrl }, createTestHostEnvironment(), ); - if (served) await expect(verdict).resolves.toBeUndefined(); + // A served remote resolves to the base URL it probed: the one `connect` records. + if (served) await expect(verdict).resolves.toBe(baseUrl); else await expect(verdict).rejects.toMatchObject({ details: { reason: 'remote_checked_rpc_unsupported', dispatched: 'no' }, diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 94f5727f60..3f4fe796c4 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -467,12 +467,13 @@ export async function resolveLocalDaemonCodeIdentity(): Promise & { daemonAuthToken?: string }, host: HostEnvironment, -): Promise { +): Promise { const [{ resolveClientSettings }, { assertHealthServesCheckedRpc }] = await Promise.all([ import('./daemon-client-lifecycle.ts'), import('./daemon-client-checked-rpc.ts'), @@ -487,13 +488,14 @@ export async function assertRemoteServesCheckedRpc( flags.daemonAuthToken, host, ); - if (!settings.remoteBaseUrl) return; + if (!settings.remoteBaseUrl) return undefined; const info: DaemonInfo = { token: settings.remoteAuthToken ?? '', pid: 0, baseUrl: settings.remoteBaseUrl, }; assertHealthServesCheckedRpc(await readRemoteDaemonHealth(info), info); + return settings.remoteBaseUrl; } /** The managed local HTTP daemon `agent-device proxy` forwards to, started if none is usable. */ diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index 2580b674a3..dad17ce0cd 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -41,8 +41,8 @@ export type RemoteConnectionState = { baseUrl?: string; transport?: CliFlags['daemonTransport']; serverMode?: CliFlags['daemonServerMode']; - /** Set only by `connect`, after every link of the remote advertised `checked-rpc`. */ - rpc?: 'checked'; + /** The sanitized URL `connect` probed and found serving checked RPC on every link. */ + checkedRpcBaseUrl?: string; }; tenant: string; runId: string; @@ -224,6 +224,8 @@ type RemoteConnectionDefaults = { connection?: RemoteConnectionRequestMetadata; /** Set only by {@link claimRemoteConnectionDefaults}: the record it claimed, or `null` for none. */ claimed?: RemoteConnectionState | null; + /** The endpoint `connect` validated for checked RPC, read from the record alone. */ + checkedRpcBaseUrl?: string; }; const REMOTE_CONNECTION_STATE_REASONS = { @@ -394,29 +396,34 @@ export function writeRemoteConnectionState(options: { writeJsonFile(activeConnectionStatePath(options.stateDir), { session: options.state.session }); } -/** - * Checked RPC holds only for the base URL `connect` validated. A command that names another - * endpoint goes health-first, because nothing checked that endpoint serves the route. - */ +/** Checked RPC holds only for the recorded URL `connect` probed; any other endpoint goes health-first. */ export function bindCheckedRpcToValidatedEndpoint( flags: CliFlags, - defaults: Partial, + checkedRpcBaseUrl: string | undefined, + env: Readonly>, ): CliFlags { - if (flags.daemonRpc !== 'checked' || flags.daemonBaseUrl === defaults.daemonBaseUrl) return flags; + if (flags.daemonRpc !== 'checked') return flags; + try { + const effective = sanitizeDaemonBaseUrl( + flags.daemonBaseUrl ?? env.AGENT_DEVICE_DAEMON_BASE_URL, + ); + if (effective !== undefined && effective === checkedRpcBaseUrl) return flags; + } catch { + // An unparsable endpoint is refused later by the client's own base URL validation. + } return { ...flags, daemonRpc: undefined }; } export function buildRemoteConnectionDaemonState( flags: Pick< CliFlags, - 'daemonBaseUrl' | 'daemonAuthToken' | 'daemonTransport' | 'daemonServerMode' | 'daemonRpc' + 'daemonBaseUrl' | 'daemonAuthToken' | 'daemonTransport' | 'daemonServerMode' >, ): RemoteConnectionState['daemon'] { return { baseUrl: sanitizeDaemonBaseUrl(flags.daemonBaseUrl), transport: flags.daemonTransport, serverMode: flags.daemonServerMode, - ...(flags.daemonRpc === 'checked' ? { rpc: 'checked' as const } : {}), }; } @@ -547,9 +554,11 @@ function remoteConnectionDefaults( } const profile = resolveConnectionProfile(state, options); const leaseScope = leaseScopeFromOptions(state); + const checkedRpcBaseUrl = state.daemon?.checkedRpcBaseUrl; return { runtime: state.runtime, connection: leaseScopeToConnectionMetadata(leaseScope), + ...(checkedRpcBaseUrl ? { checkedRpcBaseUrl } : {}), flags: { ...profile, remoteConfig: state.remoteConfigPath, @@ -561,8 +570,7 @@ function remoteConnectionDefaults( daemonAuthToken: profile.daemonAuthToken, daemonTransport: state.daemon?.transport ?? profile.daemonTransport, daemonServerMode: state.daemon?.serverMode ?? profile.daemonServerMode, - // Only the mode `connect` checked; the profile's own value is never read here. - daemonRpc: state.daemon?.rpc, + daemonRpc: checkedRpcBaseUrl ? 'checked' : undefined, ...leaseScopeToCommandFlags(leaseScope), sessionIsolation: 'tenant', session: state.session, diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index d078671065..62cbda8b98 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -9,6 +9,9 @@ import { import { runCli } from '../cli.ts'; import type { DaemonRequest, DaemonResponse } from '@agent-device/daemon-client'; import { makeTempWorkspace } from '@agent-device/test-kit'; +import type { RemoteConnectionState } from '@agent-device/remote/remote-connection-state'; + +type RemoteConnectionDaemon = NonNullable; afterEach(() => { vi.restoreAllMocks(); @@ -98,7 +101,11 @@ test('checked RPC holds only for the base URL connect validated; another endpoin session: 'checked-endpoint', remoteConfigPath: remoteConfig, remoteConfigHash: hashRemoteConfigFile(remoteConfig), - daemon: { baseUrl: 'http://127.0.0.1:7001', transport: 'http', rpc: 'checked' }, + daemon: { + baseUrl: 'http://127.0.0.1:7001', + transport: 'http', + checkedRpcBaseUrl: 'http://127.0.0.1:7001', + }, tenant: 'tenant', runId: 'run-checked', connectedAt: now, @@ -134,9 +141,62 @@ test('checked RPC holds only for the base URL connect validated; another endpoin await run([]); await run(['--daemon-base-url', 'http://127.0.0.1:7002']); + // The same endpoint, spelled with a trailing slash, is still the validated one. + await run(['--daemon-base-url', 'http://127.0.0.1:7001/']); assert.deepEqual(sent, [ { daemonBaseUrl: 'http://127.0.0.1:7001', daemonRpc: 'checked' }, { daemonBaseUrl: 'http://127.0.0.1:7002', daemonRpc: undefined }, + { daemonBaseUrl: 'http://127.0.0.1:7001/', daemonRpc: 'checked' }, ]); }); + +test('a connection that recorded checked RPC without a probed endpoint never applies it to a later URL', async () => { + const { root, home, project } = makeTempWorkspace(); + const stateDir = path.join(root, 'state'); + const remoteConfig = path.join(project, 'remote.json'); + fs.writeFileSync(remoteConfig, JSON.stringify({ daemonRpc: 'checked' }), 'utf8'); + const now = new Date().toISOString(); + // A direct-provider connection carries checked mode, but no daemon URL was probed or recorded. + writeRemoteConnectionState({ + stateDir, + state: { + version: 1, + session: 'checked-provider', + remoteConfigPath: remoteConfig, + remoteConfigHash: hashRemoteConfigFile(remoteConfig), + daemon: { transport: 'http', rpc: 'checked' } as RemoteConnectionDaemon, + tenant: 'tenant', + runId: 'run-provider', + connectedAt: now, + updatedAt: now, + }, + }); + const sent: Array<{ daemonRpc?: string }> = []; + const transportForHost = vi.fn(() => async (req: Omit) => { + sent.push({ daemonRpc: req.flags?.daemonRpc }); + return { ok: true, data: { sessions: [] } } satisfies DaemonResponse; + }); + // The endpoint arrives later, through the environment. + const host = { + env: { + HOME: home, + PATH: process.env.PATH, + AGENT_DEVICE_DAEMON_BASE_URL: 'http://127.0.0.1:7003', + }, + cwd: project, + }; + vi.spyOn(process, 'exit').mockImplementation((() => { + throw new ProcessExit(); + }) as never); + vi.spyOn(process.stdout, 'write').mockReturnValue(true); + vi.spyOn(process.stderr, 'write').mockReturnValue(true); + + await runCli( + ['session', 'list', '--session', 'checked-provider', '--state-dir', stateDir, '--json'], + { sendToDaemon: vi.fn(), transportForHost }, + host, + ); + + assert.deepEqual(sent, [{ daemonRpc: undefined }]); +}); diff --git a/src/cli.ts b/src/cli.ts index 2ac7230983..5e6640ed63 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -428,7 +428,8 @@ async function resolveRunContextOrExit( const effectiveFlags = connectionDefaults ? bindCheckedRpcToValidatedEndpoint( mergeConnectionFlags(flags, connectionDefaults.flags, explicitFlagKeys), - connectionDefaults.flags, + connectionDefaults.checkedRpcBaseUrl, + base.host.env, ) : flags; return { diff --git a/src/cli/commands/connection-runtime-checked-rpc.test.ts b/src/cli/commands/connection-runtime-checked-rpc.test.ts index 00b418e43d..b49bbce16c 100644 --- a/src/cli/commands/connection-runtime-checked-rpc.test.ts +++ b/src/cli/commands/connection-runtime-checked-rpc.test.ts @@ -23,7 +23,11 @@ function checkedConnection() { remoteConfigPath, tenant: 'tenant-a', runId: 'run-a', - daemon: { baseUrl: 'http://127.0.0.1:9', transport: 'http', rpc: 'checked' }, + daemon: { + baseUrl: 'http://127.0.0.1:9', + transport: 'http', + checkedRpcBaseUrl: 'http://127.0.0.1:9', + }, leaseId: 'lease-1', leaseBackend: 'android-instance', platform: 'android', diff --git a/src/cli/commands/connection-runtime.ts b/src/cli/commands/connection-runtime.ts index c6ac8d528d..0adc0b5eb1 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -235,8 +235,7 @@ function createRemoteConnectionStateFromFlags( session, remoteConfigPath, remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), - // Only `connect` records checked RPC, after it checks the remote serves it. - daemon: buildRemoteConnectionDaemonState({ ...flags, daemonRpc: undefined }), + daemon: buildRemoteConnectionDaemonState(flags), tenant: flags.tenant, runId, leaseId: flags.leaseId, diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 2604675315..278eed5631 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -15,6 +15,7 @@ import { connectionPlatformMatchesSelection, narrowConnectionPlatform, writeRemoteConnectionState, + buildRemoteConnectionDaemonState, type RemoteConnectionState, type RemoteConnectionRequestMetadata, } from '@agent-device/remote/remote-connection-state'; @@ -83,7 +84,7 @@ export const connectCommand: ClientCommandHandler = async ({ host, ); const scope = readRequiredConnectScope(connectFlags, connectionMetadata); - await assertCheckedRpcServed(connectFlags, host); + const checkedRpcBaseUrl = await assertCheckedRpcServed(connectFlags, host); const context = resolveConnectContext({ stateDir, flags: connectFlags, @@ -105,6 +106,7 @@ export const connectCommand: ClientCommandHandler = async ({ connectionMetadata, context, remoteConfigPath: resolved.remoteConfigPath, + checkedRpcBaseUrl, }); writeRemoteConnectionState({ stateDir, state }); const previousLeaseNotice = await cleanupForcedPreviousConnection( @@ -127,12 +129,15 @@ export const connectCommand: ClientCommandHandler = async ({ /** * `daemonRpc: checked` skips the `/health` probe on later commands, so `connect` records it only - * when every link of the remote advertises `checked-rpc`. + * when every link of the remote advertises `checked-rpc`, and only for the base URL it probed. */ -async function assertCheckedRpcServed(flags: CliFlags, host: HostEnvironment): Promise { - if (flags.daemonRpc !== 'checked') return; +async function assertCheckedRpcServed( + flags: CliFlags, + host: HostEnvironment, +): Promise { + if (flags.daemonRpc !== 'checked') return undefined; const { assertRemoteServesCheckedRpc } = await import('@agent-device/daemon-client'); - await assertRemoteServesCheckedRpc(flags, host); + return await assertRemoteServesCheckedRpc(flags, host); } function assertConnectProviderUsage(provider: ConnectProvider | undefined, flags: CliFlags): void { @@ -190,6 +195,8 @@ function buildConnectedState(options: { connectionMetadata?: RemoteConnectionRequestMetadata; context: ConnectContext; remoteConfigPath: string; + /** The base URL `connect` probed and found serving checked RPC, when it was asked to. */ + checkedRpcBaseUrl?: string; }): RemoteConnectionState { const { flags, scope, connectionMetadata, context, remoteConfigPath } = options; const previous = shouldReusePreviousConnectionState(flags, context.previous) @@ -209,7 +216,15 @@ function buildConnectedState(options: { session: context.session, remoteConfigPath, remoteConfigHash: context.remoteConfigHash, - daemon: context.daemon, + daemon: options.checkedRpcBaseUrl + ? { + ...context.daemon, + // Sanitized exactly as `baseUrl` is, so later commands compare like with like. + checkedRpcBaseUrl: buildRemoteConnectionDaemonState({ + daemonBaseUrl: options.checkedRpcBaseUrl, + })?.baseUrl, + } + : context.daemon, tenant: scope.tenant, runId: scope.runId, ...leaseBinding, From 32c01e5cdcdc0a08db5e1f0204755c8e3b5e35d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 10:27:53 +0100 Subject: [PATCH 07/10] fix(daemon-client): own checked eligibility in daemon-client and keep the endpoint out of errors - daemon-client decides alone: checked only when the connection's recorded approval fingerprints this exact target (one route resolution, shared with the send), the request uploads nothing (requestUploadsArtifacts, shared with the artifact preparer), it is not a lease allocate or heartbeat, and the process holds no instance-pinned /health answer. The leasePrepared plumbing is gone. - connect records only the target fingerprint, refuses a checked profile with no base URL, and requires a proxy's upstream to be the daemon itself. - No error at the checked connect or send boundary, and no checked timeout diagnostic, names the endpoint. An unknown refusal value is recorded as 'unknown'. - The pre-send size refusal and recovery that finds protocol skew set dispatched: no. Co-Authored-By: Claude Opus 5.5 --- packages/command-surface/src/command-flags.ts | 1 + packages/contracts/src/cli-flags.ts | 2 + packages/contracts/src/client-connection.ts | 6 + packages/contracts/src/daemon-http.ts | 2 +- .../contracts/src/remote-config-fields.ts | 6 +- ...lient-checked-rpc-connect-recovery.test.ts | 54 +++++-- .../daemon-client-checked-rpc.test.ts | 140 +++++++++++++++++- .../src/__tests__/daemon-client-rpc.test.ts | 17 ++- .../__tests__/daemon-client-timeout.test.ts | 45 +++++- .../src/daemon-client-checked-rpc.ts | 80 ++++++---- .../src/daemon-client-lifecycle.ts | 51 +++++-- .../src/daemon-client-remote-health-cache.ts | 5 + .../src/daemon-client-remote-resend.ts | 13 +- .../daemon-client/src/daemon-client-rpc.ts | 2 + .../src/daemon-client-timeout.ts | 3 +- .../src/daemon-client-transport.ts | 7 +- packages/daemon-client/src/index.ts | 49 +++--- packages/remote/src/daemon-artifacts.ts | 15 ++ .../remote/src/remote-connection-state.ts | 34 ++--- src/__tests__/cli-run-transport.test.ts | 49 ++---- src/cli.ts | 8 +- .../commands/connection-lease-transaction.ts | 6 +- .../connection-runtime-checked-rpc.test.ts | 82 ---------- src/cli/commands/connection-runtime.ts | 4 - src/cli/commands/connection.ts | 21 +-- test/wire-compat/ledger.json | 6 +- website/docs/docs/remote-proxy.md | 7 +- 27 files changed, 441 insertions(+), 274 deletions(-) delete mode 100644 src/cli/commands/connection-runtime-checked-rpc.test.ts diff --git a/packages/command-surface/src/command-flags.ts b/packages/command-surface/src/command-flags.ts index 62fd6fe045..fe37dc9f5a 100644 --- a/packages/command-surface/src/command-flags.ts +++ b/packages/command-surface/src/command-flags.ts @@ -24,6 +24,7 @@ function buildFlags(options: InternalRequestOptions): CommandFlags { daemonTransport: options.daemonTransport, daemonServerMode: options.daemonServerMode, daemonRpc: options.daemonRpc, + daemonRpcTarget: options.daemonRpcTarget, ...leaseScopeToCommandFlags(leaseScope), provider: options.provider, providerSessionId: options.providerSessionId, diff --git a/packages/contracts/src/cli-flags.ts b/packages/contracts/src/cli-flags.ts index 62d352cb8a..2ef7c192c5 100644 --- a/packages/contracts/src/cli-flags.ts +++ b/packages/contracts/src/cli-flags.ts @@ -43,6 +43,8 @@ export type CliFlags = CloudProviderProfileFields & daemonServerMode?: DaemonServerMode; /** No CLI token: the connection `connect` recorded sets it. */ daemonRpc?: DaemonRpcMode; + /** No CLI token: the fingerprint of the checked target `connect` approved. */ + daemonRpcTarget?: string; proxyHost?: string; proxyPort?: number; publicOrigin?: string; diff --git a/packages/contracts/src/client-connection.ts b/packages/contracts/src/client-connection.ts index 96bb4a55c9..9fdd4f6585 100644 --- a/packages/contracts/src/client-connection.ts +++ b/packages/contracts/src/client-connection.ts @@ -110,6 +110,12 @@ export type AgentDeviceDaemonTransport = ( export type AgentDeviceClientConfig = RemoteConnectionProfileFields & CloudProviderProfileFields & { /** See `DaemonLifecycle`. */ + /** + * The fingerprint of the checked RPC target `connect` approved. The CLI sets it from the + * connection record, and checked RPC then applies only to that exact target. SDK callers leave it + * unset. + */ + daemonRpcTarget?: string; daemonLifecycle?: DaemonLifecycle; /** * Pins this client to one daemon instance: every request addresses that instance, authenticates diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index a92753be7a..9c849d8ccf 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -173,7 +173,7 @@ export type CheckedRpcProtocolRefusal = | typeof DAEMON_HTTP_REFUSALS.protocolMismatch; /** Why a checked RPC call failed. */ -const DAEMON_CHECKED_RPC_REASONS = { +export const DAEMON_CHECKED_RPC_REASONS = { // The checked RPC call named no RPC protocol. An intermediary that strips request headers causes // this. protocolMissing: { reason: 'remote_rpc_protocol_missing' }, diff --git a/packages/contracts/src/remote-config-fields.ts b/packages/contracts/src/remote-config-fields.ts index 269efa4b82..ba8bc2d19c 100644 --- a/packages/contracts/src/remote-config-fields.ts +++ b/packages/contracts/src/remote-config-fields.ts @@ -141,9 +141,9 @@ export type RemoteConnectionProfileFields = { daemonServerMode?: DaemonServerMode; /** * How a remote command is sent; see `DaemonRpcMode`. The CLI sets it only from the connection - * `connect` recorded. An SDK caller that sets `checked` opts in explicitly: a remote that does not - * serve the checked route answers 404, which fails typed (`remote_checked_rpc_unsupported`) and - * is never resent. + * `connect` recorded. An SDK caller that sets `checked` opts in explicitly: its standalone + * commands are not fenced to one daemon instance, and a remote that does not serve the checked + * route answers 404, which fails typed (`remote_checked_rpc_unsupported`) and is never resent. */ daemonRpc?: DaemonRpcMode; tenant?: string; diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts index 0dcf58400e..cdb1a0b67d 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts @@ -24,7 +24,7 @@ function fakeResponse(): EventEmitter { * The first checked POST hangs before its socket connects. `/health` answers with `healthStatus` * (and an instance ID, so a usable answer is cached); every other request answers. */ -function firstCheckedConnectHangs(healthStatus = 200): Call[] { +function firstCheckedConnectHangs(healthStatus = 200, healthProtocol = 3): Call[] { const calls: Call[] = []; vi.spyOn(http, 'request').mockImplementation((( options: { method?: string; path?: string }, @@ -53,7 +53,7 @@ function firstCheckedConnectHangs(healthStatus = 200): Call[] { ? JSON.stringify({ ok: true, service: 'agent-device-daemon', - rpcProtocolVersion: 3, + rpcProtocolVersion: healthProtocol, instanceId: 'daemon-1', }) : JSON.stringify({ @@ -96,6 +96,13 @@ function driveFakeTime(): () => Promise { const BASE_URL = 'http://remote-mac.example.test:7777/agent-device'; +let tokenSeq = 0; +/** A token of its own per test: the process health cache is keyed by it. */ +function freshToken(): string { + tokenSeq += 1; + return `remote-secret-${tokenSeq}`; +} + function sessionList(daemonRpc?: 'checked') { return { session: 'default', @@ -111,10 +118,11 @@ afterEach(() => { }); test('a checked connect timeout runs the /health loop, then sends exactly once more', async () => { + const authToken = freshToken(); const calls = firstCheckedConnectHangs(); const stopDriving = driveFakeTime(); try { - const response = await sendToDaemon(sessionList('checked'), { authToken: 'remote-secret' }); + const response = await sendToDaemon(sessionList('checked'), { authToken }); assert.equal(response.ok, true); assert.deepEqual( @@ -132,23 +140,20 @@ test('a checked connect timeout runs the /health loop, then sends exactly once m } }); -test('a cached /health answer never stands in for the recovery probe after a checked connect timeout', async () => { +test('a process holding an instance-pinned /health answer sends the next command fenced on /rpc, with no probe', async () => { const calls = firstCheckedConnectHangs(); const stopDriving = driveFakeTime(); + const authToken = freshToken(); try { - // A health-first command in this process caches a usable `/health` answer. - await sendToDaemon(sessionList(), { authToken: 'remote-secret' }); + // A health-first command in this process pins the daemon instance. + await sendToDaemon(sessionList(), { authToken }); calls.length = 0; - const response = await sendToDaemon(sessionList('checked'), { authToken: 'remote-secret' }); + const response = await sendToDaemon(sessionList('checked'), { authToken }); assert.equal(response.ok, true); assert.deepEqual( calls.map(({ method, path }) => `${method} ${path}`), - [ - 'POST /agent-device/rpc/checked', - 'GET /agent-device/health', - 'POST /agent-device/rpc/checked', - ], + ['POST /agent-device/rpc'], ); } finally { await stopDriving(); @@ -162,7 +167,7 @@ test('an abort during checked connect recovery rejects with the typed cancellati setTimeout(() => controller.abort(), 6_000); try { const outcome = await sendToDaemon(sessionList('checked'), { - authToken: 'remote-secret', + authToken: freshToken(), signal: controller.signal, }).then( () => undefined, @@ -175,16 +180,17 @@ test('an abort during checked connect recovery rejects with the typed cancellati }); test('a concurrent call that refills the health cache during recovery never stands in for its probe', async () => { + const authToken = freshToken(); const calls = firstCheckedConnectHangs(); const stopDriving = driveFakeTime(); // Lands after the connect timeout (3 s) and before the recovery probe (4 s). const concurrent = new Promise((resolve) => { setTimeout(() => { - void sendToDaemon(sessionList(), { authToken: 'remote-secret' }).then(() => resolve()); + void sendToDaemon(sessionList(), { authToken }).then(() => resolve()); }, 3_500); }); try { - const response = await sendToDaemon(sessionList('checked'), { authToken: 'remote-secret' }); + const response = await sendToDaemon(sessionList('checked'), { authToken }); await concurrent; assert.equal(response.ok, true); @@ -197,3 +203,21 @@ test('a concurrent call that refills the health cache during recovery never stan await stopDriving(); } }); + +test('recovery that finds protocol skew proves nothing left and names no endpoint', async () => { + firstCheckedConnectHangs(200, 99); + const stopDriving = driveFakeTime(); + try { + const outcome = await sendToDaemon(sessionList('checked'), { authToken: freshToken() }).then( + () => undefined, + (error: unknown) => error, + ); + assert.ok(outcome instanceof Error, `unexpected outcome: ${String(outcome)}`); + const details = (outcome as { details?: Record }).details; + assert.equal(details?.dispatched, 'no'); + assert.equal(details?.daemonBaseUrl, undefined); + assert.equal(details?.remoteRpcProtocolVersion, 99); + } finally { + await stopDriving(); + } +}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts index e86e9be5ee..cc25ae95c4 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts @@ -14,8 +14,14 @@ import { DAEMON_RPC_PROTOCOL_VERSION, } from '@agent-device/contracts/daemon-http'; import { assertRemoteServesCheckedRpc, sendToDaemon } from '../index.ts'; +import { checkedRpcTargetFingerprint } from '../daemon-client-lifecycle.ts'; -type Seen = { method: string; url: string; protocol: string | undefined }; +type Seen = { + method: string; + url: string; + protocol: string | undefined; + instance: string | undefined; +}; type Answer = { status?: number; headers?: Record; body: string }; const OK_ANSWER: Answer = { @@ -23,21 +29,28 @@ const OK_ANSWER: Answer = { }; /** A remote daemon that records every request and answers RPCs with `answer`. */ -async function remoteDaemon(answer: Answer = OK_ANSWER) { +async function remoteDaemon(answer: Answer = OK_ANSWER, pinned = false) { const seen: Seen[] = []; const server = http.createServer((req, res) => { const protocol = req.headers[DAEMON_HTTP_RPC_PROTOCOL_HEADER]; + const instance = req.headers['x-agent-device-instance']; seen.push({ method: req.method ?? '', url: req.url ?? '', protocol: typeof protocol === 'string' ? protocol : undefined, + instance: typeof instance === 'string' ? instance : undefined, }); req.resume(); req.on('end', () => { - if (req.url === '/health') { + if (req.url?.endsWith('/health')) { res.setHeader('content-type', 'application/json'); res.end( - JSON.stringify({ ok: true, service: 'agent-device-daemon', rpcProtocolVersion: 3 }), + JSON.stringify({ + ok: true, + service: 'agent-device-daemon', + rpcProtocolVersion: 3, + ...(pinned ? { instanceId: 'daemon-1' } : {}), + }), ); return; } @@ -257,10 +270,19 @@ test.each([ health: { service: 'agent-device-proxy', capabilities: ['checked-rpc'], - upstream: { capabilities: ['checked-rpc'] }, + upstream: { service: 'agent-device-daemon', capabilities: ['checked-rpc'] }, }, served: true, }, + { + name: 'a proxy whose upstream is another proxy', + health: { + service: 'agent-device-proxy', + capabilities: ['checked-rpc'], + upstream: { service: 'agent-device-proxy', capabilities: ['checked-rpc'] }, + }, + served: false, + }, ])( 'assertRemoteServesCheckedRpc accepts only when $name proves checked-rpc on every link', async ({ health, served }) => { @@ -274,8 +296,8 @@ test.each([ { daemonBaseUrl: baseUrl }, createTestHostEnvironment(), ); - // A served remote resolves to the base URL it probed: the one `connect` records. - if (served) await expect(verdict).resolves.toBe(baseUrl); + // A served remote resolves to the fingerprint of the exact checked target `connect` records. + if (served) await expect(verdict).resolves.toBe(checkedRpcTargetFingerprint(baseUrl)); else await expect(verdict).rejects.toMatchObject({ details: { reason: 'remote_checked_rpc_unsupported', dispatched: 'no' }, @@ -306,3 +328,107 @@ test('the connect probe is refused by remote trust validation before any request requests.mockRestore(); } }); + +test('checked RPC goes only to the exact target connect fingerprinted', async () => { + const daemon = await remoteDaemon(); + try { + const approved = `${daemon.baseUrl}/agent-device`; + const target = checkedRpcTargetFingerprint(approved); + const send = async (daemonBaseUrl: string) => { + daemon.seen.length = 0; + await sendToDaemon( + sessionList(daemonBaseUrl, { daemonRpc: 'checked', daemonRpcTarget: target }), + ); + return routes(daemon.seen); + }; + + expect(await send(approved)).toEqual(['POST /agent-device/rpc/checked']); + // The same prefix with a query `token`: the route resolves at the origin root, a target + // connect never probed, so the command goes health-first. + expect(await send(`${approved}?token=x`)).toEqual(['GET /health', 'POST /rpc']); + expect(await send(daemon.baseUrl)).toEqual(['GET /health', 'POST /rpc']); + } finally { + await daemon.close(); + } +}); + +test('a lease heartbeat goes health-first under checked RPC, and the next command reuses its fenced answer', async () => { + const daemon = await remoteDaemon(OK_ANSWER, true); + try { + await sendToDaemon({ + session: 'default', + command: 'lease_heartbeat', + positionals: [], + flags: { daemonBaseUrl: daemon.baseUrl, daemonRpc: 'checked', leaseId: 'lease-1' }, + }); + await sendToDaemon(sessionList(daemon.baseUrl, { daemonRpc: 'checked' })); + + expect(routes(daemon.seen)).toEqual(['GET /health', 'POST /rpc', 'POST /rpc']); + expect(daemon.seen[2]?.instance).toBe('daemon-1'); + } finally { + await daemon.close(); + } +}); + +test('no checked failure names the endpoint, and an unknown refusal value never reaches the error', async () => { + const errors: unknown[] = []; + const capture = async (run: () => Promise) => { + errors.push(await run().catch((error: unknown) => error)); + }; + for (const answer of [ + { status: 404, body: 'Not found' }, + { + status: 409, + headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'protocol-missing' }, + body: '{}', + }, + { + status: 409, + headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'http://10.0.0.1/secret-refusal' }, + body: '{}', + }, + { + status: 409, + headers: { [DAEMON_HTTP_REFUSAL_HEADER]: 'protocol-mismatch' }, + body: JSON.stringify({ + error: { + data: { + details: { service: 'agent-device-daemon', version: '9.0.0', rpcProtocolVersion: 99 }, + }, + }, + }), + }, + ]) { + const daemon = await remoteDaemon(answer); + try { + await capture(() => sendToDaemon(sessionList(daemon.baseUrl, { daemonRpc: 'checked' }))); + } finally { + await daemon.close(); + } + } + await capture(() => + assertRemoteServesCheckedRpc( + { daemonBaseUrl: 'http://127.0.0.1:9/' }, + createTestHostEnvironment(), + ), + ); + await capture(() => + assertRemoteServesCheckedRpc( + { daemonBaseUrl: 'ftp://user:pw@127.0.0.1/x' }, + createTestHostEnvironment(), + ), + ); + await capture(() => assertRemoteServesCheckedRpc({}, createTestHostEnvironment())); + + expect(errors).toHaveLength(7); + for (const error of errors) { + expect(error).toBeInstanceOf(Error); + expect(JSON.stringify((error as { details?: unknown }).details)).not.toMatch( + /127\.0\.0\.1|10\.0\.0\.1/, + ); + } + expect(errors[2]).toMatchObject({ details: { refusal: 'unknown' } }); + expect(errors[6]).toMatchObject({ + details: { reason: 'remote_checked_rpc_unsupported', dispatched: 'no' }, + }); +}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-rpc.test.ts b/packages/daemon-client/src/__tests__/daemon-client-rpc.test.ts index 243c3dd1ee..205ad83f96 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-rpc.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-rpc.test.ts @@ -2,7 +2,12 @@ import { createTestHostEnvironment } from '@agent-device/test-kit'; import assert from 'node:assert/strict'; import { test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { buildHttpRpcPayload, handleDaemonHttpResponseBody } from '../daemon-client-rpc.ts'; +import { DAEMON_REQUEST_MAX_BYTES } from '@agent-device/contracts/daemon-http'; +import { + buildHttpRpcPayload, + handleDaemonHttpResponseBody, + refuseOversizedDaemonRequest, +} from '../daemon-client-rpc.ts'; test('lease allocation transports an optional initial provider app', () => { const payload = buildHttpRpcPayload( @@ -219,3 +224,13 @@ test('lease allocation carries the device spec a proxy backend picks by', () => physical: true, }); }); + +test('the pre-send size refusal proves the request never left', () => { + assert.throws( + () => refuseOversizedDaemonRequest('x'.repeat(DAEMON_REQUEST_MAX_BYTES + 1), 'req-big'), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'daemon_request_too_large' && + error.details?.dispatched === 'no', + ); +}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-timeout.test.ts b/packages/daemon-client/src/__tests__/daemon-client-timeout.test.ts index fe3395ee1d..3fbbdc43f4 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-timeout.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-timeout.test.ts @@ -3,9 +3,22 @@ // production seam, where the liveness-gated recovery is decided; these assertions only fix wording. import assert from 'node:assert/strict'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { resolveRequestTimeoutHint } from '../daemon-client-timeout.ts'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +import { handleRequestTimeout, resolveRequestTimeoutHint } from '../daemon-client-timeout.ts'; + +const { emitted } = vi.hoisted(() => ({ emitted: [] as Array> })); +vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + emitDiagnostic: (event: Parameters[0]) => { + emitted.push({ phase: event.phase, ...(event.data as Record) }); + }, + }; +}); test('request timeout hint names an Apple runner only on a declared Apple platform', () => { // The hint used to derive its Apple claim partly from a host-wide `pkill` sweep that counted @@ -237,3 +250,31 @@ test('a timed-out record stop on a surviving daemon names the retry that returns 'Verify the remote daemon URL, auth token, and remote host logs.', ); }); + +test('a checked request timeout keeps the endpoint out of its diagnostic', async () => { + const timeout = async (checkedRpc: boolean) => { + emitted.length = 0; + await handleRequestTimeout({ + info: { + token: 't', + pid: 0, + baseUrl: 'https://user:secret@remote.example.test/private', + ...(checkedRpc ? { checkedRpc: true as const } : {}), + }, + statePaths: resolveDaemonPaths(mkdtempForTestSync('checked-timeout-')), + remote: true, + retireUnresponsive: false, + timeoutMs: 1_000, + requestId: 'req-1', + command: 'session', + platform: undefined, + requestSent: true, + responseStarted: true, + readRemoteHealth: async () => ({ reachable: false }), + }); + return emitted.find((event) => event.phase === 'daemon_request_timeout'); + }; + + assert.equal((await timeout(true))?.daemonBaseUrl, undefined); + assert.ok((await timeout(false))?.daemonBaseUrl, 'the legacy diagnostic keeps its endpoint'); +}); diff --git a/packages/daemon-client/src/daemon-client-checked-rpc.ts b/packages/daemon-client/src/daemon-client-checked-rpc.ts index 8e85f48b37..0440765c8c 100644 --- a/packages/daemon-client/src/daemon-client-checked-rpc.ts +++ b/packages/daemon-client/src/daemon-client-checked-rpc.ts @@ -3,7 +3,7 @@ // on those paths, so a command that gets its answer never pays for it. import type { IncomingMessage } from 'node:http'; import type { Socket } from 'node:net'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, discloseUnclassifiedDispatch } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { DAEMON_CHECKED_RPC_REASONS, @@ -12,7 +12,6 @@ import { DAEMON_HTTP_REFUSALS, } from '@agent-device/contracts/daemon-http'; import { DAEMON_TRANSPORT_REASONS } from './daemon-client-transport-reasons.ts'; -import type { DaemonInfo } from './daemon-client-metadata.ts'; import { incompatibleRemoteProtocolError } from './daemon-client-rpc.ts'; import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; import { remoteDaemonUnavailableError } from './daemon-lifecycle-errors.ts'; @@ -99,7 +98,6 @@ type CheckedRpcOutcome = { kind: 'answer'; body: string } | { kind: 'refused'; e */ export async function readCheckedRpcOutcome( res: IncomingMessage, - info: DaemonInfo, readLink: ReadHealthLink, ): Promise { const notFound = res.statusCode === 404; @@ -110,29 +108,23 @@ export async function readCheckedRpcOutcome( if (notFound) { return body !== undefined && isJsonRpcAnswer(body) ? { kind: 'answer', body } - : { kind: 'refused', error: checkedRpcUnsupportedError(info, 'unknown') }; + : { kind: 'refused', error: checkedRpcUnsupportedError('unknown') }; } return { kind: 'refused', - error: checkedRpcRefusalError( - String(res.headers[DAEMON_HTTP_REFUSAL_HEADER]), - body, - info, - readLink, - ), + error: checkedRpcRefusalError(String(res.headers[DAEMON_HTTP_REFUSAL_HEADER]), body, readLink), }; } function checkedRpcRefusalError( refusal: string, body: string | undefined, - info: DaemonInfo, readLink: ReadHealthLink, ): AppError { switch (refusal) { case DAEMON_HTTP_REFUSALS.protocolMismatch: case DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch: - return protocolMismatchError(refusal, body, info, readLink); + return protocolMismatchError(refusal, body, readLink); case DAEMON_HTTP_REFUSALS.protocolMissing: return new AppError( 'COMMAND_FAILED', @@ -140,17 +132,16 @@ function checkedRpcRefusalError( { reason: DAEMON_CHECKED_RPC_REASONS.protocolMissing.reason, dispatched: 'no', - daemonBaseUrl: info.baseUrl, hint: 'An ingress between this client and the remote removes the x-agent-device-rpc-protocol header. Fix that ingress, or remove daemonRpc from the connection profile.', }, ); default: // A refusal this build does not know proves nothing about dispatch: the reply is unreadable, - // and the transport discloses it like any reply it cannot read. It is never resent. + // and the transport discloses it like any reply it cannot read. It is never resent, and its + // value, which any intermediary can set, never reaches the error. return new AppError('COMMAND_FAILED', 'Invalid daemon RPC response', { reason: DAEMON_TRANSPORT_REASONS.replyInvalid.reason, - refusal, - daemonBaseUrl: info.baseUrl, + refusal: 'unknown', }); } } @@ -163,7 +154,6 @@ function checkedRpcRefusalError( function protocolMismatchError( refusal: string, body: string | undefined, - info: DaemonInfo, readLink: ReadHealthLink, ): AppError { const link = readLink(readRefusalDetails(body)); @@ -174,19 +164,19 @@ function protocolMismatchError( if (typeof link.rpcProtocolVersion !== 'number' || !Number.isInteger(link.rpcProtocolVersion)) { return new AppError('COMMAND_FAILED', 'Remote daemon RPC protocol is incompatible', { ...typed, - daemonBaseUrl: info.baseUrl, hint: 'Upgrade agent-device so this client and the remote speak the same RPC protocol.', }); } const upgrade = incompatibleRemoteProtocolError( - info.baseUrl ?? '', + '', { ...link, rpcProtocolVersion: link.rpcProtocolVersion }, refusal === DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch ? { service: 'agent-device-proxy' } : undefined, ); + const { daemonBaseUrl: _endpoint, ...upgradeDetails } = upgrade.details ?? {}; return new AppError(upgrade.code, upgrade.message, { - ...upgrade.details, + ...upgradeDetails, ...typed, service: link.service, version: link.version, @@ -195,28 +185,58 @@ function protocolMismatchError( } /** The typed failure when the remote does not serve checked RPC. A command is never resent. */ -function checkedRpcUnsupportedError(info: DaemonInfo, dispatched: 'no' | 'unknown'): AppError { +function checkedRpcUnsupportedError( + dispatched: 'no' | 'unknown', + hint = UNSUPPORTED_HINT, +): AppError { return new AppError('COMMAND_FAILED', 'The remote does not serve checked RPC', { reason: DAEMON_CHECKED_RPC_REASONS.routeUnsupported.reason, dispatched, - daemonBaseUrl: info.baseUrl, - hint: UNSUPPORTED_HINT, + hint, }); } +/** + * The same failure without the endpoint: no error raised at the checked connect or send boundary + * names the daemon URL, which can carry a credential. The code, message, typed reason, dispatch and + * validated upgrade details stay; the cause, which may quote the URL, does not. + */ +export function withoutEndpoint(error: unknown): unknown { + if (!(error instanceof AppError)) return error; + const { daemonBaseUrl: _endpoint, ...details } = error.details ?? {}; + return new AppError(error.code, error.message, details); +} + +/** A failure that proves nothing left, without the endpoint. */ +export function undispatchedWithoutEndpoint(error: unknown): unknown { + const scrubbed = withoutEndpoint(error); + return scrubbed instanceof AppError ? discloseUnclassifiedDispatch(scrubbed, 'no') : scrubbed; +} + /** * Refuses `daemonRpc: checked` at `connect` unless every link the command RPC crosses advertises the - * `checked-rpc` capability in `health`. A proxy proves its daemon only through `upstream`: one with no readable - * `upstream` is refused, never taken for a direct daemon. + * `checked-rpc` capability in `health`. A proxy proves its daemon only through `upstream`, which must + * identify as a daemon: no upstream, or another proxy behind it, is refused rather than guessed at. */ -export function assertHealthServesCheckedRpc(health: RemoteDaemonHealth, info: DaemonInfo): void { - if (!health.reachable) { - throw remoteDaemonUnavailableError({ daemonBaseUrl: info.baseUrl, attempts: 1 }); +export function assertHealthServesCheckedRpc(health: RemoteDaemonHealth): void { + if (!health.reachable) + throw remoteDaemonUnavailableError({ daemonBaseUrl: undefined, attempts: 1 }); + const proxied = health.service === 'agent-device-proxy'; + if (proxied && health.upstream?.service !== 'agent-device-daemon') { + throw checkedRpcUnsupportedError('no'); } - const links = health.service === 'agent-device-proxy' ? [health, health.upstream] : [health]; + const links = proxied ? [health, health.upstream] : [health]; if (links.every((link) => link?.capabilities?.includes(DAEMON_HTTP_CHECKED_RPC_CAPABILITY))) return; - throw checkedRpcUnsupportedError(info, 'no'); + throw checkedRpcUnsupportedError('no'); +} + +/** The refusal for a checked profile that resolves no daemon base URL at `connect`. */ +export function checkedRpcWithoutEndpointError(): AppError { + return checkedRpcUnsupportedError( + 'no', + 'daemonRpc checked needs a daemon base URL. Set daemonBaseUrl in the profile, or remove daemonRpc.', + ); } function readRefusalDetails(body: string | undefined): Record { diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index 93280f4628..c786cf5e78 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -24,7 +24,13 @@ import { type DaemonServerMode, type DaemonTransportPreference, } from '@agent-device/daemon-contracts/daemon-resolution'; +import { createHash } from 'node:crypto'; import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; +import { + buildDaemonHttpUrl, + DAEMON_HTTP_CHECKED_RPC_ROUTE, +} from '@agent-device/contracts/daemon-http'; +import { requestUploadsArtifacts } from '@agent-device/remote/daemon-artifacts'; import type { DaemonRpcMode } from '@agent-device/contracts/remote'; import { DAEMON_CLIENT_CONFIG_REASONS, @@ -137,7 +143,10 @@ export function resolveClientSettings( ownedStateDir, remoteBaseUrl: remote.remoteBaseUrl, remoteAuthToken: remote.authToken, - ...(remote.remoteBaseUrl && remote.daemonRpc === 'checked' && isStandaloneRemoteRequest(req) + ...(remote.remoteBaseUrl && + remote.daemonRpc === 'checked' && + approvesCheckedRpcTarget(req.flags?.daemonRpcTarget, remote.remoteBaseUrl) && + isStandaloneRemoteRequest(req) ? { remoteCheckedRpc: true as const } : {}), ...(daemonBinding ? { daemonBinding } : {}), @@ -145,18 +154,35 @@ export function resolveClientSettings( } /** - * Whether a remote request reaches the daemon with nothing before its command RPC. An install may - * upload an artifact, under lease beats, before its RPC, so it keeps the `/health` probe and the - * instance headers that pin that RPC to the daemon holding the upload. + * Whether a remote request reaches the daemon with nothing before its command RPC that must land on + * the same daemon. An upload, and a lease allocate or heartbeat, keep the `/health` probe, so their + * instance ID pins what follows; every caller, the SDK included, gets this rule. */ function isStandaloneRemoteRequest(req: Omit): boolean { return ( - req.command !== PUBLIC_COMMANDS.install && - req.command !== PUBLIC_COMMANDS.reinstall && - req.command !== INTERNAL_COMMANDS.installSource + !requestUploadsArtifacts(req) && + req.command !== INTERNAL_COMMANDS.leaseAllocate && + req.command !== INTERNAL_COMMANDS.leaseHeartbeat ); } +/** + * A fingerprint of the exact HTTP target a checked call is sent to, resolved by the same + * `buildDaemonHttpUrl` the transport sends with. `connect` records only this fingerprint. + */ +export function checkedRpcTargetFingerprint(remoteBaseUrl: string): string { + const target = buildDaemonHttpUrl(remoteBaseUrl, DAEMON_HTTP_CHECKED_RPC_ROUTE); + return createHash('sha256').update(target).digest('hex'); +} + +/** + * A connection's recorded approval holds only for the target it fingerprinted. An explicit SDK opt-in + * names no fingerprint and is taken as given. + */ +function approvesCheckedRpcTarget(recorded: string | undefined, remoteBaseUrl: string): boolean { + return recorded === undefined || recorded === checkedRpcTargetFingerprint(remoteBaseUrl); +} + /** * The local daemon a request would use, in the terms `ensureDaemon` takes, or `undefined` when the * request has no shared local daemon to ensure: a remote connection has none, and a one-shot replay @@ -318,9 +344,14 @@ async function ensureRemoteDaemon( pid: 0, baseUrl: settings.remoteBaseUrl, }; - // The checked route makes the server refuse what `/health` would have: no probe goes first. - if (settings.remoteCheckedRpc) - return { info: { ...remoteInfo, checkedRpc: true }, startedByClient: false }; + // The checked route makes the server refuse what `/health` would have: no probe goes first. A + // process that already holds an instance-pinned answer uses it instead, fenced and free. + if (settings.remoteCheckedRpc) { + const { holdsPinnedRemoteHealth } = await import('./daemon-client-remote-health-cache.ts'); + if (!holdsPinnedRemoteHealth(remoteInfo)) { + return { info: { ...remoteInfo, checkedRpc: true }, startedByClient: false }; + } + } // 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( 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..e0db5f40a7 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -33,6 +33,11 @@ export function cacheRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHe }; } +/** Whether this process holds an instance-pinned `/health` answer for this daemon identity. */ +export function holdsPinnedRemoteHealth(info: DaemonInfo): boolean { + return remoteHealthCache !== undefined && matchesRemoteIdentity(remoteHealthCache, info); +} + export function invalidateRemoteDaemonHealth(info: DaemonInfo): void { remoteHealthGeneration += 1; if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) { diff --git a/packages/daemon-client/src/daemon-client-remote-resend.ts b/packages/daemon-client/src/daemon-client-remote-resend.ts index 9f33de2741..1d2f7ac160 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -5,7 +5,10 @@ // owns as a `RemoteResendPort`, declared below both in `daemon-client-remote-resend-port.ts`. import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; -import { CheckedRpcConnectFailure } from './daemon-client-checked-rpc.ts'; +import { + CheckedRpcConnectFailure, + undispatchedWithoutEndpoint, +} from './daemon-client-checked-rpc.ts'; import { cacheRemoteDaemonHealth } from './daemon-client-remote-health-cache.ts'; import { recoverRemoteDaemonHealth } from './daemon-client-remote-health-recovery.ts'; import type { RemoteResendPort } from './daemon-client-remote-resend-port.ts'; @@ -32,7 +35,7 @@ export async function sendCheckedRpcAfterConnectFailure( await port.invalidateHealth(); if (!error.timedOut) { throw remoteDaemonUnavailableError({ - daemonBaseUrl: port.info.baseUrl, + daemonBaseUrl: undefined, attempts: 1, hint: REMOTE_DAEMON_UNREACHABLE_HINT, }); @@ -50,9 +53,11 @@ export async function sendCheckedRpcAfterConnectFailure( probe: port.probeHealth, }); } catch (recoveryError) { - // The caller's abort ends the recovery, and the caller hears its own typed cancellation. + // The caller's abort ends the recovery, and the caller hears its own typed cancellation. Every + // other recovery failure, protocol skew included, comes before the resend: nothing left, and + // the error names no endpoint. port.refuseIfAborted(); - throw recoveryError; + throw undispatchedWithoutEndpoint(recoveryError); } port.refuseIfAborted(); return await port.resend(port.timeoutMs); diff --git a/packages/daemon-client/src/daemon-client-rpc.ts b/packages/daemon-client/src/daemon-client-rpc.ts index fd6a7b3ee1..9fe85dc834 100644 --- a/packages/daemon-client/src/daemon-client-rpc.ts +++ b/packages/daemon-client/src/daemon-client-rpc.ts @@ -243,6 +243,7 @@ export function refuseOversizedDaemonRequest(payload: string, requestId: string maxBytes: DAEMON_REQUEST_MAX_BYTES, requestId, daemonRequestSent: false, + dispatched: 'no', hint: 'Split the replay suite or flow into smaller runs.', }); } @@ -293,6 +294,7 @@ export function incompatibleRemoteProtocolError( supportedRpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION, remoteRpcProtocolVersion: link.rpcProtocolVersion, upgradeSide, + dispatched: 'no', hint: 'Retry after the upgrade. This check runs before any command is sent.', }, ); diff --git a/packages/daemon-client/src/daemon-client-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index 142f26019b..70b78c238f 100644 --- a/packages/daemon-client/src/daemon-client-timeout.ts +++ b/packages/daemon-client/src/daemon-client-timeout.ts @@ -212,7 +212,8 @@ function emitTimeoutDiagnostic( daemonLivenessConnectDenied: liveness?.denial, remoteResponseStarted: remoteProof.responseStarted, remoteHealthAnswered: remoteProof.healthAnswered, - daemonBaseUrl: info.baseUrl, + // A checked request's endpoint stays out of diagnostics, which reach debug output and logs. + ...(info.checkedRpc ? {} : { daemonBaseUrl: info.baseUrl }), }, }); } diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 854fa92983..21fe9a0d7f 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -270,7 +270,10 @@ function daemonHealthEndpoint(info: DaemonInfo): string | null { return daemonHttpEndpoint(info, 'health'); } -function daemonHttpEndpoint(info: DaemonInfo, route: string): string | null { +function daemonHttpEndpoint( + info: DaemonInfo, + route: 'health' | 'rpc' | typeof DAEMON_HTTP_CHECKED_RPC_ROUTE, +): string | null { return info.baseUrl ? buildDaemonHttpUrl(info.baseUrl, route) : info.httpPort @@ -856,7 +859,7 @@ async function sendHttpRequest( }, (res) => { if (checkedRpc?.isCheckedRpcOutcomeResponse(res.statusCode, res.headers ?? {})) { - void checkedRpc.readCheckedRpcOutcome(res, info, readHealthLink).then((outcome) => { + void checkedRpc.readCheckedRpcOutcome(res, readHealthLink).then((outcome) => { if (timeoutHandle) clearTimeout(timeoutHandle); if (outcome.kind === 'answer') handleBody(outcome.body); else rejectOnce(outcome.error); diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 3f4fe796c4..5c5c140ac1 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -467,35 +467,40 @@ export async function resolveLocalDaemonCodeIdentity(): Promise & { daemonAuthToken?: string }, host: HostEnvironment, -): Promise { - const [{ resolveClientSettings }, { assertHealthServesCheckedRpc }] = await Promise.all([ +): Promise { + const [lifecycle, checked] = await Promise.all([ import('./daemon-client-lifecycle.ts'), import('./daemon-client-checked-rpc.ts'), ]); - const settings = resolveClientSettings( - { - session: 'default', - command: 'connect', - positionals: [], - flags: { daemonBaseUrl: flags.daemonBaseUrl }, - }, - flags.daemonAuthToken, - host, - ); - if (!settings.remoteBaseUrl) return undefined; - const info: DaemonInfo = { - token: settings.remoteAuthToken ?? '', - pid: 0, - baseUrl: settings.remoteBaseUrl, - }; - assertHealthServesCheckedRpc(await readRemoteDaemonHealth(info), info); - return settings.remoteBaseUrl; + try { + const settings = lifecycle.resolveClientSettings( + { + session: 'default', + command: 'connect', + positionals: [], + flags: { daemonBaseUrl: flags.daemonBaseUrl }, + }, + flags.daemonAuthToken, + host, + ); + if (!settings.remoteBaseUrl) throw checked.checkedRpcWithoutEndpointError(); + const info: DaemonInfo = { + token: settings.remoteAuthToken ?? '', + pid: 0, + baseUrl: settings.remoteBaseUrl, + }; + checked.assertHealthServesCheckedRpc(await readRemoteDaemonHealth(info)); + return lifecycle.checkedRpcTargetFingerprint(settings.remoteBaseUrl); + } catch (error) { + throw checked.withoutEndpoint(error); + } } /** The managed local HTTP daemon `agent-device proxy` forwards to, started if none is usable. */ diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index ab538a7c3c..8d6d546aed 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -44,6 +44,18 @@ export type PreparedRemoteRequest = { clientArtifactPaths?: Record; }; +/** The commands whose remote preparation can upload an artifact before their command RPC. */ +const ARTIFACT_UPLOAD_COMMANDS: ReadonlySet = new Set([ + 'install', + 'reinstall', + 'install_source', +]); + +/** Whether preparing this request for a remote daemon can upload an artifact before its RPC. */ +export function requestUploadsArtifacts(req: Pick): boolean { + return ARTIFACT_UPLOAD_COMMANDS.has(req.command); +} + export async function prepareRemoteRequestArtifacts( req: Omit, info: DaemonArtifactEndpoint, @@ -93,6 +105,9 @@ async function prepareRemoteRequestArtifactsWithinBudget( flags = prepareRemoteScriptOutput(req, flags, clientArtifactPaths, host); flags = applyRemoteArtifactCommand(req, positionals, flags, clientArtifactPaths, host); + if (!requestUploadsArtifacts(req)) { + return createPreparedRemoteRequest({ positionals, flags, installSource, clientArtifactPaths }); + } const remoteInstallSource = await prepareRemoteInstallSource( req, info, diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index dad17ce0cd..0dce7af979 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -41,8 +41,11 @@ export type RemoteConnectionState = { baseUrl?: string; transport?: CliFlags['daemonTransport']; serverMode?: CliFlags['daemonServerMode']; - /** The sanitized URL `connect` probed and found serving checked RPC on every link. */ - checkedRpcBaseUrl?: string; + /** + * The fingerprint of the checked target `connect` probed and found served on every link. Only + * the fingerprint is kept; checked RPC applies to that exact target alone. + */ + checkedRpcTarget?: string; }; tenant: string; runId: string; @@ -224,8 +227,6 @@ type RemoteConnectionDefaults = { connection?: RemoteConnectionRequestMetadata; /** Set only by {@link claimRemoteConnectionDefaults}: the record it claimed, or `null` for none. */ claimed?: RemoteConnectionState | null; - /** The endpoint `connect` validated for checked RPC, read from the record alone. */ - checkedRpcBaseUrl?: string; }; const REMOTE_CONNECTION_STATE_REASONS = { @@ -396,24 +397,6 @@ export function writeRemoteConnectionState(options: { writeJsonFile(activeConnectionStatePath(options.stateDir), { session: options.state.session }); } -/** Checked RPC holds only for the recorded URL `connect` probed; any other endpoint goes health-first. */ -export function bindCheckedRpcToValidatedEndpoint( - flags: CliFlags, - checkedRpcBaseUrl: string | undefined, - env: Readonly>, -): CliFlags { - if (flags.daemonRpc !== 'checked') return flags; - try { - const effective = sanitizeDaemonBaseUrl( - flags.daemonBaseUrl ?? env.AGENT_DEVICE_DAEMON_BASE_URL, - ); - if (effective !== undefined && effective === checkedRpcBaseUrl) return flags; - } catch { - // An unparsable endpoint is refused later by the client's own base URL validation. - } - return { ...flags, daemonRpc: undefined }; -} - export function buildRemoteConnectionDaemonState( flags: Pick< CliFlags, @@ -554,11 +537,10 @@ function remoteConnectionDefaults( } const profile = resolveConnectionProfile(state, options); const leaseScope = leaseScopeFromOptions(state); - const checkedRpcBaseUrl = state.daemon?.checkedRpcBaseUrl; + const checkedRpcTarget = state.daemon?.checkedRpcTarget; return { runtime: state.runtime, connection: leaseScopeToConnectionMetadata(leaseScope), - ...(checkedRpcBaseUrl ? { checkedRpcBaseUrl } : {}), flags: { ...profile, remoteConfig: state.remoteConfigPath, @@ -570,7 +552,9 @@ function remoteConnectionDefaults( daemonAuthToken: profile.daemonAuthToken, daemonTransport: state.daemon?.transport ?? profile.daemonTransport, daemonServerMode: state.daemon?.serverMode ?? profile.daemonServerMode, - daemonRpc: checkedRpcBaseUrl ? 'checked' : undefined, + // Only the approval `connect` recorded; daemon-client checks it names this exact target. + daemonRpc: checkedRpcTarget ? 'checked' : undefined, + daemonRpcTarget: checkedRpcTarget, ...leaseScopeToCommandFlags(leaseScope), sessionIsolation: 'tenant', session: state.session, diff --git a/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index 62cbda8b98..3f143f0506 100644 --- a/src/__tests__/cli-run-transport.test.ts +++ b/src/__tests__/cli-run-transport.test.ts @@ -88,7 +88,7 @@ test('a CLI run builds one transport, shared by the remote-materialization clien } }); -test('checked RPC holds only for the base URL connect validated; another endpoint goes health-first', async () => { +test('a connection that recorded checked RPC passes the approved target fingerprint with every request', async () => { const { root, home, project } = makeTempWorkspace(); const stateDir = path.join(root, 'state'); const remoteConfig = path.join(project, 'remote.json'); @@ -101,20 +101,16 @@ test('checked RPC holds only for the base URL connect validated; another endpoin session: 'checked-endpoint', remoteConfigPath: remoteConfig, remoteConfigHash: hashRemoteConfigFile(remoteConfig), - daemon: { - baseUrl: 'http://127.0.0.1:7001', - transport: 'http', - checkedRpcBaseUrl: 'http://127.0.0.1:7001', - }, + daemon: { baseUrl: 'http://127.0.0.1:7001', transport: 'http', checkedRpcTarget: 'fp-7001' }, tenant: 'tenant', runId: 'run-checked', connectedAt: now, updatedAt: now, }, }); - const sent: Array<{ daemonBaseUrl?: string; daemonRpc?: string }> = []; + const sent: Array<{ daemonRpc?: string; daemonRpcTarget?: string }> = []; const transportForHost = vi.fn(() => async (req: Omit) => { - sent.push({ daemonBaseUrl: req.flags?.daemonBaseUrl, daemonRpc: req.flags?.daemonRpc }); + sent.push({ daemonRpc: req.flags?.daemonRpc, daemonRpcTarget: req.flags?.daemonRpcTarget }); return { ok: true, data: { sessions: [] } } satisfies DaemonResponse; }); const host = { env: { HOME: home, PATH: process.env.PATH }, cwd: project }; @@ -123,32 +119,15 @@ test('checked RPC holds only for the base URL connect validated; another endpoin }) as never); vi.spyOn(process.stdout, 'write').mockReturnValue(true); vi.spyOn(process.stderr, 'write').mockReturnValue(true); - const run = async (extra: string[]) => - await runCli( - [ - 'session', - 'list', - '--session', - 'checked-endpoint', - '--state-dir', - stateDir, - '--json', - ...extra, - ], - { sendToDaemon: vi.fn(), transportForHost }, - host, - ); - await run([]); - await run(['--daemon-base-url', 'http://127.0.0.1:7002']); - // The same endpoint, spelled with a trailing slash, is still the validated one. - await run(['--daemon-base-url', 'http://127.0.0.1:7001/']); + await runCli( + ['session', 'list', '--session', 'checked-endpoint', '--state-dir', stateDir, '--json'], + { sendToDaemon: vi.fn(), transportForHost }, + host, + ); - assert.deepEqual(sent, [ - { daemonBaseUrl: 'http://127.0.0.1:7001', daemonRpc: 'checked' }, - { daemonBaseUrl: 'http://127.0.0.1:7002', daemonRpc: undefined }, - { daemonBaseUrl: 'http://127.0.0.1:7001/', daemonRpc: 'checked' }, - ]); + // daemon-client sends checked only when this fingerprint names the request's own target. + assert.deepEqual(sent, [{ daemonRpc: 'checked', daemonRpcTarget: 'fp-7001' }]); }); test('a connection that recorded checked RPC without a probed endpoint never applies it to a later URL', async () => { @@ -172,9 +151,9 @@ test('a connection that recorded checked RPC without a probed endpoint never app updatedAt: now, }, }); - const sent: Array<{ daemonRpc?: string }> = []; + const sent: Array<{ daemonRpc?: string; daemonRpcTarget?: string }> = []; const transportForHost = vi.fn(() => async (req: Omit) => { - sent.push({ daemonRpc: req.flags?.daemonRpc }); + sent.push({ daemonRpc: req.flags?.daemonRpc, daemonRpcTarget: req.flags?.daemonRpcTarget }); return { ok: true, data: { sessions: [] } } satisfies DaemonResponse; }); // The endpoint arrives later, through the environment. @@ -198,5 +177,5 @@ test('a connection that recorded checked RPC without a probed endpoint never app host, ); - assert.deepEqual(sent, [{ daemonRpc: undefined }]); + assert.deepEqual(sent, [{ daemonRpc: undefined, daemonRpcTarget: undefined }]); }); diff --git a/src/cli.ts b/src/cli.ts index 5e6640ed63..2299df1f1f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -59,7 +59,6 @@ import { claimRemoteConnectionDefaults, remoteSessionRequiredError, resolveRemoteConnectionDefaults, - bindCheckedRpcToValidatedEndpoint, type RemoteConnectionRequestMetadata, } from '@agent-device/remote/remote-connection-state'; import { resolveRemoteAuthForCli } from './cli/auth-session.ts'; @@ -426,11 +425,7 @@ async function resolveRunContextOrExit( remoteConfig: flags.remoteConfig, }); const effectiveFlags = connectionDefaults - ? bindCheckedRpcToValidatedEndpoint( - mergeConnectionFlags(flags, connectionDefaults.flags, explicitFlagKeys), - connectionDefaults.checkedRpcBaseUrl, - base.host.env, - ) + ? mergeConnectionFlags(flags, connectionDefaults.flags, explicitFlagKeys) : flags; return { ...base, @@ -549,6 +544,7 @@ function buildClientConfig(ctx: CliRunContext): AgentDeviceClientConfig { daemonTransport: currentFlags.daemonTransport, daemonServerMode: currentFlags.daemonServerMode, daemonRpc: currentFlags.daemonRpc, + daemonRpcTarget: currentFlags.daemonRpcTarget, tenant: currentFlags.tenant, sessionIsolation: currentFlags.sessionIsolation, runId: currentFlags.runId, diff --git a/src/cli/commands/connection-lease-transaction.ts b/src/cli/commands/connection-lease-transaction.ts index 77bb277cb6..626730bb81 100644 --- a/src/cli/commands/connection-lease-transaction.ts +++ b/src/cli/commands/connection-lease-transaction.ts @@ -121,7 +121,7 @@ export async function acquireConnectionLease(options: { nextFlags: CliFlags; positionals?: string[]; leaseLedger: LeaseLedger; -}): Promise<{ state: RemoteConnectionState; changed: boolean; leasePrepared: boolean }> { +}): Promise<{ state: RemoteConnectionState; changed: boolean }> { const { command, client, state, nextFlags, leaseLedger } = options; const deferredAppSelection = connectionProviderCapabilities( state.leaseProvider, @@ -151,9 +151,7 @@ export async function acquireConnectionLease(options: { platform: carriedConnectionPlatform(state.session, nextState, nextFlags), }; nextFlags.platform = nextState.platform; - // An allocate or heartbeat just ran on the remote, so the command that uses the lease must reach - // the same daemon: the caller sends it health-first, with the instance fences. - return { state: nextState, changed, leasePrepared: leasePolicy.shouldAllocate(command) }; + return { state: nextState, changed }; } /** diff --git a/src/cli/commands/connection-runtime-checked-rpc.test.ts b/src/cli/commands/connection-runtime-checked-rpc.test.ts deleted file mode 100644 index b49bbce16c..0000000000 --- a/src/cli/commands/connection-runtime-checked-rpc.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import { test } from 'vitest'; -import type { AgentDeviceClient } from '@agent-device/command-surface'; -import { createTestHostEnvironment } from '@agent-device/test-kit'; -import { - connectionWorkspace, - seedConnectionState, -} from '../../__tests__/remote-connection.fixtures.ts'; -import { materializeRemoteConnectionForCommand } from './connection-runtime.ts'; - -/** A connection `connect` recorded with checked RPC, holding one android lease. */ -function checkedConnection() { - const { stateDir, remoteConfigPath } = connectionWorkspace('agent-device-checked-lease-'); - fs.writeFileSync( - remoteConfigPath, - JSON.stringify({ daemonBaseUrl: 'http://127.0.0.1:9', daemonRpc: 'checked' }), - ); - seedConnectionState({ - stateDir, - state: { - session: 'checked', - remoteConfigPath, - tenant: 'tenant-a', - runId: 'run-a', - daemon: { - baseUrl: 'http://127.0.0.1:9', - transport: 'http', - checkedRpcBaseUrl: 'http://127.0.0.1:9', - }, - leaseId: 'lease-1', - leaseBackend: 'android-instance', - platform: 'android', - }, - }); - const heartbeats: unknown[] = []; - const client = { - leases: { - heartbeat: async (request: { leaseId: string }) => { - heartbeats.push(request); - return { - leaseId: request.leaseId, - tenantId: 'tenant-a', - runId: 'run-a', - backend: 'android-instance', - }; - }, - }, - } as unknown as AgentDeviceClient; - const materialize = (command: string) => - materializeRemoteConnectionForCommand({ - host: createTestHostEnvironment(), - command, - client, - flags: { - json: true, - help: false, - version: false, - stateDir, - session: 'checked', - remoteConfig: remoteConfigPath, - daemonBaseUrl: 'http://127.0.0.1:9', - daemonRpc: 'checked', - platform: 'android', - }, - }); - return { materialize, heartbeats }; -} - -test('a command that renews its lease first goes health-first, fenced to the same daemon', async () => { - const connection = checkedConnection(); - const materialized = await connection.materialize('snapshot'); - assert.equal(connection.heartbeats.length, 1); - assert.equal(materialized.flags.daemonRpc, undefined); -}); - -test('a command that prepares no lease keeps checked RPC', async () => { - const connection = checkedConnection(); - const materialized = await connection.materialize('session'); - assert.equal(connection.heartbeats.length, 0); - assert.equal(materialized.flags.daemonRpc, 'checked'); -}); diff --git a/src/cli/commands/connection-runtime.ts b/src/cli/commands/connection-runtime.ts index 0adc0b5eb1..0c687dc05c 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -97,7 +97,6 @@ export async function materializeRemoteConnectionForCommand(options: { let nextRuntime = selectCompatibleRuntime(state.runtime, nextFlags.platform) ?? options.runtime; let nextState = state; let changed = !existingState; - let leasePrepared = false; // Unknown creation evidence permits discard before binding, but only confirmed creation permits // rollback after a later failure. A committed session record takes over either lease. @@ -113,7 +112,6 @@ export async function materializeRemoteConnectionForCommand(options: { }); nextState = acquired.state; changed = changed || acquired.changed; - leasePrepared = acquired.leasePrepared; const runtimePreparation = await prepareRuntimeForCommand({ command, @@ -149,8 +147,6 @@ export async function materializeRemoteConnectionForCommand(options: { leaseBackend: nextState.leaseBackend, platform: nextState.platform ?? nextFlags.platform, target: nextState.target ?? nextFlags.target, - // A command that follows a lease allocate or heartbeat goes health-first, fenced to that daemon. - ...(leasePrepared ? { daemonRpc: undefined } : {}), }, runtime: nextRuntime, connection: buildRemoteConnectionRequestMetadata(nextState), diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 278eed5631..f7dfbdcb13 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -15,7 +15,6 @@ import { connectionPlatformMatchesSelection, narrowConnectionPlatform, writeRemoteConnectionState, - buildRemoteConnectionDaemonState, type RemoteConnectionState, type RemoteConnectionRequestMetadata, } from '@agent-device/remote/remote-connection-state'; @@ -84,7 +83,7 @@ export const connectCommand: ClientCommandHandler = async ({ host, ); const scope = readRequiredConnectScope(connectFlags, connectionMetadata); - const checkedRpcBaseUrl = await assertCheckedRpcServed(connectFlags, host); + const checkedRpcTarget = await assertCheckedRpcServed(connectFlags, host); const context = resolveConnectContext({ stateDir, flags: connectFlags, @@ -106,7 +105,7 @@ export const connectCommand: ClientCommandHandler = async ({ connectionMetadata, context, remoteConfigPath: resolved.remoteConfigPath, - checkedRpcBaseUrl, + checkedRpcTarget, }); writeRemoteConnectionState({ stateDir, state }); const previousLeaseNotice = await cleanupForcedPreviousConnection( @@ -129,7 +128,7 @@ export const connectCommand: ClientCommandHandler = async ({ /** * `daemonRpc: checked` skips the `/health` probe on later commands, so `connect` records it only - * when every link of the remote advertises `checked-rpc`, and only for the base URL it probed. + * when every link of the remote advertises `checked-rpc`, and only for the exact target it probed. */ async function assertCheckedRpcServed( flags: CliFlags, @@ -195,8 +194,8 @@ function buildConnectedState(options: { connectionMetadata?: RemoteConnectionRequestMetadata; context: ConnectContext; remoteConfigPath: string; - /** The base URL `connect` probed and found serving checked RPC, when it was asked to. */ - checkedRpcBaseUrl?: string; + /** The fingerprint of the checked target `connect` probed and found served, when asked to. */ + checkedRpcTarget?: string; }): RemoteConnectionState { const { flags, scope, connectionMetadata, context, remoteConfigPath } = options; const previous = shouldReusePreviousConnectionState(flags, context.previous) @@ -216,14 +215,8 @@ function buildConnectedState(options: { session: context.session, remoteConfigPath, remoteConfigHash: context.remoteConfigHash, - daemon: options.checkedRpcBaseUrl - ? { - ...context.daemon, - // Sanitized exactly as `baseUrl` is, so later commands compare like with like. - checkedRpcBaseUrl: buildRemoteConnectionDaemonState({ - daemonBaseUrl: options.checkedRpcBaseUrl, - })?.baseUrl, - } + daemon: options.checkedRpcTarget + ? { ...context.daemon, checkedRpcTarget: options.checkedRpcTarget } : context.daemon, tenant: scope.tenant, runId: scope.runId, diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 34e27621fa..72f5ee3432 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -260,9 +260,9 @@ "packages/daemon-client/src/daemon-client-checked-rpc.ts#isCheckedRpcOutcomeResponse": "sha256:75fb9f3444a3f8f4a762811ba7cbe02d92a39ed4e55483ea0cf7f029e5720a3e", "packages/daemon-client/src/daemon-client-checked-rpc.ts#CheckedRpcOutcome": "sha256:8aa7e58307417460bb54938f6bbbd340254e14ffbbaf2093272996909592f7be", "packages/daemon-client/src/daemon-client-checked-rpc.ts#ReadHealthLink": "sha256:86a9e6f1ebdaecca3ddaa16081c221321c01c684b70197961ecd71a3f54a464f", - "packages/daemon-client/src/daemon-client-checked-rpc.ts#readCheckedRpcOutcome": "sha256:95c2757f5ad08d488b2e373af65d22422f1953b40f079fd56c2f3e7655a6589d", - "packages/daemon-client/src/daemon-client-checked-rpc.ts#checkedRpcRefusalError": "sha256:30cbda341fa43b02e0121b0520c6a9dab6dd7aff2f99974ecbe49b7661dbad93", - "packages/daemon-client/src/daemon-client-checked-rpc.ts#protocolMismatchError": "sha256:e56950b0227f839d70db1af54887270dc571ed4ac3593cc37b158bef133b0912", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#readCheckedRpcOutcome": "sha256:476b6638b99bc2d9abd8a45e881c2d7bdffdb07e9fcfb484d7bd249d3af0af94", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#checkedRpcRefusalError": "sha256:eb18282eae11aea1a06d826afbc50afe123969504addaeb9cb7bb7001e089a9c", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#protocolMismatchError": "sha256:ae7a834278884658edf41c146f8b89adfa46021af0ffc2763c44ac94ea38be6a", "packages/daemon-client/src/daemon-client-checked-rpc.ts#readRefusalDetails": "sha256:41309e8fe57616e93848c93b36e8fb665a737f87d013243c6f6f1949e9f87215", "packages/daemon-client/src/daemon-client-checked-rpc.ts#isJsonRpcAnswer": "sha256:ecbf4226264fe3d3b551f89a075729df477e5c3b183dc2a761123c7229f4fe99" }, diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index ed4aa30c8e..6cd08d8422 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. +By default, remote clients read `/health` before sending a command and compare the daemon RPC protocol version. A connection can skip that probe for standalone commands; see [Send standalone commands in one round trip](#send-standalone-commands-in-one-round-trip). Keep client and proxy versions close: patch-level differences usually work, and incompatible RPC protocol versions fail before any command runs. ### Send standalone commands in one round trip @@ -374,10 +374,11 @@ Without the field, a command's dispatch makes two requests: `GET /health`, then } ``` -Only `connect` turns the field on, and only when the proxy, and the daemon behind it, list `checked-rpc` in `capabilities` on `/health`. Otherwise `connect` fails with `reason: "remote_checked_rpc_unsupported"` and `dispatched: "no"`. No flag or environment variable turns it on. +Only `connect` turns the field on, and only when the proxy, and the daemon behind it, list `checked-rpc` in `capabilities` on `/health`. The proxy's `upstream` must be the daemon itself, not another proxy. The connection then records a fingerprint of that exact target, and a command sent to any other base URL reads `/health` first. Otherwise `connect` fails with `reason: "remote_checked_rpc_unsupported"` and `dispatched: "no"`: when a link lacks the capability, or when the profile resolves no daemon base URL. An unreachable `/health` fails with `remote_daemon_unavailable`. No flag or environment variable turns it on. -- A command that allocates or renews its lease first, and `install` or `reinstall`, still read `/health` first. Their command must reach the daemon that holds the lease or the upload. +- Lease allocate and heartbeat calls, and `install` or `reinstall`, still read `/health` first, so what follows must reach the daemon that holds the lease or the upload. A later command in the same process reuses that answer and its instance fences on `/rpc`, with no extra round trip. - If the remote stops serving the route later, for example after a rollback, commands fail with `reason: "remote_checked_rpc_unsupported"` and `dispatched: "unknown"`. The client never resends them. Update the proxy and daemon, or remove `daemonRpc` and run `connect --force`. +- A 502, 503 or 504 answer to a checked request is not waited out or resent, because the command may have run. Only a connection that never opened is retried, after `/health` answers again. - Set it only when everything between you and the proxy forwards `/rpc/checked` and its `x-agent-device-rpc-protocol` header unchanged. `/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 From bc7c8064572a0cb843cd0a82a30f84d47dc2a05a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 10:41:54 +0100 Subject: [PATCH 08/10] fix(daemon-client): start checked connect recovery from the observed connect verdict The recovery loop now takes the observed verdict as its first failed probe: a refused connection is not transient and fails at once with remote_daemon_unavailable and dispatched: no, and only a connect that timed out enters the probe loop. Adds a regression test for a refused checked POST while /health answers 503. Co-Authored-By: Claude Opus 5.5 --- ...lient-checked-rpc-connect-recovery.test.ts | 63 +++++++++++++++++++ .../src/daemon-client-remote-resend.ts | 11 +--- 2 files changed, 66 insertions(+), 8 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts index cdb1a0b67d..ff5455d08d 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts @@ -76,6 +76,45 @@ function firstCheckedConnectHangs(healthStatus = 200, healthProtocol = 3): Call[ return calls; } +/** Every checked POST is refused before it connects, while `/health` answers 503. */ +function checkedConnectRefused(): Call[] { + const calls: Call[] = []; + vi.spyOn(http, 'request').mockImplementation((( + options: { method?: string; path?: string }, + callback: (res: EventEmitter) => void, + ) => { + const call = { + method: options.method ?? 'GET', + path: options.path ?? '', + at: performance.now(), + }; + calls.push(call); + const req = Object.assign(new EventEmitter(), { + write: () => {}, + destroy: () => {}, + end: () => { + if (call.method === 'POST') { + process.nextTick(() => + req.emit( + 'error', + Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }), + ), + ); + return; + } + const res = Object.assign(fakeResponse(), { statusCode: 503 }); + process.nextTick(() => { + callback(res); + res.emit('data', ''); + res.emit('end'); + }); + }, + }); + return req; + }) as unknown as typeof http.request); + return calls; +} + /** Advances fake time to the next timer once real work has gone quiet. Returns the stop. */ function driveFakeTime(): () => Promise { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); @@ -221,3 +260,27 @@ test('recovery that finds protocol skew proves nothing left and names no endpoin await stopDriving(); } }); + +test('a refused checked POST fails at once even while /health answers 503', async () => { + const calls = checkedConnectRefused(); + const stopDriving = driveFakeTime(); + try { + const started = performance.now(); + const outcome = await sendToDaemon(sessionList('checked'), { authToken: freshToken() }).then( + () => undefined, + (error: unknown) => error, + ); + const details = (outcome as { details?: Record }).details; + assert.equal(details?.reason, 'remote_daemon_unavailable'); + assert.equal(details?.dispatched, 'no'); + assert.equal(details?.attempts, 1); + // No probe loop: one refused POST, no /health retries, no time spent waiting. + assert.deepEqual( + calls.map(({ method }) => method), + ['POST'], + ); + assert.ok(performance.now() - started < 1_000); + } finally { + await stopDriving(); + } +}); diff --git a/packages/daemon-client/src/daemon-client-remote-resend.ts b/packages/daemon-client/src/daemon-client-remote-resend.ts index 1d2f7ac160..213dfb06ae 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -33,17 +33,12 @@ export async function sendCheckedRpcAfterConnectFailure( } // A cached `/health` answer predates this failure, so recovery decides on fresh probes only. await port.invalidateHealth(); - if (!error.timedOut) { - throw remoteDaemonUnavailableError({ - daemonBaseUrl: undefined, - attempts: 1, - hint: REMOTE_DAEMON_UNREACHABLE_HINT, - }); - } try { + // The observed connect verdict is the first failed probe: a refused connection is not transient + // and fails at once, and only a connect that timed out enters the probe loop. await recoverRemoteDaemonHealth({ info: port.info, - failedProbe: { reachable: false, timedOut: true }, + failedProbe: error.timedOut ? { reachable: false, timedOut: true } : { reachable: false }, recovery: port.timeoutMs === undefined ? undefined From 18e86fc898d7239fe988fcf9b58eed243a8bb872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 11:09:58 +0100 Subject: [PATCH 09/10] fix(daemon-client): stay health-first after a /health answer that cannot be pinned A process that read /health for an endpoint and got an answer with no complete instance ID, such as a lease call's against a rolled-back daemon, now sends later commands health-first instead of on the checked route; a pinned answer is still reused, fenced and free. Docs say a refused connection fails at once, and daemonLifecycle keeps its own doc. Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/client-connection.ts | 12 ++++---- .../daemon-client-checked-rpc.test.ts | 18 ++++++++++++ .../src/daemon-client-lifecycle.ts | 7 +++-- .../src/daemon-client-remote-health-cache.ts | 28 +++++++++++++++---- website/docs/docs/remote-proxy.md | 2 +- 5 files changed, 52 insertions(+), 15 deletions(-) diff --git a/packages/contracts/src/client-connection.ts b/packages/contracts/src/client-connection.ts index 9fdd4f6585..084009057a 100644 --- a/packages/contracts/src/client-connection.ts +++ b/packages/contracts/src/client-connection.ts @@ -110,12 +110,6 @@ export type AgentDeviceDaemonTransport = ( export type AgentDeviceClientConfig = RemoteConnectionProfileFields & CloudProviderProfileFields & { /** See `DaemonLifecycle`. */ - /** - * The fingerprint of the checked RPC target `connect` approved. The CLI sets it from the - * connection record, and checked RPC then applies only to that exact target. SDK callers leave it - * unset. - */ - daemonRpcTarget?: string; daemonLifecycle?: DaemonLifecycle; /** * Pins this client to one daemon instance: every request addresses that instance, authenticates @@ -123,6 +117,12 @@ export type AgentDeviceClientConfig = RemoteConnectionProfileFields & * {@link DaemonBinding}. */ daemonBinding?: DaemonBinding; + /** + * The fingerprint of the checked RPC target `connect` approved. The CLI sets it from the + * connection record, and checked RPC then applies only to that exact target. SDK callers leave it + * unset. + */ + daemonRpcTarget?: string; session?: string; lockPolicy?: DaemonLockPolicy; lockPlatform?: PlatformSelector; diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts index cc25ae95c4..9193d75fcb 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts @@ -432,3 +432,21 @@ test('no checked failure names the endpoint, and an unknown refusal value never details: { reason: 'remote_checked_rpc_unsupported', dispatched: 'no' }, }); }); + +test('after a lease call whose /health answer cannot be pinned, the next command stays health-first', async () => { + // A daemon that reports no instance ID: its answer is reachable but never cached. + const daemon = await remoteDaemon(OK_ANSWER, false); + try { + await sendToDaemon({ + session: 'default', + command: 'lease_heartbeat', + positionals: [], + flags: { daemonBaseUrl: daemon.baseUrl, daemonRpc: 'checked', leaseId: 'lease-1' }, + }); + await sendToDaemon(sessionList(daemon.baseUrl, { daemonRpc: 'checked' })); + + expect(routes(daemon.seen)).toEqual(['GET /health', 'POST /rpc', 'GET /health', 'POST /rpc']); + } finally { + await daemon.close(); + } +}); diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index c786cf5e78..f816e9734c 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -345,10 +345,11 @@ async function ensureRemoteDaemon( baseUrl: settings.remoteBaseUrl, }; // The checked route makes the server refuse what `/health` would have: no probe goes first. A - // process that already holds an instance-pinned answer uses it instead, fenced and free. + // process that already read `/health` here, a lease call's for one, stays health-first: a pinned + // answer is reused, fenced and free, and one that could not be pinned is read again. if (settings.remoteCheckedRpc) { - const { holdsPinnedRemoteHealth } = await import('./daemon-client-remote-health-cache.ts'); - if (!holdsPinnedRemoteHealth(remoteInfo)) { + const { hasReadRemoteHealth } = await import('./daemon-client-remote-health-cache.ts'); + if (!hasReadRemoteHealth(remoteInfo)) { return { info: { ...remoteInfo, checkedRpc: true }, startedByClient: false }; } } 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 e0db5f40a7..d177e72414 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -10,10 +10,15 @@ type RemoteHealthCacheEntry = { }; let remoteHealthCache: RemoteHealthCacheEntry | undefined; +/** The identity whose last reachable answer named no complete instance ID, so it could not be cached. */ +let unpinnedRemoteIdentity: Omit | undefined; /** Bumped by every invalidation, so a probe that started before one cannot cache its answer. */ let remoteHealthGeneration = 0; -function matchesRemoteIdentity(entry: RemoteHealthCacheEntry, info: DaemonInfo): boolean { +function matchesRemoteIdentity( + entry: Omit, + info: DaemonInfo, +): boolean { return entry.baseUrl === info.baseUrl && entry.token === info.token && entry.pid === info.pid; } @@ -33,9 +38,15 @@ export function cacheRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHe }; } -/** Whether this process holds an instance-pinned `/health` answer for this daemon identity. */ -export function holdsPinnedRemoteHealth(info: DaemonInfo): boolean { - return remoteHealthCache !== undefined && matchesRemoteIdentity(remoteHealthCache, info); +/** + * Whether this process already read `/health` for this daemon identity: it holds an instance-pinned + * answer, or its last reachable answer could not be pinned. Either way, what follows goes + * health-first: the pinned answer is reused, fenced and free; an unpinnable one is read again. + */ +export function hasReadRemoteHealth(info: DaemonInfo): boolean { + return [remoteHealthCache, unpinnedRemoteIdentity].some( + (entry) => entry !== undefined && matchesRemoteIdentity(entry, info), + ); } export function invalidateRemoteDaemonHealth(info: DaemonInfo): void { @@ -43,6 +54,9 @@ export function invalidateRemoteDaemonHealth(info: DaemonInfo): void { if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) { remoteHealthCache = undefined; } + if (unpinnedRemoteIdentity && matchesRemoteIdentity(unpinnedRemoteIdentity, info)) { + unpinnedRemoteIdentity = undefined; + } } /** @@ -58,6 +72,10 @@ export async function cachedRemoteHealth( } const generation = remoteHealthGeneration; const health = await probe(); - if (generation === remoteHealthGeneration) cacheRemoteDaemonHealth(info, health); + if (generation !== remoteHealthGeneration) return health; + cacheRemoteDaemonHealth(info, health); + if (health.reachable && !isCacheableRemoteHealth(health)) { + unpinnedRemoteIdentity = { baseUrl: info.baseUrl ?? '', token: info.token, pid: info.pid }; + } return health; } diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 6cd08d8422..31d00959a5 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -378,7 +378,7 @@ Only `connect` turns the field on, and only when the proxy, and the daemon behin - Lease allocate and heartbeat calls, and `install` or `reinstall`, still read `/health` first, so what follows must reach the daemon that holds the lease or the upload. A later command in the same process reuses that answer and its instance fences on `/rpc`, with no extra round trip. - If the remote stops serving the route later, for example after a rollback, commands fail with `reason: "remote_checked_rpc_unsupported"` and `dispatched: "unknown"`. The client never resends them. Update the proxy and daemon, or remove `daemonRpc` and run `connect --force`. -- A 502, 503 or 504 answer to a checked request is not waited out or resent, because the command may have run. Only a connection that never opened is retried, after `/health` answers again. +- A 502, 503 or 504 answer to a checked request is not waited out or resent, because the command may have run. Only a connection attempt that timed out before it opened is retried, after `/health` answers again; a refused connection fails at once. - Set it only when everything between you and the proxy forwards `/rpc/checked` and its `x-agent-device-rpc-protocol` header unchanged. `/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 From 5217b08462d4c8b2c657deac9a48a4bf644887e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 12:10:02 +0100 Subject: [PATCH 10/10] fix(daemon-client): record unpinnable /health answers wherever health is cached cacheRemoteDaemonHealth now remembers a reachable answer with no complete instance ID itself, so the stale-instance retry registers it as the ordinary probe does: after a retry onto a daemon that reports no instance ID, the next checked-eligible command stays health-first. The probe generation guard and complete-pin reuse are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../daemon-client-checked-rpc.test.ts | 65 +++++++++++++++++++ .../src/daemon-client-remote-health-cache.ts | 18 +++-- 2 files changed, 77 insertions(+), 6 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts index 9193d75fcb..11d760bf21 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts @@ -450,3 +450,68 @@ test('after a lease call whose /health answer cannot be pinned, the next command await daemon.close(); } }); + +test('after a stale-instance retry onto a daemon with no instance ID, the next open stays on /rpc', async () => { + // Starts as a daemon with an instance ID; then is replaced by an older one that reports none, + // rejects the old instance on /rpc, and does not serve the checked route. + let replaced = false; + const seen: string[] = []; + const server = http.createServer((req, res) => { + const instance = req.headers['x-agent-device-instance']; + seen.push(`${req.method} ${req.url}${typeof instance === 'string' ? ` @${instance}` : ''}`); + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + if (req.url === '/health') { + res.end( + JSON.stringify({ + ok: true, + service: 'agent-device-daemon', + rpcProtocolVersion: 3, + ...(replaced ? {} : { instanceId: 'old' }), + }), + ); + return; + } + if (req.url === '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/rpc/checked') { + res.statusCode = 404; + res.end('Not found'); + return; + } + if (replaced && instance === 'old') { + res.statusCode = 409; + res.setHeader('x-agent-device-instance-mismatch', 'true'); + res.end( + JSON.stringify({ jsonrpc: '2.0', id: 'x', error: { code: -32001, message: 'stale' } }), + ); + return; + } + res.end(OK_ANSWER.body); + }); + }); + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const leaseCall = (command: string) => + sendToDaemon({ + session: 'default', + command, + positionals: [], + flags: { daemonBaseUrl: baseUrl, daemonRpc: 'checked', leaseId: 'lease-1' }, + }); + try { + await leaseCall('lease_allocate'); + replaced = true; + await leaseCall('lease_heartbeat'); + seen.length = 0; + const opened = await sendToDaemon({ + session: 'default', + command: 'open', + positionals: ['Demo'], + flags: { daemonBaseUrl: baseUrl, daemonRpc: 'checked', leaseId: 'lease-1' }, + }); + + expect(opened).toMatchObject({ ok: true }); + expect(seen).toEqual(['GET /health', 'POST /rpc']); + } finally { + await closeLoopbackServer(server); + } +}); 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 d177e72414..31f5391062 100644 --- a/packages/daemon-client/src/daemon-client-remote-health-cache.ts +++ b/packages/daemon-client/src/daemon-client-remote-health-cache.ts @@ -28,8 +28,18 @@ function isCacheableRemoteHealth(health: RemoteDaemonHealth): boolean { ); } +/** + * Records a `/health` answer: a pinned one is cached for reuse, and a reachable one that names no + * complete instance ID is remembered as unpinnable, so a later checked-eligible call stays + * health-first. Every reader goes through here: the ordinary probe and the stale-instance retry. + */ export function cacheRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHealth): void { - if (!isCacheableRemoteHealth(health)) return; + if (!isCacheableRemoteHealth(health)) { + if (health.reachable) { + unpinnedRemoteIdentity = { baseUrl: info.baseUrl ?? '', token: info.token, pid: info.pid }; + } + return; + } remoteHealthCache = { baseUrl: info.baseUrl ?? '', token: info.token, @@ -72,10 +82,6 @@ export async function cachedRemoteHealth( } const generation = remoteHealthGeneration; const health = await probe(); - if (generation !== remoteHealthGeneration) return health; - cacheRemoteDaemonHealth(info, health); - if (health.reachable && !isCacheableRemoteHealth(health)) { - unpinnedRemoteIdentity = { baseUrl: info.baseUrl ?? '', token: info.token, pid: info.pid }; - } + if (generation === remoteHealthGeneration) cacheRemoteDaemonHealth(info, health); return health; }