From 7e79e56734a4341e3f6c39a75df9a7c7cbf189be 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/7] 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 | 60 +++---- .../connection/connect-provider-adapters.ts | 2 +- src/cli/connection/limrun-profile.ts | 2 +- 17 files changed, 405 insertions(+), 64 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 eb98ee2f068..62a12d21c73 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 6ce474cabb8..94706da51d9 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 087ae588270..b7a0d62c51c 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 8458acc4897..21b86ab9449 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 25db54d2eee..e5973fbc30d 100644 --- a/packages/provider-limrun/src/index.ts +++ b/packages/provider-limrun/src/index.ts @@ -1,7 +1,6 @@ export { LIMRUN_PROFILE_FIELDS } from './device.ts'; export { createLimrunRuntime, type LimrunRuntime, 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 00000000000..d83be392180 --- /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 00000000000..936ecfebfef --- /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 00000000000..5749acc573e --- /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 25a1e8040cd..66e2179ce99 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 d66ab4b184e..7b276e5f6ca 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -926,6 +926,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 01bd9cc3854..c44d038f047 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -821,13 +821,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 77d4385fd93..c7ec1c38fd3 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-host-capabilities.ts', 'src/provider-plugin-policy.ts', ], diff --git a/src/__tests__/daemon-client-provider-credentials.test.ts b/src/__tests__/daemon-client-provider-credentials.test.ts index 676321631d5..e74df3b3abc 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 00000000000..f343243ca8e --- /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 9fda6b3f272..b3b79b8f57c 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,43 +16,32 @@ 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 (pluginHost) => { - 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', - ), - }, - // The registry's host capabilities are the boundary for shared platform mechanics; the - // adapter keeps its own lazy edges for the provider-specific ones. - dependencies.createLimrunRuntimeDependencies(host, pluginHost), - { - 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 (pluginHost) => + (await import('./sdk/limrun-runtime-dependencies.ts')).createLimrunRuntimeDependencies( + host, + pluginHost, + ), + // 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 2928340f66d..72644b27b6c 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 db5549261f5..2be12b37575 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 4b7e61602b331331b9ef6d01881ad1a52d55638a 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/7] 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 62a12d21c73..eb98ee2f068 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 21b86ab9449..acf4dc16810 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 d83be392180..882ce93663b 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 e74df3b3abc..edc5db55673 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 21180129f178c9b06f27b53870619f3e4d59d653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 05:48:24 +0100 Subject: [PATCH 3/7] feat(plugins): serve the Android provider interactor through the host facet The Android facet exposed adb mechanics but not the interactor a provider device runtime must answer `getInteractor` with, so the Limrun adapter kept its own static edge to the root's factory and the facet's host authority stopped short of every command that interactor runs. The root's facet gains one synchronous `createInteractor`. The root reads the family's factory once while it builds the capabilities, which is what makes the operation synchronous: `getInteractor` cannot await, and a lazy edge would need a proxy interactor instead of this seam. The value is wrapped in the same command scope every other facet operation re-enters, so a provider that resolves a tool of its own keeps resolving it from the host the facet was built for, never from the ambient process or an enclosing request. The operation is named on the root's own facet type and not on the published plugin contract. A plugin package bundles that contract into its own declaration, and a consumer that hands two such packages to `startAgentDevice` compares their copies of `setup` member by member; an interactor's snapshot answer reaches `SnapshotViewportSize`, branded with a `unique symbol` no second copy answers to, so naming one there would stop that consumer compiling. The adapter reads the operation as an optional facet member and keeps its embedded path, unchanged, when a caller supplies no capabilities. Its provider conversion is shared with the scope it already installed, so both arms cross the boundary the same way, and the provider mirror gains `text`, which the family reads off the provider it installs its scope over, so a provider with native text entry keeps that route. --- packages/plugins/src/host.ts | 25 ++++- src/provider-plugin-host-capabilities.test.ts | 106 ++++++++++++++++++ src/provider-plugin-host-capabilities.ts | 91 +++++++++++++-- ...ime-dependencies-host-capabilities.test.ts | 75 ++++++++++++- src/sdk/limrun-runtime-dependencies.ts | 31 ++++- .../integration/sdk-host-public-types.test.ts | 9 +- 6 files changed, 318 insertions(+), 19 deletions(-) diff --git a/packages/plugins/src/host.ts b/packages/plugins/src/host.ts index e612c01def1..191f45216c9 100644 --- a/packages/plugins/src/host.ts +++ b/packages/plugins/src/host.ts @@ -15,6 +15,14 @@ export type RunHostCommand = ( // declaration would exist twice as two unrelated copies and a branded or Node-primitive type would // never match across them. Every mirror stays structurally identical to its platform original, so // the composing root hands the same values to the platform's mechanics unchanged. +// +// Keeping the closure structural is what makes two plugin packages sharing one installed core still +// typecheck: each bundles this contract into its own declaration, and a consumer that hands such a +// plugin to `startAgentDevice` compares the bundled copy of `setup` against core's, member by member. +// An interactor cannot be named here for that reason. Its snapshot answer reaches +// `SnapshotViewportSize`, branded with a `unique symbol`, and no answer written by one copy of this +// contract answers to the other copy's brand. The composing root builds that operation and names it +// on its own facet type, which no plugin package imports. type ProviderAdbWaitTransport = '' | 'usb-' | 'local-' | 'any-'; type ProviderAdbWaitState = 'device' | 'recovery' | 'bootloader' | 'sideload' | 'sideload-window'; @@ -109,10 +117,25 @@ export type ProviderAndroidPortReverse = Readonly<{ list?(options?: ProviderAndroidPortReverseOptions): Promise; }>; -/** The provider-scoped executor the facet scopes, mirrored from the platform's provider minus its optional extras. */ +/** One text-entry request adb or the helper would have performed, mirrored from the platform's typed grammar. */ +export type ProviderAndroidTextInjectionRequest = Readonly<{ + /** Whether this is a plain entry or a replace-the-target's-text fill. */ + action: 'type' | 'fill'; + text: string; + delayMs?: number; + /** Present exactly for `fill`: the input the entry must land in, which the provider must focus first. */ + target?: Readonly<{ x: number; y: number }>; +}>; + +/** + * The provider-scoped executor the facet scopes, mirrored from the platform's provider minus its + * optional extras. `text` is carried because the Android family reads it off the provider it installs + * its scope over: a provider that can enter text natively keeps that route. + */ export type ProviderAndroidAdbProvider = Readonly<{ exec: ProviderAndroidExecutor; reverse?: ProviderAndroidPortReverse; + text?: (request: ProviderAndroidTextInjectionRequest) => Promise; }>; /** diff --git a/src/provider-plugin-host-capabilities.test.ts b/src/provider-plugin-host-capabilities.test.ts index 9c6313cf30a..cad4fa940fa 100644 --- a/src/provider-plugin-host-capabilities.test.ts +++ b/src/provider-plugin-host-capabilities.test.ts @@ -117,6 +117,112 @@ describe('provider host capabilities', () => { ]); }); + test('createInteractor answers synchronously with an interactor bound to its executor', async () => { + const { android } = await createProviderHostCapabilities({ + env: process.env, + cwd: process.cwd(), + }); + const serialSeen: string[][] = []; + const adb = async (args: readonly string[]) => { + serialSeen.push([...args]); + return { exitCode: 0, stdout: '', stderr: '' }; + }; + const device = { + platform: 'android' as const, + id: 'capability-interactor-serial', + name: 'Capability Pixel', + kind: 'emulator' as const, + target: 'mobile' as const, + booted: true, + }; + // The caller that needs this value cannot await it, so the facet must hand over the interactor + // itself and not a promise for one. + const interactor = android!.createInteractor(device, adb); + expect(interactor).not.toBeInstanceOf(Promise); + expect(Object.keys(interactor).length).toBeGreaterThan(0); + // The provider scope is the facet's own installation, not the caller's: the command the + // interactor runs arrives at the executor the caller handed the facet. + await interactor.keyboardStatus!(); + expect(serialSeen).toEqual([ + Array.from(deviceShellArgv('adb', 'shell', ['dumpsys', 'input_method'])), + ]); + }); + + test('createInteractor keeps every interactor command on the host it was built for', async () => { + const root = mkdtempForTestSync('provider-interactor-capabilities-'); + const bin = path.join(root, 'bin'); + mkdirSync(bin); + // A provider's executor is provider code, and it may reach for a tool of its own. The facet + // wraps every command the interactor runs in its host's command scope, so that tool resolves + // from the host the facet was built for — never the ambient process, nor an enclosing request. + const evidence = path.join(root, 'commands.jsonl'); + writeFileSync( + path.join(bin, 'provider-route'), + `#!${process.execPath}\n` + + `import { appendFileSync } from 'node:fs';\n` + + `appendFileSync(process.env.CAPABILITY_EVIDENCE, JSON.stringify({args:process.argv.slice(2),owner:process.env.CAPABILITY_OWNER}) + '\\n');\n`, + ); + chmodSync(path.join(bin, 'provider-route'), 0o755); + const hostFor = (owner: string) => ({ + env: { ...process.env, PATH: bin, CAPABILITY_OWNER: owner, CAPABILITY_EVIDENCE: evidence }, + cwd: root, + }); + const { android } = await createProviderHostCapabilities(hostFor('supplied')); + const device = { + platform: 'android' as const, + id: 'capability-scoped-serial', + name: 'Capability Pixel', + kind: 'emulator' as const, + target: 'mobile' as const, + booted: true, + }; + const interactor = android!.createInteractor(device, { + exec: async (args, options) => { + const { runCmd } = await import('@agent-device/host-kit/command'); + // The provider's own route is an ordinary command: it resolves its tool, and therefore this + // host, the way every other command the facet serves does. + const result = await runCmd('provider-route', [...args], { + allowFailure: true, + signal: options?.signal, + }); + return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr }; + }, + }); + // Every observed command, in arrival order, with the environment it was given. + const observed = () => + readFileSync(evidence, 'utf8') + .split('\n') + .filter((line) => line !== '') + .map((line) => JSON.parse(line) as { args: string[]; owner: string }); + const previous = { PATH: process.env.PATH, CAPABILITY_OWNER: process.env.CAPABILITY_OWNER }; + process.env.PATH = '/usr/bin:/bin'; + process.env.CAPABILITY_OWNER = 'ambient'; + try { + await interactor.keyboardStatus!(); + const standalone = observed(); + await withCommandHost( + { host: hostFor('foreign'), requestEnv: { CAPABILITY_OWNER: 'foreign-request' } }, + async () => { + await interactor.keyboardStatus!(); + }, + ); + expect(standalone.map((entry) => entry.owner)).toEqual(['supplied']); + expect( + observed() + .slice(standalone.length) + .map((entry) => entry.owner), + ).toEqual(['supplied']); + expect(observed()[0]?.args).toEqual( + Array.from(deviceShellArgv('adb', 'shell', ['dumpsys', 'input_method'])), + ); + } finally { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } + }); + test('the apple facet carries the root-composed application tools', async () => { const capabilities = await createProviderHostCapabilities({ env: {}, cwd: '/' }); expect(capabilities.apple?.applicationTools.resolveOpenTarget).toBeTypeOf('function'); diff --git a/src/provider-plugin-host-capabilities.ts b/src/provider-plugin-host-capabilities.ts index f21a3e486ea..de4011f5c31 100644 --- a/src/provider-plugin-host-capabilities.ts +++ b/src/provider-plugin-host-capabilities.ts @@ -1,9 +1,11 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { DeviceInfo } from '@agent-device/kernel/device'; import { withCommandHost } from '@agent-device/host-kit/command'; import { withMethodScope } from '@agent-device/kernel/scoped-provider'; import type { AppleApplicationToolsForProvider } from '@agent-device/contracts/application-lifecycle-runtime'; import { availableAppleApplicationToolsForProvider } from '@agent-device/contracts/application-lifecycle-runtime'; import type { + ProviderAndroidAdbProvider, ProviderAndroidExecutor, ProviderAndroidExecutorOptions, ProviderAndroidHost, @@ -16,6 +18,47 @@ type PlatformAdbExecutor = Parameters< >[0]; type PlatformAdbExecutorOptions = NonNullable[1]>; +/** The provider the Android family installs its own scope over, read from the same mechanics. */ +type PlatformAdbProvider = import('@agent-device/platform-android/mechanics').AndroidAdbProvider; + +/** + * The Android interactor operation this composition adds to the published facet: the family's own + * factory, read while the capabilities are built so the operation can answer synchronously. Naming + * the factory rather than spelling a signature keeps the device, provider and interactor types the + * platform's own, so the value crosses unchanged. + */ +type AndroidInteractorFactory = + typeof import('./core/interactors/android.ts').createAndroidInteractor; + +/** + * The Android facet as this composition builds and hands it over: the published contract's mechanics + * plus the interactor operation. The operation is named here and not in the published contract + * because an interactor cannot cross that surface: a plugin package bundles the contract into its own + * declaration, and the snapshot answer the interactor produces carries a `unique symbol` brand no + * other copy of that declaration answers to. A plugin reads the published mechanics; the root adapters + * that answer `getInteractor` are composed in this process and read this operation from the value they + * are handed, so a facet built by a composition that serves only the published contract is checked at + * use. + */ +export type ProviderAndroidHostWithInteractor = ProviderAndroidHost & + Readonly<{ + /** + * Builds the Android interactor for `device`, with every one of its commands answered through + * `adb`, which the platform scopes for `device.id` while the interactor runs. Returns + * synchronously because the caller that needs it cannot await: `getInteractor` is synchronous, so + * the factory was read while these capabilities were built and the value is assembled here with + * no promise and no device state. + */ + createInteractor( + device: DeviceInfo, + adb: ProviderAndroidAdbProvider | ProviderAndroidExecutor, + ): ReturnType; + }>; + +/** The capabilities this composition builds: the published facets with its own Android addition. */ +export type ProviderHostCapabilitiesWithInteractor = ProviderHostCapabilities & + Readonly<{ android: ProviderAndroidHostWithInteractor }>; + /** * The host capabilities the provider plugin registry adds to every plugin `setup` host, built by * `PROVIDER_PLUGIN_POLICY`. Each operation runs under `host`: commands resolve from its env/cwd, @@ -34,15 +77,19 @@ type PlatformAdbExecutorOptions = NonNullable[1] */ export async function createProviderHostCapabilities( host: HostEnvironment, -): Promise { +): Promise { // The host adb port refuses an unbound host; this wiring binds it once and loads no device state. await import('./platform-runtime-android-adb-host.ts'); + // `getInteractor` is synchronous, so the family's interactor factory is read here, once, while + // this host is wired. The Android family's mechanics are already in this process by then; nothing + // is probed and no device state is read. + const { createAndroidInteractor } = await import('./core/interactors/android.ts'); const runOnHost = (task: () => Promise) => withCommandHost({ host, requestEnv: undefined }, task); return Object.freeze({ - android: createProviderAndroidHost(runOnHost), + android: createProviderAndroidHost(runOnHost, createAndroidInteractor), apple: await createProviderAppleHost(host, runOnHost), - } satisfies ProviderHostCapabilities); + } satisfies ProviderHostCapabilitiesWithInteractor); } async function createProviderAppleHost( @@ -66,7 +113,8 @@ async function createProviderAppleHost( function createProviderAndroidHost( runOnHost: (task: () => Promise) => Promise, -): ProviderAndroidHost { + buildInteractor: AndroidInteractorFactory, +): ProviderAndroidHostWithInteractor { return Object.freeze({ runAdb: async (invocation, options) => { const { runAndroidHostAdb } = await import('@agent-device/platform-android/mechanics'); @@ -86,13 +134,9 @@ function createProviderAndroidHost( }, withAdbProvider: async (provider, serial, task) => { const { withAndroidAdbProvider } = await import('@agent-device/platform-android/mechanics'); - // The facet mirror is a structural subset of the platform provider; the platform - // normalizes a bare executor exactly as a provider carrying only `exec`. - const scoped = - typeof provider === 'function' - ? asPlatformAdbExecutor(provider) - : { ...provider, exec: asPlatformAdbExecutor(provider.exec) }; - return await runOnHost(() => withAndroidAdbProvider(scoped, { serial }, task)); + return await runOnHost( + async () => await withAndroidAdbProvider(asPlatformAdbProvider(provider), { serial }, task), + ); }, runShell: async (adb, words, options) => { const { runAdbShell } = await import('@agent-device/platform-android/mechanics'); @@ -122,7 +166,16 @@ function createProviderAndroidHost( await import('@agent-device/platform-android/mechanics'); return await dismissAndroidKeyboardWithAdb(asPlatformAdbExecutor(adb)); }, - } satisfies ProviderAndroidHost); + // The factory is already loaded, so this method assembles the value and reaches for no module. + // The scope wrapper is the one the Apple facet uses for the same reason: every command the + // interactor runs re-enters this host's command scope, and the provider scope the factory + // installed keeps those answers on the caller's executor for `device.id`. + createInteractor: (device, adb) => + withMethodScope( + buildInteractor(device, asPlatformAdbProvider(adb)), + async (task) => await runOnHost(task), + ), + } satisfies ProviderAndroidHostWithInteractor); } /** @@ -141,6 +194,20 @@ function asPlatformAdbOptions( }; } +/** + * Hands a plugin's provider to the platform's mechanics. Only `exec` needs converting, for the + * binary-answer reason below; the reverse manager and the text injector are the shapes the platform + * reads them as, so they reach it as they are. The platform normalizes a bare executor exactly as a + * provider carrying only `exec`. + */ +function asPlatformAdbProvider( + provider: ProviderAndroidAdbProvider | ProviderAndroidExecutor, +): PlatformAdbProvider { + return typeof provider === 'function' + ? { exec: asPlatformAdbExecutor(provider) } + : { ...provider, exec: asPlatformAdbExecutor(provider.exec) }; +} + /** * Hands a plugin's executor to the platform's mechanics. The contract names the binary answer a * plain byte array while the platform's mechanics read it as a Node buffer, so an answer carrying diff --git a/src/sdk/limrun-runtime-dependencies-host-capabilities.test.ts b/src/sdk/limrun-runtime-dependencies-host-capabilities.test.ts index e7c2a648c76..ca2fcc98b4f 100644 --- a/src/sdk/limrun-runtime-dependencies-host-capabilities.test.ts +++ b/src/sdk/limrun-runtime-dependencies-host-capabilities.test.ts @@ -1,6 +1,15 @@ import assert from 'node:assert/strict'; import { expect, test, vi } from 'vitest'; import type { ProviderAndroidHost, ProviderHostCapabilities } from '@agent-device/plugins/host'; +import type { ProviderAndroidHostWithInteractor } from '../provider-plugin-host-capabilities.ts'; + +/** + * The facet shape this adapter reads: the published mechanics, with the interactor operation the + * composing root adds. The operation is optional exactly as the adapter reads it. + */ +type AndroidFacet = ProviderAndroidHost & + Partial>; +import { deviceShellArgv } from '@agent-device/kernel/device-shell'; import { androidAdbHostTarget, androidAdbInvocation, @@ -18,7 +27,12 @@ const device = { type Call = { name: string; args: unknown[] }; -function recordingAndroid(calls: Call[]): ProviderAndroidHost { +/** The value a recording facet's synchronous `createInteractor` answers with, so a test can trace it. */ +const FACET_INTERACTOR = { marker: 'facet-interactor' } as unknown as ReturnType< + NonNullable +>; + +function recordingAndroid(calls: Call[]): AndroidFacet { const record = (name: string) => async (...args: unknown[]): Promise => { @@ -35,6 +49,10 @@ function recordingAndroid(calls: Call[]): ProviderAndroidHost { readLogs: record('readLogs') as ProviderAndroidHost['readLogs'], keyboardState: record('keyboardState') as ProviderAndroidHost['keyboardState'], dismissKeyboard: record('dismissKeyboard') as ProviderAndroidHost['dismissKeyboard'], + createInteractor: ((...args: unknown[]) => { + calls.push({ name: 'createInteractor', args }); + return FACET_INTERACTOR; + }) as NonNullable, }; } @@ -88,6 +106,61 @@ test('the Android adapter serves shared operations through the host capabilities ); }); +test('the Android adapter hands an interactor request to the capability facet synchronously', async () => { + const calls: Call[] = []; + const dependencies = createLimrunRuntimeDependencies( + { env: process.env, cwd: process.cwd() }, + { android: recordingAndroid(calls) }, + ); + const entered: unknown[] = []; + const stdinSeen: unknown[] = []; + const adb = { + exec: async (_args: readonly string[], options?: { stdin?: unknown }) => { + stdinSeen.push(options?.stdin); + return { exitCode: 0, stdout: '', stderr: '' }; + }, + text: async (request: unknown) => { + entered.push(request); + }, + }; + // `ProviderDeviceRuntime.getInteractor` is synchronous, so the adapter may not await the facet: + // the value it hands back is the facet's own, not a promise for it. + const interactor = dependencies.android.createInteractor(device, adb); + assert.equal(calls.length, 1); + assert.equal(calls[0]?.name, 'createInteractor'); + assert.equal(calls[0]?.args[0], device); + assert.equal(interactor, FACET_INTERACTOR); + // The provider the facet is handed is this adapter's own, read through the boundary's shapes. The + // text route is the caller's, so a provider with native text entry keeps it through the facet, and + // the executor converts the contract's byte-array payload to the Buffer this adapter reads. + const handed = calls[0]?.args[1] as { + exec: (args: readonly string[], options?: { stdin?: Uint8Array }) => Promise; + text?: (request: unknown) => Promise; + }; + await handed.text?.({ action: 'type', text: 'hello' }); + assert.deepEqual(entered, [{ action: 'type', text: 'hello' }]); + await handed.exec(['shell', 'input', 'text', 'hi'], { stdin: new Uint8Array([104, 105]) }); + assert.ok(Buffer.isBuffer(stdinSeen[0])); + assert.deepEqual([...(stdinSeen[0] as Buffer)], [104, 105]); +}); + +test('without capabilities the adapter builds its own Android interactor synchronously', async () => { + const dependencies = createLimrunRuntimeDependencies({ env: process.env, cwd: process.cwd() }); + const seen: Array = []; + const adb = { + exec: async (args: readonly string[]) => { + seen.push(args); + return { exitCode: 0, stdout: '', stderr: '' }; + }, + }; + const interactor = dependencies.android.createInteractor(device, adb); + // The embedded path keeps the same synchronous contract, and the provider scope is installed for + // this device: the command the interactor runs reaches adb through the caller's own executor. + assert.equal('then' in interactor, false); + assert.equal(await interactor.readClipboard!(), ''); + assert.deepEqual(seen, [deviceShellArgv('adb', 'shell', ['cmd', 'clipboard', 'get', 'text'])]); +}); + test('a binary stdout answer from the capabilities reaches the provider as a buffer', async () => { const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47]); const capabilities: ProviderHostCapabilities = { diff --git a/src/sdk/limrun-runtime-dependencies.ts b/src/sdk/limrun-runtime-dependencies.ts index 9e142983ac2..66e30829cfc 100644 --- a/src/sdk/limrun-runtime-dependencies.ts +++ b/src/sdk/limrun-runtime-dependencies.ts @@ -3,12 +3,24 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { withMethodScope } from '@agent-device/kernel/scoped-provider'; import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import type { + ProviderAndroidAdbProvider, ProviderAndroidExecutor, ProviderAndroidExecutorOptions, ProviderAndroidExecutorResult, ProviderAndroidHost, ProviderHostCapabilities, } from '@agent-device/plugins/host'; +import type { ProviderAndroidHostWithInteractor } from '../provider-plugin-host-capabilities.ts'; + +/** + * The facet the composing root hands this adapter: the published mechanics plus the interactor + * operation it adds. The operation is optional here because the caller's contract allows any + * published facet — the plugin contract cannot name an interactor, since its snapshot answer carries + * a brand no second copy of that declaration answers to — so the value is read where it is used and a + * facet without it takes the embedded path. + */ +type AndroidFacet = ProviderAndroidHost & + Partial>; type LimrunAndroidAdapter = LimrunRuntimeDependencies['android']; /** @@ -45,7 +57,8 @@ export function createLimrunRuntimeDependencies( ): LimrunRuntimeDependencies { const runOnHost = (task: () => Promise) => withCommandHost({ host, requestEnv: undefined }, task); - const android: ProviderAndroidHost | undefined = capabilities?.android; + const android: AndroidFacet | undefined = capabilities?.android; + const buildInteractor = android?.createInteractor; /** * Hands one of this adapter's executors to the capability boundary. The contract names a stdin * payload a plain byte array while this adapter's executors take a Node buffer, so a foreign @@ -55,6 +68,15 @@ export function createLimrunRuntimeDependencies( const toProviderExecutor = (adb: LimrunAdbExecutor): ProviderAndroidExecutor => { return async (args, options) => await adb(args, asLimrunAdbOptions(options)); }; + /** + * Hands one of this adapter's providers to the capability boundary. Only `exec` needs converting, + * for the executor reason above; the reverse manager and the text injector are the shapes the + * boundary reads them as, so they cross as they are. + */ + const toProviderAdbProvider = (adb: LimrunAdbProvider): ProviderAndroidAdbProvider => ({ + ...adb, + exec: toProviderExecutor(adb.exec), + }); /** Scopes platform adb internals to `adb` for `serial` while `task` runs, under this host. */ const withProviderScope = ( serial: string, @@ -63,9 +85,7 @@ export function createLimrunRuntimeDependencies( ): Promise => android ? android.withAdbProvider( - typeof adb === 'function' - ? toProviderExecutor(adb) - : { ...adb, exec: toProviderExecutor(adb.exec) }, + typeof adb === 'function' ? toProviderExecutor(adb) : toProviderAdbProvider(adb), serial, task, ) @@ -96,6 +116,9 @@ export function createLimrunRuntimeDependencies( ); }, createInteractor: (device, adb) => + buildInteractor?.(device, toProviderAdbProvider(adb)) ?? + // Without the capability facet, this adapter keeps its own deliberate static edge to the + // same factory, under the same host scope and with the same provider scope installed. withMethodScope(createAndroidInteractor(device, adb), runOnHost), createPortReverse: (adb, options) => android?.createPortReverse(toProviderExecutor(adb), options) ?? diff --git a/test/integration/sdk-host-public-types.test.ts b/test/integration/sdk-host-public-types.test.ts index 3efe3cbb5a2..69cd91322b6 100644 --- a/test/integration/sdk-host-public-types.test.ts +++ b/test/integration/sdk-host-public-types.test.ts @@ -133,7 +133,7 @@ void appleTools.detachRunnerSessionsForShutdown; // @ts-expect-error stopping every runner session this process holds is not a plugin's authority. void appleTools.finalizeRunnerSessionsForShutdown; -// The binary contract is nameable without a Node buffer in either direction. +// The Android facet's binary contract is nameable without a Node buffer in either direction. declare const android: ProviderAndroidHost; const invocation = { target: { selector: { kind: 'unspecified' as const }, server: { kind: 'ambient' as const } }, @@ -147,6 +147,13 @@ async function capture() { return bytes; } void capture(); + +// The published facet carries no interactor operation. A plugin package bundles this declaration into +// its own copy, and an interactor's snapshot answer carries a brand no second copy answers to, so +// naming one here would make two plugin packages sharing one installed core stop typechecking. The +// composing root builds the interactor and names it on its own facet type, which no plugin imports. +// @ts-expect-error the published contract stays structural. +void android.createInteractor; `, ); From ccc9060cffa84bc323ded5df03e29bfd389a0f7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 05:14:06 +0100 Subject: [PATCH 4/7] docs(plugins): clarify interactor factory preload --- src/provider-plugin-host-capabilities.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/provider-plugin-host-capabilities.ts b/src/provider-plugin-host-capabilities.ts index de4011f5c31..b2fed4cc511 100644 --- a/src/provider-plugin-host-capabilities.ts +++ b/src/provider-plugin-host-capabilities.ts @@ -80,9 +80,7 @@ export async function createProviderHostCapabilities( ): Promise { // The host adb port refuses an unbound host; this wiring binds it once and loads no device state. await import('./platform-runtime-android-adb-host.ts'); - // `getInteractor` is synchronous, so the family's interactor factory is read here, once, while - // this host is wired. The Android family's mechanics are already in this process by then; nothing - // is probed and no device state is read. + // Load the factory during host setup so `getInteractor` can stay synchronous. const { createAndroidInteractor } = await import('./core/interactors/android.ts'); const runOnHost = (task: () => Promise) => withCommandHost({ host, requestEnv: undefined }, task); From b2e74a301c68d8974e88469e9403a0648039c76d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 06:33:53 +0100 Subject: [PATCH 5/7] fix(plugins): keep the Android interactor facet receiver --- packages/plugins/src/host.ts | 5 +++-- .../limrun-runtime-dependencies-host-capabilities.test.ts | 8 +++++--- src/sdk/limrun-runtime-dependencies.ts | 3 +-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/plugins/src/host.ts b/packages/plugins/src/host.ts index 191f45216c9..811aba9856f 100644 --- a/packages/plugins/src/host.ts +++ b/packages/plugins/src/host.ts @@ -22,7 +22,8 @@ export type RunHostCommand = ( // An interactor cannot be named here for that reason. Its snapshot answer reaches // `SnapshotViewportSize`, branded with a `unique symbol`, and no answer written by one copy of this // contract answers to the other copy's brand. The composing root builds that operation and names it -// on its own facet type, which no plugin package imports. +// on its own facet type. The runtime value carries it for built-in composition; the published +// type does not declare it. type ProviderAdbWaitTransport = '' | 'usb-' | 'local-' | 'any-'; type ProviderAdbWaitState = 'device' | 'recovery' | 'bootloader' | 'sideload' | 'sideload-window'; @@ -118,7 +119,7 @@ export type ProviderAndroidPortReverse = Readonly<{ }>; /** One text-entry request adb or the helper would have performed, mirrored from the platform's typed grammar. */ -export type ProviderAndroidTextInjectionRequest = Readonly<{ +type ProviderAndroidTextInjectionRequest = Readonly<{ /** Whether this is a plain entry or a replace-the-target's-text fill. */ action: 'type' | 'fill'; text: string; diff --git a/src/sdk/limrun-runtime-dependencies-host-capabilities.test.ts b/src/sdk/limrun-runtime-dependencies-host-capabilities.test.ts index ca2fcc98b4f..c7da36f7715 100644 --- a/src/sdk/limrun-runtime-dependencies-host-capabilities.test.ts +++ b/src/sdk/limrun-runtime-dependencies-host-capabilities.test.ts @@ -39,7 +39,7 @@ function recordingAndroid(calls: Call[]): AndroidFacet { calls.push({ name, args }); throw new Error(`captured:${name}`); }; - return { + const facet: AndroidFacet = { runAdb: record('runAdb') as ProviderAndroidHost['runAdb'], adbError: record('adbError') as ProviderAndroidHost['adbError'], withAdbProvider: record('withAdbProvider') as ProviderAndroidHost['withAdbProvider'], @@ -49,11 +49,13 @@ function recordingAndroid(calls: Call[]): AndroidFacet { readLogs: record('readLogs') as ProviderAndroidHost['readLogs'], keyboardState: record('keyboardState') as ProviderAndroidHost['keyboardState'], dismissKeyboard: record('dismissKeyboard') as ProviderAndroidHost['dismissKeyboard'], - createInteractor: ((...args: unknown[]) => { + createInteractor(...args) { + assert.equal(this, facet); calls.push({ name: 'createInteractor', args }); return FACET_INTERACTOR; - }) as NonNullable, + }, }; + return facet; } async function captured(task: () => Promise): Promise { diff --git a/src/sdk/limrun-runtime-dependencies.ts b/src/sdk/limrun-runtime-dependencies.ts index 66e30829cfc..f898e7f9caa 100644 --- a/src/sdk/limrun-runtime-dependencies.ts +++ b/src/sdk/limrun-runtime-dependencies.ts @@ -58,7 +58,6 @@ export function createLimrunRuntimeDependencies( const runOnHost = (task: () => Promise) => withCommandHost({ host, requestEnv: undefined }, task); const android: AndroidFacet | undefined = capabilities?.android; - const buildInteractor = android?.createInteractor; /** * Hands one of this adapter's executors to the capability boundary. The contract names a stdin * payload a plain byte array while this adapter's executors take a Node buffer, so a foreign @@ -116,7 +115,7 @@ export function createLimrunRuntimeDependencies( ); }, createInteractor: (device, adb) => - buildInteractor?.(device, toProviderAdbProvider(adb)) ?? + android?.createInteractor?.(device, toProviderAdbProvider(adb)) ?? // Without the capability facet, this adapter keeps its own deliberate static edge to the // same factory, under the same host scope and with the same provider scope installed. withMethodScope(createAndroidInteractor(device, adb), runOnHost), From 209ba7b58893b1fbf50753dc0242682801175a68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 06:54:27 +0100 Subject: [PATCH 6/7] test(plugins): cover scoped Android provider text --- src/provider-plugin-host-capabilities.test.ts | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/provider-plugin-host-capabilities.test.ts b/src/provider-plugin-host-capabilities.test.ts index cad4fa940fa..a974abec4bb 100644 --- a/src/provider-plugin-host-capabilities.test.ts +++ b/src/provider-plugin-host-capabilities.test.ts @@ -7,6 +7,7 @@ import { androidAdbHostTarget, androidAdbInvocation, androidAdbSerialTarget, + resolveAndroidTextInjector, serializeAndroidAdbInvocation, withAndroidHostAdbTransport, } from '@agent-device/platform-android/mechanics'; @@ -97,6 +98,34 @@ describe('provider host capabilities', () => { expect(addressless.details?.command).toBeUndefined(); }); + test('withAdbProvider exposes the supplied text handler only in the provider scope', async () => { + const { android } = await createProviderHostCapabilities({ env: {}, cwd: '/' }); + const device = { + platform: 'android' as const, + id: 'scoped-provider-serial', + name: 'Provider Android', + kind: 'emulator' as const, + }; + const seen: unknown[] = []; + await android.withAdbProvider( + { + exec: async () => ({ exitCode: 0, stdout: '', stderr: '' }), + text: async (request) => { + seen.push(request); + }, + }, + device.id, + async () => { + const inject = resolveAndroidTextInjector(device); + assert.ok(inject); + await inject({ action: 'type', text: 'hello' }); + assert.equal(resolveAndroidTextInjector({ ...device, id: 'other-serial' }), undefined); + }, + ); + assert.deepEqual(seen, [{ action: 'type', text: 'hello' }]); + assert.equal(resolveAndroidTextInjector(device), undefined); + }); + test('runShell quotes each word for the device shell and forwards the executor', async () => { const { android } = await createProviderHostCapabilities({ env: process.env, From 15c18ec46f52f08342254348370334265e59b186 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 06:55:50 +0100 Subject: [PATCH 7/7] feat(plugins): export the Android text request type --- packages/plugins/src/host.ts | 2 +- src/sdk/plugins.ts | 1 + test/integration/sdk-host-public-types.test.ts | 14 +++++++++++++- website/docs/docs/plugins.md | 2 ++ 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/plugins/src/host.ts b/packages/plugins/src/host.ts index 811aba9856f..3955a792187 100644 --- a/packages/plugins/src/host.ts +++ b/packages/plugins/src/host.ts @@ -119,7 +119,7 @@ export type ProviderAndroidPortReverse = Readonly<{ }>; /** One text-entry request adb or the helper would have performed, mirrored from the platform's typed grammar. */ -type ProviderAndroidTextInjectionRequest = Readonly<{ +export type ProviderAndroidTextInjectionRequest = Readonly<{ /** Whether this is a plain entry or a replace-the-target's-text fill. */ action: 'type' | 'fill'; text: string; diff --git a/src/sdk/plugins.ts b/src/sdk/plugins.ts index a6896a78323..7465e0f93d4 100644 --- a/src/sdk/plugins.ts +++ b/src/sdk/plugins.ts @@ -9,6 +9,7 @@ import type { CloudWebDriverProviderOptions } from '@agent-device/provider-webdr export type { HostCommandResult, ProviderAndroidHost, + ProviderAndroidTextInjectionRequest, ProviderAppleHost, ProviderHostCapabilities, ProviderPluginHost, diff --git a/test/integration/sdk-host-public-types.test.ts b/test/integration/sdk-host-public-types.test.ts index 69cd91322b6..df06a4d0078 100644 --- a/test/integration/sdk-host-public-types.test.ts +++ b/test/integration/sdk-host-public-types.test.ts @@ -121,7 +121,11 @@ test('compiled plugin host declarations keep the provider-scoped facets', () => ); fs.writeFileSync( path.join(tempRoot, 'fixture.ts'), - `import type { ProviderAndroidHost, ProviderPluginHost } from 'agent-device/plugins'; + `import type { + ProviderAndroidHost, + ProviderAndroidTextInjectionRequest, + ProviderPluginHost, +} from 'agent-device/plugins'; // The Apple facet a plugin's \`setup\` receives carries no daemon-wide Apple shutdown authority. type AppleTools = NonNullable['applicationTools']; @@ -148,6 +152,14 @@ async function capture() { } void capture(); +function withTextEntry(text: (request: ProviderAndroidTextInjectionRequest) => Promise) { + return android.withAdbProvider({ + exec: async () => ({ exitCode: 0, stdout: '', stderr: '' }), + text, + }, 'provider-serial', async () => {}); +} +void withTextEntry; + // The published facet carries no interactor operation. A plugin package bundles this declaration into // its own copy, and an interactor's snapshot answer carries a brand no second copy answers to, so // naming one here would make two plugin packages sharing one installed core stop typechecking. The diff --git a/website/docs/docs/plugins.md b/website/docs/docs/plugins.md index 456f964d339..a11ace1009b 100644 --- a/website/docs/docs/plugins.md +++ b/website/docs/docs/plugins.md @@ -119,6 +119,8 @@ The host resolves the `./agent-device` export with import conditions. It falls b - `{ runtime, platformModule, dispose? }` implementing the [provider runtime](https://github.com/callstack/agent-device/blob/main/packages/contracts/src/provider-device-runtime.ts) and [platform module](https://github.com/callstack/agent-device/blob/main/packages/contracts/src/platform-runtime-operations.ts) contracts. The runtime's `provider` and the module owner's `provider` must equal the plugin's `provider`, and the module owner must declare `kind: 'provider-runtime'` and a nonempty `instance`. - `{ webDriver, dispose? }` for an Appium or WebDriver service. `WebDriverPluginOptions` is available through the type-only `agent-device/plugins/webdriver` import. The host supplies the client version and creates the shared runtime. Provider callbacks prepare sessions, upload apps, and retrieve artifacts. +If your Android provider handles text entry through `host.android.withAdbProvider`, import `ProviderAndroidTextInjectionRequest` from `agent-device/plugins` to type the provider's `text` callback. + The host checks required runtime methods and owner metadata when it sets the plugin up; operation contracts are checked when used. `dispose` runs once after the runtime shuts down. A failing `setup` cleans up its own resources; the host shuts down a runtime it already received if validation then refuses it. Keep the factory and `setup` fast, with no network I/O or device allocation; a stalled plugin delays daemon startup. Load platform mechanics through `platformModule.loadRuntime` and perform remote work in request-bound operations.