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-surface/src/command-flags.ts b/packages/command-surface/src/command-flags.ts index fc2be6a74f..fe37dc9f5a 100644 --- a/packages/command-surface/src/command-flags.ts +++ b/packages/command-surface/src/command-flags.ts @@ -23,6 +23,8 @@ function buildFlags(options: InternalRequestOptions): CommandFlags { daemonBaseUrl: options.daemonBaseUrl, 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 018cbb0fbe..2ef7c192c5 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,10 @@ export type CliFlags = CloudProviderProfileFields & daemonAuthToken?: string; daemonTransport?: DaemonTransportPreference; 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..084009057a 100644 --- a/packages/contracts/src/client-connection.ts +++ b/packages/contracts/src/client-connection.ts @@ -117,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/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index f53d09aaf2..9c849d8ccf 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -173,13 +173,18 @@ 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' }, // 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..ba8bc2d19c 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 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]; + export type CloudProviderProfileFields = { providerApp?: string; providerOsVersion?: string; @@ -130,6 +139,13 @@ 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: 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; 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..ff5455d08d --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc-connect-recovery.test.ts @@ -0,0 +1,286 @@ +// 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 { isRequestCanceledError } from '@agent-device/kernel/errors'; +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. `/health` answers with `healthStatus` + * (and an instance ID, so a usable answer is cached); every other request answers. + */ +function firstCheckedConnectHangs(healthStatus = 200, healthProtocol = 3): 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(), + }; + 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 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: healthProtocol, + instanceId: 'daemon-1', + }) + : JSON.stringify({ + jsonrpc: '2.0', + id: 'x', + result: { ok: true, data: { sent: true } }, + }); + const res = Object.assign(fakeResponse(), { + statusCode: call.method === 'GET' ? healthStatus : 200, + }); + process.nextTick(() => { + callback(res); + res.emit('data', body); + res.emit('end'); + }); + }, + }); + return req; + }) as unknown as typeof http.request); + 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'] }); + 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; + }; +} + +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', + 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 authToken = freshToken(); + const calls = firstCheckedConnectHangs(); + const stopDriving = driveFakeTime(); + try { + 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', + ], + ); + // 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(); + } +}); + +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 pins the daemon instance. + await sendToDaemon(sessionList(), { authToken }); + calls.length = 0; + const response = await sendToDaemon(sessionList('checked'), { authToken }); + + assert.equal(response.ok, true); + assert.deepEqual( + calls.map(({ method, path }) => `${method} ${path}`), + ['POST /agent-device/rpc'], + ); + } 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: freshToken(), + signal: controller.signal, + }).then( + () => undefined, + (error: unknown) => error, + ); + assert.ok(isRequestCanceledError(outcome), `unexpected outcome: ${String(outcome)}`); + } finally { + await stopDriving(); + } +}); + +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 }).then(() => resolve()); + }, 3_500); + }); + try { + const response = await sendToDaemon(sessionList('checked'), { authToken }); + 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(); + } +}); + +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(); + } +}); + +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/__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..11d760bf21 --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-checked-rpc.test.ts @@ -0,0 +1,517 @@ +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +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, + 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; + instance: 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, 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?.endsWith('/health')) { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ + ok: true, + service: 'agent-device-daemon', + rpcProtocolVersion: 3, + ...(pinned ? { instanceId: 'daemon-1' } : {}), + }), + ); + 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, the typed reason and the refusing side', 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: { + 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 { + await daemon.close(); + } +}); + +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]: 'future-precondition' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 'test', error: { code: -32001, message: 'no' } }), + }); + try { + 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; + 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: { + 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: { + service: 'agent-device-proxy', + 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 }) => { + const server = http.createServer((_req, res) => { + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ ok: true, ...health })); + }); + try { + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + const verdict = assertRemoteServesCheckedRpc( + { daemonBaseUrl: baseUrl }, + createTestHostEnvironment(), + ); + // 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' }, + }); + } finally { + await closeLoopbackServer(server); + } + }, +); + +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(); + } +}); + +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' }, + }); +}); + +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(); + } +}); + +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/__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 new file mode 100644 index 0000000000..0440765c8c --- /dev/null +++ b/packages/daemon-client/src/daemon-client-checked-rpc.ts @@ -0,0 +1,285 @@ +// 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_CHECKED_RPC_CAPABILITY, + DAEMON_HTTP_REFUSAL_HEADER, + DAEMON_HTTP_REFUSALS, +} from '@agent-device/contracts/daemon-http'; +import { DAEMON_TRANSPORT_REASONS } from './daemon-client-transport-reasons.ts'; +import { incompatibleRemoteProtocolError } from './daemon-client-rpc.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. */ +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 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. + * 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, + readLink: ReadHealthLink, +): 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('unknown') }; + } + return { + kind: 'refused', + error: checkedRpcRefusalError(String(res.headers[DAEMON_HTTP_REFUSAL_HEADER]), body, readLink), + }; +} + +function checkedRpcRefusalError( + refusal: string, + body: string | undefined, + readLink: ReadHealthLink, +): AppError { + switch (refusal) { + case DAEMON_HTTP_REFUSALS.protocolMismatch: + case DAEMON_HTTP_REFUSALS.upstreamProtocolMismatch: + return protocolMismatchError(refusal, body, readLink); + case DAEMON_HTTP_REFUSALS.protocolMissing: + 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', + 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 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: 'unknown', + }); + } +} + +/** + * 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, + readLink: ReadHealthLink, +): AppError { + const link = readLink(readRefusalDetails(body)); + const typed = { + reason: DAEMON_CHECKED_RPC_REASONS.protocolMismatch.reason, + 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, + hint: 'Upgrade agent-device so this client and the remote speak the same RPC protocol.', + }); + } + const upgrade = incompatibleRemoteProtocolError( + '', + { ...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, { + ...upgradeDetails, + ...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. */ +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, + 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`, which must + * identify as a daemon: no upstream, or another proxy behind it, is refused rather than guessed at. + */ +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 = proxied ? [health, health.upstream] : [health]; + if (links.every((link) => link?.capabilities?.includes(DAEMON_HTTP_CHECKED_RPC_CAPABILITY))) + return; + 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 { + 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..f816e9734c 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -24,8 +24,18 @@ 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 { 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, + 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 +66,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 +143,46 @@ export function resolveClientSettings( ownedStateDir, remoteBaseUrl: remote.remoteBaseUrl, remoteAuthToken: remote.authToken, + ...(remote.remoteBaseUrl && + remote.daemonRpc === 'checked' && + approvesCheckedRpcTarget(req.flags?.daemonRpcTarget, remote.remoteBaseUrl) && + isStandaloneRemoteRequest(req) + ? { remoteCheckedRpc: true as const } + : {}), ...(daemonBinding ? { daemonBinding } : {}), }; } +/** + * 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 ( + !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 @@ -192,12 +243,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); + 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 +344,15 @@ async function ensureRemoteDaemon( pid: 0, baseUrl: settings.remoteBaseUrl, }; + // The checked route makes the server refuse what `/health` would have: no probe goes first. A + // 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 { hasReadRemoteHealth } = await import('./daemon-client-remote-health-cache.ts'); + if (!hasReadRemoteHealth(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( @@ -300,7 +368,8 @@ 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, + probe: async (probeMs, signal) => await cachedRemoteDaemonHealth(remoteInfo, probeMs, signal), }); } 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-health-cache.ts b/packages/daemon-client/src/daemon-client-remote-health-cache.ts index 72c1b10334..31f5391062 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; } @@ -23,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, @@ -33,11 +48,25 @@ export function cacheRemoteDaemonHealth(info: DaemonInfo, health: RemoteDaemonHe }; } +/** + * 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 { remoteHealthGeneration += 1; if (remoteHealthCache && matchesRemoteIdentity(remoteHealthCache, info)) { remoteHealthCache = undefined; } + if (unpinnedRemoteIdentity && matchesRemoteIdentity(unpinnedRemoteIdentity, info)) { + unpinnedRemoteIdentity = undefined; + } } /** 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-port.ts b/packages/daemon-client/src/daemon-client-remote-resend-port.ts new file mode 100644 index 0000000000..ca3a534278 --- /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 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. */ + 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 new file mode 100644 index 0000000000..213dfb06ae --- /dev/null +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -0,0 +1,102 @@ +// 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; the transport hands in what it +// 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, + 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'; +import { + REMOTE_DAEMON_UNREACHABLE_HINT, + remoteDaemonUnavailableError, +} from './daemon-lifecycle-errors.ts'; + +/** + * 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 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, + port: RemoteResendPort, +): Promise { + if (!(error instanceof CheckedRpcConnectFailure)) { + 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(); + 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: error.timedOut ? { reachable: false, timedOut: true } : { reachable: false }, + 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. Every + // other recovery failure, protocol skew included, comes before the resend: nothing left, and + // the error names no endpoint. + port.refuseIfAborted(); + throw undispatchedWithoutEndpoint(recoveryError); + } + port.refuseIfAborted(); + return await port.resend(port.timeoutMs); +} + +/** + * 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( + port: RemoteResendPort, + scriptPublicationId: string | undefined, +): Promise { + 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 }); + } + 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 (scriptPublicationId) assertScriptArtifactsCapability(info.capabilities); + try { + return await port.resend(remainingMs); + } catch (error) { + if (port.isTransportFailure(error)) await port.invalidateHealth(); + throw error; + } +} + +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 > port.healthProbeTimeoutMs) + ) + return remainingMs; + throw port.budgetSpent(); +} 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 397cea0767..21fe9a0d7f 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,8 @@ import { import { buildDaemonHttpAuthHeaders, buildDaemonHttpUrl, + DAEMON_HTTP_CHECKED_RPC_ROUTE, + DAEMON_HTTP_RPC_PROTOCOL_HEADER, DAEMON_HTTP_INSTANCE_HEADER, DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, DAEMON_INSTANCE_REASONS, @@ -36,6 +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-port.ts'; import type { DaemonProbeVerdict, LoopbackConnectDenial, @@ -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; }; /** @@ -266,7 +270,10 @@ function daemonHealthEndpoint(info: DaemonInfo): string | null { return daemonHttpEndpoint(info, 'health'); } -function daemonHttpEndpoint(info: DaemonInfo, route: 'health' | 'rpc'): 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 @@ -494,18 +501,18 @@ 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) { - if (info.baseUrl && isRemoteInstanceMismatch(error)) { - return await retryAfterRemoteInstanceMismatch( - info, - req, - statePaths, - timeoutMs, - deadline, - transport, - options, - ); + // Loaded only on these failures: the two remote resend rules live in one module. + 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); @@ -514,58 +521,32 @@ async function sendRequestWithFallback( } } -async function retryAfterRemoteInstanceMismatch( +/** 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, - 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, +): RemoteResendPort { + return { + info, 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); + signal: options.signal, + resend: async (budgetMs) => + await sendRequestWithTransport(info, req, statePaths, budgetMs, transport, options), + readHealth: async (probeMs) => await readRemoteDaemonHealth(info, probeMs, options.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), + isTransportFailure: isRemoteTransportFailure, + healthProbeTimeoutMs: REMOTE_DAEMON_HEALTHCHECK_TIMEOUT_MS, + }; } function isRemoteInstanceMismatch(error: unknown): boolean { @@ -814,7 +795,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 +809,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 +821,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 +858,16 @@ async function sendHttpRequest( headers, }, (res) => { - if (isRemoteInstanceMismatchResponse(res.statusCode, res.headers ?? {})) { + if (checkedRpc?.isCheckedRpcOutcomeResponse(res.statusCode, res.headers ?? {})) { + void checkedRpc.readCheckedRpcOutcome(res, readHealthLink).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 +951,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; }); diff --git a/packages/daemon-client/src/daemon-lifecycle-errors.ts b/packages/daemon-client/src/daemon-lifecycle-errors.ts index 867c87efd5..47da5c9018 100644 --- a/packages/daemon-client/src/daemon-lifecycle-errors.ts +++ b/packages/daemon-client/src/daemon-lifecycle-errors.ts @@ -128,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 0c94f60bc2..5c5c140ac1 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 { @@ -393,7 +397,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 +464,45 @@ export async function resolveLocalDaemonCodeIdentity(): Promise & { daemonAuthToken?: string }, + host: HostEnvironment, +): Promise { + const [lifecycle, checked] = await Promise.all([ + import('./daemon-client-lifecycle.ts'), + import('./daemon-client-checked-rpc.ts'), + ]); + 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. */ export async function ensureProxyUpstreamDaemon( options: ProxyUpstreamDaemonOptions, 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-config-schema.ts b/packages/remote/src/remote-config-schema.ts index 517a0931d2..eb8926bf36 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, @@ -113,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..0dce7af979 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -41,6 +41,11 @@ export type RemoteConnectionState = { baseUrl?: string; transport?: CliFlags['daemonTransport']; serverMode?: CliFlags['daemonServerMode']; + /** + * 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; @@ -532,6 +537,7 @@ function remoteConnectionDefaults( } const profile = resolveConnectionProfile(state, options); const leaseScope = leaseScopeFromOptions(state); + const checkedRpcTarget = state.daemon?.checkedRpcTarget; return { runtime: state.runtime, connection: leaseScopeToConnectionMetadata(leaseScope), @@ -546,6 +552,9 @@ function remoteConnectionDefaults( daemonAuthToken: profile.daemonAuthToken, daemonTransport: state.daemon?.transport ?? profile.daemonTransport, daemonServerMode: state.daemon?.serverMode ?? profile.daemonServerMode, + // 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/packages/remote/src/session-script-destination.ts b/packages/remote/src/session-script-destination.ts index 97f5c9b735..412623a227 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 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( info: RemoteEndpoint, @@ -36,18 +41,25 @@ 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 (info.checkedRpc && 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/src/__tests__/cli-run-transport.test.ts b/src/__tests__/cli-run-transport.test.ts index 37e229b3e2..3f143f0506 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(); @@ -84,3 +87,95 @@ test('a CLI run builds one transport, shared by the remote-materialization clien fs.rmSync(root, { recursive: true, force: true }); } }); + +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'); + 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', checkedRpcTarget: 'fp-7001' }, + tenant: 'tenant', + runId: 'run-checked', + connectedAt: now, + updatedAt: now, + }, + }); + const sent: Array<{ daemonRpc?: string; daemonRpcTarget?: string }> = []; + const transportForHost = vi.fn(() => async (req: Omit) => { + 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 }; + 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-endpoint', '--state-dir', stateDir, '--json'], + { sendToDaemon: vi.fn(), transportForHost }, + host, + ); + + // 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 () => { + 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; daemonRpcTarget?: string }> = []; + const transportForHost = vi.fn(() => async (req: Omit) => { + sent.push({ daemonRpc: req.flags?.daemonRpc, daemonRpcTarget: req.flags?.daemonRpcTarget }); + 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, daemonRpcTarget: undefined }]); +}); diff --git a/src/cli.ts b/src/cli.ts index b467d1b5c7..2299df1f1f 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({ @@ -538,6 +543,8 @@ function buildClientConfig(ctx: CliRunContext): AgentDeviceClientConfig { daemonAuthToken: currentFlags.daemonAuthToken, 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.ts b/src/cli/commands/connection.ts index 1dc4c60a47..f7dfbdcb13 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); + const checkedRpcTarget = await assertCheckedRpcServed(connectFlags, host); const context = resolveConnectContext({ stateDir, flags: connectFlags, @@ -104,6 +105,7 @@ export const connectCommand: ClientCommandHandler = async ({ connectionMetadata, context, remoteConfigPath: resolved.remoteConfigPath, + checkedRpcTarget, }); writeRemoteConnectionState({ stateDir, state }); const previousLeaseNotice = await cleanupForcedPreviousConnection( @@ -124,6 +126,19 @@ export const connectCommand: ClientCommandHandler = async ({ return true; }; +/** + * `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 exact target it probed. + */ +async function assertCheckedRpcServed( + flags: CliFlags, + host: HostEnvironment, +): Promise { + if (flags.daemonRpc !== 'checked') return undefined; + const { assertRemoteServesCheckedRpc } = await import('@agent-device/daemon-client'); + return await assertRemoteServesCheckedRpc(flags, host); +} + function assertConnectProviderUsage(provider: ConnectProvider | undefined, flags: CliFlags): void { if (!provider || !flags.remoteConfig) return; throw new AppError( @@ -179,6 +194,8 @@ function buildConnectedState(options: { connectionMetadata?: RemoteConnectionRequestMetadata; context: ConnectContext; remoteConfigPath: 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) @@ -198,7 +215,9 @@ function buildConnectedState(options: { session: context.session, remoteConfigPath, remoteConfigHash: context.remoteConfigHash, - daemon: context.daemon, + daemon: options.checkedRpcTarget + ? { ...context.daemon, checkedRpcTarget: options.checkedRpcTarget } + : context.daemon, tenant: scope.tenant, runId: scope.runId, ...leaseBinding, @@ -320,18 +339,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 29bfc82186..72f5ee3432 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -248,15 +248,23 @@ "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: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", "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:8aa7e58307417460bb54938f6bbbd340254e14ffbbaf2093272996909592f7be", + "packages/daemon-client/src/daemon-client-checked-rpc.ts#ReadHealthLink": "sha256:86a9e6f1ebdaecca3ddaa16081c221321c01c684b70197961ecd71a3f54a464f", + "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" }, "compatibleChanges": [ { @@ -666,8 +674,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: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", @@ -688,6 +696,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..dac3bd6416 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,19 @@ 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', + 'ReadHealthLink', + 'readCheckedRpcOutcome', + 'checkedRpcRefusalError', + 'protocolMismatchError', + 'readRefusalDetails', + 'isJsonRpcAnswer', + ), ...from( DAEMON_PROXY, 'refuseStaleProxyInstance', 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 89f43c3074..31d00959a5 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -361,7 +361,25 @@ 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 + +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 +{ + "daemonBaseUrl": "https://example.trycloudflare.com/agent-device", + "daemonRpc": "checked" +} +``` + +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. + +- 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 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 checks `upstream.leaseBackends` for `macos-app` before handing out a macOS app lease, and older