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..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; } @@ -544,6 +553,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..a510e771bd --- /dev/null +++ b/packages/daemon-client/src/__tests__/index-lease-admission.test.ts @@ -0,0 +1,135 @@ +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, + flags: Record = {}, +) { + 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'), + ...flags, + }, + 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' } }, + }, + // 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 } }, + }, + { + 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); + + expect(result).toMatchObject({ + code: 'UNSUPPORTED_OPERATION', + details: { reason: 'lease_admission_unsupported', daemonRequestSent: false, dispatched: 'no' }, + }); + expect(routes).toEqual(['/health']); +}); + +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 ? replacement : { 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']); +}); + +// 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..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, @@ -68,7 +69,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 +107,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 +149,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 } : {}), @@ -372,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-port.ts b/packages/daemon-client/src/daemon-client-remote-resend-port.ts index ca3a534278..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. */ @@ -20,6 +21,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 213dfb06ae..1c45d66703 100644 --- a/packages/daemon-client/src/daemon-client-remote-resend.ts +++ b/packages/daemon-client/src/daemon-client-remote-resend.ts @@ -4,7 +4,11 @@ // 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, + remoteDaemonCapabilities, +} from '@agent-device/daemon-contracts/daemon-resolution'; import { CheckedRpcConnectFailure, undispatchedWithoutEndpoint, @@ -77,10 +81,12 @@ 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); + // A replacement that cannot check the lease at admission gets the heartbeat path instead. + if (port.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..667d500ed5 100644 --- a/packages/daemon-client/src/daemon-client-request.ts +++ b/packages/daemon-client/src/daemon-client-request.ts @@ -7,6 +7,12 @@ 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, so the + * request never takes the checked RPC route, which reads no `/health`. + */ + 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..51ebf3ef95 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -48,6 +48,7 @@ type ResolvedDaemonTransport = LoopbackTransport; type SendRequestOptions = { /** The host whose working directory and environment this request's client-side work reads. */ host: HostEnvironment; + leaseCheckedByAdmission?: true; onProgress?: RequestProgressSink; /** * The caller's per-request cancellation (#3178). Aborted at or before a send attempt, nothing @@ -536,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-client/src/index.ts b/packages/daemon-client/src/index.ts index 5c5c140ac1..425b394318 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'; @@ -96,6 +99,7 @@ async function sendToDaemonOnHost( host, options.daemonLifecycle, options.daemonBinding, + options.leaseCheckedByAdmission, ); const requestTimeoutMs = resolveCommandRequestTimeoutMs( resolveCommandTimeoutPolicy(requestWithoutAuthFlag.command), @@ -124,6 +128,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 +180,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..7285c2e0b5 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -95,6 +95,8 @@ const DAEMON_STATE_ROOT_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. + 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,50 @@ 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')) throw new LeaseAdmissionUnsupportedError(); +} + +type DaemonHealthIdentity = Readonly<{ + service?: string; + 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. 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; + const namesDaemon = daemon.service !== 'agent-device-proxy'; + if (namesDaemon && health.instanceId && daemon.instanceId) return daemon.capabilities; + return daemon.capabilities?.filter((capability) => capability !== 'lease-admission'); +} + 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..eee4ed0627 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -62,8 +62,53 @@ 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 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 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`. + +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`. +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: + +- 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`. +- `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. ## Admitted request work 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 cb11bf74c4..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 @@ -4,14 +4,27 @@ 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'; +import { + createLeaseSessionEnd, + 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, @@ -20,6 +33,8 @@ import { bindTestCommandHost(); +const claimStores = isolatedDeviceClaimStores('agent-device-request-scope-claims-'); + function makeRequest(overrides: Partial): DaemonRequest { return { token: 't', @@ -156,3 +171,261 @@ test.each(['rebuild', 'retire'] as const)( else expect(store.lookup(address)).toBeUndefined(); }, ); + +/** 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 leaseEnd = createLeaseSessionEnd({ + env: process.env, + sessionStore, + executionLocks: getLeaseRegistryExecutionLocks(leaseRegistry), + teardownSession: async () => {}, + cleanupSessionlessExecutionHost: async () => {}, + }); + const scopeFor = async (command: string, requestMeta: DaemonRequest['meta'] = meta) => + await createRequestExecutionScope({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + claimRecoveryGateway: daemonClaimRecoveryGatewayFixture(), + trackClaimRecoveryDisposal: () => {}, + deviceRuntimeGateway: unavailableDeviceRuntimeGateway, + platformRequestScope: platformRequestScopeFixture(), + req: makeRequest({ command, session: session.name, meta: requestMeta }), + sessionStore, + leaseRegistry, + endSessionsForLease: async (leaseId) => await leaseEnd.end(leaseId, 'LEASE_RELEASED'), + platformResourceCleanup: { + stopSnapshotHelper: async () => {}, + closeManagedBrowser: async () => {}, + cleanupSessionlessExecutionHost: async () => {}, + retainExecutionHostAfterClose: () => false, + }, + }); + 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; + }; + }; + 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 { leaseRegistry, run, expectSessionEnded } = await sessionWhoseLeaseEnded(fate); + const task = vi.fn(async () => 'ran'); + + const refusal = await run('close', task).catch((error: unknown) => error); + + expectSessionEnded(); + 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'); + }, +); + +test.each(['lease_release', 'lease_heartbeat'])( + '%s for a released lease ends the session still holding it', + async (command) => { + const { run, expectSessionEnded } = await sessionWhoseLeaseEnded('released'); + + await run(command, async () => 'ran'); + + await vi.waitFor(expectSessionEnded); + }, +); + +// `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'); + const release = holdSession(); + + const refusal = await ( + await scopeFor('close') + ) + .runAdmitted(async () => 'ran') + .catch((error: unknown) => error); + + 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); + + 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 +// 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(); + await release(); + + await vi.waitFor(expectSessionEnded); +}); 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/__tests__/request-router-fill-text-stdin.test.ts b/packages/daemon/src/server/__tests__/request-router-fill-text-stdin.test.ts index 752c42c4a0..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, @@ -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,54 @@ test.each([ }, ); +// 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 }), + { recordAs: 'PASSWORD' }, + (text) => + new AppError('COMMAND_FAILED', 'could not type', { + reason: `rejected-${text}`, + // A value outside the type, as an untrusted backend could write it. + dispatched: text as DispatchDisclosure, + }), + ); + + const result = await response; + expect(result.ok).toBe(false); + expect(JSON.stringify(result)).not.toContain(SECRET); + if (!result.ok) { + expect(result.error.details).toMatchObject({ + reason: 'rejected-${PASSWORD}', + dispatched: '${PASSWORD}', + }); + } +}); + 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..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 @@ -113,6 +113,12 @@ 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', + 'checked-rpc', + '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-binding.ts b/packages/daemon/src/server/request-binding.ts index 2a724476d5..3620d18d78 100644 --- a/packages/daemon/src/server/request-binding.ts +++ b/packages/daemon/src/server/request-binding.ts @@ -1,4 +1,7 @@ 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 { hasDeviceSelectionInput, @@ -71,6 +74,27 @@ 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); + 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..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 a535359f84..b6807babc0 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -45,7 +45,9 @@ import { type SessionTeardown, } from '../sessions/lease-lifecycle.ts'; import { + applyRequestCommandDefaults, existingSessionExecutionLockKeys, + holdsSessionExecutionLocks, prepareLockedRequestBinding, resolveRequestExecutionLockPlan, type RequestExecutionLockPlan, @@ -56,6 +58,7 @@ import { readOpenWaitBudgetMs, } from '../sessions/open-device-contention-wait.ts'; import { + bindOutsideRequestLocks, createRequestExecutionLocks, withRequestExecutionLockKeys, } from './request-execution-locks.ts'; @@ -98,10 +101,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 { @@ -236,8 +236,11 @@ export async function createRequestExecutionScope(params: { platformResourceCleanup?: PlatformResourceCleanup; providerAppCatalog?: ProviderAppCatalog; daemonPolicy?: DaemonPolicy; + endSessionsForLease?: (leaseId: string) => Promise; }): Promise { const { sessionStore, leaseRegistry } = params; + // 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. @@ -464,12 +467,14 @@ export async function createRequestExecutionScope(params: { }); } throwIfRequestCanceled(scopedReq.meta?.requestId); - await cleanupExpiredLeasedSession({ + const sessionEnded = await cleanupExpiredLeasedSession({ env: params.host.env, sessionName, sessionStore, leaseRegistry, - refuseTeardown: command === 'batch' || command === 'replay' || boundedStep, + req: scopedReq, + queueLeaseEnd, + holdsSessionLocks: (ref) => holdsSessionExecutionLocks(executionLocks, ref), teardownSession: async (ref) => await teardownExpiredSession({ ref, @@ -487,6 +492,7 @@ export async function createRequestExecutionScope(params: { leaseRegistry, providerAppCatalog: params.providerAppCatalog, daemonPolicy: params.daemonPolicy, + sessionEnded, }); scope.req = scopedReq; admissionCompleted = true; @@ -704,16 +710,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/server/request-router.ts b/packages/daemon/src/server/request-router.ts index b15cc5ffa9..a66bf1e6f8 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 { @@ -306,6 +308,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { platformResourceCleanup, providerAppCatalog, daemonPolicy, + endSessionsForLease, }); return await executeRequestScope(scope); }), @@ -485,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 @@ -625,7 +629,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. 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); @@ -635,16 +641,34 @@ 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; } +/** 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 dispatched = readDispatchDisclosure(original); + const reason = LEASE_REASON_VALUES.has(original.reason) ? original.reason : undefined; + 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..5fe154e323 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,11 +116,13 @@ 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, leaseRegistry, teardownSession, + holdsSessionLocks: () => true, }); expect(cleaned).toBe(true); @@ -101,6 +133,77 @@ test('cleanupExpiredLeasedSession consumes expired lease and deletes the session expect(leaseRegistry.listActiveLeases()).toHaveLength(0); }); +function sessionWithExpiredLease() { + 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 () => {}); + const cleanup = ( + request: Partial & Pick, + spell: (leaseId: string) => string = (leaseId) => leaseId, + ) => + cleanupExpiredLeasedSession({ + req: makeRequest({ + meta: { tenantId: 'tenant-a', runId: 'run-1', leaseId: spell(lease.leaseId) }, + ...request, + }), + env: process.env, + sessionName: 'default', + sessionStore, + leaseRegistry, + teardownSession, + holdsSessionLocks: () => true, + }); + 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, (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], + // 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) => { + const { sessionStore, session, teardownSession, cleanup } = sessionWithExpiredLease(); + + await expect(cleanup(request, spell)).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(); const lease = leaseRegistry.allocateLease({ 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 a15f2e3809..04ff3474d5 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -2,15 +2,23 @@ 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, 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,38 +61,90 @@ 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 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; 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; + /** 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, params.leaseRegistry)) return; + throw new AppError('UNAUTHORIZED', 'Lease is not active', { + reason: LEASE_REASONS.notFound.reason, + dispatched: 'no', + }); + }); + const end = async () => + await endLeasedSession( + ref, + params.sessionStore, + params.teardownSession, + 'LEASE_EXPIRED', + params.env, + ); + if (expired) { + await end(); + return true; + } if ( - !params.leaseRegistry.consumeExpiredLease(lease.leaseId, () => { - if (!params.refuseTeardown) return; - throw new AppError('UNAUTHORIZED', 'Lease is not active', { - reason: LEASE_REASONS.notFound.reason, - dispatched: 'no', - }); - }) - ) + !params.queueLeaseEnd || + doesDeviceWork(params.req) || + isBoundedCompositeRequest(params.req) || + params.leaseRegistry.inspectLeaseBackend(lease.leaseId) !== undefined + ) { return false; - await endLeasedSession( - ref, - params.sessionStore, - params.teardownSession, - 'LEASE_EXPIRED', - params.env, - ); + } + // 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, leaseRegistry: LeaseRegistry): boolean { + return ( + req.command === 'batch' || + req.command === 'replay' || + isBoundedCompositeRequest(req) || + (doesDeviceWork(req) && namesInactiveLease(req, leaseRegistry)) + ); +} + +/** 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 { + 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 + ); +} + /** * 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. @@ -133,15 +193,25 @@ 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; - 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. + // After a teardown the refusal cannot claim that nothing ran. + let activeLease: DeviceLease | undefined; + try { + activeLease = assertRequestLeaseAdmission(params.req, leaseRegistry, existingSession, { + env: params.env, + providerAppCatalog: params.providerAppCatalog, + daemonPolicy: params.daemonPolicy, + }); + } catch (error) { + throw params.sessionEnded ? error : thrownBeforeDispatch(error); + } if (!activeLease) return params.req; const nextReq = { 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-lease-admission-proxy.test.ts b/src/__tests__/cli-lease-admission-proxy.test.ts new file mode 100644 index 0000000000..e0777941e2 --- /dev/null +++ b/src/__tests__/cli-lease-admission-proxy.test.ts @@ -0,0 +1,296 @@ +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, + 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 }); + } +}); + +// 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 }); + } +}); + +// 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; + const body = JSON.parse(await request.clone().text()) as { + method?: string; + params?: { command?: string }; + }; + return `${route} ${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..1cd69acbec --- /dev/null +++ b/src/__tests__/cli-lease-admission.test.ts @@ -0,0 +1,383 @@ +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'; +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 { 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 +// 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'; +const STORED_LEASE = 'a1'.repeat(16); + +type Workspace = { root: string; home: string; project: string; stateDir: string }; + +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(remoteConfig)); + 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: STORED_LEASE, + 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') === STORED_LEASE) 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'), STORED_LEASE); + // 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, STORED_LEASE); + 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' }, + ], + // 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 }); + + 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 }); +}); + +// 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'), STORED_LEASE); + + 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'], {}], + ['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 }], + ['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 }); + + assert.equal(commandsOf(result)[0], 'lease_heartbeat', result.stdout); + assert.equal(markedOf(result).includes(true), false); + + 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 2299df1f1f..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'; @@ -66,6 +62,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 type * as LeaseAdmission from './cli/commands/connection-lease-admission.ts'; type CliDeps = { sendToDaemon: typeof sendToDaemon; @@ -74,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 @@ -222,19 +216,27 @@ 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 { 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) => { + const client = createAgentDeviceClient(buildClientConfig(ctx), { + host: ctx.host, + devicePin: ctx.devicePin, + transport: createCliDaemonTransport({ + host, + command, + flags: ctx.effectiveFlags, + replayTestReporterRuntime, + commandProgress, + transport: send, + }), + }); + await dispatchCliCommand(ctx, client, replayTestReporterRuntime, commandProgress); + }, }); - await dispatchCliCommand(ctx, client, replayTestReporterRuntime, commandProgress); } catch (error) { await handleRunCliFailure(error, ctx, logTailStopper); } finally { @@ -369,6 +371,8 @@ 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; }; @@ -471,6 +475,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 +484,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 +495,8 @@ 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( @@ -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, @@ -865,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); +} diff --git a/src/cli/commands/connection-lease-admission.ts b/src/cli/commands/connection-lease-admission.ts new file mode 100644 index 0000000000..d9270615a9 --- /dev/null +++ b/src/cli/commands/connection-lease-admission.ts @@ -0,0 +1,213 @@ +import { + commandMeetsLeaseAdmission, + isDelegatingCompositeCommand, +} from '@agent-device/command-registry/registry'; +import { + isUndispatchedInactiveLeaseRefusal, + leaseProviderRequiringRuntime, + normalizeLeaseId, + requireLeaseDeviceSpec, +} from '@agent-device/contracts/lease-scope'; +import { LeaseAdmissionUnsupportedError } from '@agent-device/daemon-contracts/daemon-resolution'; +import { requestUploadsArtifacts } from '@agent-device/remote/daemon-artifacts'; +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; +}>; + +/** + * 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; + * - 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. + */ +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 { + const { state, flags, check } = options; + 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) || + 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; + } + const leaseTtlMs = options.policy.ttlMs(state); + 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 ( + 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'; + // The client's own guard, which sent nothing. A daemon answer with its reason is not one. + return error instanceof LeaseAdmissionUnsupportedError ? '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..ffb6540683 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,16 @@ export async function acquireConnectionLease(options: { nextFlags: CliFlags; positionals?: string[]; leaseLedger: LeaseLedger; -}): Promise<{ state: RemoteConnectionState; changed: boolean }> { + 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; + /** 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 +147,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 +158,20 @@ export async function acquireConnectionLease(options: { initialApp, policy: leasePolicy, leaseLedger, + reusedLeaseCheck: options.reusedLeaseCheck, + savedState: options.savedState, + preparesRuntime: options.preparesRuntime, }); 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 +211,14 @@ async function materializeLeaseForCommand(options: { initialApp?: string; policy: ConnectionLeasePolicy; leaseLedger: LeaseLedger; -}): Promise<{ state: RemoteConnectionState; changed: boolean }> { + reusedLeaseCheck?: ReusedLeaseCheck; + savedState?: RemoteConnectionState; + preparesRuntime?: (flags: CliFlags) => boolean; +}): 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 +243,33 @@ 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, + savedState: options.savedState, + preparesRuntime: options.preparesRuntime?.(nextFlags) ?? true, + 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 +298,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 +408,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-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 0c687dc05c..aff82c5376 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -27,10 +27,12 @@ import { resolveRequestedLeaseBackend, type LeaseLedger, } from './connection-lease-transaction.ts'; +import type { AdmissionCheckedLease, ReusedLeaseCheck } from './connection-lease-admission.ts'; import { prepareRuntimeForCommand, selectCompatibleRuntime, stopMetroCleanup, + willPrepareRuntime, } from './connection-metro-runtime.ts'; import { grantedLeaseDevice } from './proxy-lease-device.ts'; @@ -43,11 +45,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 +106,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 +115,15 @@ export async function materializeRemoteConnectionForCommand(options: { nextFlags, 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; + admissionCheckedLease = acquired.admissionCheckedLease; const runtimePreparation = await prepareRuntimeForCommand({ command, @@ -151,6 +163,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()`. | 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.