diff --git a/packages/plugins/src/registry.ts b/packages/plugins/src/registry.ts index a83201326b..77ce05ea05 100644 --- a/packages/plugins/src/registry.ts +++ b/packages/plugins/src/registry.ts @@ -400,7 +400,12 @@ async function cleanUpReplaySlot(slot: Slot): Promise { ]; } -function withConnectionHost( +/** + * A plugin's connection with the host it declares added to each context. Exported for the composing + * root: a built-in provider wires its plugin's callbacks to a CLI call through the same helper the + * registry uses, so both answer `connect` identically. + */ +export function withConnectionHost( connection: PluginConnection, hostOptions: Record | undefined, ): RegisteredConnection { diff --git a/packages/provider-limrun/package.json b/packages/provider-limrun/package.json index 6ce474cabb..94706da51d 100644 --- a/packages/provider-limrun/package.json +++ b/packages/provider-limrun/package.json @@ -8,12 +8,17 @@ "@agent-device/capture-kit": "workspace:*", "@agent-device/contracts": "workspace:*", "@agent-device/kernel": "workspace:*", - "@agent-device/platform-android": "workspace:*" + "@agent-device/platform-android": "workspace:*", + "@agent-device/plugins": "workspace:*" }, "exports": { ".": { "types": "./src/index.ts", "default": "./src/index.ts" + }, + "./internal": { + "types": "./src/internal.ts", + "default": "./src/internal.ts" } }, "devDependencies": { diff --git a/packages/provider-limrun/src/connection.test.ts b/packages/provider-limrun/src/connection.test.ts new file mode 100644 index 0000000000..d64ced10cf --- /dev/null +++ b/packages/provider-limrun/src/connection.test.ts @@ -0,0 +1,284 @@ +import assert from 'node:assert/strict'; +import { afterEach, test, vi } from 'vitest'; +import type { PluginConnectionContext } from '@agent-device/plugins/contract'; +import type { ProviderPluginHost } from '@agent-device/plugins/host'; +import { AppError } from '@agent-device/kernel/errors'; +import { createLimrunConnection } from './connection.ts'; +import { LIMRUN_CONNECTION_CAPABILITIES } from './device.ts'; + +// `verify` reaches the Limrun SDK when it runs. Both routes in are stubbed so a case reads which +// one the selected platform takes, and no request leaves the process. +const limrunSdk = vi.hoisted(() => { + const clients: Array> = []; + const attached: Array> = []; + return { + clients, + attached, + androidList: vi.fn(async () => ({ getPaginatedItems: () => [] })), + iosList: vi.fn(async () => ({ getPaginatedItems: () => [] })), + connectAttached: vi.fn(async (options: Record) => { + attached.push(options); + return { disconnect: () => undefined }; + }), + }; +}); + +vi.mock('@limrun/api', () => ({ + default: class MockLimrun { + readonly androidInstances = { list: limrunSdk.androidList }; + readonly iosInstances = { list: limrunSdk.iosList }; + + constructor(options: Record) { + limrunSdk.clients.push(options); + } + }, +})); + +vi.mock('@limrun/api/ios-client', () => ({ createInstanceClient: limrunSdk.connectAttached })); +vi.mock('@limrun/api/instance-client', () => ({ + createInstanceClient: limrunSdk.connectAttached, +})); + +afterEach(() => { + limrunSdk.clients.length = 0; + limrunSdk.attached.length = 0; + limrunSdk.androidList.mockClear(); + limrunSdk.iosList.mockClear(); + limrunSdk.connectAttached.mockClear(); +}); + +const IOS_INSTANCE = { + LIM_IOS_INSTANCE_URL: 'https://region.limrun.example/v1/ios_x/api', + LIM_IOS_INSTANCE_TOKEN: 'ios-instance-token', +}; +const ANDROID_INSTANCE = { + LIM_ANDROID_INSTANCE_URL: 'https://region.limrun.example/v1/android_x/api', + LIM_ANDROID_INSTANCE_TOKEN: 'android-instance-token', + LIM_ANDROID_INSTANCE_ADB_URL: 'wss://region.limrun.example/v1/android_x/adb', +}; + +/** The `resolve` context one `agent-device connect limrun` call gives the provider. */ +function connectContext( + flags: Partial = {}, + env: Record = { LIMRUN_API_KEY: 'lim_test_key' }, +): PluginConnectionContext { + return { + flags: { json: true, help: false, version: false, ...flags }, + stateDir: '/state', + cwd: '/project', + env, + // `resolve` reads only its call's flags and environment; the host stands for the rest. + host: {} as PluginConnectionContext['host'], + }; +} + +function resolve( + flags: Partial = {}, + env?: Record, +) { + const { resolve: resolveConnection } = createLimrunConnection(); + // `resolve` answers synchronously; wrap it so a refusal reads as a rejection either way. + return Promise.resolve().then(async () => await resolveConnection(connectContext(flags, env))); +} + +test('the connection declares Limrun as a local provider with a deferred app and device', () => { + assert.deepEqual(createLimrunConnection().capabilities, LIMRUN_CONNECTION_CAPABILITIES); + assert.deepEqual( + { + leaseKind: LIMRUN_CONNECTION_CAPABILITIES.leaseKind, + requiresRemoteDaemon: LIMRUN_CONNECTION_CAPABILITIES.requiresRemoteDaemon, + supportsDeferredAppSelection: LIMRUN_CONNECTION_CAPABILITIES.supportsDeferredAppSelection, + }, + { + leaseKind: 'direct-device-provider', + requiresRemoteDaemon: false, + supportsDeferredAppSelection: true, + }, + ); +}); + +test('resolve names the platform, its lease backend, and the capture opt-in it carries forward', async () => { + const resolved = await resolve({ + platform: 'ios', + session: 'ci', + providerNetworkLogs: true, + providerNetworkHosts: 'api.example', + }); + assert.deepEqual(resolved.profile, { + daemonTransport: 'auto', + sessionIsolation: 'tenant', + target: 'mobile', + leaseBackend: 'ios-instance', + leaseProvider: 'limrun', + platform: 'ios', + clientId: undefined, + runId: 'limrun-803cad858538d077', + providerNetworkLogs: true, + providerNetworkHosts: 'api.example', + }); +}); + +test('resolve refuses the call until the platform names the one Limrun rents', async () => { + await assert.rejects(resolve({}), { + code: 'INVALID_ARGS', + message: 'connect limrun requires --platform ios or android.', + }); + await assert.rejects(resolve({ platform: 'macos' }), { + code: 'INVALID_ARGS', + message: 'connect limrun requires --platform ios or android.', + }); +}); + +test('resolve refuses a device selection and a lease backend of the other platform', async () => { + await assert.rejects(resolve({ platform: 'ios', device: 'local-ios' }), { + code: 'INVALID_ARGS', + message: + 'connect limrun does not accept --device; Limrun selects a remote simulator or emulator.', + }); + await assert.rejects(resolve({ platform: 'ios', leaseBackend: 'android-instance' }), { + code: 'INVALID_ARGS', + message: 'connect limrun --platform ios requires --lease-backend ios-instance.', + }); +}); + +test('resolve narrows the accepted credentials to the resolved platform', async () => { + // Access to the iOS instance is not access to the Android one this call rents. + await assert.rejects( + resolve({ platform: 'android' }, { ...IOS_INSTANCE, LIMRUN_API_KEY: '' }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details?.reason, 'missing_provider_credentials'); + assert.equal( + error.message, + 'connect limrun requires LIMRUN_API_KEY, or LIM_ANDROID_INSTANCE_URL, LIM_ANDROID_INSTANCE_TOKEN, LIM_ANDROID_INSTANCE_ADB_URL for an existing instance.', + ); + return true; + }, + ); + assert.equal( + (await resolve({ platform: 'ios' }, IOS_INSTANCE)).profile.leaseBackend, + 'ios-instance', + ); + assert.equal( + (await resolve({ platform: 'android' }, ANDROID_INSTANCE)).profile.leaseBackend, + 'android-instance', + ); +}); + +test('resolve reads the refused profile fields before the credentials or the platform', async () => { + await assert.rejects( + resolve({ platform: 'ios', providerOsVersion: '18.0', providerGeoLocation: 'US' }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.deepEqual(error.details?.flags, ['--provider-os-version', '--provider-geo-location']); + return true; + }, + ); + // The app to preinstall is one Limrun reads, so the same call carries it through. + assert.equal( + (await resolve({ platform: 'ios', providerApp: 'Example.ipa' })).profile.leaseBackend, + 'ios-instance', + ); +}); + +test('resolve gives each unscoped connect a run and preserves an explicit run', async () => { + const first = await resolve({ platform: 'android' }); + const second = await resolve({ platform: 'android' }); + assert.match(String(first.profile.runId), /^limrun-[a-f0-9]{16}$/); + assert.notEqual(first.profile.runId, second.profile.runId); + + assert.equal((await resolve({ platform: 'android', runId: 'run-a' })).profile.runId, 'run-a'); +}); + +/** + * The `verify` context the registry hands the callback: the same host `setup` receives, built from + * this call's env, so its `clientVersion` is the host's own. + */ +function verifyContext( + flags: Partial, + env: Record, +): Pick { + return { + flags: { json: true, help: false, version: false, ...flags }, + env, + host: { + env, + options: {}, + clientVersion: '1.2.3', + createError: (code, message, details) => new AppError(code, message, details), + runHostCommand: async () => { + throw new Error('connection verification runs no host command'); + }, + } satisfies ProviderPluginHost, + }; +} + +function verify( + flags: Partial, + env: Record = { LIMRUN_API_KEY: 'lim_test_key' }, +) { + return createLimrunConnection().verify(verifyContext(flags, env)); +} + +test('verify asks the selected platform of the account the scoped credentials reach', async () => { + const verification = await verify({ platform: 'ios' }, { LIMRUN_API_KEY: ' lim_test_key ' }); + + assert.equal(verification.verificationMessage, 'Credentials and iOS instance access verified.'); + assert.deepEqual(limrunSdk.clients, [ + { + apiKey: 'lim_test_key', + userAgent: 'agent-device-cli/1.2.3', + timeout: 15_000, + maxRetries: 0, + }, + ]); + assert.deepEqual(limrunSdk.iosList.mock.calls, [[{ limit: 1 }]]); + assert.deepEqual(limrunSdk.androidList.mock.calls, []); + assert.deepEqual(limrunSdk.attached, []); +}); + +test('verify prefers the attached instance of the selected platform over the account', async () => { + const verification = await verify( + { platform: 'android' }, + { LIMRUN_API_KEY: 'lim_test_key', ...ANDROID_INSTANCE }, + ); + + assert.equal(verification.device.status, 'verified'); + assert.deepEqual(limrunSdk.attached, [ + { + apiUrl: 'https://region.limrun.example/v1/android_x/api', + token: 'android-instance-token', + adbUrl: 'wss://region.limrun.example/v1/android_x/adb', + logLevel: 'none', + maxReconnectAttempts: 0, + }, + ]); + assert.deepEqual(limrunSdk.clients, []); +}); + +test('verify refuses a profile that missed a platform without asking the account or an instance', async () => { + // The credentials of the call are read first, so this is the typed refusal a saved profile that + // never recorded a platform gets, and no client is asked. + await assert.rejects(verify({}, { LIMRUN_API_KEY: 'lim_test_key' }), (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal(error.message, 'Limrun profile missed a mobile platform.'); + return true; + }); + assert.deepEqual(limrunSdk.clients, []); + assert.deepEqual(limrunSdk.attached, []); +}); + +test('verify refuses missing credentials before the platform it was not given', async () => { + // A call missing both answers with the one the caller can still fix on the command line, and the + // SDK stays closed. + await assert.rejects(verify({}, {}), (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details?.reason, 'missing_provider_credentials'); + return true; + }); + assert.deepEqual(limrunSdk.clients, []); + assert.deepEqual(limrunSdk.attached, []); +}); diff --git a/packages/provider-limrun/src/connection.ts b/packages/provider-limrun/src/connection.ts new file mode 100644 index 0000000000..545896c9e9 --- /dev/null +++ b/packages/provider-limrun/src/connection.ts @@ -0,0 +1,123 @@ +import crypto from 'node:crypto'; +import type { RemoteConfigProfile } from '@agent-device/contracts/remote'; +import type { PluginConnection, PluginConnectionContext } from '@agent-device/plugins/contract'; +import { + rejectRefusedProviderProfileFields, + requireResolvedProfilePlatform, +} from '@agent-device/contracts/provider-profile-fields'; +import { leaseBackendForPlatform } from '@agent-device/kernel/contracts'; +import { AppError } from '@agent-device/kernel/errors'; +import { + limrunInstanceVariables, + readLimrunCredentials, + requireLimrunCredentials, +} from './credentials.ts'; +import { + LIMRUN_CONNECTION_CAPABILITIES, + LIMRUN_PROFILE_FIELDS, + LIMRUN_PROVIDER, + type LimrunPlatform, +} from './device.ts'; + +/** The flags and environment one `connect` call gives the provider. */ +type ConnectContext = Pick; + +/** The connection callbacks Limrun answers `agent-device connect limrun` with. */ +export type LimrunConnection = Pick; + +/** + * Limrun's `connect` callbacks: the one set both the built-in CLI composition and an installed + * plugin answers with. `resolve` reads its own call's flags and environment and loads no SDK. + * `verify` loads the provider's own verification only when it runs and asks the account or the + * instance for a read only, so neither callback sets up a runtime, starts a daemon, or rents an + * instance, and no caller names the verification entry from outside the provider. + */ +export function createLimrunConnection(): LimrunConnection { + return { + capabilities: LIMRUN_CONNECTION_CAPABILITIES, + resolve: (context) => ({ profile: limrunConnectProfile(context) }), + verify: async ({ flags, env, host }) => + await ( + await import('./connection-verification.ts') + ).verifyLimrunConnection({ + ...requireLimrunCredentials(env), + clientVersion: host.clientVersion, + platform: requireResolvedProfilePlatform(flags.platform, 'Limrun'), + }), + }; +} + +/** The transport, lease and capture settings that Limrun adds to the saved profile. */ +function limrunConnectProfile(context: ConnectContext): RemoteConfigProfile { + const { flags, env, stateDir } = context; + rejectRefusedProviderProfileFields(flags, LIMRUN_PROFILE_FIELDS); + const leaseBackend = requireLimrunLeaseBackend(flags); + const platform = leaseBackend === 'ios-instance' ? 'ios' : 'android'; + requireLimrunConnectAccess(env, platform); + return { + daemonTransport: 'auto', + sessionIsolation: 'tenant', + target: 'mobile', + leaseBackend, + leaseProvider: LIMRUN_PROVIDER, + platform, + // A Limrun lease is scoped by its run and its provider, and no device is picked before + // allocation, so the provider names no client of its own and the host's identity stands. + clientId: undefined, + runId: flags.runId ?? limrunRunId(stateDir, flags.session ?? crypto.randomUUID()), + // The capture opt-in is read at lease allocation, so it must survive into later commands. + providerNetworkLogs: flags.providerNetworkLogs, + providerNetworkHosts: flags.providerNetworkHosts, + }; +} + +/** Keep the run identity of saved Limrun sessions so reconnect can reuse them. */ +function limrunRunId(stateDir: string, session: string): string { + const identity = [LIMRUN_PROVIDER, stateDir, session].join('\0'); + const digest = crypto.createHash('sha256').update(identity).digest('hex'); + return `${LIMRUN_PROVIDER}-${digest.slice(0, 16)}`; +} + +/** + * The one lease backend Limrun rents its platform on. `--platform` is what the caller selected: the + * host's own lease defaults and a previous session's recorded platform are not this call's inputs. + */ +function requireLimrunLeaseBackend( + flags: ConnectContext['flags'], +): 'android-instance' | 'ios-instance' { + if (flags.platform !== 'android' && flags.platform !== 'ios') { + throw new AppError('INVALID_ARGS', 'connect limrun requires --platform ios or android.'); + } + if (flags.device !== undefined) { + throw new AppError( + 'INVALID_ARGS', + 'connect limrun does not accept --device; Limrun selects a remote simulator or emulator.', + ); + } + const expected = flags.platform === 'ios' ? 'ios-instance' : 'android-instance'; + const leaseBackend = flags.leaseBackend ?? leaseBackendForPlatform(flags.platform); + if (leaseBackend !== expected) { + throw new AppError( + 'INVALID_ARGS', + `connect limrun --platform ${flags.platform} requires --lease-backend ${expected}.`, + ); + } + return expected; +} + +/** + * The credentials one connect reaches: an account key, or the full instance set of the platform it + * just resolved. Access to the other platform is not access to this one. + */ +function requireLimrunConnectAccess(env: ConnectContext['env'], platform: LimrunPlatform): void { + const credentials = readLimrunCredentials(env); + if (credentials?.apiKey || credentials?.instances?.[platform]) return; + throw new AppError( + 'INVALID_ARGS', + `connect limrun requires LIMRUN_API_KEY, or ${limrunInstanceVariables(platform).join(', ')} for an existing instance.`, + { + reason: 'missing_provider_credentials', + hint: 'Set the credentials in the environment before running agent-device connect limrun.', + }, + ); +} diff --git a/src/provider-limrun-credentials.test.ts b/packages/provider-limrun/src/credentials.test.ts similarity index 96% rename from src/provider-limrun-credentials.test.ts rename to packages/provider-limrun/src/credentials.test.ts index 087ae58827..b7a0d62c51 100644 --- a/src/provider-limrun-credentials.test.ts +++ b/packages/provider-limrun/src/credentials.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import { readLimrunCredentials } from './provider-limrun-credentials.ts'; +import { readLimrunCredentials } from './credentials.ts'; const IOS_ENV = { LIM_IOS_INSTANCE_URL: ' https://region.limrun.example/v1/ios_x/api ', diff --git a/src/provider-limrun-credentials.ts b/packages/provider-limrun/src/credentials.ts similarity index 70% rename from src/provider-limrun-credentials.ts rename to packages/provider-limrun/src/credentials.ts index 8458acc489..35d6ae24e9 100644 --- a/src/provider-limrun-credentials.ts +++ b/packages/provider-limrun/src/credentials.ts @@ -1,14 +1,14 @@ -import type { LimrunInstanceAccess } from '@agent-device/provider-limrun'; import { AppError } from '@agent-device/kernel/errors'; import type { EnvMap } from '@agent-device/kernel/source-value'; +import type { LimrunPlatform } from './device.ts'; +import type { LimrunInstanceAccess } from './instance-access.ts'; +/** The Limrun account and instance facts one host gives the provider. */ export type LimrunCredentials = Readonly<{ apiKey?: string; region?: string; keepAlive?: boolean; instances?: LimrunInstanceAccess; - /** Directory the `--provider-network-logs` HAR files are written under. */ - networkHarDir?: string; }>; const ACCOUNT_VARS = { apiKey: 'LIMRUN_API_KEY', region: 'LIMRUN_REGION' } as const; @@ -23,51 +23,56 @@ const INSTANCE_VARS = { } as const; /** Every variable that selects which Limrun account or instance the credentials reach. */ -export const LIMRUN_CREDENTIAL_VARIABLES: readonly string[] = [ +const LIMRUN_CREDENTIAL_VARIABLES: readonly string[] = [ ...Object.values(ACCOUNT_VARS), ...INSTANCE_VARS.ios, ...INSTANCE_VARS.android, ]; -// Mirrors platformForLimrunLeaseBackend in provider-limrun, which exposes only its root entry, and -// that entry loads the Limrun SDK; importing it here would load the SDK on every credential read. -const LEASE_BACKEND_PLATFORMS: ReadonlyMap = new Map([ - ['ios-instance', 'ios'], - ['android-instance', 'android'], -]); - -/** The platform whose instance a Limrun lease backend reaches. */ -export function limrunPlatformForLeaseBackend( - leaseBackend: string | undefined, -): 'ios' | 'android' | undefined { - return leaseBackend === undefined ? undefined : LEASE_BACKEND_PLATFORMS.get(leaseBackend); -} - /** * The variables a Limrun lease reads: the account variables plus the leased platform's instance - * variables, or every variable when the lease backend names no platform. + * variables, or every variable when the lease backend names no platform. The per-backend narrowing + * is what lets a client fingerprint the credentials of the one platform its lease reaches. */ export function limrunCredentialDeclaration(): Readonly<{ variables: readonly string[]; byBackend: Readonly>; }> { const account = Object.values(ACCOUNT_VARS); + const backends: readonly [string, LimrunPlatform][] = [ + ['ios-instance', 'ios'], + ['android-instance', 'android'], + ]; return { variables: LIMRUN_CREDENTIAL_VARIABLES, byBackend: Object.fromEntries( - [...LEASE_BACKEND_PLATFORMS].map(([backend, platform]) => [ - backend, - [...account, ...INSTANCE_VARS[platform]], - ]), + backends.map(([backend, platform]) => [backend, [...account, ...INSTANCE_VARS[platform]]]), ), }; } /** The variables that give access to an existing instance of a platform. */ -export function limrunInstanceVariables(platform: 'ios' | 'android'): readonly string[] { +export function limrunInstanceVariables(platform: LimrunPlatform): readonly string[] { return INSTANCE_VARS[platform]; } +/** + * The credentials one host must hold before Limrun can act on them: this reader's answer, or the + * typed refusal that names both ways in. + */ +export function requireLimrunCredentials(env: EnvMap): LimrunCredentials { + const credentials = readLimrunCredentials(env); + if (credentials) return credentials; + throw new AppError( + 'INVALID_ARGS', + 'Limrun requires LIMRUN_API_KEY, or an instance variable set.', + { + reason: 'missing_provider_credentials', + hint: 'Set LIMRUN_API_KEY for the account, or the full LIM_IOS_INSTANCE_* or LIM_ANDROID_INSTANCE_* set for an existing instance.', + }, + ); +} + /** * The one reader of Limrun credentials in the environment. Instance variables use the `lim` CLI * names, so an orchestrator hands a sandbox one set of variables for both tools. diff --git a/packages/provider-limrun/src/device.ts b/packages/provider-limrun/src/device.ts index b1afd85119..1750d175d3 100644 --- a/packages/provider-limrun/src/device.ts +++ b/packages/provider-limrun/src/device.ts @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto'; import type { DeviceLease } from '@agent-device/contracts/device'; +import type { ConnectionProviderCapabilities } from '@agent-device/contracts/remote'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { ProviderProfileFieldDeclaration } from '@agent-device/contracts/provider-profile-fields'; @@ -7,6 +8,22 @@ export type LimrunPlatform = 'ios' | 'android'; export const LIMRUN_PROVIDER = 'limrun'; +/** + * What a Limrun lease is, as the host must treat it: an instance the provider holds and selects, + * reached from the local daemon through its own tunnel, with the app chosen after `connect`. + */ +export const LIMRUN_CONNECTION_CAPABILITIES: ConnectionProviderCapabilities = { + leaseKind: 'direct-device-provider', + requiresAppAttachment: false, + requiresRemoteDaemon: false, + supportsArtifacts: false, + supportsDeferredAppSelection: true, + supportsDirectPortReverse: true, + usesCloudWebDriverLease: false, + holdsCloudDevice: true, + forgetsEndedConnectionLease: true, +}; + /** * Limrun reads the app to preinstall and the network capture settings; it picks the instance * itself. diff --git a/packages/provider-limrun/src/index.ts b/packages/provider-limrun/src/index.ts index fa58f02799..5d05533253 100644 --- a/packages/provider-limrun/src/index.ts +++ b/packages/provider-limrun/src/index.ts @@ -1,6 +1,3 @@ -export { LIMRUN_PROFILE_FIELDS } from './device.ts'; export { createLimrunRuntime, type LimrunRuntimeOptions } from './runtime.ts'; -export { verifyLimrunConnection } from './connection-verification.ts'; -export type { LimrunInstanceAccess } from './instance-access.ts'; export type { LimrunFileDownload, LimrunRuntimeDependencies } from './runtime-dependencies.ts'; diff --git a/packages/provider-limrun/src/internal.ts b/packages/provider-limrun/src/internal.ts new file mode 100644 index 0000000000..c1321e484e --- /dev/null +++ b/packages/provider-limrun/src/internal.ts @@ -0,0 +1,8 @@ +/** + * The seam core composes Limrun through while the provider is still built in. Nothing here loads the + * Limrun SDK: the runtime, the platform adapters, and the connection's verification each load when + * their own path asks for them. The root entry keeps the SDK-side surface. + */ +export { limrunPlugin, type LimrunPluginOptions } from './plugin.ts'; +export { LIMRUN_CONNECTION_CAPABILITIES } from './device.ts'; +export { readLimrunCredentials } from './credentials.ts'; diff --git a/packages/provider-limrun/src/plugin.test.ts b/packages/provider-limrun/src/plugin.test.ts new file mode 100644 index 0000000000..f85f9da75a --- /dev/null +++ b/packages/provider-limrun/src/plugin.test.ts @@ -0,0 +1,228 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { afterEach, test, vi } from 'vitest'; +import type { ProviderPluginHost } from '@agent-device/plugins/host'; +import { AppError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts'; +import { stubLimrunRuntimeDependencies } from './runtime-dependencies.fixtures.ts'; +import { limrunPlugin } from './plugin.ts'; + +const sdk = vi.hoisted(() => ({ + runtimeCalls: [] as { options: Record; mode: unknown }[], + clients: [] as Array>, + androidList: vi.fn(async () => ({ getPaginatedItems: () => [] })), + iosList: vi.fn(async () => ({ getPaginatedItems: () => [] })), +})); + +// The runtime module is stubbed so a case reads what the plugin hands the runtime builder without +// constructing a Limrun client. The provider's own runtime contract is what the plugin must satisfy. +vi.mock('./runtime.ts', () => ({ + createLimrunRuntime: (options: Record, _d: unknown, mode: unknown) => { + sdk.runtimeCalls.push({ options, mode }); + return { + runtime: { + provider: 'limrun', + shutdown: async () => undefined, + leaseLifecycle: {}, + ownsDevice: () => false, + getInteractor: () => undefined, + deviceInventoryProvider: async () => null, + }, + platformModule: { + owner: { kind: 'provider-runtime', provider: 'limrun', instance: 'limrun:test' }, + loadRuntime: async () => ({}), + }, + }; + }, +})); + +// The SDK is stubbed for the same reason on the other side: a case reads the read-only check's +// request instead of reaching the provider's API. +vi.mock('@limrun/api', () => ({ + default: class MockLimrun { + readonly androidInstances = { list: sdk.androidList }; + readonly iosInstances = { list: sdk.iosList }; + + constructor(options: Record) { + sdk.clients.push(options); + } + }, +})); + +afterEach(() => { + sdk.clients.length = 0; + sdk.androidList.mockClear(); + sdk.iosList.mockClear(); +}); + +function pluginHost(env: Record = {}): ProviderPluginHost { + return { + env, + options: {}, + clientVersion: '1.2.3', + createError: (code, message, details) => new AppError(code, message, details), + runHostCommand: async () => { + throw new Error('this scenario runs no host commands'); + }, + }; +} + +function stubDependencies(): LimrunRuntimeDependencies { + return stubLimrunRuntimeDependencies(); +} + +test('the plugin declares its provider and the credential variables per lease backend', () => { + const plugin = limrunPlugin({ createDependencies: () => stubDependencies() }); + assert.equal(plugin.apiVersion, 2); + assert.equal(plugin.provider, 'limrun'); + assert.deepEqual(plugin.credentials, { + variables: [ + 'LIMRUN_API_KEY', + 'LIMRUN_REGION', + 'LIM_IOS_INSTANCE_URL', + 'LIM_IOS_INSTANCE_TOKEN', + 'LIM_ANDROID_INSTANCE_URL', + 'LIM_ANDROID_INSTANCE_TOKEN', + 'LIM_ANDROID_INSTANCE_ADB_URL', + ], + byBackend: { + 'ios-instance': [ + 'LIMRUN_API_KEY', + 'LIMRUN_REGION', + 'LIM_IOS_INSTANCE_URL', + 'LIM_IOS_INSTANCE_TOKEN', + ], + 'android-instance': [ + 'LIMRUN_API_KEY', + 'LIMRUN_REGION', + 'LIM_ANDROID_INSTANCE_URL', + 'LIM_ANDROID_INSTANCE_TOKEN', + 'LIM_ANDROID_INSTANCE_ADB_URL', + ], + }, + }); +}); + +test('the plugin declares the connection callbacks without setting up any runtime', async () => { + const plugin = limrunPlugin({ createDependencies: () => stubDependencies() }); + assert.ok(plugin.connection, 'the plugin routes connect'); + assert.equal(plugin.connection.capabilities.requiresRemoteDaemon, false); + + // `resolve` runs the provider's own callbacks: the refusal comes from the provider, and nothing + // here calls setup, loads a runtime, or reads the SDK. + await assert.rejects( + async () => + await plugin.connection?.resolve({ + flags: { json: false, help: false, version: false }, + stateDir: '/state', + cwd: '/project', + env: {}, + host: {} as never, + }), + { code: 'INVALID_ARGS', message: 'connect limrun requires --platform ios or android.' }, + ); + assert.equal(sdk.runtimeCalls.length, 0); +}); + +test('verify runs its own SDK check over scoped credentials, version and platform', async () => { + // The provider owns its read-only check: no caller names the entry it verifies through. The SDK + // is asked for the credentials of this call's env, the host's version, and this call's platform, + // and nothing here sets up a runtime. + const plugin = limrunPlugin({ createDependencies: () => stubDependencies() }); + + const verification = await plugin.connection?.verify({ + flags: { json: false, help: false, version: false, platform: 'ios' }, + env: { LIMRUN_API_KEY: ' lim_test_key ', LIMRUN_REGION: 'eu', LIMRUN_KEEP_ALIVE: '1' }, + host: pluginHost({ LIMRUN_API_KEY: 'lim_test_key' }), + }); + + assert.equal(verification?.verificationMessage, 'Credentials and iOS instance access verified.'); + assert.deepEqual(sdk.clients, [ + { + apiKey: 'lim_test_key', + userAgent: 'agent-device-cli/1.2.3', + timeout: 15_000, + maxRetries: 0, + }, + ]); + // Only the platform this call selected is asked, and the region narrows its query. `keepAlive` + // leases an instance and has no part in a read-only check. + assert.deepEqual(sdk.iosList.mock.calls, [[{ limit: 1, region: 'eu' }]]); + assert.deepEqual(sdk.androidList.mock.calls, []); + assert.equal(sdk.runtimeCalls.length, 0); +}); + +test('setup builds the runtime over the credentials, host and HAR directory it was given', async () => { + const host = pluginHost({ LIMRUN_API_KEY: 'lim_test_key', LIMRUN_KEEP_ALIVE: '1' }); + const dependencies = stubDependencies(); + const createDependencies = vi.fn(() => dependencies); + const stateDir = mkdtempForTestSync('limrun-plugin-state-'); + + const setup = await limrunPlugin({ createDependencies, stateDir }).setup(host); + + if (!('runtime' in setup)) throw new Error('Limrun sets up its own runtime'); + assert.equal(setup.runtime.provider, 'limrun'); + assert.deepEqual(createDependencies.mock.calls, [[host]]); + assert.deepEqual(sdk.runtimeCalls, [ + { + options: { + apiKey: 'lim_test_key', + region: undefined, + keepAlive: true, + instances: undefined, + networkHarDir: path.join(stateDir, 'network-har'), + }, + mode: { includePlatformModule: true }, + }, + ]); +}); + +test('setup with only an attached instance builds a runtime without an API key or HAR directory', async () => { + await limrunPlugin({ createDependencies: () => stubDependencies() }).setup( + pluginHost({ LIM_IOS_INSTANCE_URL: 'https://x/api', LIM_IOS_INSTANCE_TOKEN: 'token' }), + ); + const options = sdk.runtimeCalls.at(-1)?.options; + assert.equal(options?.apiKey, undefined); + assert.deepEqual(options?.instances, { + ios: { apiUrl: 'https://x/api', token: 'token' }, + android: undefined, + }); + assert.equal('networkHarDir' in (options ?? {}), false); +}); + +test('setup refuses a host with no Limrun credentials before asking for host adapters', async () => { + const createDependencies = vi.fn(() => stubDependencies()); + await assert.rejects( + async () => { + await limrunPlugin({ createDependencies }).setup(pluginHost({ LIMRUN_REGION: 'eu' })); + }, + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details?.reason, 'missing_provider_credentials'); + return true; + }, + ); + assert.equal(createDependencies.mock.calls.length, 0); +}); + +test('setup refuses a partial instance set naming the variable it still needs', async () => { + const createDependencies = vi.fn(() => stubDependencies()); + await assert.rejects( + async () => { + await limrunPlugin({ createDependencies }).setup( + pluginHost({ + LIMRUN_API_KEY: 'lim_test_key', + LIM_ANDROID_INSTANCE_URL: 'https://region.limrun.example/v1/android_x/api', + LIM_ANDROID_INSTANCE_TOKEN: 'android-token', + }), + ); + }, + { + code: 'INVALID_ARGS', + message: 'Limrun instance access is missing LIM_ANDROID_INSTANCE_ADB_URL.', + }, + ); + assert.equal(createDependencies.mock.calls.length, 0); +}); diff --git a/packages/provider-limrun/src/plugin.ts b/packages/provider-limrun/src/plugin.ts new file mode 100644 index 0000000000..11770d12ce --- /dev/null +++ b/packages/provider-limrun/src/plugin.ts @@ -0,0 +1,71 @@ +import path from 'node:path'; +import type { AgentDevicePlugin, PluginConnection } from '@agent-device/plugins/contract'; +import type { ProviderPluginHost } from '@agent-device/plugins/host'; +import { limrunCredentialDeclaration, requireLimrunCredentials } from './credentials.ts'; +import { LIMRUN_CONNECTION_CAPABILITIES, LIMRUN_PROVIDER } from './device.ts'; +import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts'; + +export type LimrunPluginOptions = Readonly<{ + /** + * Builds the runtime's host and platform adapters for one setup host. The provider names what a + * runtime needs; whoever composes the host supplies how those needs are served, so the runtime + * graph stays free of platform implementation. + */ + createDependencies( + host: ProviderPluginHost, + ): LimrunRuntimeDependencies | Promise; + /** + * The daemon's own state directory. Each lease's `--provider-network-logs` HAR file is written + * beside the session files under it; without it the capture is unavailable. + */ + stateDir?: string; +}>; + +/** + * Limrun as a version 2 plugin: instances are rented from the Limrun API and driven through their + * own ADB tunnel or Simulator bridge. + * + * The credentials are read from the setup host's environment, so the plugin declares exactly the + * variables it reads there, narrowed per lease backend. Only this module's declaration is needed to + * list, fingerprint, or route a `connect` to the provider: the connection's flags and credential + * reading, the runtime, and its host adapters all load in the path that asks for them. + */ +export function limrunPlugin( + options: LimrunPluginOptions, +): AgentDevicePlugin & { connection: PluginConnection } { + const { createDependencies, stateDir } = options; + return { + apiVersion: 2, + provider: LIMRUN_PROVIDER, + credentials: limrunCredentialDeclaration(), + // The connect callbacks are the provider's own and load when the first `connect` runs them, so + // a process that only lists or fingerprints this provider evaluates none of them. + connection: { + capabilities: LIMRUN_CONNECTION_CAPABILITIES, + resolve: async (context) => + await (await import('./connection.ts')).createLimrunConnection().resolve(context), + verify: async (context) => + await (await import('./connection.ts')).createLimrunConnection().verify(context), + }, + setup: async (host) => { + const credentials = requireLimrunCredentials(host.env); + const [register, dependencies] = await Promise.all([ + import('./runtime.ts'), + Promise.resolve(createDependencies(host)), + ]); + return register.createLimrunRuntime( + { + ...credentials, + ...(stateDir === undefined + ? {} + : { + // HAR captures land beside the session files, under the daemon's own state dir. + networkHarDir: path.join(stateDir, 'network-har'), + }), + }, + dependencies, + { includePlatformModule: true }, + ); + }, + }; +} diff --git a/packages/provider-limrun/tsconfig.json b/packages/provider-limrun/tsconfig.json index 25a1e8040c..66e2179ce9 100644 --- a/packages/provider-limrun/tsconfig.json +++ b/packages/provider-limrun/tsconfig.json @@ -26,6 +26,9 @@ { "path": "../platform-apple" }, + { + "path": "../plugins" + }, { "path": "../test-kit" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e8573fb298..a74c78e77c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -908,6 +908,9 @@ importers: '@agent-device/platform-android': specifier: workspace:* version: link:../platform-android + '@agent-device/plugins': + specifier: workspace:* + version: link:../plugins devDependencies: '@agent-device/platform-apple': specifier: workspace:* diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index 2996884597..8ec948a269 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -822,13 +822,14 @@ test('the real tree parses, declares, and passes R11', () => { assert.ok(providerLimrunPackage, 'provider-limrun package must exist'); assert.deepEqual( [...providerLimrunPackage.exportTargets.keys()], - ['@agent-device/provider-limrun'], + ['@agent-device/provider-limrun', '@agent-device/provider-limrun/internal'], ); assert.deepEqual([...providerLimrunPackage.workspaceDependencies].sort(), [ '@agent-device/capture-kit', '@agent-device/contracts', '@agent-device/kernel', '@agent-device/platform-android', + '@agent-device/plugins', ]); const rootExternalDependencies = rootExternalDependencyRanges(repoRoot); for (const pkg of packages) { diff --git a/scripts/layering/root-module-zones.ts b/scripts/layering/root-module-zones.ts index 525eb0ff84..7cb22a26f7 100644 --- a/scripts/layering/root-module-zones.ts +++ b/scripts/layering/root-module-zones.ts @@ -51,7 +51,6 @@ export const ROOT_MODULE_ZONES: Readonly> = { 'src/platform-runtime.ts', 'src/provider-credential-fingerprint.ts', 'src/provider-device-runtimes.ts', - 'src/provider-limrun-credentials.ts', 'src/provider-plugin-policy.ts', ], // The operation host the platform runtime loads through `import()` (`loadHost`) and its facets. diff --git a/src/__tests__/cloud-connect-profile-fields.test.ts b/src/__tests__/cloud-connect-profile-fields.test.ts index e66c08bf5c..a779ddd054 100644 --- a/src/__tests__/cloud-connect-profile-fields.test.ts +++ b/src/__tests__/cloud-connect-profile-fields.test.ts @@ -1,11 +1,6 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import { AppError } from '@agent-device/kernel/errors'; -import { resolveLimrunConnectProfile } from '../cli/connection/limrun-profile.ts'; import { runCliCapture } from './cli-capture.ts'; -import { mkdtempForTestSync } from '@agent-device/test-kit'; test('connect limrun refuses profile fields Limrun does not read', async () => { const result = await runCliCapture( @@ -36,29 +31,32 @@ test('connect limrun refuses profile fields Limrun does not read', async () => { ]); }); -test('connect limrun applies the same refusal when attaching to an existing instance', () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-limrun-attach-profile-fields-'); - const connect = (flags: Record) => - resolveLimrunConnectProfile({ - stateDir: path.join(tempRoot, '.state'), - cwd: tempRoot, +test('connect limrun applies the same refusal when attaching to an existing instance', async () => { + // An attached instance is the other way in, so the same refusal has to answer there too, before + // any connection profile is written. + const result = await runCliCapture( + [ + 'connect', + 'limrun', + '--session', + 'ci', + '--platform', + 'ios', + '--provider-os-version', + '18.0', + '--json', + ], + { env: { + LIMRUN_API_KEY: '', LIM_IOS_INSTANCE_URL: 'https://region.limrun.example/v1/ios_x/api', LIM_IOS_INSTANCE_TOKEN: 'ios-instance-token', }, - flags: { json: false, help: false, version: false, platform: 'ios', ...flags }, - }); - - try { - assert.equal(connect({ providerApp: 'Example.ipa' }).flags.providerApp, 'Example.ipa'); - assert.throws( - () => connect({ providerOsVersion: '18.0' }), - (error: unknown) => - error instanceof AppError && - error.code === 'INVALID_ARGS' && - JSON.stringify(error.details?.flags) === '["--provider-os-version"]', - ); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } + stateDirPrefix: 'agent-device-connect-limrun-attach-profile-fields-', + }, + ); + assert.equal(result.code, 1); + const payload = JSON.parse(result.stdout); + assert.equal(payload.error.code, 'INVALID_ARGS'); + assert.deepEqual(payload.error.details.flags, ['--provider-os-version']); }); diff --git a/src/__tests__/cloud-connect-profile.test.ts b/src/__tests__/cloud-connect-profile.test.ts index 4e68d3453f..3bbd8f3889 100644 --- a/src/__tests__/cloud-connect-profile.test.ts +++ b/src/__tests__/cloud-connect-profile.test.ts @@ -1,8 +1,9 @@ -import { afterEach, beforeEach, test, vi } from 'vitest'; +import { afterEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { connectCommand } from '../cli/commands/connection.ts'; +import { buildConnectClientId } from '../cli/connection/client-id.ts'; import { resolveCloudAccessForConnect } from '../cli/auth-session.ts'; import { runCliCapture } from './cli-capture.ts'; import { @@ -11,8 +12,7 @@ import { type RemoteConnectionState, } from '@agent-device/remote/remote-connection-state'; import type { AgentDeviceClient } from '@agent-device/command-surface'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { verifyLimrunConnection } from '@agent-device/provider-limrun'; +import { normalizeError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync, bindTestCommandHost, @@ -22,40 +22,51 @@ import { bindTestCommandHost(); +// The Limrun SDK is the boundary this suite stubs: the provider's own connection verification is +// what `connect limrun` runs, and nothing here may reach the provider's API. Both routes in are +// answered — the account client's list, and the attached instance's client — and neither network. +const limrunSdk = vi.hoisted(() => { + const accountClients: Array> = []; + const attachedClients: Array> = []; + return { + accountClients, + attachedClients, + accountList: vi.fn(async () => ({ getPaginatedItems: () => [] })), + connectAttached: vi.fn(async (options: Record) => { + attachedClients.push(options); + return { disconnect: () => undefined }; + }), + }; +}); + +vi.mock('@limrun/api', () => ({ + default: class MockLimrun { + readonly androidInstances = { list: limrunSdk.accountList }; + readonly iosInstances = { list: limrunSdk.accountList }; + + constructor(options: Record) { + limrunSdk.accountClients.push(options); + } + }, +})); + +vi.mock('@limrun/api/ios-client', () => ({ createInstanceClient: limrunSdk.connectAttached })); +vi.mock('@limrun/api/instance-client', () => ({ createInstanceClient: limrunSdk.connectAttached })); + vi.mock('../cli/auth-session.ts', async (importOriginal) => ({ ...(await importOriginal()), resolveCloudAccessForConnect: vi.fn(), })); -vi.mock('@agent-device/provider-limrun', async (importOriginal) => ({ - ...(await importOriginal()), - verifyLimrunConnection: vi.fn(), -})); - afterEach(() => { + limrunSdk.accountClients.length = 0; + limrunSdk.attachedClients.length = 0; vi.clearAllMocks(); + vi.unstubAllEnvs(); vi.unstubAllGlobals(); }); const mockedResolveCloudAccessForConnect = vi.mocked(resolveCloudAccessForConnect); -const mockedVerifyLimrunConnection = vi.mocked(verifyLimrunConnection); - -beforeEach(() => { - mockedVerifyLimrunConnection.mockResolvedValue({ - provider: 'limrun', - service: 'Limrun', - verificationMessage: 'Credentials and Android instance access verified.', - device: { - status: 'deferred', - name: 'Provider-selected Android emulator', - platform: 'android', - }, - app: { - status: 'missing', - message: 'Run apps to choose an uploaded asset before allocation.', - }, - }); -}); test('connect without remote config generates one from cloud connection profile', async () => { const tempRoot = mkdtempForTestSync('agent-device-connect-cloud-'); @@ -131,6 +142,8 @@ test('connect limrun generates a local daemon remote profile', async () => { tenant: 'team-a', runId: 'run-a', session: 'limrun-android', + providerNetworkLogs: true, + providerNetworkHosts: 'api.example', }, client: {} as AgentDeviceClient, }); @@ -148,11 +161,15 @@ test('connect limrun generates a local daemon remote profile', async () => { state.remoteConfigPath, /remote-connections\/generated\/limrun-[a-f0-9]{16}\.json$/, ); + // The capture opt-in is read when the lease is allocated, so it must survive into the file + // later commands resolve, not stop at this call's flags. assert.deepEqual(readGeneratedConfigKeys(state.remoteConfigPath), [ 'daemonTransport', 'leaseBackend', 'leaseProvider', 'platform', + 'providerNetworkHosts', + 'providerNetworkLogs', 'runId', 'session', 'sessionIsolation', @@ -160,6 +177,9 @@ test('connect limrun generates a local daemon remote profile', async () => { 'target', 'tenant', ]); + const generated = readGeneratedConfig(state.remoteConfigPath); + assert.equal(generated.providerNetworkLogs, true); + assert.equal(generated.providerNetworkHosts, 'api.example'); } finally { fs.rmSync(tempRoot, { recursive: true, force: true }); } @@ -184,7 +204,11 @@ test('connect limrun attaches to an existing instance without storing its token' const state = readRequiredActiveState(stateDir); assert.equal(state.leaseBackend, 'ios-instance'); assert.doesNotMatch(fs.readFileSync(state.remoteConfigPath, 'utf8'), /ios-instance-token/); - assert.deepEqual(mockedVerifyLimrunConnection.mock.calls[0]?.[0].instances?.ios, ios); + // Verification went to the instance named by the scoped variables, and not to the account API. + assert.deepEqual(limrunSdk.attachedClients, [ + { ...ios, logLevel: 'none', maxReconnectAttempts: 0 }, + ]); + assert.deepEqual(limrunSdk.accountClients, []); }); test('connect limrun persists deferred Metro bridge settings', async () => { @@ -243,6 +267,78 @@ test('connect limrun persists deferred Metro bridge settings', async () => { } }); +test('connect limrun reconnects to the saved named session and profile', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-limrun-repeat-'); + const stateDir = path.join(tempRoot, '.state'); + vi.stubEnv('LIMRUN_API_KEY', 'lim_test_key'); + vi.useFakeTimers({ toFake: ['Date'] }); + const session = 'limrun-repeat'; + const savedRunId = `limrun-${buildConnectClientId('limrun', stateDir, session)}`; + const connect = async (runId?: string) => + await captureConnectStdout(async () => { + await connectCommand({ + host: createTestHostEnvironment(), + positionals: ['limrun'], + flags: { + json: true, + help: false, + version: false, + stateDir, + platform: 'android', + session, + ...(runId === undefined ? {} : { runId }), + }, + client: {} as AgentDeviceClient, + }); + }); + + try { + vi.setSystemTime(1_000); + await connect(savedRunId); + const first = readRequiredActiveState(stateDir); + // Time passes between the two connects; the connection identity must not depend on it. + vi.setSystemTime(90_000); + await connect(); + const second = readRequiredActiveState(stateDir); + + assert.equal(second.runId, first.runId); + assert.equal(second.remoteConfigPath, first.remoteConfigPath); + assert.deepEqual(fs.readdirSync(path.join(stateDir, 'remote-connections', 'generated')), [ + path.basename(first.remoteConfigPath), + ]); + } finally { + vi.useRealTimers(); + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('separate unscoped connect limrun calls get separate run ids', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-limrun-unscoped-'); + const stateDir = path.join(tempRoot, '.state'); + vi.stubEnv('LIMRUN_API_KEY', 'lim_test_key'); + const connect = async () => { + await captureConnectStdout(async () => { + await connectCommand({ + host: createTestHostEnvironment(), + positionals: ['limrun'], + flags: { json: true, help: false, version: false, stateDir, platform: 'android' }, + client: {} as AgentDeviceClient, + }); + }); + return readRequiredActiveState(stateDir); + }; + + try { + const first = await connect(); + const second = await connect(); + + assert.notEqual(second.session, first.session); + assert.notEqual(second.runId, first.runId); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + test('connect limrun requires LIMRUN_API_KEY or access to an existing instance', async () => { const tempRoot = mkdtempForTestSync('agent-device-connect-limrun-env-'); const stateDir = path.join(tempRoot, '.state'); @@ -407,9 +503,9 @@ test('connect does not activate provider state when verification fails', async ( const tempRoot = mkdtempForTestSync('agent-device-connect-verify-fail-'); const stateDir = path.join(tempRoot, '.state'); vi.stubEnv('LIMRUN_API_KEY', 'lim_bad_key'); - mockedVerifyLimrunConnection.mockRejectedValueOnce( - new AppError('UNAUTHORIZED', 'Limrun rejected connection verification.'), - ); + // The account answers the read-only check as it answers a rejected key, and the provider turns + // that into its typed refusal. + limrunSdk.accountList.mockRejectedValueOnce(Object.assign(new Error('invalid'), { status: 401 })); try { await assert.rejects( @@ -427,6 +523,7 @@ test('connect does not activate provider state when verification fails', async ( }), (error: unknown) => { assert.equal((error as { code?: string }).code, 'UNAUTHORIZED'); + assert.doesNotMatch(JSON.stringify(error), /lim_bad_key/); return true; }, ); @@ -515,6 +612,8 @@ function readGeneratedConfig(configPath: string): { providerOsVersion?: string; providerProject?: string; providerBuild?: string; + providerNetworkLogs?: boolean; + providerNetworkHosts?: string; awsProjectArn?: string; awsDeviceArn?: string; awsAppArn?: string; @@ -529,6 +628,8 @@ function readGeneratedConfig(configPath: string): { providerOsVersion?: string; providerProject?: string; providerBuild?: string; + providerNetworkLogs?: boolean; + providerNetworkHosts?: string; awsProjectArn?: string; awsDeviceArn?: string; awsAppArn?: string; diff --git a/src/__tests__/daemon-client-provider-credentials.test.ts b/src/__tests__/daemon-client-provider-credentials.test.ts index 676321631d..edc5db5567 100644 --- a/src/__tests__/daemon-client-provider-credentials.test.ts +++ b/src/__tests__/daemon-client-provider-credentials.test.ts @@ -15,7 +15,7 @@ import { import { providerCredentialFingerprint as fingerprintFor } from '@agent-device/plugins/credential-fingerprint'; import { builtinPluginInventory } from './test-utils/builtin-plugin-inventory.ts'; import type { EnvMap } from '@agent-device/kernel/source-value'; -import { LIMRUN_CREDENTIAL_VARIABLES } from '../provider-limrun-credentials.ts'; +import { pluginCredentialVariables } from '@agent-device/contracts/plugin-inventory'; import { readDaemonProviderCredentials } from '../provider-credential-fingerprint.ts'; const inventory = await builtinPluginInventory(); @@ -143,7 +143,9 @@ function readFingerprint(body: string): unknown { } function clearCredentialEnv(): void { - for (const name of LIMRUN_CREDENTIAL_VARIABLES) vi.stubEnv(name, undefined); + const variables = pluginCredentialVariables(inventory, 'limrun'); + if (!variables?.length) throw new Error('Limrun credential variables are missing from inventory'); + for (const name of variables) vi.stubEnv(name, undefined); } async function startLocalDaemon( diff --git a/src/builtin-provider-ids.ts b/src/builtin-provider-ids.ts index 6216c7010a..e0d0b87a3a 100644 --- a/src/builtin-provider-ids.ts +++ b/src/builtin-provider-ids.ts @@ -1,20 +1,9 @@ import type { ConnectionProviderCapabilities } from '@agent-device/contracts/remote'; import { ROUTING_PROVIDER_IDENTITIES } from '@agent-device/plugins/contract'; +import { LIMRUN_CONNECTION_CAPABILITIES } from '@agent-device/provider-limrun/internal'; export const LIMRUN_ID = 'limrun'; -const LIMRUN_CONNECTION: ConnectionProviderCapabilities = { - leaseKind: 'direct-device-provider', - requiresAppAttachment: false, - requiresRemoteDaemon: false, - supportsArtifacts: false, - supportsDeferredAppSelection: true, - supportsDirectPortReverse: true, - usesCloudWebDriverLease: false, - holdsCloudDevice: true, - forgetsEndedConnectionLease: true, -}; - /** Every provider id agent-device registers itself; a plugin cannot claim any of them. */ export const BUILTIN_PROVIDER_IDS: readonly string[] = [LIMRUN_ID]; @@ -24,9 +13,13 @@ export const BUILTIN_CONNECT_PROVIDER_IDS: readonly string[] = [ ...BUILTIN_PROVIDER_IDS, ]; -/** The built-in provider's connect capabilities, read without loading its implementation. */ +/** + * The built-in provider's connect capabilities, read without loading its implementation. The + * provider package declares what its lease is; this names which built-in answers with that + * declaration, so a synchronous routing read never has to load the plugin registry. + */ export function builtinConnectionCapabilities( provider: string | undefined, ): ConnectionProviderCapabilities | undefined { - return provider === LIMRUN_ID ? LIMRUN_CONNECTION : undefined; + return provider === LIMRUN_ID ? LIMRUN_CONNECTION_CAPABILITIES : undefined; } diff --git a/src/builtin-provider-plugins.test.ts b/src/builtin-provider-plugins.test.ts new file mode 100644 index 0000000000..12a7d767d6 --- /dev/null +++ b/src/builtin-provider-plugins.test.ts @@ -0,0 +1,204 @@ +import assert from 'node:assert/strict'; +import { afterEach, test, vi } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { readVersion } from '@agent-device/host-kit/version'; +import { createEmbeddedProviderRuntimeComposition } from './provider-device-runtimes.ts'; +import { builtinLimrunConnection } from './builtin-provider-plugins.ts'; + +// The built-in candidate is composed by the daemon's own registry, so the case runs the real plugin +// contract with the Limrun SDK stubbed out: nothing here reaches the provider's API. +const limrunSdk = vi.hoisted(() => { + const clients: Array> = []; + const androidList = vi.fn(async () => ({ getPaginatedItems: () => [] })); + const iosList = vi.fn(async () => ({ getPaginatedItems: () => [] })); + return { clients, androidList, iosList }; +}); + +vi.mock('@limrun/api', () => ({ + default: class MockLimrun { + readonly iosInstances = { list: limrunSdk.iosList }; + readonly androidInstances = { list: limrunSdk.androidList }; + + constructor(options: Record) { + limrunSdk.clients.push(options); + } + }, +})); + +// The root's own runtime-adapter factory is the runtime half of the built-in composition. Spying on +// it in place, and answering with the real adapters, is what proves a `connect` composes the +// provider's callbacks without setting up a runtime. +const runtimeDependencies = vi.hoisted(() => ({ create: vi.fn() })); +vi.mock('./sdk/limrun-runtime-dependencies.ts', async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + createLimrunRuntimeDependencies: ( + ...args: Parameters + ) => { + runtimeDependencies.create(...args); + return original.createLimrunRuntimeDependencies(...args); + }, + }; +}); + +afterEach(() => { + limrunSdk.clients.length = 0; + limrunSdk.androidList.mockClear(); + limrunSdk.iosList.mockClear(); + runtimeDependencies.create.mockClear(); +}); + +test('an unconfigured built-in Limrun claims its id without an inventory entry or a runtime', async () => { + const composition = await createEmbeddedProviderRuntimeComposition( + { env: {}, cwd: process.cwd() }, + [], + ); + + try { + assert.deepEqual( + composition.runtimes.map(({ provider }) => provider), + [], + ); + assert.deepEqual( + composition.inventory.map(({ provider }) => provider), + [], + ); + } finally { + await composition.shutdown(); + } +}); + +test('a configured built-in Limrun registers through the plugin contract with its per-backend credential narrowing', async () => { + const composition = await createEmbeddedProviderRuntimeComposition( + { + env: { + LIMRUN_API_KEY: 'lim_test_key', + AGENT_DEVICE_STATE_DIR: mkdtempForTestSync('agent-device-builtin-limrun-'), + }, + cwd: process.cwd(), + }, + [], + ); + + try { + assert.deepEqual( + composition.inventory + .filter(({ provider }) => provider === 'limrun') + .map(({ provider, source, state }) => [provider, source, state]), + [['limrun', 'builtin', 'active']], + ); + const registered = composition.runtimes.find(({ provider }) => provider === 'limrun'); + assert.ok(registered, 'a configured built-in registers its runtime'); + assert.deepEqual( + composition.platformModules + .filter(({ runtime }) => runtime === registered) + .map(({ module }) => [module.owner.kind, module.owner.provider]), + [['provider-runtime', 'limrun']], + ); + // The fingerprint the daemon and the client both read is the plugin's own declaration: the + // account variables plus only the leased platform's instance variables. + assert.deepEqual( + composition.inventory.find(({ provider }) => provider === 'limrun')?.credentials, + { + variables: [ + 'LIMRUN_API_KEY', + 'LIMRUN_REGION', + 'LIM_IOS_INSTANCE_URL', + 'LIM_IOS_INSTANCE_TOKEN', + 'LIM_ANDROID_INSTANCE_URL', + 'LIM_ANDROID_INSTANCE_TOKEN', + 'LIM_ANDROID_INSTANCE_ADB_URL', + ], + byBackend: { + 'ios-instance': [ + 'LIMRUN_API_KEY', + 'LIMRUN_REGION', + 'LIM_IOS_INSTANCE_URL', + 'LIM_IOS_INSTANCE_TOKEN', + ], + 'android-instance': [ + 'LIMRUN_API_KEY', + 'LIMRUN_REGION', + 'LIM_ANDROID_INSTANCE_URL', + 'LIM_ANDROID_INSTANCE_TOKEN', + 'LIM_ANDROID_INSTANCE_ADB_URL', + ], + }, + }, + ); + } finally { + await composition.shutdown(); + } +}); + +test('the built-in connection answers connect with the provider callbacks and its own verification', async () => { + const stateDir = mkdtempForTestSync('agent-device-builtin-limrun-connection-'); + const host = { + env: { LIMRUN_API_KEY: 'lim_test_key', AGENT_DEVICE_STATE_DIR: stateDir }, + cwd: process.cwd(), + }; + + const connection = await builtinLimrunConnection(host); + // Composing the connection reads nothing about a runtime: the host adapters are what `setup` + // asks for, and `connect` never calls it. + assert.deepEqual(runtimeDependencies.create.mock.calls, []); + assert.deepEqual(limrunSdk.clients, []); + + // `resolve` runs the provider's own flag, backend, and credential rules. + const resolved = await connection.resolve({ + flags: { json: true, help: false, version: false, stateDir, platform: 'android' }, + stateDir, + cwd: host.cwd, + env: host.env, + }); + assert.equal(resolved.profile.leaseProvider, 'limrun'); + assert.equal(resolved.profile.leaseBackend, 'android-instance'); + assert.deepEqual(limrunSdk.clients, []); + + // `verify` runs the provider's own read-only account check through the SDK: the credentials of + // this call's env, this host's version, and only the platform this call selected. No instance is + // created, and no runtime is set up. + const verification = await connection.verify({ + flags: { json: true, help: false, version: false, stateDir, platform: 'android' }, + cwd: host.cwd, + env: host.env, + }); + assert.equal(verification.service, 'Limrun'); + assert.equal( + verification.verificationMessage, + 'Credentials and Android instance access verified.', + ); + assert.deepEqual(limrunSdk.clients, [ + { + apiKey: 'lim_test_key', + userAgent: `agent-device-cli/${readVersion()}`, + timeout: 15_000, + maxRetries: 0, + }, + ]); + assert.deepEqual(limrunSdk.androidList.mock.calls, [[{ limit: 1 }]]); + assert.deepEqual(limrunSdk.iosList.mock.calls, []); + assert.deepEqual(runtimeDependencies.create.mock.calls, []); +}); + +test('the built-in connection verifies the iOS platform another connect call selected', async () => { + const stateDir = mkdtempForTestSync('agent-device-builtin-limrun-connection-ios-'); + const host = { + env: { LIMRUN_API_KEY: 'lim_test_key', AGENT_DEVICE_STATE_DIR: stateDir }, + cwd: process.cwd(), + }; + const connection = await builtinLimrunConnection(host); + const verification = await connection.verify({ + flags: { json: true, help: false, version: false, stateDir, platform: 'ios' }, + cwd: host.cwd, + env: { ...host.env, LIMRUN_REGION: 'eu', LIMRUN_API_KEY: ' lim_test_key ' }, + }); + + assert.equal(verification.verificationMessage, 'Credentials and iOS instance access verified.'); + // The key is read the provider reads it, the region narrows the query, and the platform decides + // which service is asked. + assert.equal(limrunSdk.clients[0]?.apiKey, 'lim_test_key'); + assert.deepEqual(limrunSdk.iosList.mock.calls, [[{ limit: 1, region: 'eu' }]]); + assert.deepEqual(limrunSdk.androidList.mock.calls, []); +}); diff --git a/src/builtin-provider-plugins.ts b/src/builtin-provider-plugins.ts index d64bd8c402..fe68cd277a 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -1,14 +1,14 @@ import type { AgentDevicePlugin } from '@agent-device/plugins/contract'; import type { PluginCandidate } from '@agent-device/plugins/registry'; +import type { PluginConnectionCallbacks } from '@agent-device/plugins/connection'; import { LIMRUN_ID } from './builtin-provider-ids.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import path from 'node:path'; import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { - limrunCredentialDeclaration, + limrunPlugin, readLimrunCredentials, - type LimrunCredentials, -} from './provider-limrun-credentials.ts'; + type LimrunPluginOptions, +} from '@agent-device/provider-limrun/internal'; /** * The built-in providers as registry candidates, in the shape a plugin has. Their implementations @@ -21,41 +21,51 @@ export function builtinProviderCandidates(host: HostEnvironment): PluginCandidat function limrunCandidate(host: HostEnvironment): PluginCandidate { const base = { source: 'builtin', provider: LIMRUN_ID } as const; - let credentials: LimrunCredentials | undefined; + // The provider owns what counts as its credentials; the candidate only asks whether this host + // holds them, so an unconfigured process keeps the id dormant and never loads the runtime. + let configured: boolean; try { - credentials = readLimrunCredentials(host.env); + configured = readLimrunCredentials(host.env) !== undefined; } catch (error) { return { ...base, load: () => Promise.reject(error) }; } - if (!credentials) return { ...base, dormant: true, load: () => undefined }; - const limrun = credentials; + if (!configured) return { ...base, dormant: true, load: () => undefined }; return { ...base, - load: (): AgentDevicePlugin => ({ - apiVersion: 2, - provider: LIMRUN_ID, - credentials: limrunCredentialDeclaration(), - setup: async () => { - const [runtime, dependencies] = await Promise.all([ - import('@agent-device/provider-limrun'), - import('./sdk/limrun-runtime-dependencies.ts'), - ]); - return runtime.createLimrunRuntime( - { - ...limrun, - // HAR captures land beside the session files, under the daemon's own state dir. - networkHarDir: path.join( - resolveDaemonPaths(host.env.AGENT_DEVICE_STATE_DIR, { env: host.env, cwd: host.cwd }) - .baseDir, - 'network-har', - ), - }, - dependencies.createLimrunRuntimeDependencies(host), - { - includePlatformModule: true, - }, - ); - }, - }), + load: (): AgentDevicePlugin => limrunPlugin(builtinLimrunPluginOptions(host)), }; } + +/** + * How the composing root answers what the built-in provider asks for: the platform's own host + * adapters build its runtime. + */ +function builtinLimrunPluginOptions(host: HostEnvironment): LimrunPluginOptions { + return { + // The host adapters are the root's own: the provider names what a runtime needs, and this + // composition answers with its platform owners and this host's env/cwd. + createDependencies: async () => + (await import('./sdk/limrun-runtime-dependencies.ts')).createLimrunRuntimeDependencies(host), + // HAR captures land beside the session files, under the daemon's own state dir. The state + // dir is resolved with the load, so an unconfigured process never probes for one. + stateDir: resolveDaemonPaths(host.env.AGENT_DEVICE_STATE_DIR, { + env: host.env, + cwd: host.cwd, + }).baseDir, + }; +} + +/** + * The built-in Limrun connection the CLI `connect` runs: the provider's own callbacks, composed as + * a plugin and wired to this host the same way the daemon's registry wires an installed plugin's. + * The read-only check is the provider's own, so both answers verify through one entry, and it loads + * only when `verify` runs. + */ +export async function builtinLimrunConnection( + host: HostEnvironment, +): Promise { + const { withConnectionHost } = await import('@agent-device/plugins/registry'); + const plugin = limrunPlugin(builtinLimrunPluginOptions(host)); + const connection = withConnectionHost(plugin.connection, undefined); + return { resolve: connection.resolve, verify: connection.verify }; +} diff --git a/src/cli/connection/connect-provider-adapters.ts b/src/cli/connection/connect-provider-adapters.ts index 2928340f66..43391bf3c1 100644 --- a/src/cli/connection/connect-provider-adapters.ts +++ b/src/cli/connection/connect-provider-adapters.ts @@ -1,16 +1,11 @@ import type { CliFlags } from '@agent-device/contracts/command'; -import { requireResolvedProfilePlatform } from '@agent-device/contracts/provider-profile-fields'; import type { ProviderConnectionVerification } from '@agent-device/contracts/remote'; -import { verifyLimrunConnection } from '@agent-device/provider-limrun'; -import { readVersion } from '@agent-device/host-kit/version'; import { leaseBackendForPlatform } from '@agent-device/kernel/contracts'; import { AppError } from '@agent-device/kernel/errors'; import { resolveRemoteConfigProfile } from '@agent-device/remote/remote-config'; import { type EnvMap, type HostEnvironment } from '@agent-device/kernel/source-value'; import { resolveCloudConnectProfile } from './cloud-profile.ts'; -import { resolveLimrunConnectProfile } from './limrun-profile.ts'; -import { readLimrunCredentials } from '../../provider-limrun-credentials.ts'; import { resolveProxyConnectProfile } from './proxy-profile.ts'; import { profileToCliFlags } from '../remote-config-flags.ts'; import { @@ -18,9 +13,10 @@ import { primeProviderConnection, type ConnectProvider, } from './provider-policy.ts'; -import { BUILTIN_PROVIDER_IDS } from '../../builtin-provider-ids.ts'; +import { builtinLimrunConnection } from '../../builtin-provider-plugins.ts'; import { withPluginConnection } from '@agent-device/plugins/load'; import type { PluginConnectionCallbacks } from '@agent-device/plugins/connection'; +import { BUILTIN_PROVIDER_IDS } from '../../builtin-provider-ids.ts'; import { readMetroProfileFields } from './profile-fields.ts'; import { buildConnectClientId } from './client-id.ts'; import { persistAndResolveGeneratedProfile } from './generated-config.ts'; @@ -52,10 +48,12 @@ type ConnectProviderAdapter = { verify(context: Pick): Promise; }; -/** Providers whose profile the CLI composes itself; every other provider supplies connection callbacks. */ -const CONNECT_PROVIDER_ADAPTERS: Readonly< - Record<'cloud' | 'proxy' | 'limrun', ConnectProviderAdapter> -> = { +/** + * The profiles the CLI composes itself: the routing identities answer with a saved connection's + * settings, not a provider's callbacks. Every real provider, built-in or installed, answers `resolve` + * and `verify` through connection callbacks. + */ +const CONNECT_PROVIDER_ADAPTERS: Readonly> = { cloud: { resolve: resolveCloudConnectProfile, verify: async () => ({ @@ -73,10 +71,6 @@ const CONNECT_PROVIDER_ADAPTERS: Readonly< 'Proxy configuration saved. Access is checked by the first remote command.', }), }, - limrun: { - resolve: resolveLimrunConnectProfile, - verify: verifyLimrun, - }, }; function builtinConnectAdapter(provider: string): ConnectProviderAdapter | undefined { @@ -85,13 +79,22 @@ function builtinConnectAdapter(provider: string): ConnectProviderAdapter | undef : undefined; } -/** Runs a provider's connection callbacks from its installed plugin. */ -async function withProviderConnection( +/** + * The connection callbacks one `connect` call runs: the built-in provider's own, composed by the + * root over the provider package's callbacks, or an installed plugin's through the registry. The + * built-in ids stay claimed against the store, so an installed plugin never answers for them. + */ +async function providerConnection( provider: string, - env: EnvMap, - run: (connection: PluginConnectionCallbacks) => Promise, -): Promise { - return await withPluginConnection(provider, BUILTIN_PROVIDER_IDS, env, run); + host: HostEnvironment, +): Promise { + if (provider === 'limrun') return await builtinLimrunConnection(host); + return await withPluginConnection( + provider, + BUILTIN_PROVIDER_IDS, + host.env, + async (connection) => connection, + ); } export async function resolveConnectProviderProfile(options: { @@ -131,10 +134,10 @@ export async function resolveConnectProviderProfile(options: { const adapter = builtinConnectAdapter(provider); const profile = adapter ? await adapter.resolve(context) - : await withProviderConnection( + : await resolveProviderConnectionProfile( provider, - env, - async (connection) => await resolveProviderConnectionProfile(provider, connection, context), + await providerConnection(provider, { env, cwd }), + context, ); return { ...profile, provider }; } @@ -198,23 +201,9 @@ export async function verifyResolvedConnectProvider( cwd: host.cwd, }; const adapter = builtinConnectAdapter(resolved.provider); - return adapter - ? await adapter.verify(context) - : await withProviderConnection( - resolved.provider, - context.env, - async (connection) => await connection.verify(context), - ); -} - -async function verifyLimrun( - context: Pick, -): Promise { - return await verifyLimrunConnection({ - ...readLimrunCredentials(context.env), - clientVersion: readVersion(), - platform: requireResolvedProfilePlatform(context.flags.platform, 'Limrun'), - }); + if (adapter) return await adapter.verify(context); + const connection = await providerConnection(resolved.provider, host); + return await connection.verify(context); } function shouldUseProxyConnectShortcut(flags: CliFlags): boolean { diff --git a/src/cli/connection/limrun-profile.test.ts b/src/cli/connection/limrun-profile.test.ts deleted file mode 100644 index beb6b1a30d..0000000000 --- a/src/cli/connection/limrun-profile.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { afterEach, test, vi } from 'vitest'; -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import { connectCommand } from '../commands/connection.ts'; -import { - readActiveConnectionState, - type RemoteConnectionState, -} from '@agent-device/remote/remote-connection-state'; -import type { AgentDeviceClient } from '@agent-device/command-surface'; -import { verifyLimrunConnection } from '@agent-device/provider-limrun'; -import { - beginStdoutCapture, - bindTestCommandHost, - createTestHostEnvironment, - mkdtempForTestSync, -} from '@agent-device/test-kit'; - -bindTestCommandHost(); - -vi.mock('@agent-device/provider-limrun', async (importOriginal) => ({ - ...(await importOriginal()), - verifyLimrunConnection: vi.fn(), -})); - -afterEach(() => { - vi.clearAllMocks(); - vi.unstubAllEnvs(); -}); - -vi.mocked(verifyLimrunConnection).mockResolvedValue({ - provider: 'limrun', - service: 'Limrun', - verificationMessage: 'Credentials and Android instance access verified.', - device: { status: 'deferred', name: 'Provider-selected Android emulator', platform: 'android' }, - app: { status: 'missing', message: 'Run apps to choose an uploaded asset before allocation.' }, -}); - -test('connect limrun repeated for the same session reuses its connection and profile', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-limrun-repeat-'); - const stateDir = path.join(tempRoot, '.state'); - vi.stubEnv('LIMRUN_API_KEY', 'lim_test_key'); - vi.useFakeTimers({ toFake: ['Date'] }); - const connect = async () => - await captureConnectStdout(async () => { - await connectCommand({ - host: createTestHostEnvironment(), - positionals: ['limrun'], - flags: { - json: true, - help: false, - version: false, - stateDir, - platform: 'android', - session: 'limrun-repeat', - }, - client: {} as AgentDeviceClient, - }); - }); - - try { - vi.setSystemTime(1_000); - await connect(); - const first = readRequiredActiveState(stateDir); - // Time passes between the two connects; the connection identity must not depend on it. - vi.setSystemTime(90_000); - await connect(); - const second = readRequiredActiveState(stateDir); - - assert.equal(second.runId, first.runId); - assert.equal(second.remoteConfigPath, first.remoteConfigPath); - assert.deepEqual(fs.readdirSync(path.join(stateDir, 'remote-connections', 'generated')), [ - path.basename(first.remoteConfigPath), - ]); - } finally { - vi.useRealTimers(); - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - -test('separate unscoped connect limrun calls get separate run ids', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-limrun-unscoped-'); - const stateDir = path.join(tempRoot, '.state'); - vi.stubEnv('LIMRUN_API_KEY', 'lim_test_key'); - const connect = async () => { - await captureConnectStdout(async () => { - await connectCommand({ - host: createTestHostEnvironment(), - positionals: ['limrun'], - flags: { json: true, help: false, version: false, stateDir, platform: 'android' }, - client: {} as AgentDeviceClient, - }); - }); - return readRequiredActiveState(stateDir); - }; - - try { - const first = await connect(); - const second = await connect(); - - assert.notEqual(second.session, first.session); - assert.notEqual(second.runId, first.runId); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - -async function captureConnectStdout(task: () => Promise): Promise { - const stdoutCapture = beginStdoutCapture(); - try { - await task(); - } finally { - stdoutCapture.restore(); - } -} - -function readRequiredActiveState(stateDir: string): RemoteConnectionState { - const state = readActiveConnectionState({ stateDir }); - assert.ok(state); - return state; -} diff --git a/src/cli/connection/limrun-profile.ts b/src/cli/connection/limrun-profile.ts deleted file mode 100644 index db5549261f..0000000000 --- a/src/cli/connection/limrun-profile.ts +++ /dev/null @@ -1,107 +0,0 @@ -import crypto from 'node:crypto'; -import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; -import type { RemoteConfigProfile } from '@agent-device/remote/remote-config-schema'; -import { AppError } from '@agent-device/kernel/errors'; -import type { CliFlags } from '@agent-device/contracts/command'; -import { type EnvMap } from '@agent-device/kernel/source-value'; -import { rejectRefusedProviderProfileFields } from '@agent-device/contracts/provider-profile-fields'; -import { LIMRUN_PROFILE_FIELDS } from '@agent-device/provider-limrun'; -import { readMetroProfileFields } from './profile-fields.ts'; -import { persistAndResolveGeneratedProfile } from './generated-config.ts'; -import { resolveRequestedLeaseBackend } from '../commands/connection-lease-transaction.ts'; -import { - limrunInstanceVariables, - limrunPlatformForLeaseBackend, - readLimrunCredentials, -} from '../../provider-limrun-credentials.ts'; -import { buildConnectClientId } from './client-id.ts'; - -const DEFAULT_LIMRUN_TENANT = 'limrun'; -export function resolveLimrunConnectProfile(options: { - flags: CliFlags; - stateDir: string; - cwd: string; - env: EnvMap; -}): { flags: CliFlags; remoteConfigPath: string } { - const { env } = options; - const profile = buildLimrunRemoteProfile({ flags: options.flags, cwd: options.cwd, env }); - const credentials = readLimrunCredentials(env); - const platform = limrunPlatformForLeaseBackend(profile.leaseBackend) ?? 'android'; - if (!credentials?.apiKey && !credentials?.instances?.[platform]) { - throw new AppError( - 'INVALID_ARGS', - `connect limrun requires LIMRUN_API_KEY, or ${limrunInstanceVariables(platform).join(', ')} for an existing instance.`, - { - hint: 'Set the credentials in the environment before running agent-device connect limrun.', - }, - ); - } - return persistAndResolveGeneratedProfile({ - stateDir: options.stateDir, - provider: 'limrun', - profile, - cwd: options.cwd, - env, - flags: options.flags, - }); -} - -function buildLimrunRemoteProfile(options: { - flags: CliFlags; - cwd: string; - env: EnvMap; -}): RemoteConfigProfile { - const flags = options.flags; - const leaseBackend = validateLimrunConnectFlags(flags); - const daemonPaths = resolveDaemonPaths(flags.stateDir, { - cwd: options.cwd, - env: options.env, - }); - return { - stateDir: daemonPaths.baseDir, - daemonTransport: 'auto', - tenant: flags.tenant ?? DEFAULT_LIMRUN_TENANT, - runId: flags.runId ?? limrunRunId(daemonPaths.baseDir, flags.session), - sessionIsolation: 'tenant', - leaseBackend, - leaseProvider: 'limrun', - platform: flags.platform, - target: 'mobile', - session: flags.session, - // The capture opt-in is read at lease allocation, so it must survive into later commands. - providerNetworkLogs: flags.providerNetworkLogs, - providerNetworkHosts: flags.providerNetworkHosts, - ...readMetroProfileFields(flags), - }; -} - -/** - * A named session reconnects under the same run. An unscoped connect gets a fresh session later in - * `resolveConnectContext`, so it gets a fresh run here rather than one shared by every unscoped call. - */ -function limrunRunId(stateDir: string, session: string | undefined): string { - const identity = session ?? crypto.randomUUID(); - return `limrun-${buildConnectClientId('limrun', stateDir, identity)}`; -} - -function validateLimrunConnectFlags(flags: CliFlags): 'android-instance' | 'ios-instance' { - rejectRefusedProviderProfileFields(flags, LIMRUN_PROFILE_FIELDS); - if (flags.platform !== 'android' && flags.platform !== 'ios') { - throw new AppError('INVALID_ARGS', 'connect limrun requires --platform ios or android.'); - } - if (flags.device !== undefined) { - throw new AppError( - 'INVALID_ARGS', - 'connect limrun does not accept --device; Limrun selects a remote simulator or emulator.', - ); - } - const leaseBackend = resolveRequestedLeaseBackend(flags); - const expectedLeaseBackend = flags.platform === 'ios' ? 'ios-instance' : 'android-instance'; - if (leaseBackend !== expectedLeaseBackend) { - throw new AppError( - 'INVALID_ARGS', - `connect limrun --platform ${flags.platform} requires --lease-backend ${expectedLeaseBackend}.`, - ); - } - return expectedLeaseBackend; -} diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index dfe311db88..e1778f3add 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -27,7 +27,10 @@ type Session = Parameters[0]; export async function createLimrunIosRunner( session: Session, host: HostEnvironment, - appleApplications: AppleApplicationTools, + appleApplications: Pick< + AppleApplicationTools, + 'resolveOpenTarget' | 'applyRuntimeHints' | 'clearRuntimeHints' + >, ): Promise { const { createAppleRunnerRuntime, diff --git a/src/sdk/limrun-runtime-dependencies.ts b/src/sdk/limrun-runtime-dependencies.ts index 5436c33fa6..471650d0e3 100644 --- a/src/sdk/limrun-runtime-dependencies.ts +++ b/src/sdk/limrun-runtime-dependencies.ts @@ -129,7 +129,13 @@ export function createLimrunRuntimeDependencies(host: HostEnvironment): LimrunRu await import('../core/interactors/limrun-ios-runner.ts'); const { createAppleApplicationTools } = await import('../platform-runtime-apple-application-tools.ts'); - return createLimrunIosRunner(session, host, createAppleApplicationTools(host.env)); + const { resolveOpenTarget, applyRuntimeHints, clearRuntimeHints } = + createAppleApplicationTools(host.env); + return createLimrunIosRunner(session, host, { + resolveOpenTarget, + applyRuntimeHints, + clearRuntimeHints, + }); }, readBundleAppName: async (appPath) => { const { readIosBundleInfo } =