diff --git a/packages/plugins/src/host.ts b/packages/plugins/src/host.ts index e612c01def..3955a79218 100644 --- a/packages/plugins/src/host.ts +++ b/packages/plugins/src/host.ts @@ -15,6 +15,15 @@ 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. 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'; @@ -109,10 +118,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/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 77% rename from src/provider-limrun-credentials.ts rename to packages/provider-limrun/src/credentials.ts index 8458acc489..acf4dc1681 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; @@ -23,48 +23,43 @@ const INSTANCE_VARS = { } as const; /** Every variable that selects which Limrun account or instance the credentials reach. */ -export const LIMRUN_CREDENTIAL_VARIABLES: readonly string[] = [ +const LIMRUN_CREDENTIAL_VARIABLES: readonly string[] = [ ...Object.values(ACCOUNT_VARS), ...INSTANCE_VARS.ios, ...INSTANCE_VARS.android, ]; -// Mirrors platformForLimrunLeaseBackend in provider-limrun, which exposes only its root entry, and -// that entry loads the Limrun SDK; importing it here would load the SDK on every credential read. -const LEASE_BACKEND_PLATFORMS: ReadonlyMap = new Map([ - ['ios-instance', 'ios'], - ['android-instance', 'android'], -]); - /** The platform whose instance a Limrun lease backend reaches. */ export function limrunPlatformForLeaseBackend( leaseBackend: string | undefined, -): 'ios' | 'android' | undefined { - return leaseBackend === undefined ? undefined : LEASE_BACKEND_PLATFORMS.get(leaseBackend); +): 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 25db54d2ee..e5973fbc30 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 0000000000..882ce93663 --- /dev/null +++ b/packages/provider-limrun/src/internal.ts @@ -0,0 +1,11 @@ +/** + * 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 { + 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 d66ab4b184..7b276e5f6c 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 01bd9cc385..c44d038f04 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 77d4385fd9..c7ec1c38fd 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 676321631d..edc5db5567 100644 --- a/src/__tests__/daemon-client-provider-credentials.test.ts +++ b/src/__tests__/daemon-client-provider-credentials.test.ts @@ -15,7 +15,7 @@ import { import { providerCredentialFingerprint as fingerprintFor } from '@agent-device/plugins/credential-fingerprint'; import { builtinPluginInventory } from './test-utils/builtin-plugin-inventory.ts'; import type { EnvMap } from '@agent-device/kernel/source-value'; -import { LIMRUN_CREDENTIAL_VARIABLES } from '../provider-limrun-credentials.ts'; +import { pluginCredentialVariables } from '@agent-device/contracts/plugin-inventory'; import { readDaemonProviderCredentials } from '../provider-credential-fingerprint.ts'; const inventory = await builtinPluginInventory(); @@ -143,7 +143,9 @@ function readFingerprint(body: string): unknown { } function clearCredentialEnv(): void { - for (const name of LIMRUN_CREDENTIAL_VARIABLES) vi.stubEnv(name, undefined); + const variables = pluginCredentialVariables(inventory, 'limrun'); + if (!variables?.length) throw new Error('Limrun credential variables are missing from inventory'); + for (const name of variables) vi.stubEnv(name, undefined); } async function startLocalDaemon( diff --git a/src/builtin-provider-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 9fda6b3f27..b3b79b8f57 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 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'; diff --git a/src/provider-plugin-host-capabilities.test.ts b/src/provider-plugin-host-capabilities.test.ts index 9c6313cf30..a974abec4b 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, @@ -117,6 +146,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 f21a3e486e..b2fed4cc51 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,17 @@ 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'); + // 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); return Object.freeze({ - android: createProviderAndroidHost(runOnHost), + android: createProviderAndroidHost(runOnHost, createAndroidInteractor), apple: await createProviderAppleHost(host, runOnHost), - } satisfies ProviderHostCapabilities); + } satisfies ProviderHostCapabilitiesWithInteractor); } async function createProviderAppleHost( @@ -66,7 +111,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 +132,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 +164,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 +192,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 e7c2a648c7..c7da36f771 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,14 +27,19 @@ 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 => { 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'], @@ -35,7 +49,13 @@ 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) { + assert.equal(this, facet); + calls.push({ name: 'createInteractor', args }); + return FACET_INTERACTOR; + }, }; + return facet; } async function captured(task: () => Promise): Promise { @@ -88,6 +108,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 9e142983ac..f898e7f9ca 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,7 @@ 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; /** * 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 +67,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 +84,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 +115,9 @@ export function createLimrunRuntimeDependencies( ); }, createInteractor: (device, 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), createPortReverse: (adb, options) => android?.createPortReverse(toProviderExecutor(adb), options) ?? diff --git a/src/sdk/plugins.ts b/src/sdk/plugins.ts index a6896a7832..7465e0f93d 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 3efe3cbb5a..df06a4d007 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']; @@ -133,7 +137,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 +151,21 @@ async function capture() { return bytes; } 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 +// 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; `, ); diff --git a/website/docs/docs/plugins.md b/website/docs/docs/plugins.md index 456f964d33..a11ace1009 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.