From 495343878ff2de39dc53d2d2954f6c7977efad88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 14:03:53 +0100 Subject: [PATCH 1/9] perf(remote): let lease admission check a reused lease instead of a heartbeat Co-Authored-By: Claude Opus 5.5 --- packages/command-registry/src/registry.ts | 9 + packages/contracts/src/lease-scope.ts | 13 + .../__tests__/index-lease-admission.test.ts | 104 +++++++ .../src/daemon-client-remote-resend.ts | 8 +- .../src/daemon-client-request.ts | 5 + .../src/daemon-client-transport.ts | 8 +- packages/daemon-client/src/index.ts | 8 +- .../daemon-contracts/src/daemon-resolution.ts | 28 +- .../docs/remote-device-lease-contracts.md | 33 ++- .../request-router-fill-text-stdin.test.ts | 26 +- .../http/daemon-runtime-quiesce.test.ts | 7 +- .../http-server-provider-scenarios.test.ts | 2 + .../daemon/src/server/http/http-server.ts | 6 +- .../src/server/request-execution-scope.ts | 2 +- packages/daemon/src/server/request-router.ts | 26 +- .../__tests__/lease-lifecycle.test.ts | 69 +++++ .../daemon/src/sessions/lease-lifecycle.ts | 45 ++- src/__tests__/cli-config.test.ts | 22 +- .../cli-lease-admission-proxy.test.ts | 126 +++++++++ src/__tests__/cli-lease-admission.test.ts | 265 ++++++++++++++++++ src/cli.ts | 36 ++- .../commands/connection-lease-admission.ts | 188 +++++++++++++ .../commands/connection-lease-transaction.ts | 62 +++- src/cli/commands/connection-runtime.ts | 8 + test/wire-compat/ledger.json | 8 +- website/docs/docs/error-reasons.md | 1 + 26 files changed, 1045 insertions(+), 70 deletions(-) create mode 100644 packages/daemon-client/src/__tests__/index-lease-admission.test.ts create mode 100644 src/__tests__/cli-lease-admission-proxy.test.ts create mode 100644 src/__tests__/cli-lease-admission.test.ts create mode 100644 src/cli/commands/connection-lease-admission.ts diff --git a/packages/command-registry/src/registry.ts b/packages/command-registry/src/registry.ts index 5f8dba7cd4..8d97dd08a1 100644 --- a/packages/command-registry/src/registry.ts +++ b/packages/command-registry/src/registry.ts @@ -712,6 +712,15 @@ const COMMAND_DESCRIPTOR_BY_NAME: ReadonlyMap< CommandDescriptor & { standaloneCommandProjection: StandaloneCommandProjection | undefined } > = new Map(commandDescriptors.map((descriptor) => [descriptor.name, descriptor])); +/** + * Whether the daemon admits this command's request against the lease it names (ADR 0007). A name + * outside the registry, or a command exempt from lease admission, never meets lease admission. + */ +export function commandMeetsLeaseAdmission(command: string): boolean { + const daemon = COMMAND_DESCRIPTOR_BY_NAME.get(command)?.daemon; + return daemon !== undefined && daemon.leaseAdmissionExempt !== true; +} + export function resolveCommandCompositeResourceTrait( command: string, ): CompositeResourceTrait | undefined { diff --git a/packages/contracts/src/lease-scope.ts b/packages/contracts/src/lease-scope.ts index 2baccbf726..ff16291ce4 100644 --- a/packages/contracts/src/lease-scope.ts +++ b/packages/contracts/src/lease-scope.ts @@ -544,6 +544,19 @@ export function isInactiveLeaseError(error: unknown): boolean { ); } +/** + * Whether `error` is the daemon's lease-admission refusal: the lease is gone, and the request never + * reached a handler. A client that let admission check a reused lease (the `lease-admission` + * capability) reallocates and resends on this refusal alone. + */ +export function isUndispatchedInactiveLeaseRefusal(error: unknown): boolean { + return ( + isInactiveLeaseError(error) && + (error as Readonly<{ details?: Readonly<{ dispatched?: unknown }> }>).details?.dispatched === + 'no' + ); +} + /** Whether `error` says the provider's device instance ended, which ends its lease. */ export function isProviderInstanceEndedError(error: unknown): boolean { return ( diff --git a/packages/daemon-client/src/__tests__/index-lease-admission.test.ts b/packages/daemon-client/src/__tests__/index-lease-admission.test.ts new file mode 100644 index 0000000000..1e61e77c67 --- /dev/null +++ b/packages/daemon-client/src/__tests__/index-lease-admission.test.ts @@ -0,0 +1,104 @@ +import http from 'node:http'; +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { DAEMON_HTTP_INSTANCE_MISMATCH_HEADER } from '@agent-device/contracts/daemon-http'; +import { sendToDaemon } from '../index.ts'; + +// A request whose reused lease no heartbeat checked reads `lease-admission` from the `/health` gate +// it already passes, so it costs `/health` and `/rpc` and nothing more. Without the capability it is +// refused before the send, so the caller can fall back to its heartbeat. + +const LEASE_ADMISSION = ['script-artifacts', 'lease-admission']; + +async function sendAdmissionChecked( + health: () => Record, + onRpc?: (res: http.ServerResponse) => boolean, +) { + const routes: string[] = []; + const server = http.createServer((req, res) => { + routes.push(req.url ?? ''); + res.setHeader('content-type', 'application/json'); + if (req.url === '/health') { + res.end(JSON.stringify({ ok: true, ...health() })); + return; + } + if (onRpc?.(res)) return; + res.end(JSON.stringify({ jsonrpc: '2.0', id: 'test', result: { ok: true, data: {} } })); + }); + const root = mkdtempForTestSync('lease-admission-'); + try { + const result = await sendToDaemon( + { + command: 'snapshot', + session: 'remote', + positionals: [], + flags: { + daemonBaseUrl: `http://127.0.0.1:${await listenOnLoopback(server)}`, + stateDir: path.join(root, 'state'), + }, + meta: { tenantId: 'proxy', runId: 'run', leaseId: 'a'.repeat(32) }, + }, + { authToken: 'test', leaseCheckedByAdmission: true }, + ).catch((error: unknown) => error); + return { result, routes }; + } finally { + await closeLoopbackServer(server); + } +} + +test.each([ + { name: 'daemon', health: { instanceId: 'daemon', capabilities: LEASE_ADMISSION } }, + { + name: 'proxy in front of the daemon', + health: { + instanceId: 'proxy', + upstream: { instanceId: 'daemon', capabilities: LEASE_ADMISSION }, + }, + }, +])('a lease-admission $name answers in /health and /rpc', async ({ health }) => { + const { result, routes } = await sendAdmissionChecked(() => health); + + expect(result).toMatchObject({ ok: true }); + expect(routes).toEqual(['/health', '/rpc']); +}); + +test.each([ + { name: 'legacy daemon', health: { instanceId: 'daemon', capabilities: ['script-artifacts'] } }, + { + name: 'upgraded proxy in front of a legacy daemon', + health: { instanceId: 'proxy', capabilities: LEASE_ADMISSION, upstream: { instanceId: 'd' } }, + }, +])('a $name is refused before the send', async ({ health }) => { + const { result, routes } = await sendAdmissionChecked(() => health); + + expect(result).toMatchObject({ + code: 'UNSUPPORTED_OPERATION', + details: { reason: 'lease_admission_unsupported', daemonRequestSent: false, dispatched: 'no' }, + }); + expect(routes).toEqual(['/health']); +}); + +test('a replacement daemon without lease admission is refused before the resend', async () => { + let replaced = false; + const { result, routes } = await sendAdmissionChecked( + () => + replaced + ? { instanceId: 'legacy', capabilities: ['script-artifacts'] } + : { instanceId: 'capable', capabilities: LEASE_ADMISSION }, + (res) => { + replaced = true; + res.statusCode = 409; + res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true'); + res.end( + JSON.stringify({ jsonrpc: '2.0', id: 'test', error: { code: -32000, message: 'x' } }), + ); + return true; + }, + ); + + expect(result).toMatchObject({ + details: { reason: 'lease_admission_unsupported', daemonRequestSent: false, dispatched: 'no' }, + }); + expect(routes).toEqual(['/health', '/rpc', '/health']); +}); diff --git a/packages/daemon-client/src/daemon-client-remote-resend.ts b/packages/daemon-client/src/daemon-client-remote-resend.ts index 213dfb06ae..c5b19bbfe1 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -4,7 +4,10 @@ // 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 { + assertLeaseAdmissionCapability, + assertScriptArtifactsCapability, +} from '@agent-device/daemon-contracts/daemon-resolution'; import { CheckedRpcConnectFailure, undispatchedWithoutEndpoint, @@ -65,6 +68,7 @@ export async function sendCheckedRpcAfterConnectFailure( export async function retryAfterRemoteInstanceMismatch( port: RemoteResendPort, scriptPublicationId: string | undefined, + leaseCheckedByAdmission: boolean | undefined, ): Promise { const { info } = port; await port.invalidateHealth(); @@ -81,6 +85,8 @@ export async function retryAfterRemoteInstanceMismatch( cacheRemoteDaemonHealth(info, health); // A replacement daemon must still deliver the script that a remote recording asks for. if (scriptPublicationId) assertScriptArtifactsCapability(info.capabilities); + // A replacement that cannot check the lease at admission gets the heartbeat path instead. + if (leaseCheckedByAdmission) assertLeaseAdmissionCapability(info.capabilities); try { return await port.resend(remainingMs); } catch (error) { diff --git a/packages/daemon-client/src/daemon-client-request.ts b/packages/daemon-client/src/daemon-client-request.ts index 2319298e5d..55734bbe19 100644 --- a/packages/daemon-client/src/daemon-client-request.ts +++ b/packages/daemon-client/src/daemon-client-request.ts @@ -7,6 +7,11 @@ export type DaemonRequest = DaemonWireRequest; export type DaemonResponse = SharedDaemonResponse; export type DaemonTransportOptions = AgentDeviceDaemonTransportContext & { onProgress?: RequestProgressSink; + /** + * The request names a reused lease that no heartbeat checked, so the daemon must check it at + * admission. A daemon whose `/health` lacks `lease-admission` is refused before the send. + */ + leaseCheckedByAdmission?: true; }; /** What a client sends one daemon request through. */ diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 21fe9a0d7f..5f58a97930 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -48,6 +48,8 @@ type ResolvedDaemonTransport = LoopbackTransport; type SendRequestOptions = { /** The host whose working directory and environment this request's client-side work reads. */ host: HostEnvironment; + /** See `DaemonTransportOptions.leaseCheckedByAdmission`; rechecked against a replacement daemon. */ + leaseCheckedByAdmission?: true; onProgress?: RequestProgressSink; /** * The caller's per-request cancellation (#3178). Aborted at or before a send attempt, nothing @@ -512,7 +514,11 @@ async function sendRequestWithFallback( 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); + : await resend.retryAfterRemoteInstanceMismatch( + port, + req.meta?.scriptPublicationId, + options.leaseCheckedByAdmission, + ); } if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); const fallback = chooseAutoFallbackTransport(info, preference, transport); diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 5c5c140ac1..e668d74c78 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -1,5 +1,8 @@ import type { DaemonConnection, EnsureDaemonOptions } from '@agent-device/contracts/client'; -import type { DaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +import { + assertLeaseAdmissionCapability, + type DaemonPaths, +} from '@agent-device/daemon-contracts/daemon-resolution'; import type { DaemonStopIdentity } from '@agent-device/daemon-contracts/daemon-registration'; import type { DaemonStopResult } from '@agent-device/daemon-contracts/daemon-stop'; import { AppError } from '@agent-device/kernel/errors'; @@ -124,6 +127,8 @@ async function sendToDaemonOnHost( ); }); const info = daemon.info; + // Read from the `/health` gate this request already passed, so the check adds no round trip. + if (options.leaseCheckedByAdmission) assertLeaseAdmissionCapability(info.capabilities); const preparedRemoteRequest = await cancellation.guard( async () => await protectArtifactUploadWithLeaseBeats( @@ -174,6 +179,7 @@ async function sendToDaemonOnHost( onProgress: options.onProgress, signal: options.signal, timeoutRecovery: resolveTimeoutRecovery(settings), + ...(options.leaseCheckedByAdmission ? { leaseCheckedByAdmission: true } : {}), }, ); if (!info.baseUrl || !request.meta?.clientArtifactPaths?.savedScript) diff --git a/packages/daemon-contracts/src/daemon-resolution.ts b/packages/daemon-contracts/src/daemon-resolution.ts index c343aaf6ba..8dd513dd4a 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -92,9 +92,11 @@ const DAEMON_STATE_ROOT_REASONS = { } as const satisfies ReasonTable<'daemon lifecycle'>; /** Why this build refuses to send a request whose delivery the answering daemon cannot promise. */ -const DAEMON_CAPABILITY_REFUSAL_REASONS = { +export const DAEMON_CAPABILITY_REFUSAL_REASONS = { // The remote daemon reports no script-artifacts capability, so it would record to its own disk. scriptArtifactsUnsupported: { reason: 'remote_script_artifacts_unsupported' }, + // The daemon reports no lease-admission capability, so it cannot check a lease no heartbeat checked. + leaseAdmissionUnsupported: { reason: 'lease_admission_unsupported' }, } as const satisfies ReasonTable<'daemon lifecycle'>; /** What the operator is told, per problem: how the component fails, and what ends it. */ @@ -322,8 +324,14 @@ export function resolveDaemonTransportPreference( /** What a daemon can do beyond the base RPC contract, published in its `daemon.json`. */ // `checked-rpc`: the daemon's HTTP server serves the checked RPC route (ADR 0006). Every daemon that -// serves it also serves `script-artifacts`. -export const DAEMON_CAPABILITIES = ['quiesce', 'script-artifacts', 'checked-rpc'] as const; +// serves it also serves `script-artifacts`. `lease-admission`: request admission refuses an inactive or +// unknown lease before dispatch with `dispatched: no`, so a client may skip its lease heartbeat. +export const DAEMON_CAPABILITIES = [ + 'quiesce', + 'script-artifacts', + 'checked-rpc', + 'lease-admission', +] as const; export type DaemonCapability = (typeof DAEMON_CAPABILITIES)[number]; /** @@ -469,6 +477,20 @@ export function assertScriptArtifactsCapability(capabilities: readonly string[] }); } +/** + * Refuses, before the send, a request whose reused lease no heartbeat checked, when the daemon does + * not report `lease-admission`. Such a daemon need not refuse an inactive lease before dispatch, + * so the caller checks the lease with a heartbeat and sends again. + */ +export function assertLeaseAdmissionCapability(capabilities: readonly string[] | undefined): void { + if (capabilities?.includes('lease-admission')) return; + throw new AppError('UNSUPPORTED_OPERATION', 'The daemon does not check leases at admission.', { + reason: DAEMON_CAPABILITY_REFUSAL_REASONS.leaseAdmissionUnsupported.reason, + daemonRequestSent: false, + dispatched: 'no', + }); +} + export function readDaemonCapabilities(value: unknown): readonly DaemonCapability[] { if (!Array.isArray(value)) return []; return DAEMON_CAPABILITIES.filter((capability) => value.includes(capability)); diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index e2f532a83d..b316647e76 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -62,8 +62,37 @@ Thus, whichever runs second finds the session gone. A close after a lease end has no session and ends no lease. If a client still stores that lease id, its next heartbeat finds the lease inactive. The client then allocates a new lease under a fresh id. -The proxy is expected to be long-lived and self-serve. -Recovery from a stale or expired device lease should not require a proxy restart. + +## Lease admission + +Request admission refuses a request that names an inactive or unknown lease. +The refusal is `UNAUTHORIZED` with `details.reason: LEASE_NOT_FOUND` and `details.dispatched: no`. +Every lease-admission refusal comes after authentication and tenant scoping, and before any handler runs. +If the request names the expired lease of its session, the daemon refuses before it tears that session down. +The lease expiry sweep ends that session later. +A sensitive `fill` value never redacts `details.reason` or `details.dispatched`. +A daemon that makes this refusal advertises the `lease-admission` capability on `/health`. +A proxy forwards the capability of the daemon behind it in `upstream`. + +The CLI can reuse a stored lease without a heartbeat. +It then marks the command as admission-checked and names the window that the heartbeat would have named. +The daemon-client reads `lease-admission` from the `/health` check that the command already makes. +If the capability is absent, the daemon-client refuses the command before the send with `lease_admission_unsupported`. +It makes the same check again after an instance-mismatch refresh. +If the only request of the command gets either refusal, the CLI materializes the connection again and sends the command once more. +After `LEASE_NOT_FOUND`, the CLI allocates a new lease. After `lease_admission_unsupported`, it sends the heartbeat. +The CLI does not resend on any other failure. + +These commands keep the heartbeat: + +- A command on a host-allocated `macos-app` lease. +- A command on a lease whose provider has a runtime. A heartbeat runs its lifecycle hooks, such as the Limrun instance liveness check. +- A command exempt from lease admission. +- `install`, `reinstall`, and `install-from-source`, which can upload a local artifact before admission. +- A command with `--save-script`. +- A by-spec `open` that allocates fresh: the connection names no device, or the request names a device spec or a device selector. + +A by-spec `open` that names no spec or selector reuses the stored device without a heartbeat. ## Admitted request work diff --git a/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts b/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts index 752c42c4a0..b27ceb2864 100644 --- a/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts @@ -51,7 +51,7 @@ function fillWithStdinText( function sendToWebSession( session: SessionState, - request: Pick, + request: Pick, fillFails?: (text: string) => Error, fillResult?: Record, ) { @@ -99,7 +99,7 @@ function sendToWebSession( token: 'test-token', session: session.name, ...request, - meta: { requestId: 'req-fill-text-stdin' }, + meta: { requestId: 'req-fill-text-stdin', ...request.meta }, }); return { response, typed, sessionStore }; } @@ -225,6 +225,28 @@ test.each([ }, ); +// A lease-admission client resends only on `dispatched: no`, so a recorded value equal to it must not +// rewrite the typed refusal. +test('a --record-as value equal to a typed detail leaves the lease refusal readable', async () => { + const { response, typed } = sendToWebSession( + makeAuthoringSession('web', { device: WEB_DESKTOP_DEVICE }), + { + command: 'fill', + positionals: ['10', '20', 'no'], + flags: { textStdin: true, recordAs: 'CODE' }, + meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId: '0'.repeat(32) }, + }, + ); + + const result = await response; + expect(typed).toEqual([]); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.code).toBe('UNAUTHORIZED'); + expect(result.error.details).toMatchObject({ reason: 'LEASE_NOT_FOUND', dispatched: 'no' }); + } +}); + test('a short --text-stdin value is redacted from the error text but not from its log path', async () => { // `stdin` also appears in this request's id, which names its diagnostics file. const { response } = fillWithStdinText( diff --git a/packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts b/packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts index 97fc5baf2b..b07990a8d1 100644 --- a/packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts +++ b/packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts @@ -231,7 +231,12 @@ test('an idle daemon accepts a quiesce, drains and releases its state directory' const published = JSON.parse(fs.readFileSync(paths.infoPath, 'utf8')) as { capabilities?: unknown; }; - expect(published.capabilities).toEqual(['quiesce', 'script-artifacts', 'checked-rpc']); + expect(published.capabilities).toEqual([ + 'quiesce', + 'script-artifacts', + 'checked-rpc', + 'lease-admission', + ]); expect(await daemon.quiesce()).toEqual({ ok: true, data: { outcome: 'draining' } }); diff --git a/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts b/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts index 460dccf9c3..e1d2bcdc7d 100644 --- a/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts +++ b/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts @@ -113,6 +113,8 @@ test('Provider-backed integration daemon HTTP server maps RPC methods, auth, and assert.equal(healthPayload.service, 'agent-device-daemon'); assert.equal(typeof healthPayload.version, 'string'); assert.equal(healthPayload.rpcProtocolVersion, DAEMON_RPC_PROTOCOL_VERSION); + // A remote client skips its lease heartbeat only for a daemon that says admission checks leases. + assert.deepEqual(healthPayload.capabilities, ['script-artifacts', 'lease-admission']); const command = await callRpc(port, { jsonrpc: '2.0', diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 4c855d569b..f76bdf898b 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -93,7 +93,11 @@ import { const MAX_HTTP_RPC_BODY_BYTES = DAEMON_REQUEST_MAX_BYTES; /** What this daemon serves over HTTP beyond the base RPC contract, as `/health` advertises it. */ -const DAEMON_HTTP_CAPABILITIES = ['script-artifacts', DAEMON_HTTP_CHECKED_RPC_CAPABILITY]; +const DAEMON_HTTP_CAPABILITIES = [ + 'script-artifacts', + DAEMON_HTTP_CHECKED_RPC_CAPABILITY, + 'lease-admission', +]; export async function createDaemonHttpServer(options: { handleRequest: DaemonInvokeFn; diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index a535359f84..32ecda9ea3 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -469,7 +469,7 @@ export async function createRequestExecutionScope(params: { sessionName, sessionStore, leaseRegistry, - refuseTeardown: command === 'batch' || command === 'replay' || boundedStep, + req: scopedReq, teardownSession: async (ref) => await teardownExpiredSession({ ref, diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index b15cc5ffa9..3b5a9527f5 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -625,7 +625,9 @@ const ERROR_TEXT_FIELDS: ReadonlySet = new Set(['message', 'hint', 'caus * A backend error can quote the text a sensitive fill failed to type, or the altered text it read * back, which `redactFillFailureReadBack` replaces whole. Only that fill's own text is otherwise * redacted, and only in the error's text fields: `logPath`, `diagnosticId` and the other - * daemon-owned fields come back as they are, and so does every other request's error. + * daemon-owned fields come back as they are, and so does every other request's error. The typed + * `details.reason` and `details.dispatched` are daemon vocabulary, never typed text, so a value + * that happens to equal one (`no`) cannot rewrite them. */ function redactSensitiveFillTextInError(req: DaemonRequest, error: DaemonError): DaemonError { const text = sensitiveFillText(req); @@ -635,16 +637,28 @@ function redactSensitiveFillTextInError(req: DaemonRequest, error: DaemonError): return Object.fromEntries( Object.entries(error).map(([field, value]) => [ field, - ERROR_TEXT_FIELDS.has(field) - ? mapErrorStrings( - field === 'details' ? redactFillFailureReadBack(value, placeholder) : value, - replace, + field === 'details' + ? withTypedDetails( + mapErrorStrings(redactFillFailureReadBack(value, placeholder), replace), + error.details, ) - : value, + : ERROR_TEXT_FIELDS.has(field) + ? mapErrorStrings(value, replace) + : value, ]), ) as DaemonError; } +function withTypedDetails(redacted: unknown, original: DaemonError['details']): unknown { + if (!redacted || typeof redacted !== 'object' || !original) return redacted; + const { reason, dispatched } = original; + return { + ...redacted, + ...(reason === undefined ? {} : { reason }), + ...(dispatched === undefined ? {} : { dispatched }), + }; +} + function mapErrorStrings(value: unknown, replace: (value: string) => string): unknown { if (typeof value === 'string') return replace(value); if (Array.isArray(value)) return value.map((entry) => mapErrorStrings(entry, replace)); diff --git a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts index 7e2a974c1b..56a38bcf96 100644 --- a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts +++ b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts @@ -63,6 +63,36 @@ test('admitRequestLeaseForLockedScope heartbeats and stores admitted lease on th expect(sessionStore.get('default')?.lease?.expiresAt).toBe(62_000); }); +// A client that let admission check its lease (`lease-admission`) reallocates and resends only on +// this refusal, so it has to say that nothing ran. +test('admitRequestLeaseForLockedScope refuses an unknown or expired lease before dispatch', () => { + let now = 1_000; + const leaseRegistry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 10_000 }); + const expired = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); + now += 20_000; + + for (const leaseId of ['0'.repeat(32), expired.leaseId]) { + expect(() => + admitRequestLeaseForLockedScope({ + env: process.env, + req: makeRequest({ + command: 'press', + positionals: ['100', '200'], + meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId }, + }), + sessionName: 'default', + sessionStore: makeSessionStore('agent-device-lease-lifecycle-'), + leaseRegistry, + }), + ).toThrow( + expect.objectContaining({ + code: 'UNAUTHORIZED', + details: expect.objectContaining({ reason: 'LEASE_NOT_FOUND', dispatched: 'no' }), + }), + ); + } +}); + test('cleanupExpiredLeasedSession consumes expired lease and deletes the session after teardown', async () => { let now = 1_000; const sessionStore = makeSessionStore('agent-device-lease-lifecycle-'); @@ -86,6 +116,7 @@ test('cleanupExpiredLeasedSession consumes expired lease and deletes the session const teardownSession = vi.fn(async () => {}); const cleaned = await cleanupExpiredLeasedSession({ + req: makeRequest({ command: 'snapshot' }), env: process.env, sessionName: 'default', sessionStore, @@ -101,6 +132,44 @@ test('cleanupExpiredLeasedSession consumes expired lease and deletes the session expect(leaseRegistry.listActiveLeases()).toHaveLength(0); }); +// The refusal says `dispatched: no`, so the request that names the expired lease must not tear its +// session down (recording, claim, runner) before the client reallocates; the expiry sweep does that. +test('cleanupExpiredLeasedSession refuses a request naming the expired lease before any teardown', async () => { + let now = 1_000; + const sessionStore = makeSessionStore('agent-device-lease-lifecycle-'); + const leaseRegistry = new LeaseRegistry({ + defaultLeaseTtlMs: 10, + minLeaseTtlMs: 1, + now: () => now, + }); + const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); + const session = makeIosSession('default', { + lease: { leaseId: lease.leaseId, tenantId: lease.tenantId, runId: lease.runId }, + }); + sessionStore.publish('default', session); + now = 1_011; + const teardownSession = vi.fn(async () => {}); + + await expect( + cleanupExpiredLeasedSession({ + req: makeRequest({ + command: 'press', + meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId: lease.leaseId }, + }), + env: process.env, + sessionName: 'default', + sessionStore, + leaseRegistry, + teardownSession, + }), + ).rejects.toMatchObject({ + code: 'UNAUTHORIZED', + details: { reason: 'LEASE_NOT_FOUND', dispatched: 'no' }, + }); + expect(teardownSession).not.toHaveBeenCalled(); + expect(sessionStore.get('default')).toBe(session); +}); + test('releaseSessionLease releases with the stored session owner scope', async () => { const leaseRegistry = new LeaseRegistry(); const lease = leaseRegistry.allocateLease({ diff --git a/packages/daemon/src/sessions/lease-lifecycle.ts b/packages/daemon/src/sessions/lease-lifecycle.ts index a15f2e3809..b65756cc0d 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -8,9 +8,15 @@ import type { LeaseLifecycleProvider, ProviderAppCatalog, } from '@agent-device/contracts/device'; -import { buildSessionLeaseFromRequest, type SessionLease } from '../core/lease-context.ts'; +import { + buildSessionLeaseFromRequest, + isBoundedCompositeRequest, + resolveLeaseScope, + type SessionLease, +} from '../core/lease-context.ts'; import { assertRequestLeaseAdmission } from './request-admission.ts'; import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { thrownBeforeDispatch } from '../execution/request-dispatch-disclosure.ts'; import type { SessionStore } from '../core/session-store.ts'; import type { DaemonRequest } from '../core/daemon-request.ts'; import type { SessionRef, SessionState } from '../core/session-state.ts'; @@ -53,21 +59,26 @@ export async function releaseExpiredProviderLease( } } +/** + * Ends the session of the request whose session lease expired, or refuses the request before that + * teardown. A composite is refused so it does not lose its session mid-run. A request that names + * that lease is refused so its client can reallocate and resend: the refusal says `dispatched: no`, so + * nothing of the request may run first. The lease expiry sweep ends that session instead. + */ export async function cleanupExpiredLeasedSession(params: { + req: DaemonRequest; env: HostEnvironment['env']; sessionName: string; sessionStore: SessionStore; leaseRegistry: LeaseRegistry; teardownSession: SessionTeardown; - /** A composite request refuses an expired lease rather than tear its session down mid-run. */ - refuseTeardown?: boolean; }): Promise { const ref = params.sessionStore.lookup(params.sessionName); const lease = ref?.session.lease; if (!ref || !lease) return false; if ( !params.leaseRegistry.consumeExpiredLease(lease.leaseId, () => { - if (!params.refuseTeardown) return; + if (!refusesExpiredLeaseTeardown(params.req, lease.leaseId)) return; throw new AppError('UNAUTHORIZED', 'Lease is not active', { reason: LEASE_REASONS.notFound.reason, dispatched: 'no', @@ -85,6 +96,15 @@ export async function cleanupExpiredLeasedSession(params: { return true; } +function refusesExpiredLeaseTeardown(req: DaemonRequest, expiredLeaseId: string): boolean { + return ( + req.command === 'batch' || + req.command === 'replay' || + isBoundedCompositeRequest(req) || + resolveLeaseScope(req).leaseId === expiredLeaseId + ); +} + /** * Ends one session whose lease is gone (released or expired). The device claim is cleared even when * teardown fails: the lease that paid for the device has ended, so nobody may keep it. @@ -137,11 +157,18 @@ export function admitRequestLeaseForLockedScope(params: { const { sessionName, sessionStore, leaseRegistry } = params; const ref = sessionStore.lookup(sessionName); const existingSession = ref?.session; - const activeLease = assertRequestLeaseAdmission(params.req, leaseRegistry, existingSession, { - env: params.env, - providerAppCatalog: params.providerAppCatalog, - daemonPolicy: params.daemonPolicy, - }); + // Admission runs before any handler, so its refusal says `dispatched: no`: a client that let + // admission check its lease (`lease-admission`) reallocates and resends on that refusal alone. + let activeLease: DeviceLease | undefined; + try { + activeLease = assertRequestLeaseAdmission(params.req, leaseRegistry, existingSession, { + env: params.env, + providerAppCatalog: params.providerAppCatalog, + daemonPolicy: params.daemonPolicy, + }); + } catch (error) { + throw thrownBeforeDispatch(error); + } if (!activeLease) return params.req; const nextReq = { diff --git a/src/__tests__/cli-config.test.ts b/src/__tests__/cli-config.test.ts index 3339adfc68..7e385d2c4a 100644 --- a/src/__tests__/cli-config.test.ts +++ b/src/__tests__/cli-config.test.ts @@ -281,18 +281,16 @@ test('active remote connection defaults override generic config and env for remo }); assert.equal(result.code, null); - assert.equal(result.calls.length, 2); - assert.equal(result.calls[0]?.command, 'lease_heartbeat'); - assert.equal(result.calls[1]?.session, 'env-session'); - assert.equal(result.calls[1]?.flags?.platform, 'android'); + // Admission checks the stored lease, so the command is the only request. + assert.equal(result.calls.length, 1); + assert.equal(result.calls[0]?.session, 'env-session'); + assert.equal(result.calls[0]?.flags?.platform, 'android'); assert.equal( - result.calls[1]?.flags?.daemonBaseUrl, + result.calls[0]?.flags?.daemonBaseUrl, 'http://remote-mac.example.test:9124/agent-device', ); assert.equal(result.calls[0]?.meta?.tenantId, 'acme'); assert.equal(result.calls[0]?.meta?.leaseId, 'lease-123'); - assert.equal(result.calls[1]?.meta?.tenantId, 'acme'); - assert.equal(result.calls[1]?.meta?.leaseId, 'lease-123'); fs.rmSync(root, { recursive: true, force: true }); }); @@ -630,11 +628,11 @@ test('remote-config commands reuse active generated session when profile has no ); assert.equal(result.code, null); - assert.equal(result.calls.length, 2); - assert.equal(result.calls[0]?.command, 'lease_heartbeat'); - assert.equal(result.calls[1]?.command, 'snapshot'); - assert.equal(result.calls[1]?.session, 'adc-generated'); - assert.equal(result.calls[1]?.meta?.leaseId, 'lease-generated-001'); + // Admission checks the stored lease, so the command is the only request. + assert.equal(result.calls.length, 1); + assert.equal(result.calls[0]?.command, 'snapshot'); + assert.equal(result.calls[0]?.session, 'adc-generated'); + assert.equal(result.calls[0]?.meta?.leaseId, 'lease-generated-001'); fs.rmSync(root, { recursive: true, force: true }); }); diff --git a/src/__tests__/cli-lease-admission-proxy.test.ts b/src/__tests__/cli-lease-admission-proxy.test.ts new file mode 100644 index 0000000000..b3e2d40719 --- /dev/null +++ b/src/__tests__/cli-lease-admission-proxy.test.ts @@ -0,0 +1,126 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { test } from 'vitest'; +import { createDaemonProxyServer } from '@agent-device/proxy'; +import { + closeLoopbackServer, + listenOnLoopback, + makeTempWorkspace, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { createAgentDeviceClient } from '@agent-device/client'; +import { + hashRemoteConfigFile, + readRemoteConnectionState, + writeRemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; +import { runCliCapture } from './cli-capture.ts'; +import { startPublicDaemonRuntime } from './test-utils/public-daemon-runtime.ts'; + +// The real CLI, daemon-client, proxy and daemon: a command on a lease the daemon no longer holds is +// refused at admission, the refusal crosses the proxy intact, and the CLI reallocates and resends +// once. No heartbeat runs on either attempt. + +const LEASE_SCOPE = { + tenant: 'proxy', + runId: 'run-admission', + leaseBackend: 'android-instance', + leaseProvider: 'proxy', + clientId: 'client-admission', + // No device answers to this serial, and the daemon may list no other. + deviceKey: 'android:mobile:emulator-9999', +} as const; + +test('a lease the daemon dropped is reallocated through the proxy without a heartbeat', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { root, home, project } = makeTempWorkspace(); + const daemon = await startPublicDaemonRuntime({ + serverMode: 'http', + env: { AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST: 'emulator-9999' }, + }); + const upstream: string[] = []; + const proxy = createDaemonProxyServer({ + upstreamBaseUrl: daemon.baseUrl, + upstreamToken: daemon.runtime.token, + clientToken: 'client-secret', + upstreamFetch: async (request) => { + upstream.push(await describe(request)); + return await fetch(request); + }, + }); + try { + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}/agent-device`; + const client = createAgentDeviceClient({ + daemonBaseUrl: baseUrl, + daemonAuthToken: 'client-secret', + daemonTransport: 'http', + }); + const lease = await client.leases.allocate({ ...LEASE_SCOPE, leaseId: 'b'.repeat(32) }); + const stateDir = path.join(root, 'state'); + writeConnection(stateDir, project, baseUrl, lease.leaseId); + await client.leases.release({ ...LEASE_SCOPE, leaseId: lease.leaseId }); + upstream.length = 0; + + const result = await runCliCapture( + ['snapshot', '--session', 'agent', '--state-dir', stateDir, '--json'], + { + cwd: project, + env: { HOME: home, AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'client-secret' }, + useRealDaemonClient: true, + }, + ); + + const reallocated = readRemoteConnectionState({ stateDir, session: 'agent' })?.leaseId; + assert.ok(reallocated && reallocated !== lease.leaseId, result.stdout); + // The setup above already cached `/health` for this endpoint in this process, so only RPCs show. + assert.deepEqual( + upstream.filter((route) => route.startsWith('/rpc')), + ['/rpc snapshot', '/rpc agent_device.lease.allocate', '/rpc snapshot'], + ); + // The resent command passed admission: whatever it answered, it was not the lease refusal. + if (result.code !== null) { + assert.notEqual(JSON.parse(result.stdout).error.details?.reason, 'LEASE_NOT_FOUND'); + } + } finally { + await closeLoopbackServer(proxy); + await daemon.close(); + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +async function describe(request: Request): Promise { + const route = new URL(request.url).pathname; + if (route !== '/rpc') return route; + const body = JSON.parse(await request.clone().text()) as { + method?: string; + params?: { command?: string }; + }; + return `/rpc ${body.method === 'agent_device.command' ? body.params?.command : body.method}`; +} + +function writeConnection(stateDir: string, project: string, baseUrl: string, leaseId: string) { + const remoteConfigPath = path.join(project, 'agent.remote.json'); + fs.writeFileSync(remoteConfigPath, JSON.stringify({})); + const now = new Date().toISOString(); + writeRemoteConnectionState({ + stateDir, + state: { + version: 1, + session: 'agent', + remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + daemon: { baseUrl, transport: 'http' }, + tenant: LEASE_SCOPE.tenant, + runId: LEASE_SCOPE.runId, + leaseId, + leaseBackend: LEASE_SCOPE.leaseBackend, + leaseProvider: LEASE_SCOPE.leaseProvider, + clientId: LEASE_SCOPE.clientId, + deviceKey: LEASE_SCOPE.deviceKey, + platform: 'android', + connectedAt: now, + updatedAt: now, + }, + }); +} diff --git a/src/__tests__/cli-lease-admission.test.ts b/src/__tests__/cli-lease-admission.test.ts new file mode 100644 index 0000000000..fad5909c4f --- /dev/null +++ b/src/__tests__/cli-lease-admission.test.ts @@ -0,0 +1,265 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { makeTempWorkspace } from '@agent-device/test-kit'; +import { AppError, type DispatchDisclosure } from '@agent-device/kernel/errors'; +import { REMOTE_LEASE_IDLE_TTL_MS } from '@agent-device/contracts/lease-scope'; +import { assertLeaseAdmissionCapability } from '@agent-device/daemon-contracts/daemon-resolution'; +import type { DaemonResponse } from '@agent-device/daemon-client'; +import { + hashRemoteConfigFile, + readRemoteConnectionState, + writeRemoteConnectionState, + type RemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; +import { runCliCapture, type CapturedDaemonRequest } from './cli-capture.ts'; + +// A daemon that advertises `lease-admission` checks a reused lease when it admits the command, so the +// CLI sends the command marked as admission-checked and without a heartbeat. The daemon-client +// refuses such a request before the send when `/health` lacks the capability; the daemon refuses an +// inactive lease before dispatch. The fake transport below stands where the daemon-client does. + +const PROXY_URL = 'http://proxy.example.test/agent-device'; + +type Workspace = { root: string; home: string; project: string; stateDir: string }; + +function workspace(connection: Partial = {}): Workspace { + const { root, home, project } = makeTempWorkspace(); + const stateDir = path.join(root, 'state'); + const remoteConfigPath = path.join(project, 'agent.remote.json'); + fs.writeFileSync(remoteConfigPath, JSON.stringify({})); + const now = new Date().toISOString(); + writeRemoteConnectionState({ + stateDir, + state: { + version: 1, + session: 'agent', + remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + daemon: { baseUrl: PROXY_URL }, + tenant: 'proxy', + runId: 'run-agent', + leaseId: 'lease-old', + leaseBackend: 'android-instance', + leaseProvider: 'proxy', + clientId: 'client-1', + deviceKey: 'android:mobile:emulator-5554', + platform: 'android', + connectedAt: now, + updatedAt: now, + ...connection, + }, + }); + return { root, home, project, stateDir }; +} + +function scopeOf(req: CapturedDaemonRequest | undefined, key: string): unknown { + return req?.meta?.[key as keyof typeof req.meta] ?? req?.flags?.[key as keyof typeof req.flags]; +} + +function leaseAnswer(req: CapturedDaemonRequest): DaemonResponse { + return { + ok: true, + data: { + lease: { + leaseId: String(scopeOf(req, 'leaseId')), + tenantId: scopeOf(req, 'tenantId') ?? scopeOf(req, 'tenant'), + runId: scopeOf(req, 'runId'), + backend: scopeOf(req, 'leaseBackend'), + leaseProvider: scopeOf(req, 'leaseProvider'), + clientId: scopeOf(req, 'clientId'), + deviceKey: scopeOf(req, 'deviceKey'), + }, + }, + }; +} + +type Daemon = Readonly<{ + /** What `/health` advertises; without `lease-admission` a marked request is refused unsent. */ + leaseAdmission?: boolean; + /** The admission refusal of a command that names the stored lease. */ + refusal?: () => Error; +}>; + +/** A fake daemon-client transport in front of a daemon that admits every lease but the stored one. */ +function transportTo(daemon: Daemon) { + return async ( + req: CapturedDaemonRequest, + options?: { leaseCheckedByAdmission?: true }, + ): Promise => { + if (options?.leaseCheckedByAdmission && !daemon.leaseAdmission) { + assertLeaseAdmissionCapability(['script-artifacts']); + } + if (req.command === 'lease_allocate' || req.command === 'lease_heartbeat') { + return leaseAnswer(req); + } + if (daemon.refusal && scopeOf(req, 'leaseId') === 'lease-old') throw daemon.refusal(); + if (req.command === 'open') return { ok: true, data: { session: req.session } }; + return { ok: true, data: { nodes: [], truncated: false } }; + }; +} + +function admissionRefusal(dispatched?: DispatchDisclosure): AppError { + return new AppError('UNAUTHORIZED', 'Lease is not active', { + reason: 'LEASE_NOT_FOUND', + ...(dispatched === undefined ? {} : { dispatched }), + }); +} + +async function run(ws: Workspace, argv: string[], daemon: Daemon) { + return await runCliCapture( + [...argv, '--session', 'agent', '--state-dir', ws.stateDir, '--json'], + { + cwd: ws.project, + env: { HOME: ws.home }, + sendToDaemon: transportTo(daemon), + }, + ); +} + +function commandsOf(result: Awaited>): string[] { + return result.calls.map((call) => call.command); +} + +function markedOf(result: Awaited>): boolean[] { + return result.transportOptions.map( + (options) => (options as { leaseCheckedByAdmission?: true })?.leaseCheckedByAdmission === true, + ); +} + +test.each([ + ['snapshot -i', ['snapshot', '-i'], 'snapshot'], + ['a proxy open on the stored device', ['open', 'com.example'], 'open'], +])('%s reaches a lease-admission daemon without a heartbeat', async (_name, argv, command) => { + const ws = workspace(); + const result = await run(ws, argv, { leaseAdmission: true }); + + assert.equal(result.code, null, result.stdout); + assert.deepEqual(commandsOf(result), [command]); + assert.deepEqual(markedOf(result), [true]); + assert.equal(scopeOf(result.calls[0], 'leaseId'), 'lease-old'); + // Admission renews for the window the heartbeat would have named. + assert.equal(result.calls[0]?.meta?.leaseTtlMs, REMOTE_LEASE_IDLE_TTL_MS); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); + +test('a daemon without lease admission gets the heartbeat, then the command once more', async () => { + const ws = workspace(); + const result = await run(ws, ['snapshot'], { leaseAdmission: false }); + + assert.equal(result.code, null, result.stdout); + assert.deepEqual(commandsOf(result), ['snapshot', 'lease_heartbeat', 'snapshot']); + assert.deepEqual(markedOf(result), [true, false, false]); + assert.equal(result.calls[2]?.meta?.leaseTtlMs, undefined); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); + +test('a lease refused at admission is reallocated and the command is sent once more', async () => { + const ws = workspace(); + const result = await run(ws, ['snapshot'], { + leaseAdmission: true, + refusal: () => admissionRefusal('no'), + }); + + assert.equal(result.code, null, result.stdout); + assert.deepEqual(commandsOf(result), ['snapshot', 'lease_allocate', 'snapshot']); + const allocated = scopeOf(result.calls[1], 'leaseId'); + assert.notEqual(allocated, 'lease-old'); + assert.equal(scopeOf(result.calls[2], 'leaseId'), allocated); + assert.equal( + readRemoteConnectionState({ stateDir: ws.stateDir, session: 'agent' })?.leaseId, + allocated, + ); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); + +test.each([ + ['an inactive-lease refusal without dispatch disclosure', () => admissionRefusal(), {}], + ['an inactive-lease refusal that may have dispatched', () => admissionRefusal('unknown'), {}], + [ + 'a transport timeout', + () => + new AppError('COMMAND_FAILED', 'Daemon request timed out', { + reason: 'daemon_request_timeout', + daemonRequestSent: true, + }), + {}, + ], + [ + 'a lease scope mismatch', + () => + new AppError('UNAUTHORIZED', 'Lease scope mismatch', { + reason: 'LEASE_SCOPE_MISMATCH', + dispatched: 'no', + }), + { dispatched: 'no' }, + ], +])('%s is never resent', async (_name, refusal, expected) => { + const ws = workspace(); + const result = await run(ws, ['snapshot'], { leaseAdmission: true, refusal }); + + assert.equal(result.code, 1, result.stdout); + assert.deepEqual(commandsOf(result), ['snapshot']); + const details = JSON.parse(result.stdout).error.details; + assert.equal(details.reason, refusal().details?.reason); + if ('dispatched' in expected) assert.equal(details.dispatched, expected.dispatched); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); + +test('a resent command refused again is not sent a third time', async () => { + const ws = workspace(); + const result = await runCliCapture( + ['snapshot', '--session', 'agent', '--state-dir', ws.stateDir, '--json'], + { + cwd: ws.project, + env: { HOME: ws.home }, + sendToDaemon: async (req) => { + if (req.command === 'lease_allocate') return leaseAnswer(req); + throw admissionRefusal('no'); + }, + }, + ); + + assert.equal(result.code, 1, result.stdout); + assert.deepEqual(commandsOf(result), ['snapshot', 'lease_allocate', 'snapshot']); + const details = JSON.parse(result.stdout).error.details; + assert.equal(details.reason, 'LEASE_NOT_FOUND'); + assert.equal(details.dispatched, 'no'); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); + +test.each<[string, string[], Partial]>([ + [ + 'a host-allocated macos-app lease', + ['snapshot'], + { + leaseId: 'a1b2c3d4e5f60718293a4b5c6d7e8f90', + leaseBackend: 'macos-app', + deviceKey: 'com.example.app@4242', + platform: 'macos', + }, + ], + [ + 'a provider lease whose runtime runs lifecycle hooks', + ['snapshot'], + { leaseProvider: 'limrun' }, + ], + ['an install that uploads a local artifact first', ['install', 'com.example', 'app.apk'], {}], + ['a remote --save-script open', ['open', 'com.example', '--save-script', 'flow.ad'], {}], + ['a proxy open naming another device mode', ['open', 'com.example', '--device-mode', 'full'], {}], + ['a proxy open with no stored device', ['open', 'com.example'], { deviceKey: undefined }], +])('%s keeps the heartbeat on a lease-admission daemon', async (_name, argv, connection) => { + const ws = workspace(connection); + const result = await run(ws, argv, { leaseAdmission: true }); + + assert.equal(commandsOf(result)[0], 'lease_heartbeat', result.stdout); + assert.equal(markedOf(result).includes(true), false); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); diff --git a/src/cli.ts b/src/cli.ts index 2299df1f1f..5a9aac31e8 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -66,6 +66,7 @@ import type { FlagKey } from '@agent-device/command-registry/flag-types'; import type { CliFlags } from '@agent-device/contracts/command'; import type { SessionRuntimeHints } from '@agent-device/kernel/contracts'; import { isKnownCliCommandName } from '@agent-device/command-registry/catalog'; +import * as LeaseAdmission from './cli/commands/connection-lease-admission.ts'; type CliDeps = { sendToDaemon: typeof sendToDaemon; @@ -222,19 +223,22 @@ async function runCliOnHost(argv: string[], deps: CliDeps, host: HostEnvironment logTailStopper = maybeStartDaemonLogTail(ctx); const replayTestReporterRuntime = await createReplayReporterForTest(ctx); const commandProgress = createCommandProgressState(); - const client = createAgentDeviceClient(buildClientConfig(ctx), { - host: ctx.host, - devicePin: ctx.devicePin, - transport: createCliDaemonTransport({ - host, - command, - flags: ctx.effectiveFlags, - replayTestReporterRuntime, - commandProgress, - transport, - }), + const transportSetup = { host, command, replayTestReporterRuntime, commandProgress }; + await LeaseAdmission.dispatchWithLeaseAdmission(ctx.leaseAdmission?.checked, transport, { + rematerialize: async (check) => await resolveRemoteContext(ctx, transport, check), + dispatch: async (send) => { + const client = createAgentDeviceClient(buildClientConfig(ctx), { + host: ctx.host, + devicePin: ctx.devicePin, + transport: createCliDaemonTransport({ + ...transportSetup, + flags: ctx.effectiveFlags, + transport: send, + }), + }); + await dispatchCliCommand(ctx, client, replayTestReporterRuntime, commandProgress); + }, }); - await dispatchCliCommand(ctx, client, replayTestReporterRuntime, commandProgress); } catch (error) { await handleRunCliFailure(error, ctx, logTailStopper); } finally { @@ -369,6 +373,7 @@ type CliRunContext = { connectionMetadata: RemoteConnectionRequestMetadata | undefined; /** The device a proxy backend granted for the lease's device spec; `open` reports it. */ leaseDevice?: LeaseDevice; + leaseAdmission?: { flagsBefore: CliFlags; checked?: LeaseAdmission.AdmissionCheckedLease }; parsedBatchSteps: BatchStep[] | undefined; devicePin: DevicePin | undefined; }; @@ -471,6 +476,7 @@ async function runReactDevtoolsCli(ctx: CliRunContext): Promise { async function resolveRemoteContext( ctx: CliRunContext, transport: CliDaemonTransport, + check?: LeaseAdmission.ReusedLeaseCheck, ): Promise { if (ctx.command === 'batch') { if (ctx.positionals.length > 0) { @@ -479,7 +485,7 @@ async function resolveRemoteContext( ctx.parsedBatchSteps = readBatchSteps(ctx.flags); } - if (shouldResolveRemoteAuth(ctx.command)) { + if (!check && shouldResolveRemoteAuth(ctx.command)) { const authResolution = await resolveRemoteAuthForCli({ command: ctx.command, flags: ctx.effectiveFlags, @@ -490,6 +496,7 @@ async function resolveRemoteContext( } if (ctx.effectiveFlags.remoteConfig && shouldMaterializeRemoteConnection(ctx.command)) { + ctx.effectiveFlags = (ctx.leaseAdmission ??= { flagsBefore: ctx.effectiveFlags }).flagsBefore; // 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( @@ -511,7 +518,9 @@ async function resolveRemoteContext( positionals: ctx.positionals, batchSteps: ctx.parsedBatchSteps, forceRuntimePrepare: hasExplicitMetroRuntimeOverrides(ctx.explicitFlagKeys), + reusedLeaseCheck: check ?? { byAdmission: true }, }); + ctx.leaseAdmission.checked = materialized.admissionCheckedLease; ctx.effectiveFlags = materialized.flags; ctx.resolvedRuntime = materialized.runtime; ctx.connectionMetadata = materialized.connection; @@ -550,6 +559,7 @@ function buildClientConfig(ctx: CliRunContext): AgentDeviceClientConfig { runId: currentFlags.runId, leaseId: currentFlags.leaseId, leaseBackend: currentFlags.leaseBackend, + leaseTtlMs: ctx.leaseAdmission?.checked?.leaseTtlMs, leaseProvider: connection?.leaseProvider, clientId: connection?.clientId, deviceKey: connection?.deviceKey, diff --git a/src/cli/commands/connection-lease-admission.ts b/src/cli/commands/connection-lease-admission.ts new file mode 100644 index 0000000000..61d8eacdeb --- /dev/null +++ b/src/cli/commands/connection-lease-admission.ts @@ -0,0 +1,188 @@ +import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; +import { commandMeetsLeaseAdmission } from '@agent-device/command-registry/registry'; +import { + isUndispatchedInactiveLeaseRefusal, + leaseProviderRequiringRuntime, + requireLeaseDeviceSpec, +} from '@agent-device/contracts/lease-scope'; +import { DAEMON_CAPABILITY_REFUSAL_REASONS } from '@agent-device/daemon-contracts/daemon-resolution'; +import { + buildRemoteConnectionRequestMetadata, + type RemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; +import type { Lease } from '@agent-device/contracts/client'; +import type { CliFlags } from '@agent-device/contracts/command'; +import type { LeaseBackend } from '@agent-device/kernel/contracts'; +import type { sendToDaemon } from '@agent-device/daemon-client'; +import type { ConnectionLeasePolicy } from './connection-lease-policy.ts'; + +// A reused lease is checked either by a heartbeat before the command or by the daemon when it admits +// the command. Admission refuses an inactive lease before dispatch with `dispatched: no`, and the +// daemon-client refuses before the send a daemon whose `/health` lacks `lease-admission`. On either +// refusal of the command's only request, the CLI materializes the connection again and reruns it. + +/** How the CLI checks the lease it reuses for one command. */ +export type ReusedLeaseCheck = Readonly<{ + /** Let the command's admission check the lease instead of a heartbeat, where that is safe. */ + byAdmission: boolean; + /** The lease the daemon refused at admission. It is reallocated without a heartbeat. */ + inactiveLeaseId?: string; +}>; + +/** A reused lease that the command's admission checks and renews instead of a heartbeat. */ +export type AdmissionCheckedLease = Readonly<{ + leaseId: string; + /** The window the heartbeat would have named; the command names it so admission renews the same. */ + leaseTtlMs?: number; +}>; + +/** Commands whose request uploads a local artifact first; the upload's own beat needs a live lease. */ +const ARTIFACT_UPLOAD_COMMANDS: ReadonlySet = new Set([ + PUBLIC_COMMANDS.install, + PUBLIC_COMMANDS.reinstall, + PUBLIC_COMMANDS.installFromSource, +]); + +/** + * The reused lease the command's own admission can check, or `undefined` when a heartbeat must. The + * heartbeat stays wherever it does more than admission does: + * - a host-allocated `macos-app` lease has its own refusal; + * - a provider with a runtime runs lifecycle hooks on a heartbeat, such as an instance liveness check; + * - a command exempt from lease admission is never checked there; + * - an upload of a local artifact runs before admission, under the lease; + * - `--save-script` records its publication before the send; + * - a by-spec allocation binds the device from the heartbeat answer, unless the connection already + * names the device and the request names no other device or spec. + */ +export function leaseCheckedByAdmission( + options: Readonly<{ + command: string; + state: RemoteConnectionState; + flags: CliFlags; + leaseBackend: LeaseBackend; + policy: ConnectionLeasePolicy; + allocateBySpec: boolean | undefined; + check: ReusedLeaseCheck | undefined; + }>, +): AdmissionCheckedLease | undefined { + const { state, flags, check } = options; + if ( + !check?.byAdmission || + !state.leaseId || + state.leaseBackend !== options.leaseBackend || + state.leaseBackend === 'macos-app' || + leaseProviderRequiringRuntime({ leaseProvider: state.leaseProvider }) !== undefined || + !commandMeetsLeaseAdmission(options.command) || + ARTIFACT_UPLOAD_COMMANDS.has(options.command) || + flags.saveScript !== undefined || + (options.allocateBySpec && !bindsStoredDevice(state, flags)) + ) { + return undefined; + } + const leaseTtlMs = options.policy.ttlMs(state); + return { leaseId: state.leaseId, ...(leaseTtlMs === undefined ? {} : { leaseTtlMs }) }; +} + +/** Whether binding would take the stored device as it is: the request names no device or spec. */ +function bindsStoredDevice(state: RemoteConnectionState, flags: CliFlags): boolean { + return ( + state.deviceKey !== undefined && + requireLeaseDeviceSpec(flags).keys.length === 0 && + flags.udid === undefined && + flags.serial === undefined && + flags.device === undefined && + flags.iosSimulatorDeviceSet === undefined && + flags.androidDeviceAllowlist === undefined + ); +} + +/** The lease a connection already names, as the heartbeat would have answered it. */ +export function leaseOfConnection( + state: RemoteConnectionState, + leaseId: string, + leaseBackend: LeaseBackend, +): Lease { + return { + leaseId, + tenantId: state.tenant, + runId: state.runId, + backend: leaseBackend, + ...buildRemoteConnectionRequestMetadata(state), + }; +} + +type DaemonTransport = typeof sendToDaemon; + +/** How the requests of a command that relies on admission fared. */ +type LeaseAdmissionAttempt = { + requests: number; + /** Set when the first request was refused before its send or its dispatch. */ + firstRefusal?: 'inactive-lease' | 'unsupported'; +}; + +/** Sends each request marked as admission-checked, and records how the first one was refused. */ +function leaseAdmissionTransport( + send: DaemonTransport, + attempt: LeaseAdmissionAttempt, +): DaemonTransport { + return async (req, options) => { + attempt.requests += 1; + const first = attempt.requests === 1; + try { + const response = await send(req, { ...options, leaseCheckedByAdmission: true }); + if (first && !response.ok) attempt.firstRefusal = refusalOf(response.error); + return response; + } catch (error) { + if (first) attempt.firstRefusal = refusalOf(error); + throw error; + } + }; +} + +function refusalOf(error: unknown): LeaseAdmissionAttempt['firstRefusal'] { + if (isUndispatchedInactiveLeaseRefusal(error)) return 'inactive-lease'; + const reason = (error as Readonly<{ details?: Readonly<{ reason?: unknown }> }> | null)?.details + ?.reason; + return reason === DAEMON_CAPABILITY_REFUSAL_REASONS.leaseAdmissionUnsupported.reason + ? 'unsupported' + : undefined; +} + +/** + * The lease check a rerun uses, or `undefined` when the failure stands. A rerun is safe only when the + * command sent one request and it was refused before dispatch, so nothing of the command ran. An + * inactive lease is reallocated; a daemon without `lease-admission` gets the heartbeat. + */ +function leaseCheckAfterRefusal( + attempt: LeaseAdmissionAttempt | undefined, + refused: AdmissionCheckedLease | undefined, +): ReusedLeaseCheck | undefined { + if (!attempt || !refused || attempt.requests !== 1) return undefined; + if (attempt.firstRefusal === 'inactive-lease') { + return { byAdmission: false, inactiveLeaseId: refused.leaseId }; + } + return attempt.firstRefusal === 'unsupported' ? { byAdmission: false } : undefined; +} + +/** + * Dispatches a command whose reused lease admission checks, and reruns it once after a refusal that + * {@link leaseCheckAfterRefusal} admits, with the connection materialized again by `rematerialize`. + */ +export async function dispatchWithLeaseAdmission( + admissionChecked: AdmissionCheckedLease | undefined, + transport: DaemonTransport, + steps: Readonly<{ + dispatch: (transport: DaemonTransport) => Promise; + rematerialize: (check: ReusedLeaseCheck) => Promise; + }>, +): Promise { + const attempt: LeaseAdmissionAttempt | undefined = admissionChecked ? { requests: 0 } : undefined; + try { + await steps.dispatch(attempt ? leaseAdmissionTransport(transport, attempt) : transport); + } catch (error) { + const check = leaseCheckAfterRefusal(attempt, admissionChecked); + if (!check) throw error; + await steps.rematerialize(check); + await steps.dispatch(transport); + } +} diff --git a/src/cli/commands/connection-lease-transaction.ts b/src/cli/commands/connection-lease-transaction.ts index 626730bb81..d0d0bb038b 100644 --- a/src/cli/commands/connection-lease-transaction.ts +++ b/src/cli/commands/connection-lease-transaction.ts @@ -24,6 +24,12 @@ import { type ConnectionLeasePolicy, } from './connection-lease-policy.ts'; import { bindLeaseNamedDevice, CONNECTION_SCOPE_REASONS } from './proxy-lease-device.ts'; +import { + leaseCheckedByAdmission, + leaseOfConnection, + type AdmissionCheckedLease, + type ReusedLeaseCheck, +} from './connection-lease-admission.ts'; type LeaseRelease = () => Promise<{ released: boolean }>; @@ -121,7 +127,13 @@ export async function acquireConnectionLease(options: { nextFlags: CliFlags; positionals?: string[]; leaseLedger: LeaseLedger; -}): Promise<{ state: RemoteConnectionState; changed: boolean }> { + reusedLeaseCheck?: ReusedLeaseCheck; +}): Promise<{ + state: RemoteConnectionState; + changed: boolean; + /** Set when the command's admission, not a heartbeat, checks this reused lease. */ + admissionCheckedLease?: AdmissionCheckedLease; +}> { const { command, client, state, nextFlags, leaseLedger } = options; const deferredAppSelection = connectionProviderCapabilities( state.leaseProvider, @@ -132,6 +144,7 @@ export async function acquireConnectionLease(options: { const leasePolicy = connectionLeasePolicyForState(state); let nextState = state; let changed = false; + let admissionCheckedLease: AdmissionCheckedLease | undefined; if (leasePolicy.shouldAllocate(command)) { const materialized = await materializeLeaseForCommand({ command, @@ -142,16 +155,18 @@ export async function acquireConnectionLease(options: { initialApp, policy: leasePolicy, leaseLedger, + reusedLeaseCheck: options.reusedLeaseCheck, }); nextState = materialized.state; changed = materialized.changed; + admissionCheckedLease = materialized.admissionCheckedLease; } nextState = { ...nextState, platform: carriedConnectionPlatform(state.session, nextState, nextFlags), }; nextFlags.platform = nextState.platform; - return { state: nextState, changed }; + return { state: nextState, changed, admissionCheckedLease }; } /** @@ -191,7 +206,12 @@ async function materializeLeaseForCommand(options: { initialApp?: string; policy: ConnectionLeasePolicy; leaseLedger: LeaseLedger; -}): Promise<{ state: RemoteConnectionState; changed: boolean }> { + reusedLeaseCheck?: ReusedLeaseCheck; +}): Promise<{ + state: RemoteConnectionState; + changed: boolean; + admissionCheckedLease?: AdmissionCheckedLease; +}> { const { command, client, state, nextFlags, policy, leaseLedger } = options; const preliminaryLeaseBackend = state.leaseBackend ?? resolveRequestedLeaseBackend(nextFlags); let nextState = options.nextState; @@ -216,16 +236,31 @@ async function materializeLeaseForCommand(options: { assertRequestedConnectionTarget(state, nextFlags); nextState = { ...nextState, platform }; nextFlags.platform = platform; - let materializedLease = await allocateOrReuseLease( - client, - nextState, + const admissionCheckedLease = leaseCheckedByAdmission({ + command, + state: nextState, + flags: nextFlags, leaseBackend, policy, - nextFlags, - options.initialApp, - resolvedLeaseState.allocateBySpec, - leaseLedger, - ); + allocateBySpec: resolvedLeaseState.allocateBySpec, + check: options.reusedLeaseCheck, + }); + let materializedLease = admissionCheckedLease + ? { + lease: leaseOfConnection(nextState, admissionCheckedLease.leaseId, leaseBackend), + acquired: false, + } + : await allocateOrReuseLease( + client, + nextState, + leaseBackend, + policy, + nextFlags, + options.initialApp, + resolvedLeaseState.allocateBySpec, + leaseLedger, + options.reusedLeaseCheck?.inactiveLeaseId, + ); if (resolvedLeaseState.allocateBySpec) { const bound = await bindLeaseNamedDevice({ client, @@ -254,7 +289,7 @@ async function materializeLeaseForCommand(options: { nextFlags.leaseBackend = leaseBackend; nextFlags.target = nextState.target ?? nextFlags.target; if (leaseStateMatches(nextState, lease, leaseBackend)) { - return { state: nextState, changed: false }; + return { state: nextState, changed: false, admissionCheckedLease }; } return { state: buildMaterializedLeaseState(nextState, lease, leaseBackend, nextFlags), @@ -364,9 +399,10 @@ async function allocateOrReuseLease( initialApp: string | undefined, allocateBySpec: boolean | undefined, leaseLedger: LeaseLedger, + inactiveLeaseId?: string, ): Promise<{ lease: Lease; acquired: boolean }> { const connection = buildRemoteConnectionRequestMetadata(state); - if (state.leaseId && state.leaseBackend === leaseBackend) { + if (state.leaseId && state.leaseBackend === leaseBackend && state.leaseId !== inactiveLeaseId) { const existing = await heartbeatOrAllocateLease(client, state.leaseId, { tenant: state.tenant, runId: state.runId, diff --git a/src/cli/commands/connection-runtime.ts b/src/cli/commands/connection-runtime.ts index 0c687dc05c..680d238e33 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -27,6 +27,7 @@ import { resolveRequestedLeaseBackend, type LeaseLedger, } from './connection-lease-transaction.ts'; +import type { AdmissionCheckedLease, ReusedLeaseCheck } from './connection-lease-admission.ts'; import { prepareRuntimeForCommand, selectCompatibleRuntime, @@ -43,11 +44,14 @@ export async function materializeRemoteConnectionForCommand(options: { positionals?: string[]; batchSteps?: BatchStep[]; forceRuntimePrepare?: boolean; + reusedLeaseCheck?: ReusedLeaseCheck; }): Promise<{ flags: CliFlags; runtime?: SessionRuntimeHints; connection?: RemoteConnectionRequestMetadata; leaseDevice?: LeaseDevice; + /** Set when the command's admission, not a heartbeat, checks the reused lease. */ + admissionCheckedLease?: AdmissionCheckedLease; }> { const { command, flags, client, host } = options; if (!flags.remoteConfig) { @@ -101,6 +105,7 @@ export async function materializeRemoteConnectionForCommand(options: { // Unknown creation evidence permits discard before binding, but only confirmed creation permits // rollback after a later failure. A committed session record takes over either lease. const leaseLedger = createLeaseLedger(); + let admissionCheckedLease: AdmissionCheckedLease | undefined; try { const acquired = await acquireConnectionLease({ command, @@ -109,9 +114,11 @@ export async function materializeRemoteConnectionForCommand(options: { nextFlags, positionals: options.positionals, leaseLedger, + reusedLeaseCheck: options.reusedLeaseCheck, }); nextState = acquired.state; changed = changed || acquired.changed; + admissionCheckedLease = acquired.admissionCheckedLease; const runtimePreparation = await prepareRuntimeForCommand({ command, @@ -151,6 +158,7 @@ export async function materializeRemoteConnectionForCommand(options: { runtime: nextRuntime, connection: buildRemoteConnectionRequestMetadata(nextState), leaseDevice: grantedLeaseDevice(nextState), + ...(admissionCheckedLease ? { admissionCheckedLease } : {}), }; } diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 72f5ee3432..23877a2a09 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -216,7 +216,7 @@ "packages/contracts/src/daemon-http.ts#CheckedRpcProtocolRefusal": "sha256:75b71253734f2a7e1bc34c42d4c9caca0c2eb25d809e5efb2ae0df58ae694202", "packages/daemon/src/server/http/http-checked-rpc.ts#readCheckedRpcProtocolRefusal": "sha256:4c8924d8480a6af3acec96883d53636e33a199649bdd8ff63087dcf2ebaf4d29", "packages/daemon/src/server/http/http-checked-rpc.ts#sendCheckedRpcProtocolRefusal": "sha256:0538d0374405a082b3c79b4225124ecbfab49dd0f53f44e401c155834c5518a5", - "packages/daemon/src/server/http/http-server.ts#DAEMON_HTTP_CAPABILITIES": "sha256:bac67f03945b928de4fece3a5e02386ebba9b7b957b1107f76c84bc8ca574f94", + "packages/daemon/src/server/http/http-server.ts#DAEMON_HTTP_CAPABILITIES": "sha256:02f316135fa0c1e898a38a4fd19becbe1c0f0441455416df3472bce7114a5314", "packages/proxy/src/daemon-proxy.ts#isRpcRoute": "sha256:1bf3b68f6bc855bd87ee7c0bbdef467c3c76232238885ae6c67bcf245ce9b846", "packages/proxy/src/checked-rpc-admission.ts#refuseCheckedRpcProtocol": "sha256:dd63d879bf97d386889f1c4603b5722b9ad018a7f3415bcf72e44e3e8fefec48", "packages/proxy/src/daemon-proxy.ts#refuseStaleProxyInstance": "sha256:5c39c2b5a1b4bc897a2b01ac47c6856af47e787e8cc5798657f0ae24fd1c78e0", @@ -239,7 +239,7 @@ "packages/proxy/src/daemon-proxy.ts#rewriteUploadDirectUrl": "sha256:b121db3ffb5a520b4b31810a2e28ff01c1a15d959514c9fbe2a61cd960d2af93", "packages/proxy/src/daemon-proxy.ts#rewriteUploadPreflightResponse": "sha256:332820b6f10e079632330c2c4996c4faa6f339e921f12f287bd83c9296df5ccd", "packages/proxy/src/daemon-proxy.ts#rewrittenUploadPreflightResponse": "sha256:21d633d947cd72f5008bcc886a8f3ecd4f778b594d0654b8d0741db8594003db", - "packages/daemon-contracts/src/daemon-resolution.ts#DAEMON_CAPABILITIES": "sha256:4ff6eba594b923a1d8f46a5856c42132b7ecd3a63d40f26c42972e06cb5a0a04", + "packages/daemon-contracts/src/daemon-resolution.ts#DAEMON_CAPABILITIES": "sha256:d4912bf7c2f3b6ad66681eb39df376d6affdf284295fd5581ef015dc55f2745a", "packages/daemon-contracts/src/daemon-resolution.ts#DaemonCapability": "sha256:2a5acf280a72e3d54c5ad7b52aece3ced37a30e4e721ef106a98e3bbd18ddbc3", "packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88", "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:ba600575e06995bc903c107477b23f7853e920751452a50a9734fab6677326bf", @@ -694,8 +694,8 @@ }, { "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." + "digest": "sha256:d4912bf7c2f3b6ad66681eb39df376d6affdf284295fd5581ef015dc55f2745a", + "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. Adds the lease-admission capability the same way: the daemon refuses a request that names an inactive lease at admission, before dispatch, with LEASE_NOT_FOUND and dispatched no. A released client drops the unknown name and keeps its lease heartbeat; a released daemon never lists it, so a new client keeps its heartbeat." }, { "declaration": "packages/remote/src/session-script-destination.ts#RemoteEndpoint", diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 56ab349868..c43a83a91e 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -608,6 +608,7 @@ These reasons can come from more than one command. | `daemon_state_root_unsafe` | The state directory, or a directory above it, is not private to your account; `details.fix` says how to fix it. | | `relative_state_dir_without_cwd` | The state dir is a relative path and the caller gave no working directory to resolve it from. | | `remote_script_artifacts_unsupported` | The remote daemon reports no script-artifacts capability, so it would record to its own disk. | +| `lease_admission_unsupported` | The daemon reports no lease-admission capability, so it cannot check a lease no heartbeat checked. | | `daemon-busy` | The daemon still holds work, so it refused to leave; `details` counts that work. | | `daemon-instance-mismatch` | The request names a different daemon instance than the one answering it. | | `daemon-owner-embedded` | A live host process owns this daemon and ends it through its own `close()`. | From 3d3f59bc8f3d252afedb6546afcdae70b225f15c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 14:25:38 +0100 Subject: [PATCH 2/9] fix(remote): keep admission-checked commands off the checked route An admission-checked request reads lease-admission from /health, so it goes health-first on /rpc even on a checked connection. Lease-free commands there still send one checked request. Fill redaction restores details.dispatched and details.reason only when they are daemon vocabulary. The CLI loads the lease-admission dispatch on demand. Co-Authored-By: Claude Sonnet 5.5 --- .../__tests__/index-lease-admission.test.ts | 14 ++++ .../src/daemon-client-lifecycle.ts | 8 +- .../src/daemon-client-request.ts | 3 +- packages/daemon-client/src/index.ts | 1 + .../docs/remote-device-lease-contracts.md | 3 +- .../request-router-fill-text-stdin.test.ts | 51 +++++++++--- .../http-server-provider-scenarios.test.ts | 6 +- packages/daemon/src/server/request-router.ts | 16 +++- .../cli-lease-admission-proxy.test.ts | 82 ++++++++++++++++++- src/cli.ts | 6 +- website/docs/docs/remote-proxy.md | 1 + 11 files changed, 165 insertions(+), 26 deletions(-) diff --git a/packages/daemon-client/src/__tests__/index-lease-admission.test.ts b/packages/daemon-client/src/__tests__/index-lease-admission.test.ts index 1e61e77c67..f4c8702955 100644 --- a/packages/daemon-client/src/__tests__/index-lease-admission.test.ts +++ b/packages/daemon-client/src/__tests__/index-lease-admission.test.ts @@ -14,6 +14,7 @@ const LEASE_ADMISSION = ['script-artifacts', 'lease-admission']; async function sendAdmissionChecked( health: () => Record, onRpc?: (res: http.ServerResponse) => boolean, + flags: Record = {}, ) { const routes: string[] = []; const server = http.createServer((req, res) => { @@ -36,6 +37,7 @@ async function sendAdmissionChecked( flags: { daemonBaseUrl: `http://127.0.0.1:${await listenOnLoopback(server)}`, stateDir: path.join(root, 'state'), + ...flags, }, meta: { tenantId: 'proxy', runId: 'run', leaseId: 'a'.repeat(32) }, }, @@ -102,3 +104,15 @@ test('a replacement daemon without lease admission is refused before the resend' }); expect(routes).toEqual(['/health', '/rpc', '/health']); }); + +// The checked route reads no `/health`, which is where `lease-admission` is reported. +test('an admission-checked request on a checked connection goes health-first', async () => { + const { result, routes } = await sendAdmissionChecked( + () => ({ instanceId: 'daemon', capabilities: [...LEASE_ADMISSION, 'checked-rpc'] }), + undefined, + { daemonRpc: 'checked' }, + ); + + expect(result).toMatchObject({ ok: true }); + expect(routes).toEqual(['/health', '/rpc']); +}); diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index f816e9734c..1ba3ac9e3a 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -68,7 +68,8 @@ export type DaemonClientSettings = { 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. + * `daemonRpc: checked`, the request has no remote side effect before its command RPC, and nothing + * about it has to be read from `/health`. */ remoteCheckedRpc?: true; /** See {@link DaemonBinding}. Present on a client that is pinned to one daemon instance. */ @@ -105,6 +106,7 @@ export function resolveClientSettings( host: HostEnvironment, daemonLifecycle: DaemonLifecycle = 'managed', daemonBinding: DaemonBinding | undefined = undefined, + leaseCheckedByAdmission?: true, ): DaemonClientSettings { const explicitStateDir = resolveExplicitStateDir(req, host.env); const remote = resolveRemoteClientSettings(req, suppliedAuthToken, host.env); @@ -146,7 +148,9 @@ export function resolveClientSettings( ...(remote.remoteBaseUrl && remote.daemonRpc === 'checked' && approvesCheckedRpcTarget(req.flags?.daemonRpcTarget, remote.remoteBaseUrl) && - isStandaloneRemoteRequest(req) + isStandaloneRemoteRequest(req) && + // An unchecked lease needs `lease-admission`, which only `/health` reports. + !leaseCheckedByAdmission ? { remoteCheckedRpc: true as const } : {}), ...(daemonBinding ? { daemonBinding } : {}), diff --git a/packages/daemon-client/src/daemon-client-request.ts b/packages/daemon-client/src/daemon-client-request.ts index 55734bbe19..667d500ed5 100644 --- a/packages/daemon-client/src/daemon-client-request.ts +++ b/packages/daemon-client/src/daemon-client-request.ts @@ -9,7 +9,8 @@ export type DaemonTransportOptions = AgentDeviceDaemonTransportContext & { onProgress?: RequestProgressSink; /** * The request names a reused lease that no heartbeat checked, so the daemon must check it at - * admission. A daemon whose `/health` lacks `lease-admission` is refused before the send. + * admission. A daemon whose `/health` lacks `lease-admission` is refused before the send, so the + * request never takes the checked RPC route, which reads no `/health`. */ leaseCheckedByAdmission?: true; }; diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index e668d74c78..425b394318 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -99,6 +99,7 @@ async function sendToDaemonOnHost( host, options.daemonLifecycle, options.daemonBinding, + options.leaseCheckedByAdmission, ); const requestTimeoutMs = resolveCommandRequestTimeoutMs( resolveCommandTimeoutPolicy(requestWithoutAuthFlag.command), diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index b316647e76..2e52553362 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -70,7 +70,7 @@ The refusal is `UNAUTHORIZED` with `details.reason: LEASE_NOT_FOUND` and `detail Every lease-admission refusal comes after authentication and tenant scoping, and before any handler runs. If the request names the expired lease of its session, the daemon refuses before it tears that session down. The lease expiry sweep ends that session later. -A sensitive `fill` value never redacts `details.reason` or `details.dispatched`. +A sensitive `fill` value never redacts a typed `details.dispatched` or a shared lease `details.reason`. Any other value in those fields stays redacted. A daemon that makes this refusal advertises the `lease-admission` capability on `/health`. A proxy forwards the capability of the daemon behind it in `upstream`. @@ -79,6 +79,7 @@ It then marks the command as admission-checked and names the window that the hea The daemon-client reads `lease-admission` from the `/health` check that the command already makes. If the capability is absent, the daemon-client refuses the command before the send with `lease_admission_unsupported`. It makes the same check again after an instance-mismatch refresh. +An admission-checked command never takes the checked RPC route. On a checked connection (`daemonRpc: checked`) it is `GET /health`, then `POST /rpc`. If the only request of the command gets either refusal, the CLI materializes the connection again and sends the command once more. After `LEASE_NOT_FOUND`, the CLI allocates a new lease. After `lease_admission_unsupported`, it sends the heartbeat. The CLI does not resend on any other failure. diff --git a/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts b/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts index b27ceb2864..e6943a60f9 100644 --- a/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts @@ -225,25 +225,50 @@ test.each([ }, ); -// A lease-admission client resends only on `dispatched: no`, so a recorded value equal to it must not -// rewrite the typed refusal. -test('a --record-as value equal to a typed detail leaves the lease refusal readable', async () => { - const { response, typed } = sendToWebSession( +// A lease-admission client resends only on `dispatched: no`, so a recorded value that occurs in a +// daemon-owned detail must not rewrite the typed refusal. +test.each(['no', 'NOT'])( + 'a --record-as value %s inside a typed detail leaves the lease refusal readable', + async (value) => { + const { response, typed } = sendToWebSession( + makeAuthoringSession('web', { device: WEB_DESKTOP_DEVICE }), + { + command: 'fill', + positionals: ['10', '20', value], + flags: { textStdin: true, recordAs: 'CODE' }, + meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId: '0'.repeat(32) }, + }, + ); + + const result = await response; + expect(typed).toEqual([]); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.code).toBe('UNAUTHORIZED'); + expect(result.error.details).toMatchObject({ reason: 'LEASE_NOT_FOUND', dispatched: 'no' }); + } + }, +); + +test('a backend error carrying the value in details.reason or details.dispatched keeps it redacted', async () => { + const { response } = fillWithStdinText( makeAuthoringSession('web', { device: WEB_DESKTOP_DEVICE }), - { - command: 'fill', - positionals: ['10', '20', 'no'], - flags: { textStdin: true, recordAs: 'CODE' }, - meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId: '0'.repeat(32) }, - }, + { recordAs: 'PASSWORD' }, + (text) => + new AppError('COMMAND_FAILED', 'could not type', { + reason: `rejected-${text}`, + dispatched: text, + }), ); const result = await response; - expect(typed).toEqual([]); expect(result.ok).toBe(false); + expect(JSON.stringify(result)).not.toContain(SECRET); if (!result.ok) { - expect(result.error.code).toBe('UNAUTHORIZED'); - expect(result.error.details).toMatchObject({ reason: 'LEASE_NOT_FOUND', dispatched: 'no' }); + expect(result.error.details).toMatchObject({ + reason: 'rejected-${PASSWORD}', + dispatched: '${PASSWORD}', + }); } }); diff --git a/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts b/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts index e1d2bcdc7d..b5610331e7 100644 --- a/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts +++ b/packages/daemon/src/server/http/http-server-provider-scenarios.test.ts @@ -114,7 +114,11 @@ test('Provider-backed integration daemon HTTP server maps RPC methods, auth, and assert.equal(typeof healthPayload.version, 'string'); assert.equal(healthPayload.rpcProtocolVersion, DAEMON_RPC_PROTOCOL_VERSION); // A remote client skips its lease heartbeat only for a daemon that says admission checks leases. - assert.deepEqual(healthPayload.capabilities, ['script-artifacts', 'lease-admission']); + assert.deepEqual(healthPayload.capabilities, [ + 'script-artifacts', + 'checked-rpc', + 'lease-admission', + ]); const command = await callRpc(port, { jsonrpc: '2.0', diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index 3b5a9527f5..1dc9f7b6b1 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -14,6 +14,7 @@ import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform import { AppError, normalizeError, + readDispatchDisclosure, retriableForErrorCode, type DaemonError, } from '@agent-device/kernel/errors'; @@ -61,6 +62,7 @@ import { saveScriptFlagResponse } from './request-save-script-policy.ts'; import { deviceSpecInvalidError, deviceSpecUnsupportedError, + LEASE_REASONS, readLeaseDeviceSpec, } from '@agent-device/contracts/lease-scope'; import { @@ -625,9 +627,9 @@ const ERROR_TEXT_FIELDS: ReadonlySet = new Set(['message', 'hint', 'caus * A backend error can quote the text a sensitive fill failed to type, or the altered text it read * back, which `redactFillFailureReadBack` replaces whole. Only that fill's own text is otherwise * redacted, and only in the error's text fields: `logPath`, `diagnosticId` and the other - * daemon-owned fields come back as they are, and so does every other request's error. The typed - * `details.reason` and `details.dispatched` are daemon vocabulary, never typed text, so a value - * that happens to equal one (`no`) cannot rewrite them. + * daemon-owned fields come back as they are, and so does every other request's error. A typed + * `details.dispatched` or a shared lease `details.reason` is daemon vocabulary, so a value that + * happens to occur in one (`no`) cannot rewrite it. Any other value in those fields stays redacted. */ function redactSensitiveFillTextInError(req: DaemonRequest, error: DaemonError): DaemonError { const text = sensitiveFillText(req); @@ -649,9 +651,15 @@ function redactSensitiveFillTextInError(req: DaemonRequest, error: DaemonError): ) as DaemonError; } +/** The lease reasons a client branches on, which the daemon writes as constants. */ +const LEASE_REASON_VALUES: ReadonlySet = new Set( + Object.values(LEASE_REASONS).map((row) => row.reason), +); + function withTypedDetails(redacted: unknown, original: DaemonError['details']): unknown { if (!redacted || typeof redacted !== 'object' || !original) return redacted; - const { reason, dispatched } = original; + const dispatched = readDispatchDisclosure(original); + const reason = LEASE_REASON_VALUES.has(original.reason) ? original.reason : undefined; return { ...redacted, ...(reason === undefined ? {} : { reason }), diff --git a/src/__tests__/cli-lease-admission-proxy.test.ts b/src/__tests__/cli-lease-admission-proxy.test.ts index b3e2d40719..ea8a72371a 100644 --- a/src/__tests__/cli-lease-admission-proxy.test.ts +++ b/src/__tests__/cli-lease-admission-proxy.test.ts @@ -89,14 +89,92 @@ test('a lease the daemon dropped is reallocated through the proxy without a hear } }); +// A checked connection keeps the one checked request for a command that checks no lease. A command on +// the connection's reused lease reads `lease-admission` from `/health`, so it goes on `/rpc`. +test('a checked connection sends a reused-lease command health-first and without a heartbeat', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { root, home, project } = makeTempWorkspace(); + const daemon = await startPublicDaemonRuntime({ + serverMode: 'http', + env: { AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST: 'emulator-9999' }, + }); + const upstream: string[] = []; + const proxy = createDaemonProxyServer({ + upstreamBaseUrl: daemon.baseUrl, + upstreamToken: daemon.runtime.token, + clientToken: 'client-secret', + upstreamFetch: async (request) => { + upstream.push(await describe(request)); + return await fetch(request); + }, + }); + try { + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}/agent-device`; + const stateDir = path.join(root, 'state'); + const remoteConfigPath = path.join(project, 'checked.remote.json'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ + daemonBaseUrl: baseUrl, + daemonRpc: 'checked', + tenant: LEASE_SCOPE.tenant, + runId: LEASE_SCOPE.runId, + leaseProvider: LEASE_SCOPE.leaseProvider, + clientId: LEASE_SCOPE.clientId, + leaseBackend: LEASE_SCOPE.leaseBackend, + platform: 'android', + }), + ); + const cli = async (argv: string[]) => + await runCliCapture([...argv, '--session', 'agent', '--state-dir', stateDir, '--json'], { + cwd: project, + env: { HOME: home, AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'client-secret' }, + useRealDaemonClient: true, + }); + const connected = await cli(['connect', '--remote-config', remoteConfigPath]); + assert.equal(connected.code, null, connected.stdout); + const state = readRemoteConnectionState({ stateDir, session: 'agent' }); + assert.ok(state?.daemon?.checkedRpcTarget, connected.stdout); + + // The lease comes from the daemon directly, so this process holds no `/health` for the proxy. + const direct = createAgentDeviceClient({ + daemonBaseUrl: daemon.baseUrl, + daemonAuthToken: daemon.runtime.token, + daemonTransport: 'http', + }); + const lease = await direct.leases.allocate({ ...LEASE_SCOPE, leaseId: 'c'.repeat(32) }); + writeRemoteConnectionState({ + stateDir, + state: { ...state, leaseId: lease.leaseId, deviceKey: LEASE_SCOPE.deviceKey }, + }); + + upstream.length = 0; + const listed = await cli(['session', 'list']); + assert.equal(listed.code, null, listed.stdout); + assert.deepEqual(upstream, ['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/rpc/checked session_list']); + + upstream.length = 0; + await cli(['snapshot']); + // No device answers, so the failed command also reads its diagnostics record. + assert.deepEqual( + upstream.filter((route) => !route.startsWith('/sessions/')), + ['/health', '/rpc snapshot'], + ); + } finally { + await closeLoopbackServer(proxy); + await daemon.close(); + fs.rmSync(root, { recursive: true, force: true }); + } +}); + async function describe(request: Request): Promise { const route = new URL(request.url).pathname; - if (route !== '/rpc') return route; + if (route !== '/rpc' && route !== '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/rpc/checked') return route; const body = JSON.parse(await request.clone().text()) as { method?: string; params?: { command?: string }; }; - return `/rpc ${body.method === 'agent_device.command' ? body.params?.command : body.method}`; + return `${route} ${body.method === 'agent_device.command' ? body.params?.command : body.method}`; } function writeConnection(stateDir: string, project: string, baseUrl: string, leaseId: string) { diff --git a/src/cli.ts b/src/cli.ts index 5a9aac31e8..2cd89bcfd6 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -66,7 +66,7 @@ import type { FlagKey } from '@agent-device/command-registry/flag-types'; import type { CliFlags } from '@agent-device/contracts/command'; import type { SessionRuntimeHints } from '@agent-device/kernel/contracts'; import { isKnownCliCommandName } from '@agent-device/command-registry/catalog'; -import * as LeaseAdmission from './cli/commands/connection-lease-admission.ts'; +import type * as LeaseAdmission from './cli/commands/connection-lease-admission.ts'; type CliDeps = { sendToDaemon: typeof sendToDaemon; @@ -224,7 +224,9 @@ async function runCliOnHost(argv: string[], deps: CliDeps, host: HostEnvironment const replayTestReporterRuntime = await createReplayReporterForTest(ctx); const commandProgress = createCommandProgressState(); const transportSetup = { host, command, replayTestReporterRuntime, commandProgress }; - await LeaseAdmission.dispatchWithLeaseAdmission(ctx.leaseAdmission?.checked, transport, { + const { dispatchWithLeaseAdmission } = + await import('./cli/commands/connection-lease-admission.ts'); + await dispatchWithLeaseAdmission(ctx.leaseAdmission?.checked, transport, { rematerialize: async (check) => await resolveRemoteContext(ctx, transport, check), dispatch: async (send) => { const client = createAgentDeviceClient(buildClientConfig(ctx), { diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 31d00959a5..c755b5b827 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -376,6 +376,7 @@ Without the field, a command's dispatch makes two requests: `GET /health`, then Only `connect` turns the field on, and only when the proxy, and the daemon behind it, list `checked-rpc` in `capabilities` on `/health`. The proxy's `upstream` must be the daemon itself, not another proxy. The connection then records a fingerprint of that exact target, and a command sent to any other base URL reads `/health` first. Otherwise `connect` fails with `reason: "remote_checked_rpc_unsupported"` and `dispatched: "no"`: when a link lacks the capability, or when the profile resolves no daemon base URL. An unreachable `/health` fails with `remote_daemon_unavailable`. No flag or environment variable turns it on. +- A command on the lease the connection already holds can skip the lease heartbeat. Such a command still reads `/health` first, then sends on `/rpc`: `/health` says whether the daemon checks the lease when it admits the command (`lease-admission`). If the lease has ended, the daemon refuses the command before it runs, and the client allocates a new lease and sends the command once more. - 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. From 370830350fb6eedfe86849768676edb3d49c8776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 14:27:15 +0100 Subject: [PATCH 3/9] refactor(cli): move the CLI daemon transport into its own module Keeps cli.ts and daemon-client-transport.ts under the line limit. Co-Authored-By: Claude Sonnet 5.5 --- .../src/daemon-client-remote-resend-port.ts | 2 + .../src/daemon-client-remote-resend.ts | 3 +- .../src/daemon-client-transport.ts | 8 +- .../request-router-fill-text-stdin.test.ts | 5 +- src/cli.ts | 84 ++----------------- src/cli/cli-daemon-transport.ts | 84 +++++++++++++++++++ 6 files changed, 100 insertions(+), 86 deletions(-) create mode 100644 src/cli/cli-daemon-transport.ts diff --git a/packages/daemon-client/src/daemon-client-remote-resend-port.ts b/packages/daemon-client/src/daemon-client-remote-resend-port.ts index ca3a534278..b4e930590a 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend-port.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend-port.ts @@ -20,6 +20,8 @@ export type RemoteResendPort = { timeoutMs: number | undefined; deadline: number | undefined; signal: AbortSignal | undefined; + /** The request relies on admission to check its lease; a replacement must report `lease-admission`. */ + leaseCheckedByAdmission?: true; /** Sends the request once more, with `timeoutMs` as its budget. */ resend(timeoutMs: number | undefined): Promise; /** A live `/health` read that refuses a skewed protocol. */ diff --git a/packages/daemon-client/src/daemon-client-remote-resend.ts b/packages/daemon-client/src/daemon-client-remote-resend.ts index c5b19bbfe1..cc01c0faa3 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -68,7 +68,6 @@ export async function sendCheckedRpcAfterConnectFailure( export async function retryAfterRemoteInstanceMismatch( port: RemoteResendPort, scriptPublicationId: string | undefined, - leaseCheckedByAdmission: boolean | undefined, ): Promise { const { info } = port; await port.invalidateHealth(); @@ -86,7 +85,7 @@ export async function retryAfterRemoteInstanceMismatch( // A replacement daemon must still deliver the script that a remote recording asks for. if (scriptPublicationId) assertScriptArtifactsCapability(info.capabilities); // A replacement that cannot check the lease at admission gets the heartbeat path instead. - if (leaseCheckedByAdmission) assertLeaseAdmissionCapability(info.capabilities); + if (port.leaseCheckedByAdmission) assertLeaseAdmissionCapability(info.capabilities); try { return await port.resend(remainingMs); } catch (error) { diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 5f58a97930..51ebf3ef95 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -48,7 +48,6 @@ type ResolvedDaemonTransport = LoopbackTransport; type SendRequestOptions = { /** The host whose working directory and environment this request's client-side work reads. */ host: HostEnvironment; - /** See `DaemonTransportOptions.leaseCheckedByAdmission`; rechecked against a replacement daemon. */ leaseCheckedByAdmission?: true; onProgress?: RequestProgressSink; /** @@ -514,11 +513,7 @@ async function sendRequestWithFallback( 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, - options.leaseCheckedByAdmission, - ); + : await resend.retryAfterRemoteInstanceMismatch(port, req.meta?.scriptPublicationId); } if (isRemoteTransportFailure(error)) await invalidateRemoteDaemonHealth(info); const fallback = chooseAutoFallbackTransport(info, preference, transport); @@ -542,6 +537,7 @@ function remoteResendPort( timeoutMs, deadline, signal: options.signal, + leaseCheckedByAdmission: options.leaseCheckedByAdmission, resend: async (budgetMs) => await sendRequestWithTransport(info, req, statePaths, budgetMs, transport, options), readHealth: async (probeMs) => await readRemoteDaemonHealth(info, probeMs, options.signal), diff --git a/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts b/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts index e6943a60f9..3c00b29c14 100644 --- a/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts @@ -7,7 +7,7 @@ import { expect, test } from 'vitest'; import fs from 'node:fs'; import path from 'node:path'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type DispatchDisclosure } from '@agent-device/kernel/errors'; import { createTestDeviceInventoryGateways } from '@agent-device/device-selection/inventory-gateways-fixtures'; import { localRuntimeOwner, @@ -257,7 +257,8 @@ test('a backend error carrying the value in details.reason or details.dispatched (text) => new AppError('COMMAND_FAILED', 'could not type', { reason: `rejected-${text}`, - dispatched: text, + // A value outside the type, as an untrusted backend could write it. + dispatched: text as DispatchDisclosure, }), ); diff --git a/src/cli.ts b/src/cli.ts index 2cd89bcfd6..5196f84b88 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -24,14 +24,10 @@ import { import fs from 'node:fs'; import type { ReplayTestReporterRuntime } from './cli/replay-test/reporting.ts'; import type { CommandProgressState } from '@agent-device/command-output'; -import { - createCommandProgressState, - createStderrCommandProgressSink, -} from './commands/command-progress.ts'; +import { createCommandProgressState } from './commands/command-progress.ts'; import { createAgentDeviceClient } from '@agent-device/client'; import type { AgentDeviceClientConfig, - AgentDeviceDaemonTransport, BatchStep, LeaseDevice, } from '@agent-device/contracts/client'; @@ -75,9 +71,6 @@ type CliDeps = { }; type CliDaemonTransport = typeof sendToDaemon; -type CliDaemonRequest = Parameters[0]; -type CliDaemonTransportOptions = Parameters[1]; -type ClientDaemonRequest = Parameters[0]; const printHumanError = async ( ...args: Parameters @@ -223,9 +216,9 @@ async function runCliOnHost(argv: string[], deps: CliDeps, host: HostEnvironment logTailStopper = maybeStartDaemonLogTail(ctx); const replayTestReporterRuntime = await createReplayReporterForTest(ctx); const commandProgress = createCommandProgressState(); - const transportSetup = { host, command, replayTestReporterRuntime, commandProgress }; const { dispatchWithLeaseAdmission } = await import('./cli/commands/connection-lease-admission.ts'); + const { createCliDaemonTransport } = await import('./cli/cli-daemon-transport.ts'); await dispatchWithLeaseAdmission(ctx.leaseAdmission?.checked, transport, { rematerialize: async (check) => await resolveRemoteContext(ctx, transport, check), dispatch: async (send) => { @@ -233,8 +226,11 @@ async function runCliOnHost(argv: string[], deps: CliDeps, host: HostEnvironment host: ctx.host, devicePin: ctx.devicePin, transport: createCliDaemonTransport({ - ...transportSetup, + host, + command, flags: ctx.effectiveFlags, + replayTestReporterRuntime, + commandProgress, transport: send, }), }); @@ -375,6 +371,7 @@ type CliRunContext = { connectionMetadata: RemoteConnectionRequestMetadata | undefined; /** The device a proxy backend granted for the lease's device spec; `open` reports it. */ leaseDevice?: LeaseDevice; + /** The flags before materialization, and the reused lease that the command's admission checks. */ leaseAdmission?: { flagsBefore: CliFlags; checked?: LeaseAdmission.AdmissionCheckedLease }; parsedBatchSteps: BatchStep[] | undefined; devicePin: DevicePin | undefined; @@ -499,6 +496,7 @@ async function resolveRemoteContext( if (ctx.effectiveFlags.remoteConfig && shouldMaterializeRemoteConnection(ctx.command)) { ctx.effectiveFlags = (ctx.leaseAdmission ??= { flagsBefore: ctx.effectiveFlags }).flagsBefore; + const { createClientDaemonTransport } = await import('./cli/cli-daemon-transport.ts'); // 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( @@ -877,72 +875,6 @@ function hasExplicitMetroRuntimeOverrides(explicitFlagKeys: Set): boole return false; } -type CliDaemonTransportSetup = { - host: HostEnvironment; - command: string; - flags: CliFlags; - replayTestReporterRuntime?: ReplayTestReporterRuntime; - commandProgress: CommandProgressState; - transport: CliDaemonTransport; -}; - -/** - * A remote connection reads each daemon reply for the leases its request ended, and forgets the - * stored lease when the reply names it. - */ -function createCliDaemonTransport(options: CliDaemonTransportSetup): AgentDeviceDaemonTransport { - const send = createCliProgressTransport(options); - if (!options.flags.remoteConfig) return send; - return async (req, context) => { - const response = await send(req, context); - const { forgetEndedConnectionLease } = await import('./cli/connection/ended-lease.ts'); - forgetEndedConnectionLease(options.flags, response, options.host); - return response; - }; -} - -/** - * The human CLI renders streamed progress itself: `test` hands its events to the - * replay-test reporter, every other command streams `command` lines to stderr - * through `commandProgress`, whose state the output formatters then read (a - * doctor summary does not repeat checks progress already printed). `--json` opts - * out of progress entirely, so it installs no sink. - */ -function createCliProgressTransport(options: CliDaemonTransportSetup): AgentDeviceDaemonTransport { - const { command, flags, replayTestReporterRuntime, transport } = options; - if (flags.json) return createClientDaemonTransport(transport); - const onProgress = - command === 'test' && replayTestReporterRuntime - ? replayTestReporterRuntime.onProgress - : createStderrCommandProgressSink(options.commandProgress, options.host.env); - return async (req, context) => { - const transportOptions = { ...context, onProgress }; - return await sendClientRequestToCliTransport( - transport, - { - ...req, - meta: { - ...req.meta, - requestProgress: command === 'test' ? 'replay-test' : 'command', - }, - }, - transportOptions, - ); - }; -} - -function createClientDaemonTransport(transport: CliDaemonTransport): AgentDeviceDaemonTransport { - return async (req, context) => await sendClientRequestToCliTransport(transport, req, context); -} - -async function sendClientRequestToCliTransport( - transport: CliDaemonTransport, - req: ClientDaemonRequest, - options?: CliDaemonTransportOptions, -): ReturnType { - return await transport(req as CliDaemonRequest, options); -} - function guessSessionFromArgv(argv: string[]): string | null { for (let i = 0; i < argv.length; i += 1) { const token = argv[i]!; diff --git a/src/cli/cli-daemon-transport.ts b/src/cli/cli-daemon-transport.ts new file mode 100644 index 0000000000..044faae922 --- /dev/null +++ b/src/cli/cli-daemon-transport.ts @@ -0,0 +1,84 @@ +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { CommandProgressState } from '@agent-device/command-output'; +import type { AgentDeviceDaemonTransport } from '@agent-device/contracts/client'; +import type { CliFlags } from '@agent-device/contracts/command'; +import type { sendToDaemon } from '@agent-device/daemon-client'; +import { createStderrCommandProgressSink } from '../commands/command-progress.ts'; +import type { ReplayTestReporterRuntime } from './replay-test/reporting.ts'; + +// The client transports built on the daemon transport one CLI run sends through. + +type CliDaemonTransport = typeof sendToDaemon; +type CliDaemonRequest = Parameters[0]; +type CliDaemonTransportOptions = Parameters[1]; +type ClientDaemonRequest = Parameters[0]; + +type CliDaemonTransportSetup = { + host: HostEnvironment; + command: string; + flags: CliFlags; + replayTestReporterRuntime?: ReplayTestReporterRuntime; + commandProgress: CommandProgressState; + transport: CliDaemonTransport; +}; + +/** + * A remote connection reads each daemon reply for the leases its request ended, and forgets the + * stored lease when the reply names it. + */ +export function createCliDaemonTransport( + options: CliDaemonTransportSetup, +): AgentDeviceDaemonTransport { + const send = createCliProgressTransport(options); + if (!options.flags.remoteConfig) return send; + return async (req, context) => { + const response = await send(req, context); + const { forgetEndedConnectionLease } = await import('./connection/ended-lease.ts'); + forgetEndedConnectionLease(options.flags, response, options.host); + return response; + }; +} + +/** + * The human CLI renders streamed progress itself: `test` hands its events to the + * replay-test reporter, every other command streams `command` lines to stderr + * through `commandProgress`, whose state the output formatters then read (a + * doctor summary does not repeat checks progress already printed). `--json` opts + * out of progress entirely, so it installs no sink. + */ +function createCliProgressTransport(options: CliDaemonTransportSetup): AgentDeviceDaemonTransport { + const { command, flags, replayTestReporterRuntime, transport } = options; + if (flags.json) return createClientDaemonTransport(transport); + const onProgress = + command === 'test' && replayTestReporterRuntime + ? replayTestReporterRuntime.onProgress + : createStderrCommandProgressSink(options.commandProgress, options.host.env); + return async (req, context) => { + const transportOptions = { ...context, onProgress }; + return await sendClientRequestToCliTransport( + transport, + { + ...req, + meta: { + ...req.meta, + requestProgress: command === 'test' ? 'replay-test' : 'command', + }, + }, + transportOptions, + ); + }; +} + +export function createClientDaemonTransport( + transport: CliDaemonTransport, +): AgentDeviceDaemonTransport { + return async (req, context) => await sendClientRequestToCliTransport(transport, req, context); +} + +async function sendClientRequestToCliTransport( + transport: CliDaemonTransport, + req: ClientDaemonRequest, + options?: CliDaemonTransportOptions, +): ReturnType { + return await transport(req as CliDaemonRequest, options); +} From 21677181b520324e556c0623a7968eee15fba755 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 14:41:34 +0100 Subject: [PATCH 4/9] fix(daemon): let close tear down a session whose lease expired Refusing before teardown now applies only to a request that would do device work under the expired lease. A close or an admission-exempt command ends the session at once, and a close also ends one whose lease the registry no longer holds. Its refusal states no dispatch disclosure, since teardown may have run. Co-Authored-By: Claude Sonnet 5.5 --- .../docs/remote-device-lease-contracts.md | 5 +- ...quest-execution-scope-lease-expiry.test.ts | 72 +++++++++++++++++++ .../__tests__/lease-lifecycle.test.ts | 51 +++++++++---- .../daemon/src/sessions/lease-lifecycle.ts | 49 +++++++++---- src/__tests__/cli-lease-admission.test.ts | 13 ++++ 5 files changed, 160 insertions(+), 30 deletions(-) diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index 2e52553362..f7d8d63ff4 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -68,8 +68,11 @@ The client then allocates a new lease under a fresh id. Request admission refuses a request that names an inactive or unknown lease. The refusal is `UNAUTHORIZED` with `details.reason: LEASE_NOT_FOUND` and `details.dispatched: no`. Every lease-admission refusal comes after authentication and tenant scoping, and before any handler runs. -If the request names the expired lease of its session, the daemon refuses before it tears that session down. +If a request that would do device work names the expired lease of its session, the daemon refuses before it tears that session down. The lease expiry sweep ends that session later. +For a `close` or an admission-exempt command, such as `lease_release`, the daemon tears that session down at once. +A `close` also tears down a session whose lease the registry no longer holds. +A refusal of `close` states no `details.dispatched`, because the teardown may have run. A sensitive `fill` value never redacts a typed `details.dispatched` or a shared lease `details.reason`. Any other value in those fields stays redacted. A daemon that makes this refusal advertises the `lease-admission` capability on `/health`. A proxy forwards the capability of the daemon behind it in `upstream`. diff --git a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts index cb11bf74c4..4f04d9a856 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts @@ -4,11 +4,18 @@ import { daemonClaimRecoveryGatewayFixture, } from '../../__tests__/support/platform-services-fixture.ts'; import { makeSession } from '../../__tests__/support/session-factories.ts'; +import fs from 'node:fs'; import { LINUX_DEVICE, createTestHostEnvironment, bindTestCommandHost, + deviceClaimFilePath, } from '@agent-device/test-kit'; +import { acquireDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; +import { + isolatedDeviceClaimStores, + retainOrphanedDeviceClaims, +} from '../../__tests__/support/device-claim-store.ts'; import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { createRequestExecutionScope } from '../request-execution-scope.ts'; @@ -20,6 +27,8 @@ import { bindTestCommandHost(); +const claimStores = isolatedDeviceClaimStores('agent-device-request-scope-claims-'); + function makeRequest(overrides: Partial): DaemonRequest { return { token: 't', @@ -156,3 +165,66 @@ test.each(['rebuild', 'retire'] as const)( else expect(store.lookup(address)).toBeUndefined(); }, ); + +test.each(['expired', 'released'] as const)( + 'a close naming its session lease that is %s tears down the session and claim and rents nothing', + async (fate) => { + let now = 1_000; + const sessionStore = makeSessionStore('agent-device-request-scope-'); + const leaseRegistry = new LeaseRegistry({ + defaultLeaseTtlMs: 10, + minLeaseTtlMs: 1, + now: () => now, + }); + const owner = { tenantId: 'tenant-a', runId: 'run-1' }; + const lease = leaseRegistry.allocateLease(owner); + const meta = { ...owner, leaseId: lease.leaseId, sessionIsolation: 'tenant' as const }; + const session = makeSession('tenant-a:default', { + device: LINUX_DEVICE, + lease: { ...owner, leaseId: lease.leaseId, leaseBackend: lease.backend }, + }); + const { stateDir } = claimStores(); + const claim = await acquireDeviceClaim({ + env: process.env, + device: session.device, + session: session.name, + workspace: stateDir, + stateDir, + reconcileOrphanedDeviceClaim: retainOrphanedDeviceClaims, + }); + if (claim.status !== 'acquired') throw new Error('expected an acquired claim'); + sessionStore.publish(session.name, { ...session, deviceClaim: claim.ownership }); + const claimFile = deviceClaimFilePath(claim.ownership.deviceKey); + expect(fs.existsSync(claimFile)).toBe(true); + if (fate === 'expired') now = 1_011; + else leaseRegistry.releaseLease({ ...owner, leaseId: lease.leaseId }); + const task = vi.fn(async () => 'ran'); + + const scope = await createRequestExecutionScope({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + claimRecoveryGateway: daemonClaimRecoveryGatewayFixture(), + trackClaimRecoveryDisposal: () => {}, + deviceRuntimeGateway: unavailableDeviceRuntimeGateway, + platformRequestScope: platformRequestScopeFixture(), + req: makeRequest({ command: 'close', session: session.name, meta }), + sessionStore, + leaseRegistry, + platformResourceCleanup: { + stopSnapshotHelper: async () => {}, + closeManagedBrowser: async () => {}, + cleanupSessionlessExecutionHost: async () => {}, + retainExecutionHostAfterClose: () => false, + }, + }); + const refusal = await scope.runLocked(task).catch((error: unknown) => error); + + expect(sessionStore.get(session.name)).toBeUndefined(); + expect(fs.existsSync(claimFile)).toBe(false); + expect(leaseRegistry.listActiveLeases()).toEqual([]); + expect(task).not.toHaveBeenCalled(); + // The lease is still refused, without claiming that nothing ran. + expect(refusal).toMatchObject({ details: { reason: 'LEASE_NOT_FOUND' } }); + expect(refusal).not.toHaveProperty('details.dispatched'); + }, +); diff --git a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts index 56a38bcf96..0f33835feb 100644 --- a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts +++ b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts @@ -132,9 +132,7 @@ test('cleanupExpiredLeasedSession consumes expired lease and deletes the session expect(leaseRegistry.listActiveLeases()).toHaveLength(0); }); -// The refusal says `dispatched: no`, so the request that names the expired lease must not tear its -// session down (recording, claim, runner) before the client reallocates; the expiry sweep does that. -test('cleanupExpiredLeasedSession refuses a request naming the expired lease before any teardown', async () => { +function sessionWithExpiredLease() { let now = 1_000; const sessionStore = makeSessionStore('agent-device-lease-lifecycle-'); const leaseRegistry = new LeaseRegistry({ @@ -149,26 +147,51 @@ test('cleanupExpiredLeasedSession refuses a request naming the expired lease bef sessionStore.publish('default', session); now = 1_011; const teardownSession = vi.fn(async () => {}); - - await expect( + const cleanup = (request: Partial & Pick) => cleanupExpiredLeasedSession({ req: makeRequest({ - command: 'press', meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId: lease.leaseId }, + ...request, }), env: process.env, sessionName: 'default', sessionStore, leaseRegistry, teardownSession, - }), - ).rejects.toMatchObject({ - code: 'UNAUTHORIZED', - details: { reason: 'LEASE_NOT_FOUND', dispatched: 'no' }, - }); - expect(teardownSession).not.toHaveBeenCalled(); - expect(sessionStore.get('default')).toBe(session); -}); + }); + return { sessionStore, session, teardownSession, cleanup }; +} + +// The refusal says `dispatched: no`, so a request that would do device work under the expired lease +// must not tear its session down (recording, claim, runner) before the client reallocates; the +// expiry sweep does that. +test.each<[string, Partial & Pick]>([ + ['press', { command: 'press' }], + ['an app-only close', { command: 'close', internal: { closeAppOnly: true } }], +])( + 'cleanupExpiredLeasedSession refuses %s naming the expired lease before any teardown', + async (_name, request) => { + const { sessionStore, session, teardownSession, cleanup } = sessionWithExpiredLease(); + + await expect(cleanup(request)).rejects.toMatchObject({ + code: 'UNAUTHORIZED', + details: { reason: 'LEASE_NOT_FOUND', dispatched: 'no' }, + }); + expect(teardownSession).not.toHaveBeenCalled(); + expect(sessionStore.get('default')).toBe(session); + }, +); + +test.each(['close', 'lease_release', 'lease_heartbeat'])( + 'cleanupExpiredLeasedSession tears down for %s naming the expired lease', + async (command) => { + const { sessionStore, teardownSession, cleanup } = sessionWithExpiredLease(); + + await expect(cleanup({ command })).resolves.toBe(true); + expect(teardownSession).toHaveBeenCalledOnce(); + expect(sessionStore.get('default')).toBeUndefined(); + }, +); test('releaseSessionLease releases with the stored session owner scope', async () => { const leaseRegistry = new LeaseRegistry(); diff --git a/packages/daemon/src/sessions/lease-lifecycle.ts b/packages/daemon/src/sessions/lease-lifecycle.ts index b65756cc0d..5331380460 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -2,6 +2,8 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { LEASE_REASONS, leaseScopeToReleaseRequest } from '@agent-device/contracts/lease-scope'; import { clearDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; +import { resolveCommandDeviceClaimPolicy } from '@agent-device/command-registry/registry'; +import { isLeaseAdmissionExempt } from '../core/daemon-command-registry.ts'; import type { LeaseRegistry } from '../resources/lease-registry.ts'; import type { DeviceLease, @@ -61,9 +63,11 @@ export async function releaseExpiredProviderLease( /** * Ends the session of the request whose session lease expired, or refuses the request before that - * teardown. A composite is refused so it does not lose its session mid-run. A request that names - * that lease is refused so its client can reallocate and resend: the refusal says `dispatched: no`, so - * nothing of the request may run first. The lease expiry sweep ends that session instead. + * teardown. A composite is refused so it does not lose its session mid-run. A request that would do + * device work under that lease is refused so its client can reallocate and resend: the refusal says + * `dispatched: no`, so nothing of the request may run first, and the lease expiry sweep ends the + * session instead. A `close` or an admission-exempt command ends it now, and a `close` also ends a + * session whose lease the registry no longer holds. */ export async function cleanupExpiredLeasedSession(params: { req: DaemonRequest; @@ -76,16 +80,18 @@ export async function cleanupExpiredLeasedSession(params: { const ref = params.sessionStore.lookup(params.sessionName); const lease = ref?.session.lease; if (!ref || !lease) return false; - if ( - !params.leaseRegistry.consumeExpiredLease(lease.leaseId, () => { - if (!refusesExpiredLeaseTeardown(params.req, lease.leaseId)) return; - throw new AppError('UNAUTHORIZED', 'Lease is not active', { - reason: LEASE_REASONS.notFound.reason, - dispatched: 'no', - }); - }) - ) - return false; + const expired = params.leaseRegistry.consumeExpiredLease(lease.leaseId, () => { + if (!refusesExpiredLeaseTeardown(params.req, lease.leaseId)) return; + throw new AppError('UNAUTHORIZED', 'Lease is not active', { + reason: LEASE_REASONS.notFound.reason, + dispatched: 'no', + }); + }); + const closesLapsedSession = + endsSession(params.req) && + !isBoundedCompositeRequest(params.req) && + params.leaseRegistry.inspectLeaseBackend(lease.leaseId) === undefined; + if (!expired && !closesLapsedSession) return false; await endLeasedSession( ref, params.sessionStore, @@ -101,7 +107,19 @@ function refusesExpiredLeaseTeardown(req: DaemonRequest, expiredLeaseId: string) req.command === 'batch' || req.command === 'replay' || isBoundedCompositeRequest(req) || - resolveLeaseScope(req).leaseId === expiredLeaseId + (doesDeviceWork(req) && resolveLeaseScope(req).leaseId === expiredLeaseId) + ); +} + +function doesDeviceWork(req: DaemonRequest): boolean { + return !endsSession(req) && !isLeaseAdmissionExempt(req.command); +} + +/** A `close` ends its session, unless a replay step asks it to close only the app. */ +function endsSession(req: DaemonRequest): boolean { + return ( + resolveCommandDeviceClaimPolicy(req.command) === 'release-session' && + req.internal?.closeAppOnly !== true ); } @@ -159,6 +177,7 @@ export function admitRequestLeaseForLockedScope(params: { const existingSession = ref?.session; // Admission runs before any handler, so its refusal says `dispatched: no`: a client that let // admission check its lease (`lease-admission`) reallocates and resends on that refusal alone. + // A `close` may have torn its session down just before this, so its refusal claims nothing. let activeLease: DeviceLease | undefined; try { activeLease = assertRequestLeaseAdmission(params.req, leaseRegistry, existingSession, { @@ -167,7 +186,7 @@ export function admitRequestLeaseForLockedScope(params: { daemonPolicy: params.daemonPolicy, }); } catch (error) { - throw thrownBeforeDispatch(error); + throw endsSession(params.req) ? error : thrownBeforeDispatch(error); } if (!activeLease) return params.req; diff --git a/src/__tests__/cli-lease-admission.test.ts b/src/__tests__/cli-lease-admission.test.ts index fad5909c4f..dbac0dfff3 100644 --- a/src/__tests__/cli-lease-admission.test.ts +++ b/src/__tests__/cli-lease-admission.test.ts @@ -211,6 +211,19 @@ test.each([ fs.rmSync(ws.root, { recursive: true, force: true }); }); +// A `close` ends the connection's session, so no lease is rented or renewed for it. +test('a close refused for an inactive lease allocates nothing and is not resent', async () => { + const ws = workspace(); + const result = await run(ws, ['close'], { leaseAdmission: true, refusal: admissionRefusal }); + + assert.equal(result.code, 1, result.stdout); + assert.deepEqual(commandsOf(result), ['close']); + assert.deepEqual(markedOf(result), [false]); + assert.equal(scopeOf(result.calls[0], 'leaseId'), 'lease-old'); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); + test('a resent command refused again is not sent a third time', async () => { const ws = workspace(); const result = await runCliCapture( From eed7a8021d531b4e900fa2ebc3466398b619d33a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 15:06:01 +0100 Subject: [PATCH 5/9] fix(remote): refuse by canonical lease id and rerun without rereading input - A request naming its session's expired lease in another spelling is refused before teardown, not after it. - A lease command also ends a session whose lease the registry removed, while no other request holds that session. - A rerun after a lease refusal reuses the fill --text-stdin value. batch, replay and test keep the heartbeat, since they read scripts while building the request. Co-Authored-By: Claude Sonnet 5.5 --- .../docs/remote-device-lease-contracts.md | 4 +- ...quest-execution-scope-lease-expiry.test.ts | 122 ++++++++++++------ packages/daemon/src/server/request-binding.ts | 12 ++ .../src/server/request-execution-locks.ts | 14 ++ .../src/server/request-execution-scope.ts | 23 ++-- .../__tests__/lease-lifecycle.test.ts | 23 +++- .../daemon/src/sessions/lease-lifecycle.ts | 55 +++++--- src/__tests__/cli-lease-admission.test.ts | 26 +++- src/cli.ts | 4 + .../commands/connection-lease-admission.ts | 8 +- src/cli/commands/generic.ts | 2 + src/cli/commands/router-types.ts | 2 + src/cli/commands/router.ts | 1 + src/commands/cli-runner.ts | 10 +- 14 files changed, 229 insertions(+), 77 deletions(-) diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index f7d8d63ff4..a2a476f99e 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -71,7 +71,8 @@ Every lease-admission refusal comes after authentication and tenant scoping, and If a request that would do device work names the expired lease of its session, the daemon refuses before it tears that session down. The lease expiry sweep ends that session later. For a `close` or an admission-exempt command, such as `lease_release`, the daemon tears that session down at once. -A `close` also tears down a session whose lease the registry no longer holds. +Such a command also tears down a session whose lease the registry no longer holds. +If another request holds that session, the daemon leaves the teardown to the queued lease end. A refusal of `close` states no `details.dispatched`, because the teardown may have run. A sensitive `fill` value never redacts a typed `details.dispatched` or a shared lease `details.reason`. Any other value in those fields stays redacted. A daemon that makes this refusal advertises the `lease-admission` capability on `/health`. @@ -94,6 +95,7 @@ These commands keep the heartbeat: - A command exempt from lease admission. - `install`, `reinstall`, and `install-from-source`, which can upload a local artifact before admission. - A command with `--save-script`. +- `batch`, `replay`, and `test`, which read local scripts while they build the request. A script path can be a pipe. - A by-spec `open` that allocates fresh: the connection names no device, or the request names a device spec or a device selector. A by-spec `open` that names no spec or selector reuses the stored device without a heartbeat. diff --git a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts index 4f04d9a856..e98e6878c2 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts @@ -18,7 +18,12 @@ import { } from '../../__tests__/support/device-claim-store.ts'; import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; -import { createRequestExecutionScope } from '../request-execution-scope.ts'; +import { + createRequestExecutionScope, + getLeaseRegistryExecutionLocks, +} from '../request-execution-scope.ts'; +import { existingSessionExecutionLockKeys } from '../request-binding.ts'; +import { withRequestExecutionLockKeys } from '../request-execution-locks.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import { platformRequestScopeFixture, @@ -166,40 +171,39 @@ test.each(['rebuild', 'retire'] as const)( }, ); -test.each(['expired', 'released'] as const)( - 'a close naming its session lease that is %s tears down the session and claim and rents nothing', - async (fate) => { - let now = 1_000; - const sessionStore = makeSessionStore('agent-device-request-scope-'); - const leaseRegistry = new LeaseRegistry({ - defaultLeaseTtlMs: 10, - minLeaseTtlMs: 1, - now: () => now, - }); - const owner = { tenantId: 'tenant-a', runId: 'run-1' }; - const lease = leaseRegistry.allocateLease(owner); - const meta = { ...owner, leaseId: lease.leaseId, sessionIsolation: 'tenant' as const }; - const session = makeSession('tenant-a:default', { - device: LINUX_DEVICE, - lease: { ...owner, leaseId: lease.leaseId, leaseBackend: lease.backend }, - }); - const { stateDir } = claimStores(); - const claim = await acquireDeviceClaim({ - env: process.env, - device: session.device, - session: session.name, - workspace: stateDir, - stateDir, - reconcileOrphanedDeviceClaim: retainOrphanedDeviceClaims, - }); - if (claim.status !== 'acquired') throw new Error('expected an acquired claim'); - sessionStore.publish(session.name, { ...session, deviceClaim: claim.ownership }); - const claimFile = deviceClaimFilePath(claim.ownership.deviceKey); - expect(fs.existsSync(claimFile)).toBe(true); - if (fate === 'expired') now = 1_011; - else leaseRegistry.releaseLease({ ...owner, leaseId: lease.leaseId }); - const task = vi.fn(async () => 'ran'); +/** A tenant session that holds a lease and a device claim, with the lease then expired or released. */ +async function sessionWhoseLeaseEnded(fate: 'expired' | 'released') { + let now = 1_000; + const sessionStore = makeSessionStore('agent-device-request-scope-'); + const leaseRegistry = new LeaseRegistry({ + defaultLeaseTtlMs: 10, + minLeaseTtlMs: 1, + now: () => now, + }); + const owner = { tenantId: 'tenant-a', runId: 'run-1' }; + const lease = leaseRegistry.allocateLease(owner); + const meta = { ...owner, leaseId: lease.leaseId, sessionIsolation: 'tenant' as const }; + const session = makeSession('tenant-a:default', { + device: LINUX_DEVICE, + lease: { ...owner, leaseId: lease.leaseId, leaseBackend: lease.backend }, + }); + const { stateDir } = claimStores(); + const claim = await acquireDeviceClaim({ + env: process.env, + device: session.device, + session: session.name, + workspace: stateDir, + stateDir, + reconcileOrphanedDeviceClaim: retainOrphanedDeviceClaims, + }); + if (claim.status !== 'acquired') throw new Error('expected an acquired claim'); + sessionStore.publish(session.name, { ...session, deviceClaim: claim.ownership }); + const claimFile = deviceClaimFilePath(claim.ownership.deviceKey); + expect(fs.existsSync(claimFile)).toBe(true); + if (fate === 'expired') now = 1_011; + else leaseRegistry.releaseLease({ ...owner, leaseId: lease.leaseId }); + const run = async (command: string, task: () => Promise) => { const scope = await createRequestExecutionScope({ host: createTestHostEnvironment(), platformServices: daemonPlatformServicesFixture(), @@ -207,7 +211,7 @@ test.each(['expired', 'released'] as const)( trackClaimRecoveryDisposal: () => {}, deviceRuntimeGateway: unavailableDeviceRuntimeGateway, platformRequestScope: platformRequestScopeFixture(), - req: makeRequest({ command: 'close', session: session.name, meta }), + req: makeRequest({ command, session: session.name, meta }), sessionStore, leaseRegistry, platformResourceCleanup: { @@ -217,7 +221,19 @@ test.each(['expired', 'released'] as const)( retainExecutionHostAfterClose: () => false, }, }); - const refusal = await scope.runLocked(task).catch((error: unknown) => error); + return await scope.runLocked(task); + }; + return { sessionStore, leaseRegistry, session, claimFile, run }; +} + +test.each(['expired', 'released'] as const)( + 'a close naming its session lease that is %s tears down the session and claim and rents nothing', + async (fate) => { + const { sessionStore, leaseRegistry, session, claimFile, run } = + await sessionWhoseLeaseEnded(fate); + const task = vi.fn(async () => 'ran'); + + const refusal = await run('close', task).catch((error: unknown) => error); expect(sessionStore.get(session.name)).toBeUndefined(); expect(fs.existsSync(claimFile)).toBe(false); @@ -228,3 +244,37 @@ test.each(['expired', 'released'] as const)( expect(refusal).not.toHaveProperty('details.dispatched'); }, ); + +test.each(['lease_release', 'lease_heartbeat'])( + '%s for a released lease tears down the session still holding it', + async (command) => { + const { sessionStore, session, claimFile, run } = await sessionWhoseLeaseEnded('released'); + + await run(command, async () => 'ran'); + + expect(sessionStore.get(session.name)).toBeUndefined(); + expect(fs.existsSync(claimFile)).toBe(false); + }, +); + +// Lease commands take no session lock, and the queued lease end waits for the command that holds it. +test('lease_heartbeat leaves a session that another request holds to the queued lease end', async () => { + const { sessionStore, leaseRegistry, session, claimFile, run } = + await sessionWhoseLeaseEnded('released'); + let finish!: () => void; + const running = new Promise((resolve) => { + finish = resolve; + }); + const held = withRequestExecutionLockKeys( + getLeaseRegistryExecutionLocks(leaseRegistry), + existingSessionExecutionLockKeys(session.name, session.device.id), + async () => await running, + ); + + await run('lease_heartbeat', async () => 'ran'); + + expect(sessionStore.get(session.name)).toBeDefined(); + expect(fs.existsSync(claimFile)).toBe(true); + finish(); + await held; +}); diff --git a/packages/daemon/src/server/request-binding.ts b/packages/daemon/src/server/request-binding.ts index 2a724476d5..47b008969d 100644 --- a/packages/daemon/src/server/request-binding.ts +++ b/packages/daemon/src/server/request-binding.ts @@ -1,4 +1,6 @@ import { resolveCommandAndroidAvdSelection } from '../core/daemon-command-registry.ts'; +import { applyCommandDefaults } from '@agent-device/command-registry/registry'; +import type { CommandFlags } from '@agent-device/contracts/command'; import type { EnvMap } from '@agent-device/kernel/source-value'; import { hasDeviceSelectionInput, @@ -71,6 +73,16 @@ export async function resolveRequestExecutionLockPlan(params: { return { keys: orderRequestExecutionLockKeys(keys), deviceId: device?.id }; } +export function applyRequestCommandDefaults(req: DaemonRequest): DaemonRequest { + const flags = { ...(req.flags ?? {}) }; + const changed = applyCommandDefaults(req.command, flags); + if (!changed) return req; + return { + ...req, + flags: flags as CommandFlags, + }; +} + export function prepareLockedRequestBinding(params: { req: DaemonRequest; existingRef: SessionRef | undefined; diff --git a/packages/daemon/src/server/request-execution-locks.ts b/packages/daemon/src/server/request-execution-locks.ts index deffb54864..af1ad7ec83 100644 --- a/packages/daemon/src/server/request-execution-locks.ts +++ b/packages/daemon/src/server/request-execution-locks.ts @@ -70,6 +70,20 @@ export function createRequestExecutionLocks(params: { }; } +/** + * Runs `task` under `keys`, unless another request holds or waits for one of them. Keys this request + * already holds are re-entered. + */ +export async function runWhileRequestExecutionLockKeysFree( + locks: Map>, + keys: readonly RequestExecutionLockKey[], + task: () => Promise, +): Promise { + const held = heldRequestLockKeys(locks); + if (keys.some((key) => !held.includes(key) && locks.has(key))) return; + await withRequestExecutionLockKeys(locks, keys, task); +} + function heldRequestLockKeys(locks: Map>): RequestExecutionLockKey[] { return heldKeyedLockKeys(locks) as RequestExecutionLockKey[]; } diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index 32ecda9ea3..5bbdccdfea 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -45,6 +45,7 @@ import { type SessionTeardown, } from '../sessions/lease-lifecycle.ts'; import { + applyRequestCommandDefaults, existingSessionExecutionLockKeys, prepareLockedRequestBinding, resolveRequestExecutionLockPlan, @@ -58,6 +59,7 @@ import { import { createRequestExecutionLocks, withRequestExecutionLockKeys, + runWhileRequestExecutionLockKeysFree, } from './request-execution-locks.ts'; import { isRequestCanceled, throwIfRequestCanceled } from '@agent-device/host-kit/request'; import { finalizeDaemonResponse } from './request-finalization.ts'; @@ -98,10 +100,7 @@ import { createDeviceClaimAdmission, type DeviceClaimAdmission, } from '../resources/device/device-claim-admission.ts'; -import { - applyCommandDefaults, - resolveCommandDeviceClaimPolicy, -} from '@agent-device/command-registry/registry'; +import { resolveCommandDeviceClaimPolicy } from '@agent-device/command-registry/registry'; import type { PlatformResourceCleanup } from '../core/platform-resource-cleanup.ts'; import type { DaemonPlatformServices } from '../core/platform-services.ts'; import { @@ -470,6 +469,12 @@ export async function createRequestExecutionScope(params: { sessionStore, leaseRegistry, req: scopedReq, + whileSessionIdle: async (ref, end) => + await runWhileRequestExecutionLockKeysFree( + executionLocks, + existingSessionExecutionLockKeys(ref.address, ref.session.device.id), + end, + ), teardownSession: async (ref) => await teardownExpiredSession({ ref, @@ -704,16 +709,6 @@ function requirePlatformCleanup( return cleanup; } -function applyRequestCommandDefaults(req: DaemonRequest): DaemonRequest { - const flags = { ...(req.flags ?? {}) }; - const changed = applyCommandDefaults(req.command, flags); - if (!changed) return req; - return { - ...req, - flags: flags as CommandFlags, - }; -} - export async function prepareLockedRequestScope(params: { scope: RequestExecutionScope; sessionStore: SessionStore; diff --git a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts index 0f33835feb..52c8cdae24 100644 --- a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts +++ b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts @@ -122,6 +122,7 @@ test('cleanupExpiredLeasedSession consumes expired lease and deletes the session sessionStore, leaseRegistry, teardownSession, + whileSessionIdle: async (_ref, end) => await end(), }); expect(cleaned).toBe(true); @@ -147,10 +148,13 @@ function sessionWithExpiredLease() { sessionStore.publish('default', session); now = 1_011; const teardownSession = vi.fn(async () => {}); - const cleanup = (request: Partial & Pick) => + const cleanup = ( + request: Partial & Pick, + spell: (leaseId: string) => string = (leaseId) => leaseId, + ) => cleanupExpiredLeasedSession({ req: makeRequest({ - meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId: lease.leaseId }, + meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId: spell(lease.leaseId) }, ...request, }), env: process.env, @@ -158,6 +162,7 @@ function sessionWithExpiredLease() { sessionStore, leaseRegistry, teardownSession, + whileSessionIdle: async (_ref, end) => await end(), }); return { sessionStore, session, teardownSession, cleanup }; } @@ -165,15 +170,19 @@ function sessionWithExpiredLease() { // The refusal says `dispatched: no`, so a request that would do device work under the expired lease // must not tear its session down (recording, claim, runner) before the client reallocates; the // expiry sweep does that. -test.each<[string, Partial & Pick]>([ - ['press', { command: 'press' }], - ['an app-only close', { command: 'close', internal: { closeAppOnly: true } }], +test.each< + [string, Partial & Pick, (leaseId: string) => string] +>([ + ['press', { command: 'press' }, (id) => id], + // The registry reads lease ids without case or surrounding space. + ['a press spelling the id differently', { command: 'press' }, (id) => ` ${id.toUpperCase()} `], + ['an app-only close', { command: 'close', internal: { closeAppOnly: true } }, (id) => id], ])( 'cleanupExpiredLeasedSession refuses %s naming the expired lease before any teardown', - async (_name, request) => { + async (_name, request, spell) => { const { sessionStore, session, teardownSession, cleanup } = sessionWithExpiredLease(); - await expect(cleanup(request)).rejects.toMatchObject({ + await expect(cleanup(request, spell)).rejects.toMatchObject({ code: 'UNAUTHORIZED', details: { reason: 'LEASE_NOT_FOUND', dispatched: 'no' }, }); diff --git a/packages/daemon/src/sessions/lease-lifecycle.ts b/packages/daemon/src/sessions/lease-lifecycle.ts index 5331380460..9baf0959ab 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -5,6 +5,7 @@ import { clearDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; import { resolveCommandDeviceClaimPolicy } from '@agent-device/command-registry/registry'; import { isLeaseAdmissionExempt } from '../core/daemon-command-registry.ts'; import type { LeaseRegistry } from '../resources/lease-registry.ts'; +import { normalizeLeaseId } from '../resources/lease-registry-scope.ts'; import type { DeviceLease, LeaseLifecycleProvider, @@ -66,8 +67,9 @@ export async function releaseExpiredProviderLease( * teardown. A composite is refused so it does not lose its session mid-run. A request that would do * device work under that lease is refused so its client can reallocate and resend: the refusal says * `dispatched: no`, so nothing of the request may run first, and the lease expiry sweep ends the - * session instead. A `close` or an admission-exempt command ends it now, and a `close` also ends a - * session whose lease the registry no longer holds. + * session instead. A `close` or an admission-exempt command ends it now. It also ends a session whose + * lease the registry no longer holds, unless another request holds the session: the queued lease end + * then runs after that request. */ export async function cleanupExpiredLeasedSession(params: { req: DaemonRequest; @@ -76,6 +78,8 @@ export async function cleanupExpiredLeasedSession(params: { sessionStore: SessionStore; leaseRegistry: LeaseRegistry; teardownSession: SessionTeardown; + /** Runs `end` under the session's execution locks, or skips it while another request holds one. */ + whileSessionIdle: (ref: SessionRef, end: () => Promise) => Promise; }): Promise { const ref = params.sessionStore.lookup(params.sessionName); const lease = ref?.session.lease; @@ -87,19 +91,33 @@ export async function cleanupExpiredLeasedSession(params: { dispatched: 'no', }); }); - const closesLapsedSession = - endsSession(params.req) && - !isBoundedCompositeRequest(params.req) && - params.leaseRegistry.inspectLeaseBackend(lease.leaseId) === undefined; - if (!expired && !closesLapsedSession) return false; - await endLeasedSession( - ref, - params.sessionStore, - params.teardownSession, - 'LEASE_EXPIRED', - params.env, - ); - return true; + const end = async (current: SessionRef) => + await endLeasedSession( + current, + params.sessionStore, + params.teardownSession, + 'LEASE_EXPIRED', + params.env, + ); + if (expired) { + await end(ref); + return true; + } + if ( + doesDeviceWork(params.req) || + isBoundedCompositeRequest(params.req) || + params.leaseRegistry.inspectLeaseBackend(lease.leaseId) !== undefined + ) { + return false; + } + let ended = false; + await params.whileSessionIdle(ref, async () => { + // A request that held the session first can have ended it. + if (params.sessionStore.resolveCurrent(ref)?.lease?.leaseId !== lease.leaseId) return; + await end(params.sessionStore.refresh(ref)); + ended = true; + }); + return ended; } function refusesExpiredLeaseTeardown(req: DaemonRequest, expiredLeaseId: string): boolean { @@ -107,10 +125,15 @@ function refusesExpiredLeaseTeardown(req: DaemonRequest, expiredLeaseId: string) req.command === 'batch' || req.command === 'replay' || isBoundedCompositeRequest(req) || - (doesDeviceWork(req) && resolveLeaseScope(req).leaseId === expiredLeaseId) + (doesDeviceWork(req) && namesLease(req, expiredLeaseId)) ); } +/** Compared as the registry reads lease ids, so another spelling of the id names the same lease. */ +function namesLease(req: DaemonRequest, leaseId: string): boolean { + return normalizeLeaseId(resolveLeaseScope(req).leaseId) === normalizeLeaseId(leaseId); +} + function doesDeviceWork(req: DaemonRequest): boolean { return !endsSession(req) && !isLeaseAdmissionExempt(req.command); } diff --git a/src/__tests__/cli-lease-admission.test.ts b/src/__tests__/cli-lease-admission.test.ts index dbac0dfff3..9561e84db1 100644 --- a/src/__tests__/cli-lease-admission.test.ts +++ b/src/__tests__/cli-lease-admission.test.ts @@ -1,4 +1,5 @@ -import { test } from 'vitest'; +import { Readable } from 'node:stream'; +import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; @@ -247,6 +248,26 @@ test('a resent command refused again is not sent a third time', async () => { fs.rmSync(ws.root, { recursive: true, force: true }); }); +// A pipe can be read only once, so the rerun sends what the refused attempt already read. +test('a rerun fill --text-stdin sends the piped text again', async () => { + const stdin = vi + .spyOn(process, 'stdin', 'get') + .mockReturnValue(Readable.from(['piped-secret\n']) as typeof process.stdin); + const ws = workspace(); + const result = await run(ws, ['fill', '@e3', '--text-stdin'], { + leaseAdmission: true, + refusal: () => admissionRefusal('no'), + }); + stdin.mockRestore(); + + assert.equal(result.code, null, result.stdout); + assert.deepEqual(commandsOf(result), ['fill', 'lease_allocate', 'fill']); + assert.deepEqual(result.calls[0]?.positionals, ['@e3', 'piped-secret']); + assert.deepEqual(result.calls[2]?.positionals, ['@e3', 'piped-secret']); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); + test.each<[string, string[], Partial]>([ [ 'a host-allocated macos-app lease', @@ -267,6 +288,9 @@ test.each<[string, string[], Partial]>([ ['a remote --save-script open', ['open', 'com.example', '--save-script', 'flow.ad'], {}], ['a proxy open naming another device mode', ['open', 'com.example', '--device-mode', 'full'], {}], ['a proxy open with no stored device', ['open', 'com.example'], { deviceKey: undefined }], + ['a batch', ['batch', '--steps', '[{"command":"snapshot","input":{}}]'], {}], + ['a replay, which reads its script from a path', ['replay', '/dev/null'], {}], + ['a test run, which reads its scripts from paths', ['test', 'flow.ad'], {}], ])('%s keeps the heartbeat on a lease-admission daemon', async (_name, argv, connection) => { const ws = workspace(connection); const result = await run(ws, argv, { leaseAdmission: true }); diff --git a/src/cli.ts b/src/cli.ts index 5196f84b88..ab6790ede6 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -23,6 +23,7 @@ import { } from '@agent-device/daemon-client'; import fs from 'node:fs'; import type { ReplayTestReporterRuntime } from './cli/replay-test/reporting.ts'; +import type { CliRunInputs } from './commands/cli-runner.ts'; import type { CommandProgressState } from '@agent-device/command-output'; import { createCommandProgressState } from './commands/command-progress.ts'; import { createAgentDeviceClient } from '@agent-device/client'; @@ -373,6 +374,7 @@ type CliRunContext = { leaseDevice?: LeaseDevice; /** The flags before materialization, and the reused lease that the command's admission checks. */ leaseAdmission?: { flagsBefore: CliFlags; checked?: LeaseAdmission.AdmissionCheckedLease }; + inputs: CliRunInputs; parsedBatchSteps: BatchStep[] | undefined; devicePin: DevicePin | undefined; }; @@ -443,6 +445,7 @@ async function resolveRunContextOrExit( resolvedRuntime: connectionDefaults?.runtime, connectionMetadata: connectionDefaults?.connection, parsedBatchSteps: undefined, + inputs: {}, devicePin: parsed.devicePin, }; } catch (error) { @@ -671,6 +674,7 @@ async function dispatchCliCommand( debug: ctx.debugOutputEnabled, replayTestReporterRuntime, commandProgress, + inputs: ctx.inputs, leaseDevice: ctx.leaseDevice, claimedConnection: ctx.connectionDefaults?.claimed, }) diff --git a/src/cli/commands/connection-lease-admission.ts b/src/cli/commands/connection-lease-admission.ts index 61d8eacdeb..ee618d342c 100644 --- a/src/cli/commands/connection-lease-admission.ts +++ b/src/cli/commands/connection-lease-admission.ts @@ -1,5 +1,8 @@ import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; -import { commandMeetsLeaseAdmission } from '@agent-device/command-registry/registry'; +import { + commandMeetsLeaseAdmission, + isDelegatingCompositeCommand, +} from '@agent-device/command-registry/registry'; import { isUndispatchedInactiveLeaseRefusal, leaseProviderRequiringRuntime, @@ -50,6 +53,8 @@ const ARTIFACT_UPLOAD_COMMANDS: ReadonlySet = new Set([ * - a provider with a runtime runs lifecycle hooks on a heartbeat, such as an instance liveness check; * - a command exempt from lease admission is never checked there; * - an upload of a local artifact runs before admission, under the lease; + * - a composite (`batch`, `replay`, `test`) reads local scripts while it builds its request, and a + * rerun could not read a pipe again; * - `--save-script` records its publication before the send; * - a by-spec allocation binds the device from the heartbeat answer, unless the connection already * names the device and the request names no other device or spec. @@ -74,6 +79,7 @@ export function leaseCheckedByAdmission( leaseProviderRequiringRuntime({ leaseProvider: state.leaseProvider }) !== undefined || !commandMeetsLeaseAdmission(options.command) || ARTIFACT_UPLOAD_COMMANDS.has(options.command) || + isDelegatingCompositeCommand({ command: options.command, positionals: [] }) || flags.saveScript !== undefined || (options.allocateBySpec && !bindsStoredDevice(state, flags)) ) { diff --git a/src/cli/commands/generic.ts b/src/cli/commands/generic.ts index dd00780e98..980bb12ce7 100644 --- a/src/cli/commands/generic.ts +++ b/src/cli/commands/generic.ts @@ -25,6 +25,7 @@ export async function runGenericClientBackedCommand({ debug, replayTestReporterRuntime, commandProgress, + inputs, leaseDevice, }: ClientCommandParams & { command: ClientBackedCliCommandName }): Promise { const { result, cliOutput: formatted } = await runCliCommandWithOutput({ @@ -33,6 +34,7 @@ export async function runGenericClientBackedCommand({ positionals, flags, commandProgress, + inputs, env: host.env, }); const cliOutput = diff --git a/src/cli/commands/router-types.ts b/src/cli/commands/router-types.ts index a76992ba08..8dc0e2ae4d 100644 --- a/src/cli/commands/router-types.ts +++ b/src/cli/commands/router-types.ts @@ -6,6 +6,7 @@ import type { AgentDeviceClient } from '@agent-device/command-surface'; import type { CliCommandName } from '@agent-device/command-registry/catalog'; import type { CommandProgressState } from '@agent-device/command-output'; import type { ReplayTestReporterRuntime } from '../replay-test/reporting.ts'; +import type { CliRunInputs } from '../../commands/cli-runner.ts'; export type ClientCommandParams = { /** The host this run reads its environment and working directory from. */ @@ -17,6 +18,7 @@ export type ClientCommandParams = { replayTestReporterRuntime?: ReplayTestReporterRuntime; /** Progress this run's transport already rendered to stderr, read by the output formatters. */ commandProgress?: CommandProgressState; + inputs?: CliRunInputs; /** The device a proxy backend granted for the lease's device spec; `open` reports it. */ leaseDevice?: LeaseDevice; /** The record `disconnect` claimed before its client was built, or `null` when it claimed none. */ diff --git a/src/cli/commands/router.ts b/src/cli/commands/router.ts index 57b98afa0f..1646666217 100644 --- a/src/cli/commands/router.ts +++ b/src/cli/commands/router.ts @@ -34,6 +34,7 @@ export async function tryRunClientBackedCommand(params: { debug?: boolean; replayTestReporterRuntime?: ClientCommandParams['replayTestReporterRuntime']; commandProgress?: ClientCommandParams['commandProgress']; + inputs?: ClientCommandParams['inputs']; leaseDevice?: ClientCommandParams['leaseDevice']; claimedConnection?: ClientCommandParams['claimedConnection']; }): Promise { diff --git a/src/commands/cli-runner.ts b/src/commands/cli-runner.ts index 53070bc2a1..19d31f0d85 100644 --- a/src/commands/cli-runner.ts +++ b/src/commands/cli-runner.ts @@ -15,12 +15,19 @@ import { } from '@agent-device/command-surface'; import type { CliFlags } from '@agent-device/contracts/command'; +/** Input a CLI run can read only once. A rerun of the command reuses what is here. */ +export type CliRunInputs = { + /** The `fill --text-stdin` value. */ + fillText?: Promise; +}; + type CliRunOptions = { client: AgentDeviceClient; command: CommandName; positionals: string[]; flags: CliFlags; commandProgress?: CommandProgressState; + inputs?: CliRunInputs; /** The CLI run's own host environment; output formatters read styling from it (#3794). */ env: EnvMap; }; @@ -35,7 +42,8 @@ export async function runCliCommandWithOutput(options: CliRunOptions): Promise<{ }> { const input = readInputFromCli(options.command, options.positionals, options.flags); if (options.flags.textStdin) { - const text = await readFillTextFromStdin(process.stdin); + const inputs = options.inputs ?? {}; + const text = await (inputs.fillText ??= readFillTextFromStdin(process.stdin)); registerDiagnosticSensitiveValue(text); input.text = text; } From 39a7e8a1ac31aa53f430016985f2902837146766 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 15:24:38 +0100 Subject: [PATCH 6/9] fix(daemon): defer a removed lease's teardown through the lease end A close or lease command that found a busy session skipped the teardown and nothing queued it. It now starts the daemon's lease end, which runs once no other request holds the session. A close waits for it. Co-Authored-By: Claude Sonnet 5.5 --- .../docs/remote-device-lease-contracts.md | 5 +- ...quest-execution-scope-lease-expiry.test.ts | 96 +++++++++++++------ .../src/server/request-execution-locks.ts | 14 --- .../src/server/request-execution-scope.ts | 9 +- packages/daemon/src/server/request-router.ts | 2 + .../__tests__/lease-lifecycle.test.ts | 2 - .../daemon/src/sessions/lease-lifecycle.ts | 28 +++--- 7 files changed, 86 insertions(+), 70 deletions(-) diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index a2a476f99e..9fa47e6dfa 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -71,8 +71,9 @@ Every lease-admission refusal comes after authentication and tenant scoping, and If a request that would do device work names the expired lease of its session, the daemon refuses before it tears that session down. The lease expiry sweep ends that session later. For a `close` or an admission-exempt command, such as `lease_release`, the daemon tears that session down at once. -Such a command also tears down a session whose lease the registry no longer holds. -If another request holds that session, the daemon leaves the teardown to the queued lease end. +For a session whose lease the registry no longer holds, such a command starts the lease end of that lease. +The lease end runs once no other request holds the session. +A `close` waits for that lease end. A lease command does not wait. A refusal of `close` states no `details.dispatched`, because the teardown may have run. A sensitive `fill` value never redacts a typed `details.dispatched` or a shared lease `details.reason`. Any other value in those fields stays redacted. A daemon that makes this refusal advertises the `lease-admission` capability on `/health`. diff --git a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts index e98e6878c2..c12e7a1de9 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts @@ -19,6 +19,7 @@ import { import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { + createLeaseSessionEnd, createRequestExecutionScope, getLeaseRegistryExecutionLocks, } from '../request-execution-scope.ts'; @@ -203,8 +204,15 @@ async function sessionWhoseLeaseEnded(fate: 'expired' | 'released') { if (fate === 'expired') now = 1_011; else leaseRegistry.releaseLease({ ...owner, leaseId: lease.leaseId }); - const run = async (command: string, task: () => Promise) => { - const scope = await createRequestExecutionScope({ + const leaseEnd = createLeaseSessionEnd({ + env: process.env, + sessionStore, + executionLocks: getLeaseRegistryExecutionLocks(leaseRegistry), + teardownSession: async () => {}, + cleanupSessionlessExecutionHost: async () => {}, + }); + const scopeFor = async (command: string) => + await createRequestExecutionScope({ host: createTestHostEnvironment(), platformServices: daemonPlatformServicesFixture(), claimRecoveryGateway: daemonClaimRecoveryGatewayFixture(), @@ -214,6 +222,7 @@ async function sessionWhoseLeaseEnded(fate: 'expired' | 'released') { req: makeRequest({ command, session: session.name, meta }), sessionStore, leaseRegistry, + endSessionsForLease: async (leaseId) => await leaseEnd.end(leaseId, 'LEASE_RELEASED'), platformResourceCleanup: { stopSnapshotHelper: async () => {}, closeManagedBrowser: async () => {}, @@ -221,22 +230,40 @@ async function sessionWhoseLeaseEnded(fate: 'expired' | 'released') { retainExecutionHostAfterClose: () => false, }, }); - return await scope.runLocked(task); + const run = async (command: string, task: () => Promise) => + await (await scopeFor(command)).runLocked(task); + /** Another request that holds the session until `finish`. */ + const holdSession = () => { + let finish!: () => void; + const running = new Promise((resolve) => { + finish = resolve; + }); + const held = withRequestExecutionLockKeys( + getLeaseRegistryExecutionLocks(leaseRegistry), + existingSessionExecutionLockKeys(session.name, session.device.id), + async () => await running, + ); + return async () => { + finish(); + await held; + }; }; - return { sessionStore, leaseRegistry, session, claimFile, run }; + const expectSessionEnded = () => { + expect(sessionStore.get(session.name)).toBeUndefined(); + expect(fs.existsSync(claimFile)).toBe(false); + }; + return { sessionStore, leaseRegistry, session, scopeFor, run, holdSession, expectSessionEnded }; } test.each(['expired', 'released'] as const)( 'a close naming its session lease that is %s tears down the session and claim and rents nothing', async (fate) => { - const { sessionStore, leaseRegistry, session, claimFile, run } = - await sessionWhoseLeaseEnded(fate); + const { leaseRegistry, run, expectSessionEnded } = await sessionWhoseLeaseEnded(fate); const task = vi.fn(async () => 'ran'); const refusal = await run('close', task).catch((error: unknown) => error); - expect(sessionStore.get(session.name)).toBeUndefined(); - expect(fs.existsSync(claimFile)).toBe(false); + expectSessionEnded(); expect(leaseRegistry.listActiveLeases()).toEqual([]); expect(task).not.toHaveBeenCalled(); // The lease is still refused, without claiming that nothing ran. @@ -246,35 +273,48 @@ test.each(['expired', 'released'] as const)( ); test.each(['lease_release', 'lease_heartbeat'])( - '%s for a released lease tears down the session still holding it', + '%s for a released lease ends the session still holding it', async (command) => { - const { sessionStore, session, claimFile, run } = await sessionWhoseLeaseEnded('released'); + const { run, expectSessionEnded } = await sessionWhoseLeaseEnded('released'); await run(command, async () => 'ran'); - expect(sessionStore.get(session.name)).toBeUndefined(); - expect(fs.existsSync(claimFile)).toBe(false); + await vi.waitFor(expectSessionEnded); }, ); -// Lease commands take no session lock, and the queued lease end waits for the command that holds it. -test('lease_heartbeat leaves a session that another request holds to the queued lease end', async () => { - const { sessionStore, leaseRegistry, session, claimFile, run } = +// `runAdmitted` takes no lock, as for a close whose lock plan missed the session's keys. +test('a close that finds its session busy ends it once that request finishes', async () => { + const { sessionStore, session, scopeFor, holdSession, expectSessionEnded } = await sessionWhoseLeaseEnded('released'); - let finish!: () => void; - const running = new Promise((resolve) => { - finish = resolve; - }); - const held = withRequestExecutionLockKeys( - getLeaseRegistryExecutionLocks(leaseRegistry), - existingSessionExecutionLockKeys(session.name, session.device.id), - async () => await running, - ); + const release = holdSession(); + let settled = false; + const closing = (await scopeFor('close')) + .runAdmitted(async () => 'ran') + .catch((error: unknown) => error) + .finally(() => { + settled = true; + }); - await run('lease_heartbeat', async () => 'ran'); + await new Promise((resolve) => setImmediate(resolve)); + expect(settled).toBe(false); + expect(sessionStore.get(session.name)).toBeDefined(); + await release(); + + await expect(closing).resolves.toMatchObject({ details: { reason: 'LEASE_NOT_FOUND' } }); + expectSessionEnded(); +}); + +// Lease commands take no session lock: they must neither wait for the command that holds the session +// nor end it underneath that command. +test('lease_heartbeat on a busy session ends it once that request finishes', async () => { + const { sessionStore, session, run, holdSession, expectSessionEnded } = + await sessionWhoseLeaseEnded('released'); + const release = holdSession(); + await run('lease_heartbeat', async () => 'ran'); expect(sessionStore.get(session.name)).toBeDefined(); - expect(fs.existsSync(claimFile)).toBe(true); - finish(); - await held; + await release(); + + await vi.waitFor(expectSessionEnded); }); diff --git a/packages/daemon/src/server/request-execution-locks.ts b/packages/daemon/src/server/request-execution-locks.ts index af1ad7ec83..deffb54864 100644 --- a/packages/daemon/src/server/request-execution-locks.ts +++ b/packages/daemon/src/server/request-execution-locks.ts @@ -70,20 +70,6 @@ export function createRequestExecutionLocks(params: { }; } -/** - * Runs `task` under `keys`, unless another request holds or waits for one of them. Keys this request - * already holds are re-entered. - */ -export async function runWhileRequestExecutionLockKeysFree( - locks: Map>, - keys: readonly RequestExecutionLockKey[], - task: () => Promise, -): Promise { - const held = heldRequestLockKeys(locks); - if (keys.some((key) => !held.includes(key) && locks.has(key))) return; - await withRequestExecutionLockKeys(locks, keys, task); -} - function heldRequestLockKeys(locks: Map>): RequestExecutionLockKey[] { return heldKeyedLockKeys(locks) as RequestExecutionLockKey[]; } diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index 5bbdccdfea..618da4a242 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -59,7 +59,6 @@ import { import { createRequestExecutionLocks, withRequestExecutionLockKeys, - runWhileRequestExecutionLockKeysFree, } from './request-execution-locks.ts'; import { isRequestCanceled, throwIfRequestCanceled } from '@agent-device/host-kit/request'; import { finalizeDaemonResponse } from './request-finalization.ts'; @@ -235,6 +234,7 @@ export async function createRequestExecutionScope(params: { platformResourceCleanup?: PlatformResourceCleanup; providerAppCatalog?: ProviderAppCatalog; daemonPolicy?: DaemonPolicy; + endSessionsForLease?: (leaseId: string) => Promise; }): Promise { const { sessionStore, leaseRegistry } = params; const tenantScopedReq = scopeRequestSession(restrictRemoteHostInputs(params.req)); @@ -469,12 +469,7 @@ export async function createRequestExecutionScope(params: { sessionStore, leaseRegistry, req: scopedReq, - whileSessionIdle: async (ref, end) => - await runWhileRequestExecutionLockKeysFree( - executionLocks, - existingSessionExecutionLockKeys(ref.address, ref.session.device.id), - end, - ), + endSessionsForLease: params.endSessionsForLease, teardownSession: async (ref) => await teardownExpiredSession({ ref, diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index 1dc9f7b6b1..a66bf1e6f8 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -308,6 +308,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { platformResourceCleanup, providerAppCatalog, daemonPolicy, + endSessionsForLease, }); return await executeRequestScope(scope); }), @@ -487,6 +488,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { platformResourceCleanup, providerAppCatalog, daemonPolicy, + endSessionsForLease, }); // The outer replay keeps its stable session lock plus the device lock // from the first device binding through response projection and ref diff --git a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts index 52c8cdae24..5aa477f99e 100644 --- a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts +++ b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts @@ -122,7 +122,6 @@ test('cleanupExpiredLeasedSession consumes expired lease and deletes the session sessionStore, leaseRegistry, teardownSession, - whileSessionIdle: async (_ref, end) => await end(), }); expect(cleaned).toBe(true); @@ -162,7 +161,6 @@ function sessionWithExpiredLease() { sessionStore, leaseRegistry, teardownSession, - whileSessionIdle: async (_ref, end) => await end(), }); return { sessionStore, session, teardownSession, cleanup }; } diff --git a/packages/daemon/src/sessions/lease-lifecycle.ts b/packages/daemon/src/sessions/lease-lifecycle.ts index 9baf0959ab..456278bdeb 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -67,9 +67,9 @@ export async function releaseExpiredProviderLease( * teardown. A composite is refused so it does not lose its session mid-run. A request that would do * device work under that lease is refused so its client can reallocate and resend: the refusal says * `dispatched: no`, so nothing of the request may run first, and the lease expiry sweep ends the - * session instead. A `close` or an admission-exempt command ends it now. It also ends a session whose - * lease the registry no longer holds, unless another request holds the session: the queued lease end - * then runs after that request. + * session instead. A `close` or an admission-exempt command ends it now. For a session whose lease + * the registry no longer holds, such a command starts the daemon's lease end, which runs once no + * other request holds the session. A `close` waits for that end; a lease command does not. */ export async function cleanupExpiredLeasedSession(params: { req: DaemonRequest; @@ -78,8 +78,8 @@ export async function cleanupExpiredLeasedSession(params: { sessionStore: SessionStore; leaseRegistry: LeaseRegistry; teardownSession: SessionTeardown; - /** Runs `end` under the session's execution locks, or skips it while another request holds one. */ - whileSessionIdle: (ref: SessionRef, end: () => Promise) => Promise; + /** The daemon's lease end: it ends the lease's sessions under their execution locks. */ + endSessionsForLease?: (leaseId: string) => Promise; }): Promise { const ref = params.sessionStore.lookup(params.sessionName); const lease = ref?.session.lease; @@ -91,33 +91,27 @@ export async function cleanupExpiredLeasedSession(params: { dispatched: 'no', }); }); - const end = async (current: SessionRef) => + if (expired) { await endLeasedSession( - current, + ref, params.sessionStore, params.teardownSession, 'LEASE_EXPIRED', params.env, ); - if (expired) { - await end(ref); return true; } if ( + !params.endSessionsForLease || doesDeviceWork(params.req) || isBoundedCompositeRequest(params.req) || params.leaseRegistry.inspectLeaseBackend(lease.leaseId) !== undefined ) { return false; } - let ended = false; - await params.whileSessionIdle(ref, async () => { - // A request that held the session first can have ended it. - if (params.sessionStore.resolveCurrent(ref)?.lease?.leaseId !== lease.leaseId) return; - await end(params.sessionStore.refresh(ref)); - ended = true; - }); - return ended; + const ending = params.endSessionsForLease(lease.leaseId); + if (endsSession(params.req)) await ending; + return true; } function refusesExpiredLeaseTeardown(req: DaemonRequest, expiredLeaseId: string): boolean { From 6082299338bd1e33727d36a92dc4f995881d1426 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 16:22:22 +0100 Subject: [PATCH 7/9] fix(remote): keep the heartbeat wherever admission checks less than it does CLI: the heartbeat stays for Metro preparation, fill --text-stdin, a stored lease id that is not canonical, and a command whose daemon or owner scope is not the saved connection's. Only the client's own pre-send guard falls back for a daemon without lease-admission, and that capability needs every instance ID. Daemon: an ended lease named against another session lease is the inactive refusal. Device work under a lease that is not live is refused before teardown, a refusal after a teardown claims no dispatch verdict, and no request waits for a whole-lease end under its execution locks. Co-Authored-By: Claude Sonnet 5.5 --- packages/contracts/src/lease-scope.ts | 9 ++ .../__tests__/index-lease-admission.test.ts | 23 ++- .../src/daemon-client-lifecycle.ts | 3 +- .../src/daemon-client-remote-resend.ts | 3 +- .../daemon-contracts/src/daemon-resolution.ts | 39 ++++- .../docs/remote-device-lease-contracts.md | 18 ++- .../src/resources/lease-registry-scope.ts | 9 +- .../daemon/src/resources/lease-registry.ts | 9 +- ...quest-execution-scope-lease-expiry.test.ts | 133 +++++++++++++++-- .../__tests__/request-execution-scope.test.ts | 4 +- packages/daemon/src/server/request-binding.ts | 12 ++ .../src/server/request-execution-scope.ts | 11 +- .../__tests__/lease-lifecycle.test.ts | 4 + .../__tests__/request-admission.test.ts | 26 ++++ .../daemon/src/sessions/lease-lifecycle.ts | 47 +++--- .../daemon/src/sessions/request-admission.ts | 8 +- src/__tests__/cli-config.test.ts | 22 +-- src/__tests__/cli-lease-admission.test.ts | 135 ++++++++++++++---- src/cli.ts | 4 - .../commands/connection-lease-admission.ts | 53 ++++--- .../commands/connection-lease-transaction.ts | 9 ++ src/cli/commands/connection-metro-runtime.ts | 28 +++- src/cli/commands/connection-runtime.ts | 5 + src/cli/commands/generic.ts | 2 - src/cli/commands/router-types.ts | 2 - src/cli/commands/router.ts | 1 - src/commands/cli-runner.ts | 10 +- 27 files changed, 489 insertions(+), 140 deletions(-) diff --git a/packages/contracts/src/lease-scope.ts b/packages/contracts/src/lease-scope.ts index ff16291ce4..bbf7320904 100644 --- a/packages/contracts/src/lease-scope.ts +++ b/packages/contracts/src/lease-scope.ts @@ -471,6 +471,15 @@ export function parseLeaseDeviceKey( return { platform: platform!, target: target!, id: id! }; } +/** A lease id as the registry stores it: trimmed lower-case hex. `undefined` for any other value. */ +export function normalizeLeaseId(raw: string | undefined): string | undefined { + if (!raw) return undefined; + const value = raw.trim(); + if (!value) return undefined; + if (!/^[a-f0-9]{16,128}$/i.test(value)) return undefined; + return value.toLowerCase(); +} + export function isProxyLeaseScope(scope: LeaseScope): boolean { return scope.leaseProvider === PROXY_LEASE_PROVIDER; } diff --git a/packages/daemon-client/src/__tests__/index-lease-admission.test.ts b/packages/daemon-client/src/__tests__/index-lease-admission.test.ts index f4c8702955..8c343a8963 100644 --- a/packages/daemon-client/src/__tests__/index-lease-admission.test.ts +++ b/packages/daemon-client/src/__tests__/index-lease-admission.test.ts @@ -71,6 +71,16 @@ test.each([ name: 'upgraded proxy in front of a legacy daemon', health: { instanceId: 'proxy', capabilities: LEASE_ADMISSION, upstream: { instanceId: 'd' } }, }, + // Without every instance ID, nothing holds the next request to the daemon that answered. + { name: 'daemon that names no instance', health: { capabilities: LEASE_ADMISSION } }, + { + name: 'proxy whose daemon names no instance', + health: { instanceId: 'proxy', upstream: { capabilities: LEASE_ADMISSION } }, + }, + { + name: 'proxy that names no instance', + health: { upstream: { instanceId: 'daemon', capabilities: LEASE_ADMISSION } }, + }, ])('a $name is refused before the send', async ({ health }) => { const { result, routes } = await sendAdmissionChecked(() => health); @@ -81,13 +91,16 @@ test.each([ expect(routes).toEqual(['/health']); }); -test('a replacement daemon without lease admission is refused before the resend', async () => { +test.each([ + { + name: 'without lease admission', + replacement: { instanceId: 'legacy', capabilities: ['script-artifacts'] }, + }, + { name: 'that names no instance', replacement: { capabilities: LEASE_ADMISSION } }, +])('a replacement daemon $name is refused before the resend', async ({ replacement }) => { let replaced = false; const { result, routes } = await sendAdmissionChecked( - () => - replaced - ? { instanceId: 'legacy', capabilities: ['script-artifacts'] } - : { instanceId: 'capable', capabilities: LEASE_ADMISSION }, + () => (replaced ? replacement : { instanceId: 'capable', capabilities: LEASE_ADMISSION }), (res) => { replaced = true; res.statusCode = 409; diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index 1ba3ac9e3a..44d62cf525 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -20,6 +20,7 @@ import { resolveDaemonServerMode, resolveDaemonTransportPreference, DAEMON_RETIREMENT_REASONS, + remoteDaemonCapabilities, type DaemonPaths, type DaemonServerMode, type DaemonTransportPreference, @@ -376,7 +377,7 @@ async function ensureRemoteDaemon( probe: async (probeMs, signal) => await cachedRemoteDaemonHealth(remoteInfo, probeMs, signal), }); } - remoteInfo.capabilities = (health.upstream ?? health).capabilities; + remoteInfo.capabilities = remoteDaemonCapabilities(health); remoteInfo.remoteInstanceId = health.instanceId; remoteInfo.remoteUpstreamInstanceId = health.upstream?.instanceId; return { info: remoteInfo, startedByClient: false }; diff --git a/packages/daemon-client/src/daemon-client-remote-resend.ts b/packages/daemon-client/src/daemon-client-remote-resend.ts index cc01c0faa3..1c45d66703 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -7,6 +7,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { assertLeaseAdmissionCapability, assertScriptArtifactsCapability, + remoteDaemonCapabilities, } from '@agent-device/daemon-contracts/daemon-resolution'; import { CheckedRpcConnectFailure, @@ -80,7 +81,7 @@ export async function retryAfterRemoteInstanceMismatch( } info.remoteInstanceId = health.instanceId; info.remoteUpstreamInstanceId = health.upstream?.instanceId; - info.capabilities = (health.upstream ?? health).capabilities; + info.capabilities = remoteDaemonCapabilities(health); cacheRemoteDaemonHealth(info, health); // A replacement daemon must still deliver the script that a remote recording asks for. if (scriptPublicationId) assertScriptArtifactsCapability(info.capabilities); diff --git a/packages/daemon-contracts/src/daemon-resolution.ts b/packages/daemon-contracts/src/daemon-resolution.ts index 8dd513dd4a..1a81eaf3de 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -477,18 +477,45 @@ export function assertScriptArtifactsCapability(capabilities: readonly string[] }); } +/** + * The client's own refusal, before the send, of a daemon that does not report `lease-admission`. Only + * the client builds this class, so a daemon answer that names the same reason is never one. + */ +export class LeaseAdmissionUnsupportedError extends AppError { + constructor() { + super('UNSUPPORTED_OPERATION', 'The daemon does not check leases at admission.', { + reason: DAEMON_CAPABILITY_REFUSAL_REASONS.leaseAdmissionUnsupported.reason, + daemonRequestSent: false, + dispatched: 'no', + }); + } +} + /** * Refuses, before the send, a request whose reused lease no heartbeat checked, when the daemon does * not report `lease-admission`. Such a daemon need not refuse an inactive lease before dispatch, * so the caller checks the lease with a heartbeat and sends again. */ export function assertLeaseAdmissionCapability(capabilities: readonly string[] | undefined): void { - if (capabilities?.includes('lease-admission')) return; - throw new AppError('UNSUPPORTED_OPERATION', 'The daemon does not check leases at admission.', { - reason: DAEMON_CAPABILITY_REFUSAL_REASONS.leaseAdmissionUnsupported.reason, - daemonRequestSent: false, - dispatched: 'no', - }); + if (!capabilities?.includes('lease-admission')) throw new LeaseAdmissionUnsupportedError(); +} + +type DaemonHealthIdentity = Readonly<{ + instanceId?: string; + capabilities?: readonly DaemonCapability[]; +}>; + +/** + * The capabilities of the daemon a remote `/health` answer describes. `lease-admission` counts only + * when the answer names the instance of every link, the daemon and any proxy in front of it: the + * instance fences then hold the next request to the daemon that reported it. + */ +export function remoteDaemonCapabilities( + health: DaemonHealthIdentity & Readonly<{ upstream?: DaemonHealthIdentity }>, +): readonly DaemonCapability[] | undefined { + const daemon = health.upstream ?? health; + if (health.instanceId && daemon.instanceId) return daemon.capabilities; + return daemon.capabilities?.filter((capability) => capability !== 'lease-admission'); } export function readDaemonCapabilities(value: unknown): readonly DaemonCapability[] { diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index 9fa47e6dfa..2c6d2d3b11 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -68,13 +68,15 @@ The client then allocates a new lease under a fresh id. Request admission refuses a request that names an inactive or unknown lease. The refusal is `UNAUTHORIZED` with `details.reason: LEASE_NOT_FOUND` and `details.dispatched: no`. Every lease-admission refusal comes after authentication and tenant scoping, and before any handler runs. -If a request that would do device work names the expired lease of its session, the daemon refuses before it tears that session down. +If a request names a lease other than its session's lease, and the registry does not hold the named lease, the refusal is `LEASE_NOT_FOUND`. +If the registry holds that lease, the refusal is `LEASE_SESSION_MISMATCH`. +If the session lease expired and a request that would do device work names a lease that is not live, the daemon refuses before it tears that session down. The lease expiry sweep ends that session later. For a `close` or an admission-exempt command, such as `lease_release`, the daemon tears that session down at once. -For a session whose lease the registry no longer holds, such a command starts the lease end of that lease. -The lease end runs once no other request holds the session. -A `close` waits for that lease end. A lease command does not wait. -A refusal of `close` states no `details.dispatched`, because the teardown may have run. +For a session whose lease the registry no longer holds, such a command starts the lease end of that lease and does not wait for it. +The lease end runs outside the execution locks of that request. +A `close` that holds the locks of that session also ends that session at once. +A refusal that follows a teardown, or a started lease end, states no `details.dispatched`. A sensitive `fill` value never redacts a typed `details.dispatched` or a shared lease `details.reason`. Any other value in those fields stays redacted. A daemon that makes this refusal advertises the `lease-admission` capability on `/health`. A proxy forwards the capability of the daemon behind it in `upstream`. @@ -82,11 +84,13 @@ A proxy forwards the capability of the daemon behind it in `upstream`. The CLI can reuse a stored lease without a heartbeat. It then marks the command as admission-checked and names the window that the heartbeat would have named. The daemon-client reads `lease-admission` from the `/health` check that the command already makes. +It accepts the capability only if that answer names the instance of the daemon, and of the proxy in front of it. If the capability is absent, the daemon-client refuses the command before the send with `lease_admission_unsupported`. It makes the same check again after an instance-mismatch refresh. An admission-checked command never takes the checked RPC route. On a checked connection (`daemonRpc: checked`) it is `GET /health`, then `POST /rpc`. If the only request of the command gets either refusal, the CLI materializes the connection again and sends the command once more. After `LEASE_NOT_FOUND`, the CLI allocates a new lease. After `lease_admission_unsupported`, it sends the heartbeat. +Only the refusal that the daemon-client itself builds counts. A daemon answer with that reason is an ordinary failure. The CLI does not resend on any other failure. These commands keep the heartbeat: @@ -97,6 +101,10 @@ These commands keep the heartbeat: - `install`, `reinstall`, and `install-from-source`, which can upload a local artifact before admission. - A command with `--save-script`. - `batch`, `replay`, and `test`, which read local scripts while they build the request. A script path can be a pipe. +- `fill --text-stdin`, so that a refusal comes before the CLI reads the pipe. +- A command that prepares a Metro runtime, which registers remote work under the lease before the command. +- A command whose daemon URL, tenant, run, lease backend, or device key differs from the saved connection, or that has no saved connection. +- A command whose stored lease id is not canonical lower-case hex. - A by-spec `open` that allocates fresh: the connection names no device, or the request names a device spec or a device selector. A by-spec `open` that names no spec or selector reuses the stored device without a heartbeat. diff --git a/packages/daemon/src/resources/lease-registry-scope.ts b/packages/daemon/src/resources/lease-registry-scope.ts index 4a1c2827d9..05052ae9ad 100644 --- a/packages/daemon/src/resources/lease-registry-scope.ts +++ b/packages/daemon/src/resources/lease-registry-scope.ts @@ -5,6 +5,7 @@ import { MIN_LEASE_WINDOW_MS, leaseScopeToReleaseRequest, leaseProviderRequiringRuntime, + normalizeLeaseId, } from '@agent-device/contracts/lease-scope'; import { LEASE_BACKENDS, type LeaseBackend } from '@agent-device/kernel/contracts'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; @@ -137,14 +138,6 @@ function normalizeRunId(raw: string | undefined): string | undefined { return value; } -export function normalizeLeaseId(raw: string | undefined): string | undefined { - if (!raw) return undefined; - const value = raw.trim(); - if (!value) return undefined; - if (!/^[a-f0-9]{16,128}$/i.test(value)) return undefined; - return value.toLowerCase(); -} - export function normalizeRequiredLeaseId(raw: string | undefined): string { const leaseId = normalizeLeaseId(raw); if (!leaseId) throw new AppError('INVALID_ARGS', 'Invalid lease id.'); diff --git a/packages/daemon/src/resources/lease-registry.ts b/packages/daemon/src/resources/lease-registry.ts index c51ccd1055..64ef035c32 100644 --- a/packages/daemon/src/resources/lease-registry.ts +++ b/packages/daemon/src/resources/lease-registry.ts @@ -1,5 +1,5 @@ import type { DeviceLease } from '@agent-device/contracts/device'; -import { LEASE_REASONS } from '@agent-device/contracts/lease-scope'; +import { LEASE_REASONS, normalizeLeaseId } from '@agent-device/contracts/lease-scope'; import type { HumanControlHold, HumanControlHoldScope } from '@agent-device/contracts/client'; import type { LeaseBackend } from '@agent-device/kernel/contracts'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; @@ -20,7 +20,6 @@ import { deviceLeaseBusyError, DEVICE_LEASE_REASONS, hasAllocatedScope, - normalizeLeaseId, normalizeRequiredLeaseId, normalizeLeaseAdmissionRequest, assertLeaseOwnerScope, @@ -312,6 +311,12 @@ export class LeaseRegistry { return { ...lease }; } + /** Refuses a lease the registry does not hold, whatever its scope. */ + assertLeaseActive(leaseId: string): void { + this.cleanupExpiredLeases(); + this.getActiveLease(normalizeLeaseId(leaseId) ?? leaseId); + } + assertLeaseAdmission(request: AdmissionRequest): void { const scope = normalizeLeaseAdmissionRequest(request); this.cleanupExpiredLeases(); diff --git a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts index c12e7a1de9..4a0e008722 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts @@ -211,7 +211,7 @@ async function sessionWhoseLeaseEnded(fate: 'expired' | 'released') { teardownSession: async () => {}, cleanupSessionlessExecutionHost: async () => {}, }); - const scopeFor = async (command: string) => + const scopeFor = async (command: string, requestMeta: DaemonRequest['meta'] = meta) => await createRequestExecutionScope({ host: createTestHostEnvironment(), platformServices: daemonPlatformServicesFixture(), @@ -219,7 +219,7 @@ async function sessionWhoseLeaseEnded(fate: 'expired' | 'released') { trackClaimRecoveryDisposal: () => {}, deviceRuntimeGateway: unavailableDeviceRuntimeGateway, platformRequestScope: platformRequestScopeFixture(), - req: makeRequest({ command, session: session.name, meta }), + req: makeRequest({ command, session: session.name, meta: requestMeta }), sessionStore, leaseRegistry, endSessionsForLease: async (leaseId) => await leaseEnd.end(leaseId, 'LEASE_RELEASED'), @@ -288,21 +288,132 @@ test('a close that finds its session busy ends it once that request finishes', a const { sessionStore, session, scopeFor, holdSession, expectSessionEnded } = await sessionWhoseLeaseEnded('released'); const release = holdSession(); - let settled = false; - const closing = (await scopeFor('close')) + + const refusal = await ( + await scopeFor('close') + ) .runAdmitted(async () => 'ran') - .catch((error: unknown) => error) - .finally(() => { - settled = true; - }); + .catch((error: unknown) => error); - await new Promise((resolve) => setImmediate(resolve)); - expect(settled).toBe(false); + expect(refusal).toMatchObject({ details: { reason: 'LEASE_NOT_FOUND' } }); + // The teardown is queued, so the refusal cannot claim that nothing runs. + expect(refusal).not.toHaveProperty('details.dispatched'); expect(sessionStore.get(session.name)).toBeDefined(); await release(); + await vi.waitFor(expectSessionEnded); +}); + +// A lease end started under the close's own session lock would hold that lock until it got the rest. +test('a close holding only its session lock finishes while another request holds the device', async () => { + const { leaseRegistry, session, scopeFor, expectSessionEnded } = + await sessionWhoseLeaseEnded('released'); + const executionLocks = getLeaseRegistryExecutionLocks(leaseRegistry); + let finish!: () => void; + const running = new Promise((resolve) => { + finish = resolve; + }); + const device = withRequestExecutionLockKeys( + executionLocks, + [`device:${session.device.id}`], + async () => await running, + ); + const scope = await scopeFor('close'); + + const refusal = await withRequestExecutionLockKeys( + executionLocks, + [`session:${session.name}`], + async () => await scope.runAdmitted(async () => 'ran').catch((error: unknown) => error), + ); + + expect(refusal).toMatchObject({ details: { reason: 'LEASE_NOT_FOUND' } }); + finish(); + await device; + await vi.waitFor(expectSessionEnded); +}); + +test('a refusal after an expired session was torn down claims no dispatch verdict', async () => { + const { scopeFor, expectSessionEnded } = await sessionWhoseLeaseEnded('expired'); + // It names no lease, so it is refused only once the session and its lease are gone. + const scope = await scopeFor('press', { + tenantId: 'tenant-a', + runId: 'run-1', + sessionIsolation: 'tenant', + }); + + const refusal = await scope.runLocked(async () => 'ran').catch((error: unknown) => error); - await expect(closing).resolves.toMatchObject({ details: { reason: 'LEASE_NOT_FOUND' } }); expectSessionEnded(); + expect(refusal).toBeInstanceOf(Error); + expect(refusal).not.toHaveProperty('details.dispatched'); +}); + +// Each close holds its own session and the lease end needs both: neither may wait for it there. +test('two closes of sessions sharing a removed lease both finish', async () => { + const leaseRegistry = new LeaseRegistry(); + const sessionStore = makeSessionStore('agent-device-request-scope-'); + const owner = { tenantId: 'tenant-a', runId: 'run-1' }; + const lease = leaseRegistry.allocateLease(owner); + const names = ['tenant-a:first', 'tenant-a:second']; + for (const name of names) { + sessionStore.publish( + name, + makeSession(name, { + device: { ...LINUX_DEVICE, id: name }, + lease: { ...owner, leaseId: lease.leaseId }, + }), + ); + } + leaseRegistry.releaseLease({ ...owner, leaseId: lease.leaseId }); + const executionLocks = getLeaseRegistryExecutionLocks(leaseRegistry); + const leaseEnd = createLeaseSessionEnd({ + env: process.env, + sessionStore, + executionLocks, + teardownSession: async () => {}, + cleanupSessionlessExecutionHost: async () => {}, + }); + const scopes = await Promise.all( + names.map( + async (session) => + await createRequestExecutionScope({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + claimRecoveryGateway: daemonClaimRecoveryGatewayFixture(), + trackClaimRecoveryDisposal: () => {}, + deviceRuntimeGateway: unavailableDeviceRuntimeGateway, + platformRequestScope: platformRequestScopeFixture(), + req: makeRequest({ + command: 'close', + session, + meta: { ...owner, leaseId: lease.leaseId, sessionIsolation: 'tenant' }, + }), + sessionStore, + leaseRegistry, + endSessionsForLease: async (leaseId) => await leaseEnd.end(leaseId, 'LEASE_RELEASED'), + }), + ), + ); + // Both closes queue behind one holder, so both hold their locks before either reaches the end. + let finish!: () => void; + const running = new Promise((resolve) => { + finish = resolve; + }); + const held = withRequestExecutionLockKeys( + executionLocks, + names.flatMap((name) => existingSessionExecutionLockKeys(name, name)), + async () => await running, + ); + const closes = scopes.map( + async (scope) => await scope.runLocked(async () => 'ran').catch((error: unknown) => error), + ); + await new Promise((resolve) => setImmediate(resolve)); + finish(); + await held; + + for (const refusal of await Promise.all(closes)) { + expect(refusal).toMatchObject({ details: { reason: 'LEASE_NOT_FOUND' } }); + } + await vi.waitFor(() => expect(sessionStore.listRefs()).toEqual([])); }); // Lease commands take no session lock: they must neither wait for the command that holds the session diff --git a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts index c28e4040b9..0ff2032b66 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts @@ -402,8 +402,10 @@ test('leased session rejects mismatched lease id before dispatch', async () => { }), ); + // Another live lease: an ended one is refused as inactive instead. + const other = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-2' }); const scope = await createTestRequestScope({ - req: makeRequest({ command: 'snapshot', meta: { leaseId: '1'.repeat(32) } }), + req: makeRequest({ command: 'snapshot', meta: { leaseId: other.leaseId } }), sessionStore, leaseRegistry, }); diff --git a/packages/daemon/src/server/request-binding.ts b/packages/daemon/src/server/request-binding.ts index 47b008969d..3620d18d78 100644 --- a/packages/daemon/src/server/request-binding.ts +++ b/packages/daemon/src/server/request-binding.ts @@ -1,5 +1,6 @@ import { resolveCommandAndroidAvdSelection } from '../core/daemon-command-registry.ts'; import { applyCommandDefaults } from '@agent-device/command-registry/registry'; +import { heldKeyedLockKeys } from '@agent-device/kernel/keyed-lock'; import type { CommandFlags } from '@agent-device/contracts/command'; import type { EnvMap } from '@agent-device/kernel/source-value'; import { @@ -73,6 +74,17 @@ export async function resolveRequestExecutionLockPlan(params: { return { keys: orderRequestExecutionLockKeys(keys), deviceId: device?.id }; } +/** Whether the current request holds the lock pair of the session `ref` names. */ +export function holdsSessionExecutionLocks( + locks: Map>, + ref: SessionRef, +): boolean { + const held = heldKeyedLockKeys(locks); + return existingSessionExecutionLockKeys(ref.address, ref.session.device.id).every((key) => + held.includes(key), + ); +} + export function applyRequestCommandDefaults(req: DaemonRequest): DaemonRequest { const flags = { ...(req.flags ?? {}) }; const changed = applyCommandDefaults(req.command, flags); diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index 618da4a242..d744979aed 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -1,3 +1,4 @@ +import { AsyncResource } from 'node:async_hooks'; import { restrictRemoteHostInputs } from './remote-host-input-policy.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -47,6 +48,7 @@ import { import { applyRequestCommandDefaults, existingSessionExecutionLockKeys, + holdsSessionExecutionLocks, prepareLockedRequestBinding, resolveRequestExecutionLockPlan, type RequestExecutionLockPlan, @@ -237,6 +239,9 @@ export async function createRequestExecutionScope(params: { endSessionsForLease?: (leaseId: string) => Promise; }): Promise { const { sessionStore, leaseRegistry } = params; + // Bound before this request takes a lock, so the lease end it starts never runs under one. + const queueLeaseEnd = + params.endSessionsForLease && AsyncResource.bind(params.endSessionsForLease); const tenantScopedReq = scopeRequestSession(restrictRemoteHostInputs(params.req)); // A nested batch or replay step arrives with the identity of the request that spawned it, and its // own name is already the store key. @@ -463,13 +468,14 @@ export async function createRequestExecutionScope(params: { }); } throwIfRequestCanceled(scopedReq.meta?.requestId); - await cleanupExpiredLeasedSession({ + const sessionEnded = await cleanupExpiredLeasedSession({ env: params.host.env, sessionName, sessionStore, leaseRegistry, req: scopedReq, - endSessionsForLease: params.endSessionsForLease, + queueLeaseEnd, + holdsSessionLocks: (ref) => holdsSessionExecutionLocks(executionLocks, ref), teardownSession: async (ref) => await teardownExpiredSession({ ref, @@ -487,6 +493,7 @@ export async function createRequestExecutionScope(params: { leaseRegistry, providerAppCatalog: params.providerAppCatalog, daemonPolicy: params.daemonPolicy, + sessionEnded, }); scope.req = scopedReq; admissionCompleted = true; diff --git a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts index 5aa477f99e..5fe154e323 100644 --- a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts +++ b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts @@ -122,6 +122,7 @@ test('cleanupExpiredLeasedSession consumes expired lease and deletes the session sessionStore, leaseRegistry, teardownSession, + holdsSessionLocks: () => true, }); expect(cleaned).toBe(true); @@ -161,6 +162,7 @@ function sessionWithExpiredLease() { sessionStore, leaseRegistry, teardownSession, + holdsSessionLocks: () => true, }); return { sessionStore, session, teardownSession, cleanup }; } @@ -175,6 +177,8 @@ test.each< // The registry reads lease ids without case or surrounding space. ['a press spelling the id differently', { command: 'press' }, (id) => ` ${id.toUpperCase()} `], ['an app-only close', { command: 'close', internal: { closeAppOnly: true } }, (id) => id], + // Admission would refuse that lease only after the teardown, with `dispatched: no`. + ['a press naming another lease that is not live', { command: 'press' }, () => 'f'.repeat(32)], ])( 'cleanupExpiredLeasedSession refuses %s naming the expired lease before any teardown', async (_name, request, spell) => { diff --git a/packages/daemon/src/sessions/__tests__/request-admission.test.ts b/packages/daemon/src/sessions/__tests__/request-admission.test.ts index efec73795c..417bc050f0 100644 --- a/packages/daemon/src/sessions/__tests__/request-admission.test.ts +++ b/packages/daemon/src/sessions/__tests__/request-admission.test.ts @@ -550,3 +550,29 @@ test('a daemon policy that requires a macos-app lease refuses unleased and other lease.leaseId, ); }); + +// A client whose stored lease was replaced must hear that it is inactive, so it reallocates. +test.each([ + ['an ended lease', false, 'LEASE_NOT_FOUND'], + ['a live lease', true, 'LEASE_SESSION_MISMATCH'], +])('a request naming %s other than its session lease is refused as such', (_name, live, reason) => { + const registry = new LeaseRegistry(); + const owner = { tenantId: 'tenant-a', runId: 'run-1' }; + const held = registry.allocateLease(owner); + const other = live ? registry.allocateLease({ tenantId: 'tenant-a', runId: 'run-2' }) : undefined; + const session = makeIosSession('default', { lease: { ...owner, leaseId: held.leaseId } }); + + assert.throws( + () => + assertRequestLeaseAdmission( + makeRequest({ + command: 'snapshot', + meta: { ...owner, leaseId: other?.leaseId ?? 'f'.repeat(32), sessionIsolation: 'tenant' }, + }), + registry, + session, + { env: process.env }, + ), + (error: unknown) => error instanceof AppError && error.details?.reason === reason, + ); +}); diff --git a/packages/daemon/src/sessions/lease-lifecycle.ts b/packages/daemon/src/sessions/lease-lifecycle.ts index 456278bdeb..04ff3474d5 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -5,7 +5,6 @@ import { clearDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; import { resolveCommandDeviceClaimPolicy } from '@agent-device/command-registry/registry'; import { isLeaseAdmissionExempt } from '../core/daemon-command-registry.ts'; import type { LeaseRegistry } from '../resources/lease-registry.ts'; -import { normalizeLeaseId } from '../resources/lease-registry-scope.ts'; import type { DeviceLease, LeaseLifecycleProvider, @@ -65,11 +64,12 @@ export async function releaseExpiredProviderLease( /** * Ends the session of the request whose session lease expired, or refuses the request before that * teardown. A composite is refused so it does not lose its session mid-run. A request that would do - * device work under that lease is refused so its client can reallocate and resend: the refusal says - * `dispatched: no`, so nothing of the request may run first, and the lease expiry sweep ends the - * session instead. A `close` or an admission-exempt command ends it now. For a session whose lease - * the registry no longer holds, such a command starts the daemon's lease end, which runs once no - * other request holds the session. A `close` waits for that end; a lease command does not. + * device work and names a lease that is not live is refused so its client can reallocate and resend: + * the refusal says `dispatched: no`, so nothing of the request may run first, and the lease expiry + * sweep ends the session instead. A `close` or an admission-exempt command ends it now. For a + * session whose lease the registry no longer holds, such a command queues the daemon's lease end, + * and a `close` that holds the session also ends it at once. + * Returns whether the request ended the session or queued its end. */ export async function cleanupExpiredLeasedSession(params: { req: DaemonRequest; @@ -78,20 +78,21 @@ export async function cleanupExpiredLeasedSession(params: { sessionStore: SessionStore; leaseRegistry: LeaseRegistry; teardownSession: SessionTeardown; - /** The daemon's lease end: it ends the lease's sessions under their execution locks. */ - endSessionsForLease?: (leaseId: string) => Promise; + /** Starts the daemon's lease end outside this request's execution locks. */ + queueLeaseEnd?: (leaseId: string) => Promise; + holdsSessionLocks: (ref: SessionRef) => boolean; }): Promise { const ref = params.sessionStore.lookup(params.sessionName); const lease = ref?.session.lease; if (!ref || !lease) return false; const expired = params.leaseRegistry.consumeExpiredLease(lease.leaseId, () => { - if (!refusesExpiredLeaseTeardown(params.req, lease.leaseId)) return; + if (!refusesExpiredLeaseTeardown(params.req, params.leaseRegistry)) return; throw new AppError('UNAUTHORIZED', 'Lease is not active', { reason: LEASE_REASONS.notFound.reason, dispatched: 'no', }); }); - if (expired) { + const end = async () => await endLeasedSession( ref, params.sessionStore, @@ -99,33 +100,37 @@ export async function cleanupExpiredLeasedSession(params: { 'LEASE_EXPIRED', params.env, ); + if (expired) { + await end(); return true; } if ( - !params.endSessionsForLease || + !params.queueLeaseEnd || doesDeviceWork(params.req) || isBoundedCompositeRequest(params.req) || params.leaseRegistry.inspectLeaseBackend(lease.leaseId) !== undefined ) { return false; } - const ending = params.endSessionsForLease(lease.leaseId); - if (endsSession(params.req)) await ending; + // The lease end locks every session of the lease, so no request waits for it under its own locks. + void params.queueLeaseEnd(lease.leaseId); + if (endsSession(params.req) && params.holdsSessionLocks(ref)) await end(); return true; } -function refusesExpiredLeaseTeardown(req: DaemonRequest, expiredLeaseId: string): boolean { +function refusesExpiredLeaseTeardown(req: DaemonRequest, leaseRegistry: LeaseRegistry): boolean { return ( req.command === 'batch' || req.command === 'replay' || isBoundedCompositeRequest(req) || - (doesDeviceWork(req) && namesLease(req, expiredLeaseId)) + (doesDeviceWork(req) && namesInactiveLease(req, leaseRegistry)) ); } -/** Compared as the registry reads lease ids, so another spelling of the id names the same lease. */ -function namesLease(req: DaemonRequest, leaseId: string): boolean { - return normalizeLeaseId(resolveLeaseScope(req).leaseId) === normalizeLeaseId(leaseId); +/** Whether admission would refuse the lease the request names, which must then come first. */ +function namesInactiveLease(req: DaemonRequest, leaseRegistry: LeaseRegistry): boolean { + const { leaseId } = resolveLeaseScope(req); + return leaseId !== undefined && leaseRegistry.inspectLeaseBackend(leaseId) === undefined; } function doesDeviceWork(req: DaemonRequest): boolean { @@ -188,13 +193,15 @@ export function admitRequestLeaseForLockedScope(params: { leaseRegistry: LeaseRegistry; providerAppCatalog?: ProviderAppCatalog; daemonPolicy?: DaemonPolicy; + /** The request ended its session, or queued that end, just before admission. */ + sessionEnded?: boolean; }): DaemonRequest { const { sessionName, sessionStore, leaseRegistry } = params; const ref = sessionStore.lookup(sessionName); const existingSession = ref?.session; // Admission runs before any handler, so its refusal says `dispatched: no`: a client that let // admission check its lease (`lease-admission`) reallocates and resends on that refusal alone. - // A `close` may have torn its session down just before this, so its refusal claims nothing. + // After a teardown the refusal cannot claim that nothing ran. let activeLease: DeviceLease | undefined; try { activeLease = assertRequestLeaseAdmission(params.req, leaseRegistry, existingSession, { @@ -203,7 +210,7 @@ export function admitRequestLeaseForLockedScope(params: { daemonPolicy: params.daemonPolicy, }); } catch (error) { - throw endsSession(params.req) ? error : thrownBeforeDispatch(error); + throw params.sessionEnded ? error : thrownBeforeDispatch(error); } if (!activeLease) return params.req; diff --git a/packages/daemon/src/sessions/request-admission.ts b/packages/daemon/src/sessions/request-admission.ts index e03e88719a..f9dcbe623e 100644 --- a/packages/daemon/src/sessions/request-admission.ts +++ b/packages/daemon/src/sessions/request-admission.ts @@ -122,7 +122,13 @@ function admitLease( session: SessionState | undefined, env: HostEnvironment['env'], ): DeviceLease { - assertRequestSessionLeaseMatches(resolveLeaseScope(req), session?.lease); + const named = resolveLeaseScope(req); + // A request that names another lease than its session's is a mismatch only while that lease is + // live. An ended one is the typed inactive refusal, so a client with a replaced lease reallocates. + if (named.leaseId && session?.lease && named.leaseId !== session.lease.leaseId) { + leaseRegistry.assertLeaseActive(named.leaseId); + } + assertRequestSessionLeaseMatches(named, session?.lease); const leaseScope = resolveRequestOrSessionLeaseScope(req, session); leaseRegistry.assertLeaseAdmission(leaseScopeToHeartbeatRequest(leaseScope)); // Admission renews for the window the lease already carries, or the window this request named. diff --git a/src/__tests__/cli-config.test.ts b/src/__tests__/cli-config.test.ts index 7e385d2c4a..3339adfc68 100644 --- a/src/__tests__/cli-config.test.ts +++ b/src/__tests__/cli-config.test.ts @@ -281,16 +281,18 @@ test('active remote connection defaults override generic config and env for remo }); assert.equal(result.code, null); - // Admission checks the stored lease, so the command is the only request. - assert.equal(result.calls.length, 1); - assert.equal(result.calls[0]?.session, 'env-session'); - assert.equal(result.calls[0]?.flags?.platform, 'android'); + assert.equal(result.calls.length, 2); + assert.equal(result.calls[0]?.command, 'lease_heartbeat'); + assert.equal(result.calls[1]?.session, 'env-session'); + assert.equal(result.calls[1]?.flags?.platform, 'android'); assert.equal( - result.calls[0]?.flags?.daemonBaseUrl, + result.calls[1]?.flags?.daemonBaseUrl, 'http://remote-mac.example.test:9124/agent-device', ); assert.equal(result.calls[0]?.meta?.tenantId, 'acme'); assert.equal(result.calls[0]?.meta?.leaseId, 'lease-123'); + assert.equal(result.calls[1]?.meta?.tenantId, 'acme'); + assert.equal(result.calls[1]?.meta?.leaseId, 'lease-123'); fs.rmSync(root, { recursive: true, force: true }); }); @@ -628,11 +630,11 @@ test('remote-config commands reuse active generated session when profile has no ); assert.equal(result.code, null); - // Admission checks the stored lease, so the command is the only request. - assert.equal(result.calls.length, 1); - assert.equal(result.calls[0]?.command, 'snapshot'); - assert.equal(result.calls[0]?.session, 'adc-generated'); - assert.equal(result.calls[0]?.meta?.leaseId, 'lease-generated-001'); + assert.equal(result.calls.length, 2); + assert.equal(result.calls[0]?.command, 'lease_heartbeat'); + assert.equal(result.calls[1]?.command, 'snapshot'); + assert.equal(result.calls[1]?.session, 'adc-generated'); + assert.equal(result.calls[1]?.meta?.leaseId, 'lease-generated-001'); fs.rmSync(root, { recursive: true, force: true }); }); diff --git a/src/__tests__/cli-lease-admission.test.ts b/src/__tests__/cli-lease-admission.test.ts index 9561e84db1..1cd69acbec 100644 --- a/src/__tests__/cli-lease-admission.test.ts +++ b/src/__tests__/cli-lease-admission.test.ts @@ -14,7 +14,14 @@ import { writeRemoteConnectionState, type RemoteConnectionState, } from '@agent-device/remote/remote-connection-state'; +import { prepareMetroRuntime } from '@agent-device/react-native'; import { runCliCapture, type CapturedDaemonRequest } from './cli-capture.ts'; +import { metroPrepareResult } from './remote-connection.fixtures.ts'; + +vi.mock('@agent-device/react-native', async (importOriginal) => ({ + ...(await importOriginal()), + prepareMetroRuntime: vi.fn(), +})); // A daemon that advertises `lease-admission` checks a reused lease when it admits the command, so the // CLI sends the command marked as admission-checked and without a heartbeat. The daemon-client @@ -22,14 +29,18 @@ import { runCliCapture, type CapturedDaemonRequest } from './cli-capture.ts'; // inactive lease before dispatch. The fake transport below stands where the daemon-client does. const PROXY_URL = 'http://proxy.example.test/agent-device'; +const STORED_LEASE = 'a1'.repeat(16); type Workspace = { root: string; home: string; project: string; stateDir: string }; -function workspace(connection: Partial = {}): Workspace { +function workspace( + connection: Partial = {}, + remoteConfig: Record = {}, +): Workspace { const { root, home, project } = makeTempWorkspace(); const stateDir = path.join(root, 'state'); const remoteConfigPath = path.join(project, 'agent.remote.json'); - fs.writeFileSync(remoteConfigPath, JSON.stringify({})); + fs.writeFileSync(remoteConfigPath, JSON.stringify(remoteConfig)); const now = new Date().toISOString(); writeRemoteConnectionState({ stateDir, @@ -41,7 +52,7 @@ function workspace(connection: Partial = {}): Workspace { daemon: { baseUrl: PROXY_URL }, tenant: 'proxy', runId: 'run-agent', - leaseId: 'lease-old', + leaseId: STORED_LEASE, leaseBackend: 'android-instance', leaseProvider: 'proxy', clientId: 'client-1', @@ -95,7 +106,7 @@ function transportTo(daemon: Daemon) { if (req.command === 'lease_allocate' || req.command === 'lease_heartbeat') { return leaseAnswer(req); } - if (daemon.refusal && scopeOf(req, 'leaseId') === 'lease-old') throw daemon.refusal(); + if (daemon.refusal && scopeOf(req, 'leaseId') === STORED_LEASE) throw daemon.refusal(); if (req.command === 'open') return { ok: true, data: { session: req.session } }; return { ok: true, data: { nodes: [], truncated: false } }; }; @@ -139,7 +150,7 @@ test.each([ assert.equal(result.code, null, result.stdout); assert.deepEqual(commandsOf(result), [command]); assert.deepEqual(markedOf(result), [true]); - assert.equal(scopeOf(result.calls[0], 'leaseId'), 'lease-old'); + assert.equal(scopeOf(result.calls[0], 'leaseId'), STORED_LEASE); // Admission renews for the window the heartbeat would have named. assert.equal(result.calls[0]?.meta?.leaseTtlMs, REMOTE_LEASE_IDLE_TTL_MS); @@ -168,7 +179,7 @@ test('a lease refused at admission is reallocated and the command is sent once m assert.equal(result.code, null, result.stdout); assert.deepEqual(commandsOf(result), ['snapshot', 'lease_allocate', 'snapshot']); const allocated = scopeOf(result.calls[1], 'leaseId'); - assert.notEqual(allocated, 'lease-old'); + assert.notEqual(allocated, STORED_LEASE); assert.equal(scopeOf(result.calls[2], 'leaseId'), allocated); assert.equal( readRemoteConnectionState({ stateDir: ws.stateDir, session: 'agent' })?.leaseId, @@ -199,6 +210,16 @@ test.each([ }), { dispatched: 'no' }, ], + // Only the client's own guard proves nothing was sent: a gateway answer can follow a forward. + [ + 'a daemon answer with the unsupported-capability reason', + () => + new AppError('UNSUPPORTED_OPERATION', 'The daemon does not check leases at admission.', { + reason: 'lease_admission_unsupported', + dispatched: 'no', + }), + { dispatched: 'no' }, + ], ])('%s is never resent', async (_name, refusal, expected) => { const ws = workspace(); const result = await run(ws, ['snapshot'], { leaseAdmission: true, refusal }); @@ -220,7 +241,7 @@ test('a close refused for an inactive lease allocates nothing and is not resent' assert.equal(result.code, 1, result.stdout); assert.deepEqual(commandsOf(result), ['close']); assert.deepEqual(markedOf(result), [false]); - assert.equal(scopeOf(result.calls[0], 'leaseId'), 'lease-old'); + assert.equal(scopeOf(result.calls[0], 'leaseId'), STORED_LEASE); fs.rmSync(ws.root, { recursive: true, force: true }); }); @@ -248,26 +269,6 @@ test('a resent command refused again is not sent a third time', async () => { fs.rmSync(ws.root, { recursive: true, force: true }); }); -// A pipe can be read only once, so the rerun sends what the refused attempt already read. -test('a rerun fill --text-stdin sends the piped text again', async () => { - const stdin = vi - .spyOn(process, 'stdin', 'get') - .mockReturnValue(Readable.from(['piped-secret\n']) as typeof process.stdin); - const ws = workspace(); - const result = await run(ws, ['fill', '@e3', '--text-stdin'], { - leaseAdmission: true, - refusal: () => admissionRefusal('no'), - }); - stdin.mockRestore(); - - assert.equal(result.code, null, result.stdout); - assert.deepEqual(commandsOf(result), ['fill', 'lease_allocate', 'fill']); - assert.deepEqual(result.calls[0]?.positionals, ['@e3', 'piped-secret']); - assert.deepEqual(result.calls[2]?.positionals, ['@e3', 'piped-secret']); - - fs.rmSync(ws.root, { recursive: true, force: true }); -}); - test.each<[string, string[], Partial]>([ [ 'a host-allocated macos-app lease', @@ -285,6 +286,19 @@ test.each<[string, string[], Partial]>([ { leaseProvider: 'limrun' }, ], ['an install that uploads a local artifact first', ['install', 'com.example', 'app.apk'], {}], + ['an install from a source', ['install-from-source', 'https://example.com/app.apk'], {}], + [ + 'a stored lease id that is not canonical', + ['snapshot'], + { leaseId: STORED_LEASE.toUpperCase() }, + ], + ['a command naming another run', ['snapshot', '--run-id', 'run-other'], {}], + ['a command naming another tenant', ['snapshot', '--tenant', 'tenant-other'], {}], + [ + 'a command naming another daemon', + ['snapshot', '--daemon-base-url', 'http://other.example.test/agent-device'], + {}, + ], ['a remote --save-script open', ['open', 'com.example', '--save-script', 'flow.ad'], {}], ['a proxy open naming another device mode', ['open', 'com.example', '--device-mode', 'full'], {}], ['a proxy open with no stored device', ['open', 'com.example'], { deviceKey: undefined }], @@ -300,3 +314,70 @@ test.each<[string, string[], Partial]>([ fs.rmSync(ws.root, { recursive: true, force: true }); }); + +// Metro preparation registers the companion tunnel under the connection's lease before the command, +// so the lease is checked first and the tunnel and the app share the live one. +test('an open that prepares Metro replaces an ended lease before the bridge setup', async () => { + const ws = workspace({}, { metroProxyBaseUrl: 'https://bridge.example.test' }); + const events: string[] = []; + vi.mocked(prepareMetroRuntime).mockImplementation(async (input) => { + events.push(`prepare ${input.bridgeScope?.leaseId}`); + return metroPrepareResult(); + }); + const result = await runCliCapture( + ['open', 'com.example', '--session', 'agent', '--state-dir', ws.stateDir, '--json'], + { + cwd: ws.project, + env: { HOME: ws.home }, + sendToDaemon: async (req) => { + events.push(`${req.command} ${scopeOf(req, 'leaseId')}`); + if (req.command === 'lease_heartbeat') throw admissionRefusal(); + // The by-spec allocation names no device; the lease answer does. + if (req.command === 'lease_allocate') { + return leaseAnswer({ + ...req, + meta: { ...req.meta, deviceKey: 'android:mobile:emulator-5554' }, + }); + } + return { ok: true, data: { session: req.session } }; + }, + }, + ); + + assert.equal(result.code, null, result.stdout); + const live = readRemoteConnectionState({ stateDir: ws.stateDir, session: 'agent' })?.leaseId; + assert.ok(live && live !== STORED_LEASE); + assert.deepEqual(events, [ + `lease_heartbeat ${STORED_LEASE}`, + `lease_allocate ${live}`, + `prepare ${live}`, + `open ${live}`, + ]); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); + +test('a lease scope refusal arrives before fill --text-stdin reads the pipe', async () => { + const pipe = Readable.from(['piped-secret']); + const stdin = vi.spyOn(process, 'stdin', 'get').mockReturnValue(pipe as typeof process.stdin); + const ws = workspace(); + const result = await runCliCapture( + ['fill', '@e3', '--text-stdin', '--session', 'agent', '--state-dir', ws.stateDir, '--json'], + { + cwd: ws.project, + env: { HOME: ws.home }, + sendToDaemon: async () => { + throw new AppError('UNAUTHORIZED', 'Lease scope mismatch', { + reason: 'LEASE_SCOPE_MISMATCH', + }); + }, + }, + ); + stdin.mockRestore(); + + assert.equal(result.code, 1, result.stdout); + assert.deepEqual(commandsOf(result), ['lease_heartbeat']); + assert.equal(pipe.readableDidRead, false); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); diff --git a/src/cli.ts b/src/cli.ts index ab6790ede6..5196f84b88 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -23,7 +23,6 @@ import { } from '@agent-device/daemon-client'; import fs from 'node:fs'; import type { ReplayTestReporterRuntime } from './cli/replay-test/reporting.ts'; -import type { CliRunInputs } from './commands/cli-runner.ts'; import type { CommandProgressState } from '@agent-device/command-output'; import { createCommandProgressState } from './commands/command-progress.ts'; import { createAgentDeviceClient } from '@agent-device/client'; @@ -374,7 +373,6 @@ type CliRunContext = { leaseDevice?: LeaseDevice; /** The flags before materialization, and the reused lease that the command's admission checks. */ leaseAdmission?: { flagsBefore: CliFlags; checked?: LeaseAdmission.AdmissionCheckedLease }; - inputs: CliRunInputs; parsedBatchSteps: BatchStep[] | undefined; devicePin: DevicePin | undefined; }; @@ -445,7 +443,6 @@ async function resolveRunContextOrExit( resolvedRuntime: connectionDefaults?.runtime, connectionMetadata: connectionDefaults?.connection, parsedBatchSteps: undefined, - inputs: {}, devicePin: parsed.devicePin, }; } catch (error) { @@ -674,7 +671,6 @@ async function dispatchCliCommand( debug: ctx.debugOutputEnabled, replayTestReporterRuntime, commandProgress, - inputs: ctx.inputs, leaseDevice: ctx.leaseDevice, claimedConnection: ctx.connectionDefaults?.claimed, }) diff --git a/src/cli/commands/connection-lease-admission.ts b/src/cli/commands/connection-lease-admission.ts index ee618d342c..d9270615a9 100644 --- a/src/cli/commands/connection-lease-admission.ts +++ b/src/cli/commands/connection-lease-admission.ts @@ -1,4 +1,3 @@ -import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; import { commandMeetsLeaseAdmission, isDelegatingCompositeCommand, @@ -6,9 +5,11 @@ import { import { isUndispatchedInactiveLeaseRefusal, leaseProviderRequiringRuntime, + normalizeLeaseId, requireLeaseDeviceSpec, } from '@agent-device/contracts/lease-scope'; -import { DAEMON_CAPABILITY_REFUSAL_REASONS } from '@agent-device/daemon-contracts/daemon-resolution'; +import { LeaseAdmissionUnsupportedError } from '@agent-device/daemon-contracts/daemon-resolution'; +import { requestUploadsArtifacts } from '@agent-device/remote/daemon-artifacts'; import { buildRemoteConnectionRequestMetadata, type RemoteConnectionState, @@ -39,13 +40,6 @@ export type AdmissionCheckedLease = Readonly<{ leaseTtlMs?: number; }>; -/** Commands whose request uploads a local artifact first; the upload's own beat needs a live lease. */ -const ARTIFACT_UPLOAD_COMMANDS: ReadonlySet = new Set([ - PUBLIC_COMMANDS.install, - PUBLIC_COMMANDS.reinstall, - PUBLIC_COMMANDS.installFromSource, -]); - /** * The reused lease the command's own admission can check, or `undefined` when a heartbeat must. The * heartbeat stays wherever it does more than admission does: @@ -53,9 +47,14 @@ const ARTIFACT_UPLOAD_COMMANDS: ReadonlySet = new Set([ * - a provider with a runtime runs lifecycle hooks on a heartbeat, such as an instance liveness check; * - a command exempt from lease admission is never checked there; * - an upload of a local artifact runs before admission, under the lease; - * - a composite (`batch`, `replay`, `test`) reads local scripts while it builds its request, and a - * rerun could not read a pipe again; + * - Metro preparation registers remote work under the lease before the command; + * - a composite (`batch`, `replay`, `test`) reads local scripts while it builds its request, and + * `fill --text-stdin` reads a pipe: a refusal must come before either, and a rerun could not read + * a pipe again; * - `--save-script` records its publication before the send; + * - a command whose daemon or lease owner scope is not the saved connection's would have admission + * check another lease than the heartbeat does; + * - a stored lease id that is not canonical is one only the heartbeat answer can correct; * - a by-spec allocation binds the device from the heartbeat answer, unless the connection already * names the device and the request names no other device or spec. */ @@ -63,10 +62,13 @@ export function leaseCheckedByAdmission( options: Readonly<{ command: string; state: RemoteConnectionState; + /** The stored connection record, absent while the connection is still built from flags. */ + savedState: RemoteConnectionState | undefined; flags: CliFlags; leaseBackend: LeaseBackend; policy: ConnectionLeasePolicy; allocateBySpec: boolean | undefined; + preparesRuntime: boolean; check: ReusedLeaseCheck | undefined; }>, ): AdmissionCheckedLease | undefined { @@ -74,13 +76,17 @@ export function leaseCheckedByAdmission( if ( !check?.byAdmission || !state.leaseId || + normalizeLeaseId(state.leaseId) !== state.leaseId || state.leaseBackend !== options.leaseBackend || state.leaseBackend === 'macos-app' || leaseProviderRequiringRuntime({ leaseProvider: state.leaseProvider }) !== undefined || !commandMeetsLeaseAdmission(options.command) || - ARTIFACT_UPLOAD_COMMANDS.has(options.command) || + requestUploadsArtifacts({ command: options.command }) || + options.preparesRuntime || isDelegatingCompositeCommand({ command: options.command, positionals: [] }) || + flags.textStdin === true || flags.saveScript !== undefined || + !namesSavedConnection(options.savedState, state, flags) || (options.allocateBySpec && !bindsStoredDevice(state, flags)) ) { return undefined; @@ -89,6 +95,22 @@ export function leaseCheckedByAdmission( return { leaseId: state.leaseId, ...(leaseTtlMs === undefined ? {} : { leaseTtlMs }) }; } +/** Whether the command goes to the saved connection's daemon, under its owner scope. */ +function namesSavedConnection( + saved: RemoteConnectionState | undefined, + state: RemoteConnectionState, + flags: CliFlags, +): boolean { + return ( + saved?.daemon?.baseUrl !== undefined && + flags.daemonBaseUrl === saved.daemon.baseUrl && + flags.tenant === saved.tenant && + flags.runId === saved.runId && + state.leaseBackend === saved.leaseBackend && + state.deviceKey === saved.deviceKey + ); +} + /** Whether binding would take the stored device as it is: the request names no device or spec. */ function bindsStoredDevice(state: RemoteConnectionState, flags: CliFlags): boolean { return ( @@ -147,11 +169,8 @@ function leaseAdmissionTransport( function refusalOf(error: unknown): LeaseAdmissionAttempt['firstRefusal'] { if (isUndispatchedInactiveLeaseRefusal(error)) return 'inactive-lease'; - const reason = (error as Readonly<{ details?: Readonly<{ reason?: unknown }> }> | null)?.details - ?.reason; - return reason === DAEMON_CAPABILITY_REFUSAL_REASONS.leaseAdmissionUnsupported.reason - ? 'unsupported' - : undefined; + // The client's own guard, which sent nothing. A daemon answer with its reason is not one. + return error instanceof LeaseAdmissionUnsupportedError ? 'unsupported' : undefined; } /** diff --git a/src/cli/commands/connection-lease-transaction.ts b/src/cli/commands/connection-lease-transaction.ts index d0d0bb038b..ffb6540683 100644 --- a/src/cli/commands/connection-lease-transaction.ts +++ b/src/cli/commands/connection-lease-transaction.ts @@ -128,6 +128,9 @@ export async function acquireConnectionLease(options: { positionals?: string[]; leaseLedger: LeaseLedger; reusedLeaseCheck?: ReusedLeaseCheck; + savedState?: RemoteConnectionState; + /** Whether the command prepares a runtime under the lease; unknown counts as yes. */ + preparesRuntime?: (flags: CliFlags) => boolean; }): Promise<{ state: RemoteConnectionState; changed: boolean; @@ -156,6 +159,8 @@ export async function acquireConnectionLease(options: { policy: leasePolicy, leaseLedger, reusedLeaseCheck: options.reusedLeaseCheck, + savedState: options.savedState, + preparesRuntime: options.preparesRuntime, }); nextState = materialized.state; changed = materialized.changed; @@ -207,6 +212,8 @@ async function materializeLeaseForCommand(options: { policy: ConnectionLeasePolicy; leaseLedger: LeaseLedger; reusedLeaseCheck?: ReusedLeaseCheck; + savedState?: RemoteConnectionState; + preparesRuntime?: (flags: CliFlags) => boolean; }): Promise<{ state: RemoteConnectionState; changed: boolean; @@ -243,6 +250,8 @@ async function materializeLeaseForCommand(options: { leaseBackend, policy, allocateBySpec: resolvedLeaseState.allocateBySpec, + savedState: options.savedState, + preparesRuntime: options.preparesRuntime?.(nextFlags) ?? true, check: options.reusedLeaseCheck, }); let materializedLease = admissionCheckedLease diff --git a/src/cli/commands/connection-metro-runtime.ts b/src/cli/commands/connection-metro-runtime.ts index 6a372cf58f..fdf1072511 100644 --- a/src/cli/commands/connection-metro-runtime.ts +++ b/src/cli/commands/connection-metro-runtime.ts @@ -30,11 +30,7 @@ export async function prepareRuntimeForCommand(options: { const { command, flags, state, client } = options; let nextState = ensureRuntimeLeaseState(options.nextState, flags); const nextRuntime = options.runtime; - if ( - !shouldPrepareRuntimeForCommand(command, flags, options.batchSteps, options.positionals) || - !hasDeferredMetroConfig(flags) || - !shouldPrepareRuntime(options.forceRuntimePrepare, nextRuntime, flags.platform) - ) { + if (!willPrepareRuntime(options)) { return { state: nextState, runtime: nextRuntime, changed: false }; } if (!nextState.leaseId) { @@ -70,6 +66,28 @@ export async function prepareRuntimeForCommand(options: { }; } +/** + * Whether materializing the command prepares a Metro runtime. Preparation registers remote work + * under the connection's lease before the command is sent. + */ +export function willPrepareRuntime( + options: Readonly<{ + command: string; + flags: CliFlags; + runtime?: SessionRuntimeHints; + positionals?: string[]; + batchSteps?: BatchStep[]; + forceRuntimePrepare?: boolean; + }>, +): boolean { + const { command, flags } = options; + return ( + shouldPrepareRuntimeForCommand(command, flags, options.batchSteps, options.positionals) && + hasDeferredMetroConfig(flags) && + shouldPrepareRuntime(options.forceRuntimePrepare, options.runtime, flags.platform) + ); +} + function ensureRuntimeLeaseState( state: RemoteConnectionState, flags: CliFlags, diff --git a/src/cli/commands/connection-runtime.ts b/src/cli/commands/connection-runtime.ts index 680d238e33..aff82c5376 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -32,6 +32,7 @@ import { prepareRuntimeForCommand, selectCompatibleRuntime, stopMetroCleanup, + willPrepareRuntime, } from './connection-metro-runtime.ts'; import { grantedLeaseDevice } from './proxy-lease-device.ts'; @@ -115,6 +116,10 @@ export async function materializeRemoteConnectionForCommand(options: { positionals: options.positionals, leaseLedger, reusedLeaseCheck: options.reusedLeaseCheck, + savedState: existingState ?? undefined, + // Decided before the lease is reused, from what preparation below will read. + preparesRuntime: (leaseFlags) => + willPrepareRuntime({ ...options, flags: leaseFlags, runtime: nextRuntime }), }); nextState = acquired.state; changed = changed || acquired.changed; diff --git a/src/cli/commands/generic.ts b/src/cli/commands/generic.ts index 980bb12ce7..dd00780e98 100644 --- a/src/cli/commands/generic.ts +++ b/src/cli/commands/generic.ts @@ -25,7 +25,6 @@ export async function runGenericClientBackedCommand({ debug, replayTestReporterRuntime, commandProgress, - inputs, leaseDevice, }: ClientCommandParams & { command: ClientBackedCliCommandName }): Promise { const { result, cliOutput: formatted } = await runCliCommandWithOutput({ @@ -34,7 +33,6 @@ export async function runGenericClientBackedCommand({ positionals, flags, commandProgress, - inputs, env: host.env, }); const cliOutput = diff --git a/src/cli/commands/router-types.ts b/src/cli/commands/router-types.ts index 8dc0e2ae4d..a76992ba08 100644 --- a/src/cli/commands/router-types.ts +++ b/src/cli/commands/router-types.ts @@ -6,7 +6,6 @@ import type { AgentDeviceClient } from '@agent-device/command-surface'; import type { CliCommandName } from '@agent-device/command-registry/catalog'; import type { CommandProgressState } from '@agent-device/command-output'; import type { ReplayTestReporterRuntime } from '../replay-test/reporting.ts'; -import type { CliRunInputs } from '../../commands/cli-runner.ts'; export type ClientCommandParams = { /** The host this run reads its environment and working directory from. */ @@ -18,7 +17,6 @@ export type ClientCommandParams = { replayTestReporterRuntime?: ReplayTestReporterRuntime; /** Progress this run's transport already rendered to stderr, read by the output formatters. */ commandProgress?: CommandProgressState; - inputs?: CliRunInputs; /** The device a proxy backend granted for the lease's device spec; `open` reports it. */ leaseDevice?: LeaseDevice; /** The record `disconnect` claimed before its client was built, or `null` when it claimed none. */ diff --git a/src/cli/commands/router.ts b/src/cli/commands/router.ts index 1646666217..57b98afa0f 100644 --- a/src/cli/commands/router.ts +++ b/src/cli/commands/router.ts @@ -34,7 +34,6 @@ export async function tryRunClientBackedCommand(params: { debug?: boolean; replayTestReporterRuntime?: ClientCommandParams['replayTestReporterRuntime']; commandProgress?: ClientCommandParams['commandProgress']; - inputs?: ClientCommandParams['inputs']; leaseDevice?: ClientCommandParams['leaseDevice']; claimedConnection?: ClientCommandParams['claimedConnection']; }): Promise { diff --git a/src/commands/cli-runner.ts b/src/commands/cli-runner.ts index 19d31f0d85..53070bc2a1 100644 --- a/src/commands/cli-runner.ts +++ b/src/commands/cli-runner.ts @@ -15,19 +15,12 @@ import { } from '@agent-device/command-surface'; import type { CliFlags } from '@agent-device/contracts/command'; -/** Input a CLI run can read only once. A rerun of the command reuses what is here. */ -export type CliRunInputs = { - /** The `fill --text-stdin` value. */ - fillText?: Promise; -}; - type CliRunOptions = { client: AgentDeviceClient; command: CommandName; positionals: string[]; flags: CliFlags; commandProgress?: CommandProgressState; - inputs?: CliRunInputs; /** The CLI run's own host environment; output formatters read styling from it (#3794). */ env: EnvMap; }; @@ -42,8 +35,7 @@ export async function runCliCommandWithOutput(options: CliRunOptions): Promise<{ }> { const input = readInputFromCli(options.command, options.positionals, options.flags); if (options.flags.textStdin) { - const inputs = options.inputs ?? {}; - const text = await (inputs.fillText ??= readFillTextFromStdin(process.stdin)); + const text = await readFillTextFromStdin(process.stdin); registerDiagnosticSensitiveValue(text); input.text = text; } From b58d30358521f57f1b97d160a9ba0056a09eb79f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 16:34:38 +0100 Subject: [PATCH 8/9] chore(remote): unexport an unused reason table and move the lock binding The capability refusal table has no outside reader since the CLI matches the refusal class. Binding the lease end outside a request's locks moves to the execution-lock module. Co-Authored-By: Claude Sonnet 5.5 --- packages/daemon-contracts/src/daemon-resolution.ts | 2 +- packages/daemon/src/server/request-execution-locks.ts | 11 +++++++++++ packages/daemon/src/server/request-execution-scope.ts | 7 +++---- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/daemon-contracts/src/daemon-resolution.ts b/packages/daemon-contracts/src/daemon-resolution.ts index 1a81eaf3de..c969b4771d 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -92,7 +92,7 @@ const DAEMON_STATE_ROOT_REASONS = { } as const satisfies ReasonTable<'daemon lifecycle'>; /** Why this build refuses to send a request whose delivery the answering daemon cannot promise. */ -export const DAEMON_CAPABILITY_REFUSAL_REASONS = { +const DAEMON_CAPABILITY_REFUSAL_REASONS = { // The remote daemon reports no script-artifacts capability, so it would record to its own disk. scriptArtifactsUnsupported: { reason: 'remote_script_artifacts_unsupported' }, // The daemon reports no lease-admission capability, so it cannot check a lease no heartbeat checked. diff --git a/packages/daemon/src/server/request-execution-locks.ts b/packages/daemon/src/server/request-execution-locks.ts index deffb54864..3798053828 100644 --- a/packages/daemon/src/server/request-execution-locks.ts +++ b/packages/daemon/src/server/request-execution-locks.ts @@ -1,3 +1,4 @@ +import { AsyncResource } from 'node:async_hooks'; import { heldKeyedLockKeys, withKeyedLock, @@ -70,6 +71,16 @@ export function createRequestExecutionLocks(params: { }; } +/** + * `end` bound to the current context. Bound before a request takes a lock, it runs outside that + * request's locks wherever the request calls it, so it never holds one while it waits for another. + */ +export function bindOutsideRequestLocks( + end: ((leaseId: string) => Promise) | undefined, +): ((leaseId: string) => Promise) | undefined { + return end && AsyncResource.bind(end); +} + function heldRequestLockKeys(locks: Map>): RequestExecutionLockKey[] { return heldKeyedLockKeys(locks) as RequestExecutionLockKey[]; } diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index d744979aed..b6807babc0 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -1,4 +1,3 @@ -import { AsyncResource } from 'node:async_hooks'; import { restrictRemoteHostInputs } from './remote-host-input-policy.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -59,6 +58,7 @@ import { readOpenWaitBudgetMs, } from '../sessions/open-device-contention-wait.ts'; import { + bindOutsideRequestLocks, createRequestExecutionLocks, withRequestExecutionLockKeys, } from './request-execution-locks.ts'; @@ -239,9 +239,8 @@ export async function createRequestExecutionScope(params: { endSessionsForLease?: (leaseId: string) => Promise; }): Promise { const { sessionStore, leaseRegistry } = params; - // Bound before this request takes a lock, so the lease end it starts never runs under one. - const queueLeaseEnd = - params.endSessionsForLease && AsyncResource.bind(params.endSessionsForLease); + // Bound here, before this request takes a lock. + const queueLeaseEnd = bindOutsideRequestLocks(params.endSessionsForLease); const tenantScopedReq = scopeRequestSession(restrictRemoteHostInputs(params.req)); // A nested batch or replay step arrives with the identity of the request that spawned it, and its // own name is already the store key. From 53800bd0265e5d2bfade541904d0a4f819d8bbb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 27 Nov 2026 17:08:04 +0100 Subject: [PATCH 9/9] fix(daemon-client): count a proxy's lease admission only through its upstream A health answer from agent-device-proxy with no upstream named only the proxy's instance, so nothing held the next request to the daemon that checks the lease. Such an answer now takes the heartbeat. Co-Authored-By: Claude Sonnet 5.5 --- .../__tests__/index-lease-admission.test.ts | 4 + .../src/daemon-client-remote-resend-port.ts | 3 +- .../daemon-contracts/src/daemon-resolution.ts | 7 +- .../docs/remote-device-lease-contracts.md | 1 + .../cli-lease-admission-proxy.test.ts | 92 +++++++++++++++++++ 5 files changed, 104 insertions(+), 3 deletions(-) diff --git a/packages/daemon-client/src/__tests__/index-lease-admission.test.ts b/packages/daemon-client/src/__tests__/index-lease-admission.test.ts index 8c343a8963..a510e771bd 100644 --- a/packages/daemon-client/src/__tests__/index-lease-admission.test.ts +++ b/packages/daemon-client/src/__tests__/index-lease-admission.test.ts @@ -81,6 +81,10 @@ test.each([ name: 'proxy that names no instance', health: { upstream: { instanceId: 'daemon', capabilities: LEASE_ADMISSION } }, }, + { + name: 'proxy that reports no upstream', + health: { service: 'agent-device-proxy', instanceId: 'proxy', capabilities: LEASE_ADMISSION }, + }, ])('a $name is refused before the send', async ({ health }) => { const { result, routes } = await sendAdmissionChecked(() => health); diff --git a/packages/daemon-client/src/daemon-client-remote-resend-port.ts b/packages/daemon-client/src/daemon-client-remote-resend-port.ts index b4e930590a..f9b9e811c1 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend-port.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend-port.ts @@ -8,9 +8,10 @@ import type { DaemonInfo } from './daemon-client-metadata.ts'; export type RemoteResendHealth = { reachable: boolean; timedOut?: true; + service?: string; instanceId?: string; capabilities?: readonly DaemonCapability[]; - upstream?: { instanceId?: string; capabilities?: readonly DaemonCapability[] }; + upstream?: { service?: string; instanceId?: string; capabilities?: readonly DaemonCapability[] }; }; /** The transport's side of one failed send: how to probe, resend and refuse for that request. */ diff --git a/packages/daemon-contracts/src/daemon-resolution.ts b/packages/daemon-contracts/src/daemon-resolution.ts index c969b4771d..7285c2e0b5 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -501,6 +501,7 @@ export function assertLeaseAdmissionCapability(capabilities: readonly string[] | } type DaemonHealthIdentity = Readonly<{ + service?: string; instanceId?: string; capabilities?: readonly DaemonCapability[]; }>; @@ -508,13 +509,15 @@ type DaemonHealthIdentity = Readonly<{ /** * The capabilities of the daemon a remote `/health` answer describes. `lease-admission` counts only * when the answer names the instance of every link, the daemon and any proxy in front of it: the - * instance fences then hold the next request to the daemon that reported it. + * instance fences then hold the next request to the daemon that reported it. A link that calls + * itself a proxy is never that daemon, so a proxy counts only through its upstream link. */ export function remoteDaemonCapabilities( health: DaemonHealthIdentity & Readonly<{ upstream?: DaemonHealthIdentity }>, ): readonly DaemonCapability[] | undefined { const daemon = health.upstream ?? health; - if (health.instanceId && daemon.instanceId) return daemon.capabilities; + const namesDaemon = daemon.service !== 'agent-device-proxy'; + if (namesDaemon && health.instanceId && daemon.instanceId) return daemon.capabilities; return daemon.capabilities?.filter((capability) => capability !== 'lease-admission'); } diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index 2c6d2d3b11..eee4ed0627 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -85,6 +85,7 @@ The CLI can reuse a stored lease without a heartbeat. It then marks the command as admission-checked and names the window that the heartbeat would have named. The daemon-client reads `lease-admission` from the `/health` check that the command already makes. It accepts the capability only if that answer names the instance of the daemon, and of the proxy in front of it. +If the answer is from `agent-device-proxy`, the capability counts only from its `upstream` link. If the capability is absent, the daemon-client refuses the command before the send with `lease_admission_unsupported`. It makes the same check again after an instance-mismatch refresh. An admission-checked command never takes the checked RPC route. On a checked connection (`daemonRpc: checked`) it is `GET /health`, then `POST /rpc`. diff --git a/src/__tests__/cli-lease-admission-proxy.test.ts b/src/__tests__/cli-lease-admission-proxy.test.ts index ea8a72371a..e0777941e2 100644 --- a/src/__tests__/cli-lease-admission-proxy.test.ts +++ b/src/__tests__/cli-lease-admission-proxy.test.ts @@ -1,8 +1,10 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; +import http from 'node:http'; import path from 'node:path'; import { test } from 'vitest'; import { createDaemonProxyServer } from '@agent-device/proxy'; +import { DAEMON_HTTP_INSTANCE_MISMATCH_HEADER } from '@agent-device/contracts/daemon-http'; import { closeLoopbackServer, listenOnLoopback, @@ -167,6 +169,96 @@ test('a checked connection sends a reused-lease command health-first and without } }); +// A proxy that names no upstream daemon cannot say whose admission would check the lease: the next +// request carries only the proxy's own instance fence. +test.for([ + { path: 'the first health check', replaced: false, rpcs: ['heartbeat', 'snapshot'] }, + // The first send is refused before dispatch for its stale instance, so only the second one runs. + { + path: 'the refresh after an instance mismatch', + replaced: true, + rpcs: ['snapshot', 'heartbeat', 'snapshot'], + }, +])( + 'a proxy answer with no upstream on $path gets the heartbeat before the command', + async ({ replaced, rpcs }, context) => { + if (await skipWhenLoopbackUnavailable(context)) return; + const { root, home, project } = makeTempWorkspace(); + const proxy = await proxyWithoutUpstream(replaced); + try { + const stateDir = path.join(root, 'state'); + writeConnection(stateDir, project, proxy.baseUrl, 'd'.repeat(32)); + + const result = await runCliCapture( + ['snapshot', '--session', 'agent', '--state-dir', stateDir, '--json'], + { + cwd: project, + env: { HOME: home, AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'client-secret' }, + useRealDaemonClient: true, + }, + ); + + assert.equal(result.code, null, result.stdout); + assert.deepEqual(proxy.rpcs, rpcs); + } finally { + await proxy.close(); + fs.rmSync(root, { recursive: true, force: true }); + } + }, +); + +/** + * A remote whose `/health` is a proxy's with a top-level `lease-admission` and no upstream. With + * `replaced`, it first names an upstream daemon and refuses the first RPC for its stale instance. + */ +async function proxyWithoutUpstream(replaced: boolean) { + const capabilities = ['script-artifacts', 'lease-admission']; + let named = replaced; + const rpcs: string[] = []; + const server = http.createServer((req, res) => { + res.setHeader('content-type', 'application/json'); + if (req.url === '/health') { + const link = named + ? { upstream: { service: 'agent-device-daemon', instanceId: 'daemon-1', capabilities } } + : { capabilities }; + res.end( + JSON.stringify({ + ok: true, + service: 'agent-device-proxy', + instanceId: named ? 'proxy-1' : 'proxy-2', + ...link, + }), + ); + return; + } + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + const { id, method, params } = JSON.parse(body); + rpcs.push(method === 'agent_device.lease.heartbeat' ? 'heartbeat' : params.command); + if (named) { + named = false; + res.statusCode = 409; + res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true'); + const error = { code: -32000, message: 'stale instance' }; + res.end(JSON.stringify({ jsonrpc: '2.0', id, error })); + return; + } + const lease = { + leaseId: params.leaseId, + tenantId: LEASE_SCOPE.tenant, + runId: LEASE_SCOPE.runId, + backend: LEASE_SCOPE.leaseBackend, + }; + const data = + method === 'agent_device.lease.heartbeat' ? { lease } : { nodes: [], truncated: false }; + res.end(JSON.stringify({ jsonrpc: '2.0', id, result: { ok: true, data } })); + }); + }); + const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`; + return { baseUrl, rpcs, close: () => closeLoopbackServer(server) }; +} + async function describe(request: Request): Promise { const route = new URL(request.url).pathname; if (route !== '/rpc' && route !== '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/rpc/checked') return route;