From bf240717ad2cfb3334e30f7c9ba612ffc98aec24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 00:33:49 +0100 Subject: [PATCH 1/8] refactor(limrun): add transitional v2 plugin factory and move credentials to the provider package Issue #3311. Builds on #4720 (provider-plugin host). - Add packages/provider-limrun/src/plugin.ts: the single transitional limrunPlugin(options) factory. Its setup reads credentials, builds runtime dependencies through the injected plugin host, and loads the runtime with the platform module; its credentials declaration keeps per-backend fingerprint narrowing. - Move the credential reader and declaration from src/provider-limrun-credentials.ts to packages/provider-limrun/src/credentials.ts so the provider package owns credential interpretation. - Expose the factory through the new lazy, SDK-free @agent-device/provider-limrun/internal entry; the built-in candidate in src/builtin-provider-plugins.ts composes the factory with the root-owned runtime dependencies and state paths, preserving dormant/failed/active candidate semantics. - Rewire src/cli/connection and the daemon credential test to the internal entry; drop the migrated root-module-zone row; update the boundary and dependency pins, package manifests, and lockfile. --- .fallowrc.json | 5 + packages/provider-limrun/package.json | 7 +- .../provider-limrun/src/credentials.test.ts | 2 +- .../provider-limrun/src/credentials.ts | 31 ++-- packages/provider-limrun/src/index.ts | 1 - packages/provider-limrun/src/internal.ts | 12 ++ packages/provider-limrun/src/plugin.test.ts | 157 ++++++++++++++++++ packages/provider-limrun/src/plugin.ts | 81 +++++++++ packages/provider-limrun/tsconfig.json | 3 + pnpm-lock.yaml | 3 + scripts/layering/package-boundaries.test.ts | 3 +- scripts/layering/root-module-zones.ts | 1 - ...daemon-client-provider-credentials.test.ts | 2 +- src/builtin-provider-plugins.test.ts | 97 +++++++++++ src/builtin-provider-plugins.ts | 55 +++--- .../connection/connect-provider-adapters.ts | 2 +- src/cli/connection/limrun-profile.ts | 2 +- 17 files changed, 402 insertions(+), 62 deletions(-) rename src/provider-limrun-credentials.test.ts => packages/provider-limrun/src/credentials.test.ts (96%) rename src/provider-limrun-credentials.ts => packages/provider-limrun/src/credentials.ts (79%) create mode 100644 packages/provider-limrun/src/internal.ts create mode 100644 packages/provider-limrun/src/plugin.test.ts create mode 100644 packages/provider-limrun/src/plugin.ts create mode 100644 src/builtin-provider-plugins.test.ts diff --git a/.fallowrc.json b/.fallowrc.json index eb98ee2f06..62a12d21c7 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -378,6 +378,11 @@ "summarizeAgentBrowserProcesses" ] }, + { + // LIMRUN_CREDENTIAL_VARIABLES is consumed only by src/__tests__/daemon-client-provider-credentials.test.ts, which unsets every credential variable between provider-credential cases; --production analysis does not see test-tree consumers. + "file": "packages/provider-limrun/src/internal.ts", + "exports": ["LIMRUN_CREDENTIAL_VARIABLES"] + }, { // Web process matching helpers are retained for package-owned lifecycle tests; production export analysis does not traverse those test consumers. "file": "packages/platform-web/src/agent-browser-lifecycle.ts", 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/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 79% rename from src/provider-limrun-credentials.ts rename to packages/provider-limrun/src/credentials.ts index 8458acc489..21b86ab944 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 { platformForLimrunLeaseBackend, 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; @@ -29,42 +29,37 @@ export const LIMRUN_CREDENTIAL_VARIABLES: readonly string[] = [ ...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); +): LimrunPlatform | undefined { + return leaseBackend === undefined ? undefined : platformForLimrunLeaseBackend(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]; } diff --git a/packages/provider-limrun/src/index.ts b/packages/provider-limrun/src/index.ts index fa58f02799..13438e53d6 100644 --- a/packages/provider-limrun/src/index.ts +++ b/packages/provider-limrun/src/index.ts @@ -1,6 +1,5 @@ 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..d83be39218 --- /dev/null +++ b/packages/provider-limrun/src/internal.ts @@ -0,0 +1,12 @@ +/** + * 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 verification each load when + * their own path asks for them. The root entry keeps the SDK-side surface. + */ +export { limrunPlugin } from './plugin.ts'; +export { + LIMRUN_CREDENTIAL_VARIABLES, + limrunInstanceVariables, + limrunPlatformForLeaseBackend, + 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..936ecfebfe --- /dev/null +++ b/packages/provider-limrun/src/plugin.test.ts @@ -0,0 +1,157 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { 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 }[], +})); + +// 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 () => ({}), + }, + }; + }, +})); + +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('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..5749acc573 --- /dev/null +++ b/packages/provider-limrun/src/plugin.ts @@ -0,0 +1,81 @@ +import path from 'node:path'; +import type { AgentDevicePlugin } from '@agent-device/plugins/contract'; +import type { ProviderPluginHost } from '@agent-device/plugins/host'; +import { AppError } from '@agent-device/kernel/errors'; +import { + limrunCredentialDeclaration, + readLimrunCredentials, + type LimrunCredentials, +} from './credentials.ts'; +import { 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 or fingerprint the provider: the runtime and its host adapters load in `setup`. + */ +export function limrunPlugin(options: LimrunPluginOptions): AgentDevicePlugin { + const { createDependencies, stateDir } = options; + return { + apiVersion: 2, + provider: LIMRUN_PROVIDER, + credentials: limrunCredentialDeclaration(), + 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 }, + ); + }, + }; +} + +/** + * The credentials this host's environment holds, refusing the shapes a runtime cannot act on: + * nothing at all, or an instance set missing one of its variables. + */ +function requireLimrunCredentials(env: Record): 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.', + }, + ); +} 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__/daemon-client-provider-credentials.test.ts b/src/__tests__/daemon-client-provider-credentials.test.ts index 676321631d..e74df3b3ab 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 { LIMRUN_CREDENTIAL_VARIABLES } from '@agent-device/provider-limrun/internal'; import { readDaemonProviderCredentials } from '../provider-credential-fingerprint.ts'; const inventory = await builtinPluginInventory(); diff --git a/src/builtin-provider-plugins.test.ts b/src/builtin-provider-plugins.test.ts new file mode 100644 index 0000000000..f343243ca8 --- /dev/null +++ b/src/builtin-provider-plugins.test.ts @@ -0,0 +1,97 @@ +import assert from 'node:assert/strict'; +import { test, vi } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { createEmbeddedProviderRuntimeComposition } from './provider-device-runtimes.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. +vi.mock('@limrun/api', () => ({ + default: class MockLimrun { + readonly iosInstances = { create: vi.fn(), list: vi.fn(), delete: vi.fn() }; + readonly androidInstances = { create: vi.fn(), list: vi.fn(), delete: vi.fn() }; + readonly assets = { list: vi.fn(async () => []) }; + }, +})); + +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(); + } +}); diff --git a/src/builtin-provider-plugins.ts b/src/builtin-provider-plugins.ts index d64bd8c402..283ba18b98 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -2,13 +2,8 @@ import type { AgentDevicePlugin } from '@agent-device/plugins/contract'; import type { PluginCandidate } from '@agent-device/plugins/registry'; 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, - readLimrunCredentials, - type LimrunCredentials, -} from './provider-limrun-credentials.ts'; +import { limrunPlugin, readLimrunCredentials } from '@agent-device/provider-limrun/internal'; /** * The built-in providers as registry candidates, in the shape a plugin has. Their implementations @@ -21,41 +16,29 @@ 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({ + // 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, + }), }; } diff --git a/src/cli/connection/connect-provider-adapters.ts b/src/cli/connection/connect-provider-adapters.ts index 2928340f66..72644b27b6 100644 --- a/src/cli/connection/connect-provider-adapters.ts +++ b/src/cli/connection/connect-provider-adapters.ts @@ -10,7 +10,7 @@ import { type EnvMap, type HostEnvironment } from '@agent-device/kernel/source-v import { resolveCloudConnectProfile } from './cloud-profile.ts'; import { resolveLimrunConnectProfile } from './limrun-profile.ts'; -import { readLimrunCredentials } from '../../provider-limrun-credentials.ts'; +import { readLimrunCredentials } from '@agent-device/provider-limrun/internal'; import { resolveProxyConnectProfile } from './proxy-profile.ts'; import { profileToCliFlags } from '../remote-config-flags.ts'; import { diff --git a/src/cli/connection/limrun-profile.ts b/src/cli/connection/limrun-profile.ts index db5549261f..2be12b3757 100644 --- a/src/cli/connection/limrun-profile.ts +++ b/src/cli/connection/limrun-profile.ts @@ -13,7 +13,7 @@ import { limrunInstanceVariables, limrunPlatformForLeaseBackend, readLimrunCredentials, -} from '../../provider-limrun-credentials.ts'; +} from '@agent-device/provider-limrun/internal'; import { buildConnectClientId } from './client-id.ts'; const DEFAULT_LIMRUN_TENANT = 'limrun'; From 4af273492bf21e785e501eac2446b2a2250813c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 01:16:15 +0100 Subject: [PATCH 2/8] test(limrun): read credential names from plugin inventory --- .fallowrc.json | 5 ----- packages/provider-limrun/src/credentials.ts | 2 +- packages/provider-limrun/src/internal.ts | 1 - src/__tests__/daemon-client-provider-credentials.test.ts | 6 ++++-- 4 files changed, 5 insertions(+), 9 deletions(-) diff --git a/.fallowrc.json b/.fallowrc.json index 62a12d21c7..eb98ee2f06 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -378,11 +378,6 @@ "summarizeAgentBrowserProcesses" ] }, - { - // LIMRUN_CREDENTIAL_VARIABLES is consumed only by src/__tests__/daemon-client-provider-credentials.test.ts, which unsets every credential variable between provider-credential cases; --production analysis does not see test-tree consumers. - "file": "packages/provider-limrun/src/internal.ts", - "exports": ["LIMRUN_CREDENTIAL_VARIABLES"] - }, { // Web process matching helpers are retained for package-owned lifecycle tests; production export analysis does not traverse those test consumers. "file": "packages/platform-web/src/agent-browser-lifecycle.ts", diff --git a/packages/provider-limrun/src/credentials.ts b/packages/provider-limrun/src/credentials.ts index 21b86ab944..acf4dc1681 100644 --- a/packages/provider-limrun/src/credentials.ts +++ b/packages/provider-limrun/src/credentials.ts @@ -23,7 +23,7 @@ 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, diff --git a/packages/provider-limrun/src/internal.ts b/packages/provider-limrun/src/internal.ts index d83be39218..882ce93663 100644 --- a/packages/provider-limrun/src/internal.ts +++ b/packages/provider-limrun/src/internal.ts @@ -5,7 +5,6 @@ */ export { limrunPlugin } from './plugin.ts'; export { - LIMRUN_CREDENTIAL_VARIABLES, limrunInstanceVariables, limrunPlatformForLeaseBackend, readLimrunCredentials, diff --git a/src/__tests__/daemon-client-provider-credentials.test.ts b/src/__tests__/daemon-client-provider-credentials.test.ts index e74df3b3ab..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 '@agent-device/provider-limrun/internal'; +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( From e886714d90b82ff94371f054655018a482e0724d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 09:17:27 +0100 Subject: [PATCH 3/8] style(limrun): format the reconciled factory call --- src/builtin-provider-plugins.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/builtin-provider-plugins.ts b/src/builtin-provider-plugins.ts index 283ba18b98..d8a8bb226f 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -32,7 +32,9 @@ function limrunCandidate(host: HostEnvironment): PluginCandidate { // 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), + (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, { From 01ea44f303c026fd9f439999f3d8faf7a567fb6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 05:56:03 +0100 Subject: [PATCH 4/8] refactor(limrun): route the built-in connect through the provider's own v2 connection callbacks Move the connect decisions into one provider-owned set of callbacks: the connect-flag refusals (including --device), the per-platform credential narrowing, the connection capabilities, and the verification read-only check now live in the provider package's connection module, which the plugin declares lazily. The CLI composition drops its hand-written Limrun adapter and runs the same callbacks through the plugin shape, wired to the host the way the daemon's registry wires an installed plugin's, so both answers come from the provider. The profile fields the host owns stay with the host: tenant, session, run identity, state dir, and Metro settings. --- packages/plugins/src/registry.ts | 7 +- .../provider-limrun/src/connection.test.ts | 152 ++++++++++++++++++ packages/provider-limrun/src/connection.ts | 143 ++++++++++++++++ packages/provider-limrun/src/credentials.ts | 26 ++- packages/provider-limrun/src/device.ts | 17 ++ packages/provider-limrun/src/index.ts | 1 - packages/provider-limrun/src/internal.ts | 12 +- packages/provider-limrun/src/plugin.test.ts | 69 ++++++++ packages/provider-limrun/src/plugin.ts | 55 ++++--- .../cloud-connect-profile-fields.test.ts | 50 +++--- src/__tests__/cloud-connect-profile.test.ts | 69 ++++++++ src/builtin-provider-ids.ts | 21 +-- src/builtin-provider-plugins.test.ts | 33 ++++ src/builtin-provider-plugins.ts | 70 ++++++-- .../connection/connect-provider-adapters.ts | 69 ++++---- src/cli/connection/limrun-profile.test.ts | 121 -------------- src/cli/connection/limrun-profile.ts | 107 ------------ 17 files changed, 655 insertions(+), 367 deletions(-) create mode 100644 packages/provider-limrun/src/connection.test.ts create mode 100644 packages/provider-limrun/src/connection.ts delete mode 100644 src/cli/connection/limrun-profile.test.ts delete mode 100644 src/cli/connection/limrun-profile.ts 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/src/connection.test.ts b/packages/provider-limrun/src/connection.test.ts new file mode 100644 index 0000000000..90ecc28e70 --- /dev/null +++ b/packages/provider-limrun/src/connection.test.ts @@ -0,0 +1,152 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import type { PluginConnectionContext } from '@agent-device/plugins/contract'; +import { AppError } from '@agent-device/kernel/errors'; +import { createLimrunConnection } from './connection.ts'; +import { LIMRUN_CONNECTION_CAPABILITIES } from './device.ts'; + +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, + 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 an unscoped connect a run of its own and leaves identity to the host', 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); + + // A named session reconnects under the run the host derives from that session, and a run the + // caller passed is theirs to share; neither is the provider's to name. + assert.equal((await resolve({ platform: 'android', session: 'ci' })).profile.runId, undefined); + assert.equal((await resolve({ platform: 'android', runId: 'run-a' })).profile.runId, undefined); +}); diff --git a/packages/provider-limrun/src/connection.ts b/packages/provider-limrun/src/connection.ts new file mode 100644 index 0000000000..fe451c6306 --- /dev/null +++ b/packages/provider-limrun/src/connection.ts @@ -0,0 +1,143 @@ +import crypto from 'node:crypto'; +import type { + ProviderConnectionVerification, + 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'; +import type { LimrunConnectionVerificationOptions } from './connection-verification.ts'; + +/** The flags and environment one `connect` call gives the provider. */ +type ConnectContext = Pick; + +/** + * The read-only account or instance check `verify` performs. The provider's own verification fills + * this in; the composing root may name the entry it reads verification through, the same way it + * supplies the runtime's host adapters. + */ +export type LimrunConnectionVerifier = ( + options: LimrunConnectionVerificationOptions, +) => Promise; + +/** 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 Limrun SDK 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. + */ +export function createLimrunConnection( + options: Readonly<{ verify?: LimrunConnectionVerifier }> = {}, +): LimrunConnection { + const verify: LimrunConnectionVerifier = + options.verify ?? + (async (verificationOptions) => + await ( + await import('./connection-verification.ts') + ).verifyLimrunConnection(verificationOptions)); + return { + capabilities: LIMRUN_CONNECTION_CAPABILITIES, + resolve: (context) => ({ profile: limrunConnectProfile(context) }), + verify: async ({ flags, env, host }) => + await verify({ + ...requireLimrunCredentials(env), + clientVersion: host.clientVersion, + platform: requireResolvedProfilePlatform(flags.platform, 'Limrun'), + }), + }; +} + +/** + * The profile Limrun contributes to a connection; the host owns the identity written around it. + * Limrun serves a local daemon through its own tunnel, and both the instance and its app are chosen + * after connect, so the profile fixes those axes instead of carrying over selections that cannot + * apply to them. A named session keeps the run the host derives from that session, which is what + * lets a reconnect reuse its connection; an unscoped connect resolves its own session after this + * call, so it gets a run of its own rather than one shared by every unscoped connect. + */ +function limrunConnectProfile(context: ConnectContext): RemoteConfigProfile { + const { flags, env } = 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, + ...(flags.runId === undefined && flags.session === undefined + ? { runId: `limrun-${crypto.randomBytes(8).toString('hex')}` } + : {}), + // The capture opt-in is read at lease allocation, so it must survive into later commands. + providerNetworkLogs: flags.providerNetworkLogs, + providerNetworkHosts: flags.providerNetworkHosts, + }; +} + +/** + * 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/packages/provider-limrun/src/credentials.ts b/packages/provider-limrun/src/credentials.ts index acf4dc1681..35d6ae24e9 100644 --- a/packages/provider-limrun/src/credentials.ts +++ b/packages/provider-limrun/src/credentials.ts @@ -1,6 +1,6 @@ import { AppError } from '@agent-device/kernel/errors'; import type { EnvMap } from '@agent-device/kernel/source-value'; -import { platformForLimrunLeaseBackend, type LimrunPlatform } from './device.ts'; +import type { LimrunPlatform } from './device.ts'; import type { LimrunInstanceAccess } from './instance-access.ts'; /** The Limrun account and instance facts one host gives the provider. */ @@ -29,13 +29,6 @@ const LIMRUN_CREDENTIAL_VARIABLES: readonly string[] = [ ...INSTANCE_VARS.android, ]; -/** The platform whose instance a Limrun lease backend reaches. */ -export function limrunPlatformForLeaseBackend( - leaseBackend: string | undefined, -): LimrunPlatform | undefined { - return leaseBackend === undefined ? undefined : platformForLimrunLeaseBackend(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. The per-backend narrowing @@ -63,6 +56,23 @@ export function limrunInstanceVariables(platform: LimrunPlatform): readonly stri 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 13438e53d6..2b073668f0 100644 --- a/packages/provider-limrun/src/index.ts +++ b/packages/provider-limrun/src/index.ts @@ -1,4 +1,3 @@ -export { LIMRUN_PROFILE_FIELDS } from './device.ts'; export { createLimrunRuntime, type LimrunRuntimeOptions } from './runtime.ts'; export { verifyLimrunConnection } from './connection-verification.ts'; diff --git a/packages/provider-limrun/src/internal.ts b/packages/provider-limrun/src/internal.ts index 882ce93663..f36424ad53 100644 --- a/packages/provider-limrun/src/internal.ts +++ b/packages/provider-limrun/src/internal.ts @@ -1,11 +1,9 @@ /** * 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 verification each load when + * 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 } from './plugin.ts'; -export { - limrunInstanceVariables, - limrunPlatformForLeaseBackend, - readLimrunCredentials, -} from './credentials.ts'; +export { limrunPlugin, type LimrunPluginOptions } from './plugin.ts'; +export { LIMRUN_CONNECTION_CAPABILITIES } from './device.ts'; +export { readLimrunCredentials } from './credentials.ts'; +export type { LimrunConnectionVerifier } from './connection.ts'; diff --git a/packages/provider-limrun/src/plugin.test.ts b/packages/provider-limrun/src/plugin.test.ts index 936ecfebfe..60e3a4f782 100644 --- a/packages/provider-limrun/src/plugin.test.ts +++ b/packages/provider-limrun/src/plugin.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import path from 'node:path'; import { test, vi } from 'vitest'; import type { ProviderPluginHost } from '@agent-device/plugins/host'; +import type { ProviderConnectionVerification } from '@agent-device/contracts/remote'; import { AppError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts'; @@ -82,6 +83,74 @@ test('the plugin declares its provider and the credential variables per lease ba }); }); +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('a composed verifier answers verify in place of the provider SDK check', async () => { + const seen: Array> = []; + const verify = vi.fn( + async (options: Record): Promise => { + seen.push(options); + return { + provider: 'limrun', + service: 'Limrun', + verificationMessage: 'verified by the composing root', + device: { + status: 'deferred', + name: 'Provider-selected Android emulator', + platform: 'android', + }, + app: { + status: 'missing', + message: 'Run apps to choose an uploaded asset before allocation.', + }, + }; + }, + ); + const plugin = limrunPlugin({ + createDependencies: () => stubDependencies(), + verifyConnection: verify, + }); + + const verification = await plugin.connection?.verify({ + flags: { json: false, help: false, version: false, platform: 'ios' }, + env: { LIMRUN_API_KEY: 'lim_test_key' }, + host: pluginHost({ LIMRUN_API_KEY: 'lim_test_key' }), + }); + + assert.equal(verification?.verificationMessage, 'verified by the composing root'); + // The provider hands the verifier its full credential read, the host's version, and the platform. + assert.deepEqual(seen, [ + { + apiKey: 'lim_test_key', + region: undefined, + keepAlive: false, + instances: undefined, + clientVersion: '1.2.3', + platform: 'ios', + }, + ]); + assert.equal(verify.mock.calls.length, 1); +}); + 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(); diff --git a/packages/provider-limrun/src/plugin.ts b/packages/provider-limrun/src/plugin.ts index 5749acc573..4bfaa75ecd 100644 --- a/packages/provider-limrun/src/plugin.ts +++ b/packages/provider-limrun/src/plugin.ts @@ -1,13 +1,9 @@ import path from 'node:path'; import type { AgentDevicePlugin } from '@agent-device/plugins/contract'; import type { ProviderPluginHost } from '@agent-device/plugins/host'; -import { AppError } from '@agent-device/kernel/errors'; -import { - limrunCredentialDeclaration, - readLimrunCredentials, - type LimrunCredentials, -} from './credentials.ts'; -import { LIMRUN_PROVIDER } from './device.ts'; +import { limrunCredentialDeclaration, requireLimrunCredentials } from './credentials.ts'; +import type { LimrunConnectionVerifier } from './connection.ts'; +import { LIMRUN_CONNECTION_CAPABILITIES, LIMRUN_PROVIDER } from './device.ts'; import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts'; export type LimrunPluginOptions = Readonly<{ @@ -24,6 +20,12 @@ export type LimrunPluginOptions = Readonly<{ * beside the session files under it; without it the capture is unavailable. */ stateDir?: string; + /** + * Replaces the read-only check `connection.verify` performs. The provider's own verification is + * the default; the composing root names the entry it reads verification through when it already + * owns one, the same way it supplies the runtime's host adapters. + */ + verifyConnection?: LimrunConnectionVerifier; }>; /** @@ -32,14 +34,32 @@ export type LimrunPluginOptions = Readonly<{ * * 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 or fingerprint the provider: the runtime and its host adapters load in `setup`. + * 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 { - const { createDependencies, stateDir } = options; + const { createDependencies, stateDir, verifyConnection } = 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({ verify: verifyConnection }) + .resolve(context), + verify: async (context) => + await ( + await import('./connection.ts') + ) + .createLimrunConnection({ verify: verifyConnection }) + .verify(context), + }, setup: async (host) => { const credentials = requireLimrunCredentials(host.env); const [register, dependencies] = await Promise.all([ @@ -62,20 +82,3 @@ export function limrunPlugin(options: LimrunPluginOptions): AgentDevicePlugin { }, }; } - -/** - * The credentials this host's environment holds, refusing the shapes a runtime cannot act on: - * nothing at all, or an instance set missing one of its variables. - */ -function requireLimrunCredentials(env: Record): 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.', - }, - ); -} 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..35def21500 100644 --- a/src/__tests__/cloud-connect-profile.test.ts +++ b/src/__tests__/cloud-connect-profile.test.ts @@ -243,6 +243,75 @@ test('connect limrun persists deferred Metro bridge settings', async () => { } }); +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 }); + } +}); + 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'); 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 index f343243ca8..a0a693629f 100644 --- a/src/builtin-provider-plugins.test.ts +++ b/src/builtin-provider-plugins.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import { test, vi } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; 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. @@ -95,3 +96,35 @@ test('a configured built-in Limrun registers through the plugin contract with it await composition.shutdown(); } }); + +test('the built-in connection answers connect with the provider callbacks and the root verifier', 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); + // `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'); + + // `verify` reaches the SDK through the root's published verification entry and runs the + // read-only account check the stubbed SDK above answers; no instance is created. + 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.', + ); +}); diff --git a/src/builtin-provider-plugins.ts b/src/builtin-provider-plugins.ts index d8a8bb226f..d560b0b82d 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -1,9 +1,15 @@ 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 { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; -import { limrunPlugin, readLimrunCredentials } from '@agent-device/provider-limrun/internal'; +import { + limrunPlugin, + readLimrunCredentials, + type LimrunConnectionVerifier, + type LimrunPluginOptions, +} from '@agent-device/provider-limrun/internal'; /** * The built-in providers as registry candidates, in the shape a plugin has. Their implementations @@ -27,20 +33,52 @@ function limrunCandidate(host: HostEnvironment): PluginCandidate { if (!configured) return { ...base, dormant: true, load: () => undefined }; return { ...base, - load: (): AgentDevicePlugin => - limrunPlugin({ - // 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, - }), + 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. The optional verifier replaces the connection's read-only check, so + * the root can route it through an entry it already owns. + */ +function builtinLimrunPluginOptions( + host: HostEnvironment, + verifyConnection?: LimrunConnectionVerifier, +): 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, + ...(verifyConnection === undefined ? {} : { verifyConnection }), + }; +} + +/** + * 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 verification is the root's published entry, so the same read-only check answers for both. + */ +export async function builtinLimrunConnection( + host: HostEnvironment, +): Promise { + const [{ withConnectionHost }, { verifyLimrunConnection }] = await Promise.all([ + import('@agent-device/plugins/registry'), + import('@agent-device/provider-limrun'), + ]); + const plugin = limrunPlugin( + builtinLimrunPluginOptions(host, async (options) => await verifyLimrunConnection(options)), + ); + if (!plugin.connection) { + throw new Error('The built-in Limrun plugin declares no connection.'); + } + 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 72644b27b6..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 '@agent-device/provider-limrun/internal'; 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 2be12b3757..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 '@agent-device/provider-limrun/internal'; -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; -} From 6eb0a2a22650e3f989fbcc61c1ffbde93c8a274f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 06:28:06 +0100 Subject: [PATCH 5/8] fix(limrun): retain saved named-session identity --- .../provider-limrun/src/connection.test.ts | 8 +++---- packages/provider-limrun/src/connection.ts | 24 +++++++++---------- src/__tests__/cloud-connect-profile.test.ts | 12 ++++++---- 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/packages/provider-limrun/src/connection.test.ts b/packages/provider-limrun/src/connection.test.ts index 90ecc28e70..972762802e 100644 --- a/packages/provider-limrun/src/connection.test.ts +++ b/packages/provider-limrun/src/connection.test.ts @@ -70,6 +70,7 @@ test('resolve names the platform, its lease backend, and the capture opt-in it c leaseProvider: 'limrun', platform: 'ios', clientId: undefined, + runId: 'limrun-803cad858538d077', providerNetworkLogs: true, providerNetworkHosts: 'api.example', }); @@ -139,14 +140,11 @@ test('resolve reads the refused profile fields before the credentials or the pla ); }); -test('resolve gives an unscoped connect a run of its own and leaves identity to the host', async () => { +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); - // A named session reconnects under the run the host derives from that session, and a run the - // caller passed is theirs to share; neither is the provider's to name. - assert.equal((await resolve({ platform: 'android', session: 'ci' })).profile.runId, undefined); - assert.equal((await resolve({ platform: 'android', runId: 'run-a' })).profile.runId, undefined); + assert.equal((await resolve({ platform: 'android', runId: 'run-a' })).profile.runId, 'run-a'); }); diff --git a/packages/provider-limrun/src/connection.ts b/packages/provider-limrun/src/connection.ts index fe451c6306..8e032c882f 100644 --- a/packages/provider-limrun/src/connection.ts +++ b/packages/provider-limrun/src/connection.ts @@ -24,7 +24,7 @@ import { import type { LimrunConnectionVerificationOptions } from './connection-verification.ts'; /** The flags and environment one `connect` call gives the provider. */ -type ConnectContext = Pick; +type ConnectContext = Pick; /** * The read-only account or instance check `verify` performs. The provider's own verification fills @@ -65,16 +65,9 @@ export function createLimrunConnection( }; } -/** - * The profile Limrun contributes to a connection; the host owns the identity written around it. - * Limrun serves a local daemon through its own tunnel, and both the instance and its app are chosen - * after connect, so the profile fixes those axes instead of carrying over selections that cannot - * apply to them. A named session keeps the run the host derives from that session, which is what - * lets a reconnect reuse its connection; an unscoped connect resolves its own session after this - * call, so it gets a run of its own rather than one shared by every unscoped connect. - */ +/** The transport, lease and capture settings that Limrun adds to the saved profile. */ function limrunConnectProfile(context: ConnectContext): RemoteConfigProfile { - const { flags, env } = context; + const { flags, env, stateDir } = context; rejectRefusedProviderProfileFields(flags, LIMRUN_PROFILE_FIELDS); const leaseBackend = requireLimrunLeaseBackend(flags); const platform = leaseBackend === 'ios-instance' ? 'ios' : 'android'; @@ -89,15 +82,20 @@ function limrunConnectProfile(context: ConnectContext): RemoteConfigProfile { // 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, - ...(flags.runId === undefined && flags.session === undefined - ? { runId: `limrun-${crypto.randomBytes(8).toString('hex')}` } - : {}), + 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. diff --git a/src/__tests__/cloud-connect-profile.test.ts b/src/__tests__/cloud-connect-profile.test.ts index 35def21500..dfd85215c2 100644 --- a/src/__tests__/cloud-connect-profile.test.ts +++ b/src/__tests__/cloud-connect-profile.test.ts @@ -3,6 +3,7 @@ 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 { @@ -243,12 +244,14 @@ test('connect limrun persists deferred Metro bridge settings', async () => { } }); -test('connect limrun repeated for the same session reuses its connection and profile', 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 connect = async () => + const session = 'limrun-repeat'; + const savedRunId = `limrun-${buildConnectClientId('limrun', stateDir, session)}`; + const connect = async (runId?: string) => await captureConnectStdout(async () => { await connectCommand({ host: createTestHostEnvironment(), @@ -259,7 +262,8 @@ test('connect limrun repeated for the same session reuses its connection and pro version: false, stateDir, platform: 'android', - session: 'limrun-repeat', + session, + ...(runId === undefined ? {} : { runId }), }, client: {} as AgentDeviceClient, }); @@ -267,7 +271,7 @@ test('connect limrun repeated for the same session reuses its connection and pro try { vi.setSystemTime(1_000); - await connect(); + 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); From d0dd8f0891f4e6628d7e4865964d93b9b006f7cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 07:53:37 +0100 Subject: [PATCH 6/8] refactor(limrun): keep the connection's verification inside the provider The built-in `connect` composed its provider's callbacks through the provider package's root entry just to inject that provider's own read-only check, which evaluated the runtime the composition was meant to keep lazy, and let a caller replace a verification it does not own. The connection now loads the provider's own verification in the `verify` path alone, so the built-in and an installed plugin answer with the same entry and nothing above the connection decides what it verifies through; the plugin option, the verifier type, and the root's verification export go with it. The suites read the Limrun SDK boundary instead of the provider package, so they assert what the account or the attached instance is asked for: the scoped credentials, the host's version, and the selected platform, with no runtime set up on `connect`. --- .../provider-limrun/src/connection.test.ts | 136 +++++++++++++++++- packages/provider-limrun/src/connection.ts | 34 ++--- packages/provider-limrun/src/index.ts | 1 - packages/provider-limrun/src/internal.ts | 1 - packages/provider-limrun/src/plugin.test.ts | 76 +++++----- packages/provider-limrun/src/plugin.ts | 21 +-- src/__tests__/cloud-connect-profile.test.ts | 88 ++++++++---- src/builtin-provider-plugins.test.ts | 88 +++++++++++- src/builtin-provider-plugins.ts | 22 +-- 9 files changed, 330 insertions(+), 137 deletions(-) diff --git a/packages/provider-limrun/src/connection.test.ts b/packages/provider-limrun/src/connection.test.ts index 972762802e..d64ced10cf 100644 --- a/packages/provider-limrun/src/connection.test.ts +++ b/packages/provider-limrun/src/connection.test.ts @@ -1,10 +1,52 @@ import assert from 'node:assert/strict'; -import { test } from 'vitest'; +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', @@ -148,3 +190,95 @@ test('resolve gives each unscoped connect a run and preserves an explicit run', 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 index 8e032c882f..545896c9e9 100644 --- a/packages/provider-limrun/src/connection.ts +++ b/packages/provider-limrun/src/connection.ts @@ -1,8 +1,5 @@ import crypto from 'node:crypto'; -import type { - ProviderConnectionVerification, - RemoteConfigProfile, -} from '@agent-device/contracts/remote'; +import type { RemoteConfigProfile } from '@agent-device/contracts/remote'; import type { PluginConnection, PluginConnectionContext } from '@agent-device/plugins/contract'; import { rejectRefusedProviderProfileFields, @@ -21,43 +18,28 @@ import { LIMRUN_PROVIDER, type LimrunPlatform, } from './device.ts'; -import type { LimrunConnectionVerificationOptions } from './connection-verification.ts'; /** The flags and environment one `connect` call gives the provider. */ type ConnectContext = Pick; -/** - * The read-only account or instance check `verify` performs. The provider's own verification fills - * this in; the composing root may name the entry it reads verification through, the same way it - * supplies the runtime's host adapters. - */ -export type LimrunConnectionVerifier = ( - options: LimrunConnectionVerificationOptions, -) => Promise; - /** 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 Limrun SDK 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. + * `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( - options: Readonly<{ verify?: LimrunConnectionVerifier }> = {}, -): LimrunConnection { - const verify: LimrunConnectionVerifier = - options.verify ?? - (async (verificationOptions) => - await ( - await import('./connection-verification.ts') - ).verifyLimrunConnection(verificationOptions)); +export function createLimrunConnection(): LimrunConnection { return { capabilities: LIMRUN_CONNECTION_CAPABILITIES, resolve: (context) => ({ profile: limrunConnectProfile(context) }), verify: async ({ flags, env, host }) => - await verify({ + await ( + await import('./connection-verification.ts') + ).verifyLimrunConnection({ ...requireLimrunCredentials(env), clientVersion: host.clientVersion, platform: requireResolvedProfilePlatform(flags.platform, 'Limrun'), diff --git a/packages/provider-limrun/src/index.ts b/packages/provider-limrun/src/index.ts index 2b073668f0..5d05533253 100644 --- a/packages/provider-limrun/src/index.ts +++ b/packages/provider-limrun/src/index.ts @@ -1,4 +1,3 @@ export { createLimrunRuntime, type LimrunRuntimeOptions } from './runtime.ts'; -export { verifyLimrunConnection } from './connection-verification.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 index f36424ad53..c1321e484e 100644 --- a/packages/provider-limrun/src/internal.ts +++ b/packages/provider-limrun/src/internal.ts @@ -6,4 +6,3 @@ export { limrunPlugin, type LimrunPluginOptions } from './plugin.ts'; export { LIMRUN_CONNECTION_CAPABILITIES } from './device.ts'; export { readLimrunCredentials } from './credentials.ts'; -export type { LimrunConnectionVerifier } from './connection.ts'; diff --git a/packages/provider-limrun/src/plugin.test.ts b/packages/provider-limrun/src/plugin.test.ts index 60e3a4f782..f85f9da75a 100644 --- a/packages/provider-limrun/src/plugin.test.ts +++ b/packages/provider-limrun/src/plugin.test.ts @@ -1,8 +1,7 @@ import assert from 'node:assert/strict'; import path from 'node:path'; -import { test, vi } from 'vitest'; +import { afterEach, test, vi } from 'vitest'; import type { ProviderPluginHost } from '@agent-device/plugins/host'; -import type { ProviderConnectionVerification } from '@agent-device/contracts/remote'; import { AppError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts'; @@ -11,6 +10,9 @@ 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 @@ -35,6 +37,25 @@ vi.mock('./runtime.ts', () => ({ }, })); +// 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, @@ -104,51 +125,32 @@ test('the plugin declares the connection callbacks without setting up any runtim assert.equal(sdk.runtimeCalls.length, 0); }); -test('a composed verifier answers verify in place of the provider SDK check', async () => { - const seen: Array> = []; - const verify = vi.fn( - async (options: Record): Promise => { - seen.push(options); - return { - provider: 'limrun', - service: 'Limrun', - verificationMessage: 'verified by the composing root', - device: { - status: 'deferred', - name: 'Provider-selected Android emulator', - platform: 'android', - }, - app: { - status: 'missing', - message: 'Run apps to choose an uploaded asset before allocation.', - }, - }; - }, - ); - const plugin = limrunPlugin({ - createDependencies: () => stubDependencies(), - verifyConnection: verify, - }); +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' }, + 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, 'verified by the composing root'); - // The provider hands the verifier its full credential read, the host's version, and the platform. - assert.deepEqual(seen, [ + assert.equal(verification?.verificationMessage, 'Credentials and iOS instance access verified.'); + assert.deepEqual(sdk.clients, [ { apiKey: 'lim_test_key', - region: undefined, - keepAlive: false, - instances: undefined, - clientVersion: '1.2.3', - platform: 'ios', + userAgent: 'agent-device-cli/1.2.3', + timeout: 15_000, + maxRetries: 0, }, ]); - assert.equal(verify.mock.calls.length, 1); + // 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 () => { diff --git a/packages/provider-limrun/src/plugin.ts b/packages/provider-limrun/src/plugin.ts index 4bfaa75ecd..c5c519f8a6 100644 --- a/packages/provider-limrun/src/plugin.ts +++ b/packages/provider-limrun/src/plugin.ts @@ -2,7 +2,6 @@ import path from 'node:path'; import type { AgentDevicePlugin } from '@agent-device/plugins/contract'; import type { ProviderPluginHost } from '@agent-device/plugins/host'; import { limrunCredentialDeclaration, requireLimrunCredentials } from './credentials.ts'; -import type { LimrunConnectionVerifier } from './connection.ts'; import { LIMRUN_CONNECTION_CAPABILITIES, LIMRUN_PROVIDER } from './device.ts'; import type { LimrunRuntimeDependencies } from './runtime-dependencies.ts'; @@ -20,12 +19,6 @@ export type LimrunPluginOptions = Readonly<{ * beside the session files under it; without it the capture is unavailable. */ stateDir?: string; - /** - * Replaces the read-only check `connection.verify` performs. The provider's own verification is - * the default; the composing root names the entry it reads verification through when it already - * owns one, the same way it supplies the runtime's host adapters. - */ - verifyConnection?: LimrunConnectionVerifier; }>; /** @@ -38,7 +31,7 @@ export type LimrunPluginOptions = Readonly<{ * reading, the runtime, and its host adapters all load in the path that asks for them. */ export function limrunPlugin(options: LimrunPluginOptions): AgentDevicePlugin { - const { createDependencies, stateDir, verifyConnection } = options; + const { createDependencies, stateDir } = options; return { apiVersion: 2, provider: LIMRUN_PROVIDER, @@ -48,17 +41,9 @@ export function limrunPlugin(options: LimrunPluginOptions): AgentDevicePlugin { connection: { capabilities: LIMRUN_CONNECTION_CAPABILITIES, resolve: async (context) => - await ( - await import('./connection.ts') - ) - .createLimrunConnection({ verify: verifyConnection }) - .resolve(context), + await (await import('./connection.ts')).createLimrunConnection().resolve(context), verify: async (context) => - await ( - await import('./connection.ts') - ) - .createLimrunConnection({ verify: verifyConnection }) - .verify(context), + await (await import('./connection.ts')).createLimrunConnection().verify(context), }, setup: async (host) => { const credentials = requireLimrunCredentials(host.env); diff --git a/src/__tests__/cloud-connect-profile.test.ts b/src/__tests__/cloud-connect-profile.test.ts index dfd85215c2..3bbd8f3889 100644 --- a/src/__tests__/cloud-connect-profile.test.ts +++ b/src/__tests__/cloud-connect-profile.test.ts @@ -1,4 +1,4 @@ -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'; @@ -12,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, @@ -23,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-'); @@ -132,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, }); @@ -149,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', @@ -161,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 }); } @@ -185,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 () => { @@ -480,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( @@ -500,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; }, ); @@ -588,6 +612,8 @@ function readGeneratedConfig(configPath: string): { providerOsVersion?: string; providerProject?: string; providerBuild?: string; + providerNetworkLogs?: boolean; + providerNetworkHosts?: string; awsProjectArn?: string; awsDeviceArn?: string; awsAppArn?: string; @@ -602,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/builtin-provider-plugins.test.ts b/src/builtin-provider-plugins.test.ts index a0a693629f..12a7d767d6 100644 --- a/src/builtin-provider-plugins.test.ts +++ b/src/builtin-provider-plugins.test.ts @@ -1,19 +1,54 @@ import assert from 'node:assert/strict'; -import { test, vi } from 'vitest'; +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 = { create: vi.fn(), list: vi.fn(), delete: vi.fn() }; - readonly androidInstances = { create: vi.fn(), list: vi.fn(), delete: vi.fn() }; - readonly assets = { list: vi.fn(async () => []) }; + 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() }, @@ -97,7 +132,7 @@ test('a configured built-in Limrun registers through the plugin contract with it } }); -test('the built-in connection answers connect with the provider callbacks and the root verifier', async () => { +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 }, @@ -105,6 +140,11 @@ test('the built-in connection answers connect with the provider callbacks and th }; 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' }, @@ -114,9 +154,11 @@ test('the built-in connection answers connect with the provider callbacks and th }); assert.equal(resolved.profile.leaseProvider, 'limrun'); assert.equal(resolved.profile.leaseBackend, 'android-instance'); + assert.deepEqual(limrunSdk.clients, []); - // `verify` reaches the SDK through the root's published verification entry and runs the - // read-only account check the stubbed SDK above answers; no instance is created. + // `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, @@ -127,4 +169,36 @@ test('the built-in connection answers connect with the provider callbacks and th 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 d560b0b82d..f99a4f222b 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -7,7 +7,6 @@ import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolu import { limrunPlugin, readLimrunCredentials, - type LimrunConnectionVerifier, type LimrunPluginOptions, } from '@agent-device/provider-limrun/internal'; @@ -39,13 +38,9 @@ function limrunCandidate(host: HostEnvironment): PluginCandidate { /** * How the composing root answers what the built-in provider asks for: the platform's own host - * adapters build its runtime. The optional verifier replaces the connection's read-only check, so - * the root can route it through an entry it already owns. + * adapters build its runtime. */ -function builtinLimrunPluginOptions( - host: HostEnvironment, - verifyConnection?: LimrunConnectionVerifier, -): LimrunPluginOptions { +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. @@ -57,25 +52,20 @@ function builtinLimrunPluginOptions( env: host.env, cwd: host.cwd, }).baseDir, - ...(verifyConnection === undefined ? {} : { verifyConnection }), }; } /** * 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 verification is the root's published entry, so the same read-only check answers for both. + * 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 }, { verifyLimrunConnection }] = await Promise.all([ - import('@agent-device/plugins/registry'), - import('@agent-device/provider-limrun'), - ]); - const plugin = limrunPlugin( - builtinLimrunPluginOptions(host, async (options) => await verifyLimrunConnection(options)), - ); + const { withConnectionHost } = await import('@agent-device/plugins/registry'); + const plugin = limrunPlugin(builtinLimrunPluginOptions(host)); if (!plugin.connection) { throw new Error('The built-in Limrun plugin declares no connection.'); } From bd56dfd1a23b4f51d9ef7268048ed0369558c743 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 13:03:33 +0100 Subject: [PATCH 7/8] refactor(limrun): pass only the three Apple tools the iOS runner uses --- src/core/interactors/limrun-ios-runner.ts | 5 ++++- src/sdk/limrun-runtime-dependencies.ts | 8 +++++++- 2 files changed, 11 insertions(+), 2 deletions(-) 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 } = From 39299ab340196a2e502607d9eb56d4de256158e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 14:58:43 +0100 Subject: [PATCH 8/8] refactor(limrun): declare the plugin's connection in its return type limrunPlugin always declares a connection, so its type says so and the built-in connection no longer checks for a missing one. --- packages/provider-limrun/src/plugin.ts | 6 ++++-- src/builtin-provider-plugins.ts | 3 --- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/provider-limrun/src/plugin.ts b/packages/provider-limrun/src/plugin.ts index c5c519f8a6..11770d12ce 100644 --- a/packages/provider-limrun/src/plugin.ts +++ b/packages/provider-limrun/src/plugin.ts @@ -1,5 +1,5 @@ import path from 'node:path'; -import type { AgentDevicePlugin } from '@agent-device/plugins/contract'; +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'; @@ -30,7 +30,9 @@ export type LimrunPluginOptions = Readonly<{ * 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 { +export function limrunPlugin( + options: LimrunPluginOptions, +): AgentDevicePlugin & { connection: PluginConnection } { const { createDependencies, stateDir } = options; return { apiVersion: 2, diff --git a/src/builtin-provider-plugins.ts b/src/builtin-provider-plugins.ts index f99a4f222b..fe68cd277a 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -66,9 +66,6 @@ export async function builtinLimrunConnection( ): Promise { const { withConnectionHost } = await import('@agent-device/plugins/registry'); const plugin = limrunPlugin(builtinLimrunPluginOptions(host)); - if (!plugin.connection) { - throw new Error('The built-in Limrun plugin declares no connection.'); - } const connection = withConnectionHost(plugin.connection, undefined); return { resolve: connection.resolve, verify: connection.verify }; }