Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions packages/contracts/src/lease-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'>;

/**
Expand Down Expand Up @@ -544,17 +546,14 @@ 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 (
typeof error === 'object' &&
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
);
}

Expand Down
12 changes: 11 additions & 1 deletion packages/contracts/src/platform-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
Expand Down
10 changes: 8 additions & 2 deletions packages/provider-limrun/src/android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<ReturnType<LimrunAndroidClient['startAdbTunnel']>>;

type LimrunAndroidAdbSession = {
Expand Down Expand Up @@ -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.`,
Expand Down
3 changes: 2 additions & 1 deletion packages/provider-limrun/src/app-log-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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(
Expand Down
10 changes: 8 additions & 2 deletions packages/provider-limrun/src/app-state-read.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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,
Expand Down
14 changes: 11 additions & 3 deletions packages/provider-limrun/src/lease-release.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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,
Expand Down Expand Up @@ -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 }) }),
Expand Down Expand Up @@ -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 }),
Expand Down
18 changes: 13 additions & 5 deletions packages/provider-limrun/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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.',
},
);
Expand Down
14 changes: 11 additions & 3 deletions packages/provider-limrun/src/sync-cache.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -17,7 +25,7 @@ export class LimrunSyncCache {
): Promise<Value> {
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 () => {
Expand All @@ -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,
},
Expand Down
14 changes: 11 additions & 3 deletions packages/provider-revyl/src/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof createRevylConnection>;

Expand Down Expand Up @@ -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.`,
},
);
Expand Down Expand Up @@ -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,
});
}

Expand Down
10 changes: 8 additions & 2 deletions packages/provider-revyl/src/credentials.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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],
});
Expand Down
Loading
Loading