diff --git a/packages/contracts/src/lease-scope.ts b/packages/contracts/src/lease-scope.ts index cd6a9862eb..c46e1ee042 100644 --- a/packages/contracts/src/lease-scope.ts +++ b/packages/contracts/src/lease-scope.ts @@ -516,6 +516,8 @@ export const LEASE_REASONS = { scopeMismatch: { reason: 'LEASE_SCOPE_MISMATCH' }, // The lease was allocated with an owner scope that the request does not repeat. scopeRequired: { reason: 'LEASE_SCOPE_REQUIRED' }, + // The device instance behind the lease ended outside the daemon, which ends the lease with it. + instanceEnded: { reason: 'provider-instance-ended' }, } as const satisfies ReasonTable<'leases'>; /** @@ -544,9 +546,6 @@ export function isInactiveLeaseError(error: unknown): boolean { ); } -/** The reason a provider gives when the device instance behind a lease ended outside the daemon. */ -export const PROVIDER_INSTANCE_ENDED = 'provider-instance-ended'; - /** Whether `error` says the provider's device instance ended, which ends its lease. */ export function isProviderInstanceEndedError(error: unknown): boolean { return ( @@ -554,7 +553,7 @@ export function isProviderInstanceEndedError(error: unknown): boolean { error !== null && (error as Readonly<{ code?: unknown }>).code === 'COMMAND_FAILED' && (error as Readonly<{ details?: Readonly<{ reason?: unknown }> }>).details?.reason === - PROVIDER_INSTANCE_ENDED + LEASE_REASONS.instanceEnded.reason ); } diff --git a/packages/contracts/src/platform-runtime.ts b/packages/contracts/src/platform-runtime.ts index dc18513ebd..b13c347e6d 100644 --- a/packages/contracts/src/platform-runtime.ts +++ b/packages/contracts/src/platform-runtime.ts @@ -7,7 +7,7 @@ import { type DeviceTarget, type Platform, } from '@agent-device/kernel/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { PlatformModuleMetadata } from './platform-module.ts'; import type { PlatformRequestScope } from './platform-runtime-host.ts'; import type { ApplicationLifecycleResourceLifecycle } from './application-lifecycle-runtime.ts'; @@ -163,6 +163,16 @@ export function sameRuntimeOwner(left: RuntimeOwnerRef, right: RuntimeOwnerRef): export type RuntimeProviderMode = 'local' | 'transport-composed' | 'provider-runtime'; +/** + * Every `details.reason` a hosted provider's runtime owner publishes when it refuses to serve a + * request. More than one provider raises these, so the row lives with the runtime contract the + * providers all bind through. + */ +export const PROVIDER_RUNTIME_REASONS = { + // The provider's session for the device ended, so the runtime has nothing left to serve. + sessionUnavailable: { reason: 'provider-session-unavailable' }, +} as const satisfies ReasonTable<'provider runtime'>; + export type RuntimeDeviceShape = Readonly<{ family: Platform; appleOs?: AppleOS; diff --git a/packages/provider-limrun/src/android.ts b/packages/provider-limrun/src/android.ts index f97d81f53a..a66145d5f5 100644 --- a/packages/provider-limrun/src/android.ts +++ b/packages/provider-limrun/src/android.ts @@ -11,7 +11,7 @@ import type { ProviderDeviceInstallResult, ProviderPortReverseOptions, } from '@agent-device/contracts/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { LimrunAdbCommandOptions, @@ -29,6 +29,12 @@ import { type LimrunRequestOperationDrain, } from './request-cancellation.ts'; +/** Why a Limrun Android operation refused. */ +const LIMRUN_ANDROID_REASONS = { + // The ADB tunnel of this lease was already cleaned up, so nothing can be typed over it. + adbTunnelCleanedUp: { reason: 'limrun_adb_tunnel_cleaned_up' }, +} as const satisfies ReasonTable<'limrun provider'>; + type LimrunAdbTunnel = Awaited>; type LimrunAndroidAdbSession = { @@ -346,7 +352,7 @@ function alreadyCleanedUp(session: LimrunAndroidAdbSession): AppError { 'SESSION_NOT_FOUND', `Limrun ADB tunnel for instance '${session.instanceId}' was already cleaned up`, { - reason: 'limrun_adb_tunnel_cleaned_up', + reason: LIMRUN_ANDROID_REASONS.adbTunnelCleanedUp.reason, // The tunnel is gone whether the instance's delete confirmed or is still held for retry, so the hint // sends the caller to a new lease, and to Limrun only for the state where a release would refuse again. hint: `This interactor's ADB tunnel is closed for lease '${session.lease.leaseId}'. Open a new lease. If this lease's release was refused as an unconfirmed delete, ask Limrun to delete the instance first.`, diff --git a/packages/provider-limrun/src/app-log-runtime.ts b/packages/provider-limrun/src/app-log-runtime.ts index f608a5241c..434ece95c5 100644 --- a/packages/provider-limrun/src/app-log-runtime.ts +++ b/packages/provider-limrun/src/app-log-runtime.ts @@ -13,6 +13,7 @@ import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-ru import { type DeviceBinding, providerRuntimeOwner, + PROVIDER_RUNTIME_REASONS, sameRuntimeOwner, whenAdmitted, } from '@agent-device/contracts/platform-runtime'; @@ -121,7 +122,7 @@ export function createLimrunPlatformRuntimeOwner( throw new AppError( 'UNSUPPORTED_OPERATION', 'Limrun provider session is no longer live for the selected device', - { reason: 'provider-session-unavailable' }, + { reason: PROVIDER_RUNTIME_REASONS.sessionUnavailable.reason }, ); } return bindLimrunAppLogs( diff --git a/packages/provider-limrun/src/app-state-read.ts b/packages/provider-limrun/src/app-state-read.ts index ce85bb9311..282d4278a8 100644 --- a/packages/provider-limrun/src/app-state-read.ts +++ b/packages/provider-limrun/src/app-state-read.ts @@ -1,8 +1,14 @@ import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-runtime'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { LimrunDeviceSession } from './device-session.ts'; import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; +/** Why reading app state from a Limrun instance failed. */ +const LIMRUN_APP_STATE_REASONS = { + // The instance stopped answering, so its app state cannot be read. + instanceUnreachable: { reason: 'limrun_instance_unreachable' }, +} as const satisfies ReasonTable<'limrun provider'>; + /** * Android reads the foreground app. Limrun exposes no foreground bundle id on iOS, so an iOS read * only proves the instance still answers: its empty result leaves the session record to name the @@ -41,7 +47,7 @@ async function confirmLimrunIosInstanceAnswers( 'COMMAND_FAILED', 'Could not confirm that the Limrun iOS instance is running, so its app state is unknown.', { - reason: 'limrun_instance_unreachable', + reason: LIMRUN_APP_STATE_REASONS.instanceUnreachable.reason, hint: 'Retry appstate. If it keeps failing, the instance may have been terminated: run connect limrun and open again.', }, error, diff --git a/packages/provider-limrun/src/lease-release.ts b/packages/provider-limrun/src/lease-release.ts index 0f8652fade..8ee88e8921 100644 --- a/packages/provider-limrun/src/lease-release.ts +++ b/packages/provider-limrun/src/lease-release.ts @@ -1,6 +1,6 @@ import type Limrun from '@limrun/api'; import type { DeviceLease } from '@agent-device/contracts/device'; -import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; import { cleanupLimrunAndroidAdbTunnel } from './android.ts'; import { CAPTURE_OPEN_BUDGET_MS } from './capture-lifecycle.ts'; import { deleteLimrunInstance } from './client-options.ts'; @@ -15,6 +15,14 @@ import type { } from './lease-ownership.ts'; import type { SettledNetworkCapture } from './network-har.ts'; +/** Why a Limrun lease release could not be confirmed. */ +const LIMRUN_LEASE_RELEASE_REASONS = { + // A release could not confirm Limrun deleted the instance, so it may still be billed. + instanceDeleteUnconfirmed: { reason: 'limrun_instance_delete_unconfirmed' }, + // The lease was released while its instance was still being prepared for the allocation. + leaseReleasedMidAllocation: { reason: 'limrun_lease_released_mid_allocation' }, +} as const satisfies ReasonTable<'limrun provider'>; + /** * Everything this runtime does once a lease has been taken for good: end what its owner holds, and answer with * what came of it. One lease's disposal runs here, and every route that ends a lease — release, daemon close, @@ -498,7 +506,7 @@ export function allocationRefusedForTake( 'DEVICE_IN_USE', `Limrun lease '${lease.leaseId}' was released while its instance was being prepared`, { - reason: 'limrun_lease_released_mid_allocation', + reason: LIMRUN_LEASE_RELEASE_REASONS.leaseReleasedMidAllocation.reason, ...(instanceId === undefined ? { hint: `Instance create for lease '${lease.leaseId}' may still rent one. Check Limrun.` } : { limrunInstanceId: instanceId, ...(ended === undefined ? {} : { hint: ended }) }), @@ -562,7 +570,7 @@ function throwUnconfirmedDelete( 'COMMAND_FAILED', message, { - reason: 'limrun_instance_delete_unconfirmed', + reason: LIMRUN_LEASE_RELEASE_REASONS.instanceDeleteUnconfirmed.reason, retriable: true, ...instanceDetails, ...(failure === undefined ? {} : { cause: failure }), diff --git a/packages/provider-limrun/src/runtime.ts b/packages/provider-limrun/src/runtime.ts index f4dda0e1c4..13c5f060d3 100644 --- a/packages/provider-limrun/src/runtime.ts +++ b/packages/provider-limrun/src/runtime.ts @@ -14,7 +14,7 @@ import type { ProviderPortReverseOptions, } from '@agent-device/contracts/device'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; import { configureLimrunAndroidPortReverse, createLimrunAndroidInteractor, @@ -67,6 +67,14 @@ import type { import type { LimrunCaptureLifecycle } from './capture-lifecycle.ts'; import type { LimrunDisposalHost } from './lease-release.ts'; +/** Why the Limrun runtime refuses a lease request. */ +const LIMRUN_RUNTIME_REASONS = { + // The lease holds no live session, so the command that addresses it has nothing to act on. + leaseNotLive: { reason: 'limrun_lease_not_live' }, + // This runtime is shut down, so it refuses to allocate a lease into it. + runtimeShutDown: { reason: 'limrun_runtime_shut_down' }, +} as const satisfies ReasonTable<'limrun provider'>; + const HEARTBEAT_PROBE_BUDGET_MS = 2_000; const KEEP_ALIVE_INTERVAL_MS = 30_000; @@ -783,9 +791,9 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { terminationReason = 'Unknown'; } if (terminationReason === undefined) return undefined; - const { PROVIDER_INSTANCE_ENDED } = await import('@agent-device/contracts/lease-scope'); + const { LEASE_REASONS } = await import('@agent-device/contracts/lease-scope'); throw new AppError('COMMAND_FAILED', `The Limrun instance ended (${terminationReason}).`, { - reason: PROVIDER_INSTANCE_ENDED, + reason: LEASE_REASONS.instanceEnded.reason, terminationReason, instanceId: session.instanceId, }); @@ -816,7 +824,7 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { throw new AppError( 'COMMAND_FAILED', `Limrun lease '${owner.lease.leaseId}' has no live session`, - { reason: 'limrun_lease_not_live' }, + { reason: LIMRUN_RUNTIME_REASONS.leaseNotLive.reason }, ); } return session; @@ -945,7 +953,7 @@ function allocationRefusedAfterShutdown(lease: DeviceLease): never { 'SESSION_NOT_FOUND', `Cannot allocate Limrun lease '${lease.leaseId}': this runtime is shut down`, { - reason: 'limrun_runtime_shut_down', + reason: LIMRUN_RUNTIME_REASONS.runtimeShutDown.reason, hint: 'Start the daemon again to allocate a Limrun lease.', }, ); diff --git a/packages/provider-limrun/src/sync-cache.ts b/packages/provider-limrun/src/sync-cache.ts index bf1981660e..c2497b4146 100644 --- a/packages/provider-limrun/src/sync-cache.ts +++ b/packages/provider-limrun/src/sync-cache.ts @@ -1,7 +1,15 @@ import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +/** Why a Limrun app sync failed. */ +const LIMRUN_APP_SYNC_REASONS = { + // The app-sync session of this lease has ended, so no further sync runs on it. + appSyncRetired: { reason: 'limrun_app_sync_retired' }, + // App sync or local cache maintenance failed; check the device for the app before retrying. + appSyncFailed: { reason: 'limrun_app_sync_failed' }, +} as const satisfies ReasonTable<'limrun provider'>; /** One lease retains only its latest artifact's basis, even when materialization paths change. */ export class LimrunSyncCache { @@ -17,7 +25,7 @@ export class LimrunSyncCache { ): Promise { if (this.retired) { throw new AppError('COMMAND_FAILED', 'Limrun app sync session has ended.', { - reason: 'limrun_app_sync_retired', + reason: LIMRUN_APP_SYNC_REASONS.appSyncRetired.reason, }); } const operation = this.pending.then(async () => { @@ -43,7 +51,7 @@ export class LimrunSyncCache { 'COMMAND_FAILED', 'Limrun app sync failed.', { - reason: 'limrun_app_sync_failed', + reason: LIMRUN_APP_SYNC_REASONS.appSyncFailed.reason, platform, installablePath, }, diff --git a/packages/provider-revyl/src/connection.ts b/packages/provider-revyl/src/connection.ts index 3b0a6566c3..a9bb0f3453 100644 --- a/packages/provider-revyl/src/connection.ts +++ b/packages/provider-revyl/src/connection.ts @@ -5,13 +5,21 @@ import { requireResolvedProfilePlatform, } from '@agent-device/contracts/provider-profile-fields'; import type { ProviderConnectionVerification } from '@agent-device/contracts/remote'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { REVYL_PROVIDER, REVYL_SERVICE, type RevylPlatform } from './device.ts'; import { requireRevylCredentials, type RevylCredentials } from './credentials.ts'; import { createRevylClient } from './revyl-client.ts'; import { REVYL_PROFILE_FIELDS } from './profile-fields.ts'; import { revylTextFlag } from './session-allocation.ts'; +/** Why a Revyl connection request is refused. */ +const REVYL_CONNECTION_REASONS = { + // Revyl installs the app from a URL, so `--provider-app` cannot name a local file. + invalidApp: { reason: 'invalid_provider_app' }, + // Revyl rents an iOS simulator or an Android emulator, and the request names neither. + unsupportedPlatform: { reason: 'unsupported_platform' }, +} as const satisfies ReasonTable<'revyl provider'>; + /** The connect half of the plugin, bound to one host's environment. */ export type RevylConnection = ReturnType; @@ -87,7 +95,7 @@ export async function verifyRevylProfile( 'INVALID_ARGS', `${REVYL_SERVICE} installs the app from a URL, so --provider-app must be an https URL.`, { - reason: 'invalid_provider_app', + reason: REVYL_CONNECTION_REASONS.invalidApp.reason, hint: `Pass the URL ${REVYL_SERVICE} can read the build from; a local path cannot.`, }, ); @@ -140,7 +148,7 @@ function isRevylAppUrl(value: string | undefined): boolean { function requireConnectPlatform(flags: CliFlags): RevylPlatform { if (flags.platform === 'ios' || flags.platform === 'android') return flags.platform; throw new AppError('INVALID_ARGS', `connect ${REVYL_PROVIDER} requires --platform ios|android.`, { - reason: 'unsupported_platform', + reason: REVYL_CONNECTION_REASONS.unsupportedPlatform.reason, }); } diff --git a/packages/provider-revyl/src/credentials.ts b/packages/provider-revyl/src/credentials.ts index b8d93c123c..94f016efb6 100644 --- a/packages/provider-revyl/src/credentials.ts +++ b/packages/provider-revyl/src/credentials.ts @@ -1,4 +1,10 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +/** Every `details.reason` this module raises when it reads the Revyl credentials. */ +const REVYL_CREDENTIAL_REASONS = { + // No Revyl API key is set, so the provider cannot authenticate the request. + missingCredentials: { reason: 'missing_provider_credentials' }, +} as const satisfies ReasonTable<'revyl provider'>; export const REVYL_API_KEY_VARIABLE = 'REVYL_API_KEY'; export const REVYL_API_URL_VARIABLE = 'REVYL_API_URL'; @@ -22,7 +28,7 @@ export function requireRevylCredentials( return { apiKey, apiUrl: env[REVYL_API_URL_VARIABLE]?.trim() || undefined }; } throw new AppError('INVALID_ARGS', `${command} requires a Revyl API key.`, { - reason: 'missing_provider_credentials', + reason: REVYL_CREDENTIAL_REASONS.missingCredentials.reason, hint: `Set ${REVYL_API_KEY_VARIABLE} to a Revyl API key. Revyl issues keys to its customers; a partner integration gets one through Revyl's partner program.`, variables: [REVYL_API_KEY_VARIABLE], }); diff --git a/packages/provider-revyl/src/deployment.ts b/packages/provider-revyl/src/deployment.ts index bd66ae3b35..b9c55850e7 100644 --- a/packages/provider-revyl/src/deployment.ts +++ b/packages/provider-revyl/src/deployment.ts @@ -5,11 +5,17 @@ import type { } from '@agent-device/contracts/app-deployment-runtime'; import { packGzipTar } from '@agent-device/host-kit/gzip-tar'; import { Deadline, type DeadlineClock, pollUntilSettled } from '@agent-device/host-kit/retry'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { EnvMap } from '@agent-device/kernel/source-value'; -import type { RevylClient } from './revyl-client.ts'; +import { REVYL_OUTCOME_REASONS, type RevylClient } from './revyl-client.ts'; import type { RevylWorkerActionResponse } from './revyl-types.ts'; +/** Why a Revyl app deployment is refused. */ +const REVYL_DEPLOYMENT_REASONS = { + // Revyl installs an iOS simulator build or an Android .apk, and the build is neither. + unsupportedAppArtifact: { reason: 'unsupported_app_artifact' }, +} as const satisfies ReasonTable<'revyl provider'>; + /** * The whole install's budget: packing, upload, and Revyl's install. It stays inside the daemon's * share of the install command's 480 s envelope, so the plugin reports its own timeout before the @@ -50,7 +56,7 @@ export async function deployRevylApp( const scoped = AbortSignal.any([signal, budget]); const timedOut = (cause?: unknown) => installStopped( - 'provider-unconfirmed', + REVYL_OUTCOME_REASONS.unconfirmed.reason, `Revyl did not finish the install within ${budgetMs / 1000} s.`, cause, ); @@ -96,7 +102,14 @@ async function uploadAndInstall( } } -function installStopped(reason: string, message: string, cause: unknown): AppError { +/** + * Why an install stopped short of a confirmed result: the provider's own verdicts, or the caller's + * cancellation. `request_canceled` is the kernel's cancellation vocabulary, which no provider table + * re-declares, so it is named here as the one spelling this wrapper also takes. + */ +type RevylInstallStopReason = typeof REVYL_OUTCOME_REASONS.unconfirmed.reason | 'request_canceled'; + +function installStopped(reason: RevylInstallStopReason, message: string, cause: unknown): AppError { return new AppError( 'COMMAND_FAILED', message, @@ -148,13 +161,13 @@ function unsupportedBuild(platform: 'ios' | 'android', appPath: string): AppErro 'INVALID_ARGS', 'Revyl installs an iOS simulator build: a .app directory, or a .zip, .tar.gz, or .tgz of one.', { - reason: 'unsupported_app_artifact', + reason: REVYL_DEPLOYMENT_REASONS.unsupportedAppArtifact.reason, appPath, hint: 'Build for the iOS simulator; a device .ipa does not run on a simulator.', }, ) : new AppError('INVALID_ARGS', 'Revyl installs an Android build from an .apk file.', { - reason: 'unsupported_app_artifact', + reason: REVYL_DEPLOYMENT_REASONS.unsupportedAppArtifact.reason, appPath, hint: 'Pass the .apk the build produced.', }); @@ -179,7 +192,7 @@ async function installAndWait( const installId = accepted.install_id?.trim(); if (accepted.status !== 'accepted' || !installId) { throw new AppError('COMMAND_FAILED', 'Revyl did not accept the app install.', { - reason: 'provider-refused', + reason: REVYL_OUTCOME_REASONS.refused.reason, ...(accepted.status === undefined ? {} : { providerDetail: accepted.status }), }); } @@ -195,7 +208,7 @@ async function installAndWait( return requireInstalled(value.status, value.result ?? undefined); } throw new AppError('COMMAND_FAILED', `Revyl reported install status "${value.status}".`, { - reason: 'provider-refused', + reason: REVYL_OUTCOME_REASONS.refused.reason, installId, }); } @@ -212,7 +225,7 @@ function requireInstalled( 'COMMAND_FAILED', `Revyl could not install the app${error === undefined ? '' : `: ${error}`}`, { - reason: 'provider-refused', + reason: REVYL_OUTCOME_REASONS.refused.reason, installStatus: status, ...(error === undefined ? {} : { providerDetail: error }), }, diff --git a/packages/provider-revyl/src/interactor.ts b/packages/provider-revyl/src/interactor.ts index c4cf42c890..6e4085134a 100644 --- a/packages/provider-revyl/src/interactor.ts +++ b/packages/provider-revyl/src/interactor.ts @@ -29,11 +29,22 @@ import { AppError, discloseDispatch, discloseDispatchAfterSteps, + type ReasonTable, } from '@agent-device/kernel/errors'; import { setTimeout as sleep } from 'node:timers/promises'; import type { RevylSession } from './revyl-session.ts'; import { captureRevylSnapshot, createRevylSnapshotReader } from './snapshot.ts'; +/** Why a Revyl interaction cannot run or be trusted. */ +const REVYL_INTERACTOR_REASONS = { + // The session runs no app, so a close or setting that names one has nothing to act on. + appNotLaunched: { reason: 'provider-app-not-launched' }, + // The session reports no viewport, so a scroll distance or screenshot density has nothing to scale by. + viewportUnavailable: { reason: 'provider-viewport-unavailable' }, + // Revyl answered a worker action with a value outside the field's own range. + invalidResponse: { reason: 'provider-invalid-response' }, +} as const satisfies ReasonTable<'revyl provider'>; + /** Revyl's worker holds the touch this long when the caller names no hold. */ const DEFAULT_LONG_PRESS_DURATION_MS = 1_500; @@ -155,7 +166,7 @@ class RevylInteractor implements Interactor { 'UNSUPPORTED_OPERATION', `This Revyl session has not launched ${target}, so it has no app to end.`, { - reason: 'provider-app-not-launched', + reason: REVYL_INTERACTOR_REASONS.appNotLaunched.reason, command: 'close', requestedApp: target, hint: 'Close without an app name to end the app this session runs, or open the app first.', @@ -283,7 +294,10 @@ class RevylInteractor implements Interactor { throw new AppError( 'COMMAND_FAILED', 'Revyl reported no screen size for this session, so the scroll distance cannot be planned.', - { reason: 'provider-viewport-unavailable', runId: this.session.runId }, + { + reason: REVYL_INTERACTOR_REASONS.viewportUnavailable.reason, + runId: this.session.runId, + }, ); } const plan = buildScrollGesturePlan({ @@ -451,7 +465,7 @@ class RevylInteractor implements Interactor { const current = await this.workerAction('appearance'); if (current.appearance !== 'light' && current.appearance !== 'dark') { throw new AppError('COMMAND_FAILED', 'Revyl did not report the current appearance.', { - reason: 'provider-invalid-response', + reason: REVYL_INTERACTOR_REASONS.invalidResponse.reason, runId: this.session.runId, }); } @@ -518,7 +532,7 @@ class RevylInteractor implements Interactor { const app = appId?.trim() || this.session.launchedApp.bundleId; if (app) return app; throw new AppError('INVALID_ARGS', `The ${setting} setting needs an app.`, { - reason: 'provider-app-not-launched', + reason: REVYL_INTERACTOR_REASONS.appNotLaunched.reason, command: 'settings', hint: 'Pass --app, or open the app first.', }); @@ -569,7 +583,7 @@ async function normalizeRevylIosDensity( throw new AppError( 'COMMAND_FAILED', 'Revyl reported no screen size for this session, so the screenshot density cannot be known.', - { reason: 'provider-viewport-unavailable' }, + { reason: REVYL_INTERACTOR_REASONS.viewportUnavailable.reason }, ); } const [{ readPngSize }, { resizePngFile }, { computeDensityScaledScreenshotSize }] = diff --git a/packages/provider-revyl/src/platform-runtime.ts b/packages/provider-revyl/src/platform-runtime.ts index ae918f9110..48349248b9 100644 --- a/packages/provider-revyl/src/platform-runtime.ts +++ b/packages/provider-revyl/src/platform-runtime.ts @@ -2,6 +2,7 @@ import { AppError } from '@agent-device/kernel/errors'; import { REVYL_PROVIDER, isSupportedRevylRuntimeDevice } from './device.ts'; import { providerRuntimeOwner, + PROVIDER_RUNTIME_REASONS, sameRuntimeOwner, type DeviceBinding, type RuntimeFacts, @@ -69,7 +70,7 @@ export function createRevylPlatformRuntimeOwner( throw new AppError( 'UNSUPPORTED_OPERATION', 'Revyl provider session is no longer live for the selected device', - { reason: 'provider-session-unavailable' }, + { reason: PROVIDER_RUNTIME_REASONS.sessionUnavailable.reason }, ); } return bindRevylRuntime(options, owner, request.device, request.scope.signal, live); @@ -152,7 +153,7 @@ function bindRevylDeployment( const live = options.getDeploymentSession(device); if (live) return live; throw new AppError('UNSUPPORTED_OPERATION', 'Revyl provider session is no longer live.', { - reason: 'provider-session-unavailable', + reason: PROVIDER_RUNTIME_REASONS.sessionUnavailable.reason, }); }; return { diff --git a/packages/provider-revyl/src/revyl-client.ts b/packages/provider-revyl/src/revyl-client.ts index 4404bb6181..ee348c1475 100644 --- a/packages/provider-revyl/src/revyl-client.ts +++ b/packages/provider-revyl/src/revyl-client.ts @@ -1,4 +1,4 @@ -import { AppError, type AppErrorCode } from '@agent-device/kernel/errors'; +import { AppError, type AppErrorCode, type ReasonTable } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import fs from 'node:fs'; import net from 'node:net'; @@ -45,6 +45,44 @@ export type RevylClientOptions = Readonly<{ fetch?: typeof fetch; }>; +/** + * Request outcomes the Revyl client, deployment and snapshot code all publish. With + * `REVYL_HTTP_REASONS` below, these rows are the provider-owned reasons this client publishes; + * `request_canceled` is shared cancellation vocabulary. + * `missing_provider_credentials` sits with the credential reader instead, which the plugin's eager + * entry loads before this module exists. + */ +export const REVYL_OUTCOME_REASONS = { + // Revyl refused the request or the action it carries. + refused: { reason: 'provider-refused' }, + // Revyl answered in a way agent-device cannot read, such as a body that is not JSON. + responseInvalid: { reason: 'provider-response-invalid' }, + // agent-device could not confirm the outcome of the request; check the session before retrying. + unconfirmed: { reason: 'provider-unconfirmed' }, +} as const satisfies ReasonTable<'revyl provider'>; + +const REVYL_HTTP_REASONS = { + // Revyl never answered the request, or the connection to its backend failed. + unreachable: { reason: 'provider-unreachable' }, + // Revyl rejected the credentials on the request. + authRejected: { reason: 'provider-auth-rejected' }, + // The session the request addresses no longer exists at Revyl. + sessionGone: { reason: 'provider-session-gone' }, + // Revyl rejected the request because its state conflicts with what it asks for. + conflict: { reason: 'provider-conflict' }, + // Revyl refused a request it never routed, with a status that settles the failure. + requestFailed: { reason: 'provider-request-failed' }, + // Revyl gave no response before the request's own deadline passed. + requestTimeout: { reason: 'request_timeout' }, + // `REVYL_API_URL` is not an origin Revyl's API can be addressed at. + invalidProviderUrl: { reason: 'invalid_provider_url' }, +} as const satisfies ReasonTable<'revyl provider'>; + +/** The `details.reason` spellings the Revyl client publishes: its HTTP rows and the shared outcomes. */ +type RevylProviderReason = + | (typeof REVYL_HTTP_REASONS)[keyof typeof REVYL_HTTP_REASONS]['reason'] + | (typeof REVYL_OUTCOME_REASONS)[keyof typeof REVYL_OUTCOME_REASONS]['reason']; + /** * Which half of the API one request belongs to, which is what a 404 or 410 means. A route that * addresses one session or run reports a session Revyl no longer has; a route that starts or @@ -274,7 +312,7 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { throw new AppError( 'COMMAND_FAILED', 'Revyl storage did not accept the app upload.', - { reason: 'provider-unreachable' }, + { reason: REVYL_HTTP_REASONS.unreachable.reason }, error, ); } @@ -282,7 +320,10 @@ export function createRevylClient(options: RevylClientOptions): RevylClient { throw new AppError( 'COMMAND_FAILED', `Revyl storage refused the app upload with HTTP ${response.status}.`, - { reason: 'provider-refused', status: response.status }, + { + reason: REVYL_OUTCOME_REASONS.refused.reason, + status: response.status, + }, ); } }, @@ -341,7 +382,7 @@ async function sendOnce( return new AppError( 'COMMAND_FAILED', `Revyl did not answer ${request.method} ${request.path}.`, - { reason: 'provider-unreachable', path: request.path }, + { reason: REVYL_HTTP_REASONS.unreachable.reason, path: request.path }, error, ); } @@ -354,7 +395,10 @@ async function sendOnce( */ function isRetryable(request: RevylRequest, outcome: RevylResponse | Error): boolean { if (outcome instanceof Error) { - return outcome instanceof AppError && outcome.details?.reason === 'provider-unreachable'; + return ( + outcome instanceof AppError && + outcome.details?.reason === REVYL_HTTP_REASONS.unreachable.reason + ); } if (request.retryServerError === true && outcome.status === 500) return true; return revylFailure(request.route ?? 'general', outcome.status).retryable; @@ -376,7 +420,7 @@ function requestTimedOut(request: RevylRequest, cause: unknown): AppError { request.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS } ms.`, { - reason: 'request_timeout', + reason: REVYL_HTTP_REASONS.requestTimeout.reason, path: request.path, hint: 'Revyl may have carried out the request. Check the session before retrying it.', }, @@ -422,7 +466,7 @@ function assertLifecycleAccepted( 'COMMAND_FAILED', `Revyl did not stop the session${message === undefined ? '' : `: ${message}`}`, { - reason: 'provider-refused', + reason: REVYL_OUTCOME_REASONS.refused.reason, operation, ...(message === undefined ? {} : { providerDetail: message }), hint: 'The Revyl session may still be rented. End it from Revyl if it stays listed.', @@ -453,7 +497,10 @@ function assertWorkerActionSuccess( error === undefined ? '' : `: ${error}` }`, { - reason: response.execution_uncertain === true ? 'provider-unconfirmed' : 'provider-refused', + reason: + response.execution_uncertain === true + ? REVYL_OUTCOME_REASONS.unconfirmed.reason + : REVYL_OUTCOME_REASONS.refused.reason, path: request.path, ...(error === undefined ? {} : { providerDetail: error }), }, @@ -493,7 +540,7 @@ function parseJson(request: RevylRequest, response: RevylResponse): T { throw new AppError( 'COMMAND_FAILED', `Revyl returned a response to ${request.method} ${request.path} that is not JSON (HTTP ${response.status}).`, - { reason: 'provider-response-invalid', path: request.path }, + { reason: REVYL_OUTCOME_REASONS.responseInvalid.reason, path: request.path }, error, ); } @@ -506,7 +553,7 @@ function parseJson(request: RevylRequest, response: RevylResponse): T { */ type RevylStatusVerdict = Readonly<{ code: AppErrorCode; - reason: string; + reason: RevylProviderReason; /** Revyl left it unknown whether the request landed, which is what a hint has to say. */ uncertain: boolean; /** Replaying the request is safe and may succeed, which is what the retry budget is for. */ @@ -515,7 +562,7 @@ type RevylStatusVerdict = Readonly<{ const REVYL_REQUEST_FAILED: RevylStatusVerdict = { code: 'COMMAND_FAILED', - reason: 'provider-request-failed', + reason: REVYL_HTTP_REASONS.requestFailed.reason, uncertain: false, retryable: false, }; @@ -523,7 +570,7 @@ const REVYL_REQUEST_FAILED: RevylStatusVerdict = { /** A server error Revyl has no rule for: the request went in, the verdict did not come back. */ const REVYL_SERVER_ERROR: RevylStatusVerdict = { code: 'COMMAND_FAILED', - reason: 'provider-unconfirmed', + reason: REVYL_OUTCOME_REASONS.unconfirmed.reason, uncertain: true, retryable: false, }; @@ -533,48 +580,68 @@ const REVYL_STATUS_VERDICTS: Readonly> = { 400: REVYL_REQUEST_FAILED, 401: { code: 'UNAUTHORIZED', - reason: 'provider-auth-rejected', + reason: REVYL_HTTP_REASONS.authRejected.reason, uncertain: false, retryable: false, }, 403: { code: 'UNAUTHORIZED', - reason: 'provider-auth-rejected', + reason: REVYL_HTTP_REASONS.authRejected.reason, uncertain: false, retryable: false, }, 404: { code: 'SESSION_NOT_FOUND', - reason: 'provider-session-gone', + reason: REVYL_HTTP_REASONS.sessionGone.reason, uncertain: false, retryable: false, }, 408: { code: 'COMMAND_FAILED', - reason: 'provider-unconfirmed', + reason: REVYL_OUTCOME_REASONS.unconfirmed.reason, uncertain: true, retryable: false, }, - 409: { code: 'COMMAND_FAILED', reason: 'provider-conflict', uncertain: false, retryable: false }, + 409: { + code: 'COMMAND_FAILED', + reason: REVYL_HTTP_REASONS.conflict.reason, + uncertain: false, + retryable: false, + }, 410: { code: 'SESSION_NOT_FOUND', - reason: 'provider-session-gone', + reason: REVYL_HTTP_REASONS.sessionGone.reason, uncertain: false, retryable: false, }, 500: { code: 'COMMAND_FAILED', - reason: 'provider-unconfirmed', + reason: REVYL_OUTCOME_REASONS.unconfirmed.reason, uncertain: true, retryable: false, }, - 502: { code: 'COMMAND_FAILED', reason: 'provider-unconfirmed', uncertain: true, retryable: true }, - 503: { code: 'COMMAND_FAILED', reason: 'provider-unconfirmed', uncertain: true, retryable: true }, - 504: { code: 'COMMAND_FAILED', reason: 'provider-unconfirmed', uncertain: true, retryable: true }, + 502: { + code: 'COMMAND_FAILED', + reason: REVYL_OUTCOME_REASONS.unconfirmed.reason, + uncertain: true, + retryable: true, + }, + 503: { + code: 'COMMAND_FAILED', + reason: REVYL_OUTCOME_REASONS.unconfirmed.reason, + uncertain: true, + retryable: true, + }, + 504: { + code: 'COMMAND_FAILED', + reason: REVYL_OUTCOME_REASONS.unconfirmed.reason, + uncertain: true, + retryable: true, + }, }; /** - * The verdict one status carries, read together with the route that answered. `session-gone` is only + * The verdict one status carries, read together with the route that answered. `sessionGone` is only * ever a session route's answer: a 404 from `start_device` or the credential check is a request the * backend did not route, not a session that ended, and reading it as one sends the user to run `open` * on a session they already have. @@ -582,7 +649,7 @@ const REVYL_STATUS_VERDICTS: Readonly> = { function revylFailure(route: RevylRoute, status: number): RevylStatusVerdict { const verdict = REVYL_STATUS_VERDICTS[status] ?? (status >= 500 ? REVYL_SERVER_ERROR : REVYL_REQUEST_FAILED); - if (verdict.reason === 'provider-session-gone' && route !== 'session') + if (verdict.reason === REVYL_HTTP_REASONS.sessionGone.reason && route !== 'session') return REVYL_REQUEST_FAILED; return verdict; } @@ -605,7 +672,9 @@ export function revylFailureRefusedTheRequest(error: unknown): boolean { * the same way. */ export function isRevylSessionGone(error: unknown): boolean { - return error instanceof AppError && error.details?.reason === 'provider-session-gone'; + return ( + error instanceof AppError && error.details?.reason === REVYL_HTTP_REASONS.sessionGone.reason + ); } /** The loopback ranges, the same set the daemon client trusts for a local daemon. */ @@ -629,7 +698,7 @@ export function resolveRevylBackendUrl(raw: string): string { url = new URL(raw); } catch { throw new AppError('INVALID_ARGS', 'REVYL_API_URL is not a valid URL.', { - reason: 'invalid_provider_url', + reason: REVYL_HTTP_REASONS.invalidProviderUrl.reason, }); } const loopback = isLoopbackHostname(url.hostname); @@ -637,14 +706,17 @@ export function resolveRevylBackendUrl(raw: string): string { throw new AppError( 'INVALID_ARGS', 'REVYL_API_URL must use HTTPS; plain HTTP is allowed only on loopback.', - { reason: 'invalid_provider_url', hint: 'Example: https://backend.revyl.ai' }, + { + reason: REVYL_HTTP_REASONS.invalidProviderUrl.reason, + hint: 'Example: https://backend.revyl.ai', + }, ); } if (url.username || url.password || url.search || url.hash) { throw new AppError( 'INVALID_ARGS', 'REVYL_API_URL must be an origin without credentials, query, or fragment.', - { reason: 'invalid_provider_url' }, + { reason: REVYL_HTTP_REASONS.invalidProviderUrl.reason }, ); } return url.origin; diff --git a/packages/provider-revyl/src/revyl-session.ts b/packages/provider-revyl/src/revyl-session.ts index c46a64d1b3..e8f09a7bf7 100644 --- a/packages/provider-revyl/src/revyl-session.ts +++ b/packages/provider-revyl/src/revyl-session.ts @@ -1,4 +1,4 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { setTimeout as sleep } from 'node:timers/promises'; import type { DeviceLease } from '@agent-device/contracts/device'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -16,6 +16,20 @@ import type { RevylWorkerHealth, } from './revyl-types.ts'; +/** Why a Revyl session could not start, be confirmed, or be cleaned up. */ +const REVYL_SESSION_REASONS = { + // Revyl started a session under an identity agent-device did not issue for the lease. + sessionIdentityMismatch: { reason: 'provider-session-identity-mismatch' }, + // Revyl refused to start the device and named why in its start answer. + startRefused: { reason: 'provider-start-refused' }, + // Revyl's worker connection ended in a state that never serves the device. + startFailed: { reason: 'provider-start-failed' }, + // Revyl never reported a ready device within the wait the caller could spend. + notReady: { reason: 'provider-not-ready' }, + // Revyl did not confirm it released the session, which stays rented and billed until it does. + cleanupPending: { reason: 'provider-cleanup-pending' }, +} as const satisfies ReasonTable<'revyl provider'>; + /** How long Revyl may take to assign a worker and connect the device before the start is given up on. */ const READY_TIMEOUT_MS = 240_000; /** @@ -148,7 +162,7 @@ export async function startRevylSession( 'COMMAND_FAILED', `Revyl started the device as session ${echoed} instead of ${sessionId}.`, { - reason: 'provider-session-identity-mismatch', + reason: REVYL_SESSION_REASONS.sessionIdentityMismatch.reason, runId, providerSessionId: echoed, hint: 'Retry the command; agent-device ends a Revyl session by the identity it issued.', @@ -166,7 +180,7 @@ export async function startRevylSession( 'COMMAND_FAILED', `Revyl did not start a ${input.platform} device: ${started.error ?? started.message ?? 'no workflow run was returned'}`, { - reason: 'provider-start-refused', + reason: REVYL_SESSION_REASONS.startRefused.reason, platform: input.platform, ...(started.trace_id === undefined ? {} : { traceId: started.trace_id }), }, @@ -267,7 +281,7 @@ export function revylCallerGaveUp( 'COMMAND_FAILED', `Revyl did not report a ready device within ${budgetMs} ms.`, { - reason: 'provider-not-ready', + reason: REVYL_SESSION_REASONS.notReady.reason, timeoutMs: budgetMs, providerSessionId, ...(budget.deadline === undefined ? {} : { deadline: budget.deadline }), @@ -305,7 +319,7 @@ export function revylCleanupPending( 'COMMAND_FAILED', `Revyl did not release session${one ? '' : 's'} ${ids}.`, { - reason: 'provider-cleanup-pending', + reason: REVYL_SESSION_REASONS.cleanupPending.reason, ...details, providerSessionIds: unconfirmed.map((stop) => stop.sessionId), causes: unconfirmed.map((stop) => stop.failure), @@ -431,7 +445,11 @@ async function untilRevylWorkerReady( ? '' : ` (${connection.message})` }`, - { reason: 'provider-start-failed', runId, status: connection.status }, + { + reason: REVYL_SESSION_REASONS.startFailed.reason, + runId, + status: connection.status, + }, ); } await sleepBefore(deadline, input.signal); diff --git a/packages/provider-revyl/src/runtime.ts b/packages/provider-revyl/src/runtime.ts index b154d1efdc..5875ab1312 100644 --- a/packages/provider-revyl/src/runtime.ts +++ b/packages/provider-revyl/src/runtime.ts @@ -14,7 +14,7 @@ import type { import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { matchesPlatformSelector } from '@agent-device/kernel/device'; -import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; import { parseRevylDeviceId, platformForRevylLeaseBackend, @@ -46,6 +46,14 @@ import { resolveRevylRuntimeInstance } from './runtime-instance.ts'; import type { RevylStartRequest } from './session-allocation.ts'; import type { RevylDeploymentSession } from './deployment.ts'; +/** Why the Revyl runtime refuses a lease request. */ +const REVYL_RUNTIME_REASONS = { + // The lease is being released, so it cannot serve another allocation. + leaseReleasing: { reason: 'provider-lease-releasing' }, + // The provider runtime is ending the sessions it holds, so it takes no new work. + runtimeShuttingDown: { reason: 'runtime-shutting-down' }, +} as const satisfies ReasonTable<'revyl provider'>; + /** What one lease's start asks Revyl for, with the platform the lease was admitted for. */ type RevylLeaseRequest = RevylStartRequest & Readonly<{ platform: RevylPlatform }>; @@ -268,7 +276,7 @@ function createRevylLeaseDriver( shuttingDown: (lease) => shuttingDownDuring(lease.leaseId, 'allocate'), releasing: (lease) => new AppError('COMMAND_FAILED', `Revyl lease ${lease.leaseId} is being released.`, { - reason: 'provider-lease-releasing', + reason: REVYL_RUNTIME_REASONS.leaseReleasing.reason, leaseId: lease.leaseId, hint: 'Run open again; it allocates a new lease and rents a fresh device.', }), @@ -340,7 +348,7 @@ function requireRevylLease(lease: DeviceLease, operation: 'recover' | 'release') function shuttingDownDuring(leaseId: string, operation: string): AppError { return new AppError('COMMAND_FAILED', `The Revyl runtime is shutting down.`, { - reason: 'runtime-shutting-down', + reason: REVYL_RUNTIME_REASONS.runtimeShuttingDown.reason, operation, leaseId, hint: 'Retry the command; the daemon is ending the sessions it holds.', diff --git a/packages/provider-revyl/src/session-allocation.ts b/packages/provider-revyl/src/session-allocation.ts index b5c76af7a1..a3a7e5c12b 100644 --- a/packages/provider-revyl/src/session-allocation.ts +++ b/packages/provider-revyl/src/session-allocation.ts @@ -1,8 +1,14 @@ import type { LeaseLifecycleContext } from '@agent-device/contracts/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { rejectRefusedProviderProfileFields } from '@agent-device/contracts/provider-profile-fields'; import { REVYL_PROFILE_FIELDS } from './profile-fields.ts'; +/** Why a Revyl lease allocation is refused. */ +const REVYL_ALLOCATION_REASONS = { + // An allocation joins a lease whose device was started for another app or device. + leaseRequestMismatch: { reason: 'provider-lease-request-mismatch' }, +} as const satisfies ReasonTable<'revyl provider'>; + /** * Refuses the connect flags Revyl has no field for, so a flag that would be ignored is reported * instead of dropped. Runs before a lease is reused as well as before a device is started: a repeat @@ -78,7 +84,7 @@ export function requireSameRevylStartRequest( 'INVALID_ARGS', `Revyl lease ${leaseId} already has a device started for a different ${differing.join(', ')}.`, { - reason: 'provider-lease-request-mismatch', + reason: REVYL_ALLOCATION_REASONS.leaseRequestMismatch.reason, leaseId, fields: differing, hint: 'Disconnect and connect again to rent a device for the new app or device selection.', diff --git a/packages/provider-revyl/src/snapshot.ts b/packages/provider-revyl/src/snapshot.ts index 1a746f8a0c..0ce625c8e3 100644 --- a/packages/provider-revyl/src/snapshot.ts +++ b/packages/provider-revyl/src/snapshot.ts @@ -6,6 +6,7 @@ import { acquireProviderKeyboard } from '@agent-device/contracts/tap-keyboard-oc import type { IosTreeNode } from '@agent-device/capture-kit/ios-ax-tree'; import type { RevylPlatform } from './device.ts'; import type { RevylSession } from './revyl-session.ts'; +import { REVYL_OUTCOME_REASONS } from './revyl-client.ts'; /** Reads one Revyl worker's accessibility tree and the box its actions measure. */ export type RevylSnapshotReader = Readonly<{ @@ -102,7 +103,7 @@ function invalidIosHierarchy(cause?: unknown): AppError { return new AppError( 'COMMAND_FAILED', 'Revyl returned an iOS hierarchy that is not an accessibility node tree.', - { reason: 'provider-response-invalid' }, + { reason: REVYL_OUTCOME_REASONS.responseInvalid.reason }, cause, ); } diff --git a/packages/provider-webdriver/src/runtime-session.ts b/packages/provider-webdriver/src/runtime-session.ts index 26c92db152..c0a3afd364 100644 --- a/packages/provider-webdriver/src/runtime-session.ts +++ b/packages/provider-webdriver/src/runtime-session.ts @@ -4,7 +4,7 @@ import type { } from '@agent-device/contracts/observability'; import type { DeviceLease, LeaseLifecycleContext } from '@agent-device/contracts/device'; import { deviceFieldsFromPublicPlatform, type DeviceInfo } from '@agent-device/kernel/device'; -import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { AppError, errorMessage, type ReasonTable } from '@agent-device/kernel/errors'; import { unavailableCloudArtifactsResult } from './artifact-results.ts'; import { createCloudWebDriverCapabilities, @@ -23,6 +23,20 @@ import type { } from './runtime.ts'; import type { Interactor } from '@agent-device/contracts/interactor-types'; +/** Why a provider WebDriver session could not be allocated or cleaned up. */ +const WEBDRIVER_SESSION_REASONS = { + // The provider did not create the WebDriver session within the session-creation budget. + sessionCreateTimeout: { reason: 'provider_session_create_timeout' }, + // Releasing the lease interrupted the allocation; `details.cleanup` reports how cleanup ended. + sessionReleasedDuringAllocation: { reason: 'provider_session_released_during_allocation' }, + // The WebDriver runtime could not finish the allocation: shutdown was in progress or done. + sessionShutdownDuringAllocation: { reason: 'provider_session_shutdown_during_allocation' }, + // The lease is still releasing its previous session, so a new allocation gets no session. + sessionReleaseInProgress: { reason: 'provider_session_release_in_progress' }, + // Shutdown could not confirm that all WebDriver sessions and provider resources were cleaned up. + sessionCleanupIncomplete: { reason: 'provider_session_cleanup_incomplete' }, +} as const satisfies ReasonTable<'webdriver provider'>; + export type WebDriverProviderSession = Readonly<{ lease: DeviceLease; device: DeviceInfo; @@ -653,7 +667,7 @@ function sessionCreateTimeoutError( 'COMMAND_FAILED', `${provider} did not create the WebDriver session within ${String(timeoutMs)}ms.`, { - reason: 'provider_session_create_timeout', + reason: WEBDRIVER_SESSION_REASONS.sessionCreateTimeout.reason, provider, leaseId: lease.leaseId, runId: lease.runId, @@ -688,8 +702,8 @@ function refusalForTeardown( { reason: by === 'release' - ? 'provider_session_released_during_allocation' - : 'provider_session_shutdown_during_allocation', + ? WEBDRIVER_SESSION_REASONS.sessionReleasedDuringAllocation.reason + : WEBDRIVER_SESSION_REASONS.sessionShutdownDuringAllocation.reason, provider, leaseId: lease.leaseId, runId: lease.runId, @@ -730,7 +744,7 @@ function refusalForTeardownInProgress( 'DEVICE_IN_USE', `${provider} is releasing lease ${lease.leaseId} and allocated no WebDriver session for it.`, { - reason: 'provider_session_release_in_progress', + reason: WEBDRIVER_SESSION_REASONS.sessionReleaseInProgress.reason, provider, leaseId: lease.leaseId, runId: lease.runId, @@ -752,7 +766,7 @@ function allocationRefusedAfterShutdown(provider: string, lease: DeviceLease): A 'COMMAND_FAILED', `${provider} is shut down and created no WebDriver session for lease ${lease.leaseId}.`, { - reason: 'provider_session_shutdown_during_allocation', + reason: WEBDRIVER_SESSION_REASONS.sessionShutdownDuringAllocation.reason, provider, leaseId: lease.leaseId, runId: lease.runId, @@ -797,7 +811,7 @@ function shutdownLeftSessionsRunning( 'COMMAND_FAILED', `${provider} left ${String(outcomes.length)} WebDriver session(s) running after shutdown: ${providerSessionIds.join(', ')}.`, { - reason: 'provider_session_cleanup_incomplete', + reason: WEBDRIVER_SESSION_REASONS.sessionCleanupIncomplete.reason, provider, providerSessionIds, cleanup: 'uncertain', diff --git a/packages/provider-webdriver/src/webdriver-interactor.ts b/packages/provider-webdriver/src/webdriver-interactor.ts index 966234c37e..e6df251b47 100644 --- a/packages/provider-webdriver/src/webdriver-interactor.ts +++ b/packages/provider-webdriver/src/webdriver-interactor.ts @@ -17,7 +17,7 @@ import { import type { TvRemoteButton } from '@agent-device/contracts/tv-remote'; import type { SettingOptions } from '@agent-device/contracts/settings'; import { snapshotViewportSizeFrom } from '@agent-device/kernel/rect'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { capabilitySupported, unsupportedCapabilityMessage, @@ -33,6 +33,12 @@ import { } from './webdriver-scroll-frame.ts'; import { setWebDriverOrientation } from './webdriver-orientation.ts'; +/** Why WebDriver text entry refused. */ +const WEBDRIVER_TEXT_ENTRY_REASONS = { + // `fill` has no focused element reference to clear before it types the replacement text. + textEntryClearTargetUnavailable: { reason: 'text_entry_clear_target_unavailable' }, +} as const satisfies ReasonTable<'webdriver provider'>; + /** * How long a tapped field gets to take text entry focus before `fill` gives up. * Mirrors the Apple runner's `TextEntryTiming.readinessTimeout` @@ -80,7 +86,7 @@ function textEntryClearTargetUnavailableError(): AppError { return new AppError( 'UNSUPPORTED_OPERATION', 'fill requires a focused element reference to clear and replace the field', - { reason: 'text_entry_clear_target_unavailable' }, + { reason: WEBDRIVER_TEXT_ENTRY_REASONS.textEntryClearTargetUnavailable.reason }, ); } diff --git a/packages/provider-webdriver/src/webdriver-transport.ts b/packages/provider-webdriver/src/webdriver-transport.ts index 404bc9df14..717aa9e355 100644 --- a/packages/provider-webdriver/src/webdriver-transport.ts +++ b/packages/provider-webdriver/src/webdriver-transport.ts @@ -1,8 +1,20 @@ import { setTimeout as sleep } from 'node:timers/promises'; -import { AppError, type DispatchDisclosure } from '@agent-device/kernel/errors'; +import { AppError, type DispatchDisclosure, type ReasonTable } from '@agent-device/kernel/errors'; import { agentDeviceRequestHeaders } from './request-headers.ts'; import { basicAuthHeader, trimLeadingSlash, withTrailingSlash } from './webdriver-utils.ts'; +/** Why a WebDriver request failed at the transport. */ +const WEBDRIVER_TRANSPORT_REASONS = { + // The transport stopped waiting on a WebDriver request the driver may still be carrying out. + requestTimeout: { reason: 'webdriver_request_timeout' }, + // The request never reached the driver: the connection was refused or the host is unreachable. + connectRefused: { reason: 'webdriver_connect_refused' }, + // The connection to the driver failed after the request may have reached it. + requestInterrupted: { reason: 'webdriver_request_interrupted' }, + // The driver answered that it does not implement the route. + routeUnsupported: { reason: 'webdriver_route_unsupported' }, +} as const satisfies ReasonTable<'webdriver provider'>; + export type WebDriverAuth = { username: string; accessKey: string; @@ -21,12 +33,12 @@ export type WebDriverRequestPolicy = { sessionCreateTimeoutMs?: number; }; -/** Machine-readable `details.reason` of a request the transport gave up waiting on. */ -const WEBDRIVER_REQUEST_TIMEOUT_REASON = 'webdriver_request_timeout'; - /** A request the transport stopped waiting on; the server may still complete it. */ export function isWebDriverRequestTimeout(error: unknown): error is AppError { - return error instanceof AppError && error.details?.reason === WEBDRIVER_REQUEST_TIMEOUT_REASON; + return ( + error instanceof AppError && + error.details?.reason === WEBDRIVER_TRANSPORT_REASONS.requestTimeout.reason + ); } /** @@ -38,15 +50,6 @@ function dispatchDisclosure(dispatched: DispatchDisclosure): { dispatched: Dispa return { dispatched }; } -/** Machine-readable `details.reason` of a request that never reached the driver. */ -const WEBDRIVER_CONNECT_REFUSED_REASON = 'webdriver_connect_refused'; - -/** - * Machine-readable `details.reason` of a request whose connection failed after it may have - * reached the driver: a socket reset, or a response body cut off after the status line. - */ -const WEBDRIVER_REQUEST_INTERRUPTED_REASON = 'webdriver_request_interrupted'; - /** * Socket error codes that prove the connection was never established, so no byte of the request * reached the driver. @@ -65,7 +68,10 @@ const ERROR_CAUSE_DEPTH_LIMIT = 4; /** A request whose connection failed before it was established (refused or unreachable host). */ export function isWebDriverConnectRefused(error: unknown): error is AppError { - return error instanceof AppError && error.details?.reason === WEBDRIVER_CONNECT_REFUSED_REASON; + return ( + error instanceof AppError && + error.details?.reason === WEBDRIVER_TRANSPORT_REASONS.connectRefused.reason + ); } export type WebDriverRequestOverrides = { @@ -217,7 +223,7 @@ export class WebDriverTransport { const payload = parsed.json; const error = webdriverError(status, payload); if (isWebDriverRouteUnsupported(error)) { - emitWebDriverDiagnostic(WEBDRIVER_ROUTE_UNSUPPORTED_REASON, { + emitWebDriverDiagnostic(WEBDRIVER_TRANSPORT_REASONS.routeUnsupported.reason, { method, path, status, @@ -398,9 +404,6 @@ function nonJsonAnswerError(status: number, text: string): AppError { }); } -/** Machine-readable `details.reason` of a driver answer that it does not implement the route. */ -const WEBDRIVER_ROUTE_UNSUPPORTED_REASON = 'webdriver_route_unsupported'; - /** * The driver answered with the W3C `invalid session id` error: the session it was asked about does * not exist (never did, was deleted, or timed out on the driver). @@ -418,10 +421,13 @@ export function isWebDriverInvalidSession(error: unknown): error is AppError { * the route. A command that tried every route it has and was refused by each carries the same. */ export function unsupportedRouteRefusal(): { - reason: typeof WEBDRIVER_ROUTE_UNSUPPORTED_REASON; + reason: typeof WEBDRIVER_TRANSPORT_REASONS.routeUnsupported.reason; dispatched: DispatchDisclosure; } { - return { reason: WEBDRIVER_ROUTE_UNSUPPORTED_REASON, ...dispatchDisclosure('no') }; + return { + reason: WEBDRIVER_TRANSPORT_REASONS.routeUnsupported.reason, + ...dispatchDisclosure('no'), + }; } /** W3C `error` codes a driver answers with when it does not implement the route. */ @@ -472,7 +478,10 @@ export function emitWebDriverDiagnostic(phase: string, data: Record; + /** Best-effort release after a failure; a failed release rides along as `cleanupError`, never masks the primary. */ export async function releaseOnFailure( primaryError: unknown, @@ -137,7 +147,9 @@ export async function postHubAppUpload( 'COMMAND_FAILED', `${options.service} app upload failed.`, { - reason: timedOut ? 'hub_app_upload_timeout' : 'hub_app_upload_transport_failed', + reason: timedOut + ? WEBDRIVER_APP_UPLOAD_REASONS.hubAppUploadTimeout.reason + : WEBDRIVER_APP_UPLOAD_REASONS.hubAppUploadTransportFailed.reason, ...(timedOut ? { timeoutMs: HUB_APP_UPLOAD_TIMEOUT_MS } : {}), hint: `Check network access to the ${options.service} upload API, then retry.`, }, @@ -217,7 +229,10 @@ function requireAppCwd(options: { service: string; app: string; cwd?: string }): throw new AppError( 'INVALID_ARGS', `${options.service} --provider-app ${options.app} is a relative path and the request names no working directory; pass an absolute path.`, - { providerApp: options.app, reason: 'provider_app_cwd_missing' }, + { + providerApp: options.app, + reason: WEBDRIVER_APP_UPLOAD_REASONS.providerAppCwdMissing.reason, + }, ); } diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 3fe47ed2a4..3f5a58e456 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -291,11 +291,25 @@ These reasons can come from more than one command. | `LEASE_NOT_FOUND` | The lease that the request names is not active. | | `LEASE_SCOPE_MISMATCH` | The lease does not match the tenant, run, backend, provider, device, or client of the request. | | `LEASE_SCOPE_REQUIRED` | The lease was allocated with an owner scope that the request does not repeat. | +| `provider-instance-ended` | The device instance behind the lease ended outside the daemon, which ends the lease with it. | | `LEASE_ID_IN_USE` | The requested lease id already names a lease that this daemon issued. | | `LEASE_CAPACITY_EXCEEDED` | Every iOS simulator lease slot is taken; retry after another lease is released. | | `LEASE_SESSION_MISMATCH` | The lease scope of the request differs from the lease of its session; `details.field` names the field. | | `LEASE_LEDGER_OVERWRITE` | The CLI already tracks an allocated lease and must release or transfer it before it allocates another. | +### Limrun provider + +| Reason | Meaning | +| --- | --- | +| `limrun_adb_tunnel_cleaned_up` | The ADB tunnel of this lease was already cleaned up, so nothing can be typed over it. | +| `limrun_instance_unreachable` | The instance stopped answering, so its app state cannot be read. | +| `limrun_instance_delete_unconfirmed` | A release could not confirm Limrun deleted the instance, so it may still be billed. | +| `limrun_lease_released_mid_allocation` | The lease was released while its instance was still being prepared for the allocation. | +| `limrun_lease_not_live` | The lease holds no live session, so the command that addresses it has nothing to act on. | +| `limrun_runtime_shut_down` | This runtime is shut down, so it refuses to allocate a lease into it. | +| `limrun_app_sync_retired` | The app-sync session of this lease has ended, so no further sync runs on it. | +| `limrun_app_sync_failed` | App sync or local cache maintenance failed; check the device for the app before retrying. | + ### Macos helper | Reason | Meaning | @@ -328,6 +342,12 @@ These reasons can come from more than one command. | `exit-timeout` | SIGKILL was sent and nothing proved the process exited within the budget it was given. | | `identity-unverified` | Nothing confirmed the pid names the recorded process, so signalling it was refused. | +### Provider runtime + +| Reason | Meaning | +| --- | --- | +| `provider-session-unavailable` | The provider's session for the device ended, so the runtime has nothing left to serve. | + ### Remote connection | Reason | Meaning | @@ -359,6 +379,36 @@ These reasons can come from more than one command. | --- | --- | | `duplicate_request_id` | A request arrived with an id another request is still in flight under. | +### Revyl provider + +| Reason | Meaning | +| --- | --- | +| `invalid_provider_app` | Revyl installs the app from a URL, so `--provider-app` cannot name a local file. | +| `unsupported_platform` | Revyl rents an iOS simulator or an Android emulator, and the request names neither. | +| `missing_provider_credentials` | No Revyl API key is set, so the provider cannot authenticate the request. | +| `unsupported_app_artifact` | Revyl installs an iOS simulator build or an Android .apk, and the build is neither. | +| `provider-app-not-launched` | The session runs no app, so a close or setting that names one has nothing to act on. | +| `provider-viewport-unavailable` | The session reports no viewport, so a scroll distance or screenshot density has nothing to scale by. | +| `provider-invalid-response` | Revyl answered a worker action with a value outside the field's own range. | +| `provider-refused` | Revyl refused the request or the action it carries. | +| `provider-response-invalid` | Revyl answered in a way agent-device cannot read, such as a body that is not JSON. | +| `provider-unconfirmed` | agent-device could not confirm the outcome of the request; check the session before retrying. | +| `provider-unreachable` | Revyl never answered the request, or the connection to its backend failed. | +| `provider-auth-rejected` | Revyl rejected the credentials on the request. | +| `provider-session-gone` | The session the request addresses no longer exists at Revyl. | +| `provider-conflict` | Revyl rejected the request because its state conflicts with what it asks for. | +| `provider-request-failed` | Revyl refused a request it never routed, with a status that settles the failure. | +| `request_timeout` | Revyl gave no response before the request's own deadline passed. | +| `invalid_provider_url` | `REVYL_API_URL` is not an origin Revyl's API can be addressed at. | +| `provider-session-identity-mismatch` | Revyl started a session under an identity agent-device did not issue for the lease. | +| `provider-start-refused` | Revyl refused to start the device and named why in its start answer. | +| `provider-start-failed` | Revyl's worker connection ended in a state that never serves the device. | +| `provider-not-ready` | Revyl never reported a ready device within the wait the caller could spend. | +| `provider-cleanup-pending` | Revyl did not confirm it released the session, which stays rented and billed until it does. | +| `provider-lease-releasing` | The lease is being released, so it cannot serve another allocation. | +| `runtime-shutting-down` | The provider runtime is ending the sessions it holds, so it takes no new work. | +| `provider-lease-request-mismatch` | An allocation joins a lease whose device was started for another app or device. | + ### Script publication | Reason | Meaning | @@ -389,3 +439,21 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `web_session_name_invalid` | The session name is longer than the backend key allows or holds a character it rejects. | + +### Webdriver provider + +| Reason | Meaning | +| --- | --- | +| `provider_session_create_timeout` | The provider did not create the WebDriver session within the session-creation budget. | +| `provider_session_released_during_allocation` | Releasing the lease interrupted the allocation; `details.cleanup` reports how cleanup ended. | +| `provider_session_shutdown_during_allocation` | The WebDriver runtime could not finish the allocation: shutdown was in progress or done. | +| `provider_session_release_in_progress` | The lease is still releasing its previous session, so a new allocation gets no session. | +| `provider_session_cleanup_incomplete` | Shutdown could not confirm that all WebDriver sessions and provider resources were cleaned up. | +| `text_entry_clear_target_unavailable` | `fill` has no focused element reference to clear before it types the replacement text. | +| `webdriver_request_timeout` | The transport stopped waiting on a WebDriver request the driver may still be carrying out. | +| `webdriver_connect_refused` | The request never reached the driver: the connection was refused or the host is unreachable. | +| `webdriver_request_interrupted` | The connection to the driver failed after the request may have reached it. | +| `webdriver_route_unsupported` | The driver answered that it does not implement the route. | +| `hub_app_upload_timeout` | The app upload to the provider's storage did not answer within its own deadline. | +| `hub_app_upload_transport_failed` | The app upload to the provider's storage never completed its transport. | +| `provider_app_cwd_missing` | `--provider-app` is a relative path and the request names no working directory to resolve it in. |