@e2e-dev/mobile 0.12.5-nightly-20261030030232 → 0.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/.build.json CHANGED
@@ -1 +1 @@
1
- {"version":"0.12.5-nightly-20261030030232"}
1
+ {"version":"0.12.5"}
@@ -0,0 +1,26 @@
1
+ import type { DriverGrant, DriverRequest } from './driver.ts';
2
+ /**
3
+ * Allocates a lease from a fresh daemon in a separate process, so each daemon
4
+ * gets its own credentials and home without changing the runner's environment.
5
+ * Not cancellable: an interrupted allocation can still grant a lease, which
6
+ * the caller then releases.
7
+ */
8
+ export declare function startDriver(request: DriverRequest, env: NodeJS.ProcessEnv, label: string): Promise<DriverGrant>;
9
+ /**
10
+ * Stops the daemon, which releases its leases and so ends their sessions at
11
+ * the service, and throws unless it confirms they ended. `leaseId` is the
12
+ * lease the daemon granted, when it granted one.
13
+ */
14
+ export declare function stopDriver(stateDir: string, env: NodeJS.ProcessEnv, leaseId: string | undefined, label: string, signal: AbortSignal): Promise<void>;
15
+ /**
16
+ * Throws unless `daemon stop --json` reports every session ended.
17
+ * A forced stop or a lost shutdown report comes back as `status: 'unknown'`
18
+ * with `pending: null`: the session may still be running, and billed.
19
+ *
20
+ * A granted lease also needs the report to list it as released. A daemon
21
+ * that is not running reports nothing pending (`mode: 'not-running'`), and so
22
+ * does one started after the granting daemon died, while the session may
23
+ * still be open. Without `leaseId`, before anything was granted, such a
24
+ * report means there is nothing to release.
25
+ */
26
+ export declare function assertSessionsEnded(stdout: string, leaseId: string | undefined, label: string): void;
@@ -0,0 +1,103 @@
1
+ import { execFile, fork } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import path from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ const exec = promisify(execFile);
7
+ /** A property of a parsed JSON value, or undefined when the value is not an object. */
8
+ function field(value, key) {
9
+ return typeof value === 'object' && value !== null ? Reflect.get(value, key) : undefined;
10
+ }
11
+ /** The installed agent-device CLI entry, resolved from its package without importing it. */
12
+ function agentDeviceBin() {
13
+ let directory = path.dirname(fileURLToPath(import.meta.resolve('agent-device')));
14
+ while (true) {
15
+ let manifest;
16
+ try {
17
+ manifest = JSON.parse(readFileSync(path.join(directory, 'package.json'), 'utf8'));
18
+ }
19
+ catch { /* The entry may be several directories below its package. */ }
20
+ if (field(manifest, 'name') === 'agent-device') {
21
+ const bin = field(field(manifest, 'bin'), 'agent-device');
22
+ if (typeof bin !== 'string')
23
+ throw new Error('The installed agent-device package has no agent-device bin');
24
+ return path.join(directory, bin);
25
+ }
26
+ const parent = path.dirname(directory);
27
+ if (parent === directory)
28
+ throw new Error('Cannot find the installed agent-device package');
29
+ directory = parent;
30
+ }
31
+ }
32
+ /**
33
+ * Allocates a lease from a fresh daemon in a separate process, so each daemon
34
+ * gets its own credentials and home without changing the runner's environment.
35
+ * Not cancellable: an interrupted allocation can still grant a lease, which
36
+ * the caller then releases.
37
+ */
38
+ export async function startDriver(request, env, label) {
39
+ const entry = new URL(import.meta.url.endsWith('.ts') ? './driver.ts' : './driver.js', import.meta.url);
40
+ return new Promise((resolve, reject) => {
41
+ const child = fork(entry, [], { env, execArgv: [], stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
42
+ let answered = false;
43
+ child.once('error', reject);
44
+ child.once('message', (reply) => {
45
+ answered = true;
46
+ if (reply.grant)
47
+ resolve(reply.grant);
48
+ else
49
+ reject(new Error(reply.error ?? `${label} driver returned no lease`));
50
+ });
51
+ child.once('exit', () => {
52
+ if (!answered)
53
+ reject(new Error(`${label} driver exited before allocation finished`));
54
+ });
55
+ child.send(request);
56
+ });
57
+ }
58
+ /**
59
+ * Stops the daemon, which releases its leases and so ends their sessions at
60
+ * the service, and throws unless it confirms they ended. `leaseId` is the
61
+ * lease the daemon granted, when it granted one.
62
+ */
63
+ export async function stopDriver(stateDir, env, leaseId, label, signal) {
64
+ const { stdout } = await exec(process.execPath, [agentDeviceBin(), 'daemon', 'stop', '--state-dir', stateDir, '--clean', '--json'], { env, signal });
65
+ assertSessionsEnded(stdout, leaseId, label);
66
+ }
67
+ /**
68
+ * Throws unless `daemon stop --json` reports every session ended.
69
+ * A forced stop or a lost shutdown report comes back as `status: 'unknown'`
70
+ * with `pending: null`: the session may still be running, and billed.
71
+ *
72
+ * A granted lease also needs the report to list it as released. A daemon
73
+ * that is not running reports nothing pending (`mode: 'not-running'`), and so
74
+ * does one started after the granting daemon died, while the session may
75
+ * still be open. Without `leaseId`, before anything was granted, such a
76
+ * report means there is nothing to release.
77
+ */
78
+ export function assertSessionsEnded(stdout, leaseId, label) {
79
+ let report;
80
+ try {
81
+ report = JSON.parse(stdout);
82
+ }
83
+ catch {
84
+ throw new Error(`agent-device stopped without a readable shutdown report; ${label} sessions may still be running`);
85
+ }
86
+ const data = field(report, 'data');
87
+ const releases = field(data, 'providerReleases');
88
+ const pending = field(releases, 'pending');
89
+ if (Array.isArray(pending) && pending.length > 0)
90
+ throw new Error(`agent-device stopped without ending ${pending.length} ${label} session(s)`);
91
+ if (field(releases, 'status') !== 'completed' || !Array.isArray(pending)) {
92
+ const warnings = field(data, 'warnings');
93
+ const detail = Array.isArray(warnings) ? warnings.filter((warning) => typeof warning === 'string').join(' ') : '';
94
+ throw new Error(`agent-device could not confirm its ${label} sessions ended${detail === '' ? '' : `: ${detail}`}`);
95
+ }
96
+ if (leaseId === undefined)
97
+ return;
98
+ const released = field(releases, 'released');
99
+ if (Array.isArray(released) && released.some((entry) => field(entry, 'leaseId') === leaseId))
100
+ return;
101
+ const what = field(data, 'mode') === 'not-running' ? `found no daemon running for lease ${leaseId}` : `stopped without listing lease ${leaseId} as released`;
102
+ throw new Error(`agent-device ${what}, so nothing confirms its ${label} session ended`);
103
+ }
@@ -0,0 +1,12 @@
1
+ import { type LeaseAllocateOptions } from 'agent-device';
2
+ /** One lease allocation from the daemon in `stateDir`, run in its own process so the daemon gets that process's environment. */
3
+ export interface DriverRequest {
4
+ stateDir: string;
5
+ allocate: LeaseAllocateOptions;
6
+ }
7
+ export interface DriverGrant {
8
+ leaseId: string;
9
+ tenantId: string;
10
+ runId: string;
11
+ retainOnClose: boolean;
12
+ }
@@ -0,0 +1,8 @@
1
+ import { createAgentDeviceClient } from 'agent-device';
2
+ process.once('message', (request) => {
3
+ void allocate(request).then((grant) => process.send?.({ grant }, () => process.disconnect?.()), (cause) => process.send?.({ error: cause instanceof Error ? cause.message : String(cause) }, () => process.disconnect?.()));
4
+ });
5
+ async function allocate({ stateDir, allocate: options }) {
6
+ const lease = await createAgentDeviceClient({ stateDir }).leases.allocate(options);
7
+ return { leaseId: lease.leaseId, tenantId: lease.tenantId, runId: lease.runId, retainOnClose: lease.retainOnClose === true };
8
+ }
@@ -0,0 +1,4 @@
1
+ import { type LeaseScopedOptions } from 'agent-device';
2
+ export declare const LEASE_TTL_MS = 60000;
3
+ /** Renew idle leases while other targets run; session retention alone does not prevent expiry. */
4
+ export declare function startHeartbeat(stateDir: string, scope: LeaseScopedOptions, log: (line: string) => void): Promise<() => Promise<void>>;
@@ -0,0 +1,34 @@
1
+ import { createAgentDeviceClient } from 'agent-device';
2
+ export const LEASE_TTL_MS = 60_000;
3
+ /** Renew idle leases while other targets run; session retention alone does not prevent expiry. */
4
+ export async function startHeartbeat(stateDir, scope, log) {
5
+ // An explicit empty URL selects the local stateDir instead of an ambient remote daemon.
6
+ const client = createAgentDeviceClient({ stateDir, daemonBaseUrl: '', daemonAuthToken: '', daemonTransport: 'auto' });
7
+ const controller = new AbortController();
8
+ const beat = () => client.leases.heartbeat({ ...scope, ttlMs: LEASE_TTL_MS, signal: AbortSignal.any([controller.signal, AbortSignal.timeout(10_000)]) });
9
+ await beat();
10
+ let pending = Promise.resolve();
11
+ let timer;
12
+ const schedule = () => {
13
+ timer = setTimeout(() => {
14
+ pending = beat().then(() => { }, (error) => {
15
+ if (controller.signal.aborted)
16
+ return;
17
+ try {
18
+ log(`lease ${scope.leaseId}: renewal failed: ${error instanceof Error ? error.message : String(error)}`);
19
+ }
20
+ catch {
21
+ // The run's log may be closed by now.
22
+ }
23
+ }).finally(() => { if (!controller.signal.aborted)
24
+ schedule(); });
25
+ }, 20_000);
26
+ timer.unref();
27
+ };
28
+ schedule();
29
+ return async () => {
30
+ controller.abort();
31
+ clearTimeout(timer);
32
+ await pending;
33
+ };
34
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * `@e2e-dev/mobile/lease`: what a device-cloud provider package builds on
3
+ * when agent-device runs the cloud's sessions itself (`leaseProvider`). Each
4
+ * lease comes from its own agent-device daemon, in a private state directory
5
+ * and home with the service's credentials, which this package's agent-device
6
+ * starts, renews, and stops.
7
+ */
8
+ import type { DeviceClientConfig } from '../bindings.ts';
9
+ import type { DeviceLease, DeviceReleaseContext, DeviceRequest } from '../provider.ts';
10
+ type ProviderSelector = Extract<keyof DeviceClientConfig, `provider${string}`>;
11
+ /** The device a lease asks the service for, and the `provider*` capabilities its session starts with. */
12
+ export type LeaseSelectors = {
13
+ readonly device: string;
14
+ } & Readonly<Partial<Pick<DeviceClientConfig, ProviderSelector>>>;
15
+ /** One service agent-device leases devices from. */
16
+ export interface AgentDeviceLeaseOptions {
17
+ /** agent-device's name for the service, as the lease provider and tenant: `'browserstack'`. */
18
+ readonly provider: string;
19
+ /** The service's name in errors: `'BrowserStack'`. */
20
+ readonly label: string;
21
+ }
22
+ /** What one `acquire` allocates. */
23
+ export interface AgentDeviceLeaseRequest {
24
+ /** Set on the daemon's environment over the run's: the service's credentials. */
25
+ readonly env: Readonly<Record<string, string>>;
26
+ /** Allocated with the lease and put on its `client`, so the worker's session matches it. */
27
+ readonly selectors: LeaseSelectors;
28
+ /** What the progress line names once the lease is granted, after `lease <id>: `. */
29
+ readonly summary: string;
30
+ /** Runs on the daemon's empty agent-device home before it starts, to install a plugin there. */
31
+ readonly prepareHome?: ((home: string) => Promise<void>) | undefined;
32
+ }
33
+ /** `acquire` and `release` of a `DeviceProvider` backed by agent-device leases. */
34
+ export interface AgentDeviceLeases {
35
+ acquire(request: DeviceRequest, lease: AgentDeviceLeaseRequest): Promise<DeviceLease>;
36
+ /** Stops the lease's daemon, and throws unless agent-device confirms it ended the lease's session. */
37
+ release(lease: DeviceLease, context: DeviceReleaseContext): Promise<void>;
38
+ }
39
+ /**
40
+ * Leases from `options.provider` for a `DeviceProvider`: one isolated
41
+ * agent-device daemon per lease, allocated with `retainOnClose` so closing
42
+ * the engine session keeps it, renewed while held, and stopped on release,
43
+ * which ends the session at the service.
44
+ */
45
+ export declare function agentDeviceLeases({ provider, label }: AgentDeviceLeaseOptions): AgentDeviceLeases;
46
+ export {};
@@ -0,0 +1,106 @@
1
+ /**
2
+ * `@e2e-dev/mobile/lease`: what a device-cloud provider package builds on
3
+ * when agent-device runs the cloud's sessions itself (`leaseProvider`). Each
4
+ * lease comes from its own agent-device daemon, in a private state directory
5
+ * and home with the service's credentials, which this package's agent-device
6
+ * starts, renews, and stops.
7
+ */
8
+ import { mkdtemp, rm } from 'node:fs/promises';
9
+ import { tmpdir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { startDriver, stopDriver } from './daemon.js';
12
+ import { LEASE_TTL_MS, startHeartbeat } from './heartbeat.js';
13
+ /**
14
+ * Leases from `options.provider` for a `DeviceProvider`: one isolated
15
+ * agent-device daemon per lease, allocated with `retainOnClose` so closing
16
+ * the engine session keeps it, renewed while held, and stopped on release,
17
+ * which ends the session at the service.
18
+ */
19
+ export function agentDeviceLeases({ provider, label }) {
20
+ const held = new Map();
21
+ /** One release per lease, shared by every caller; a failed one may be tried again. */
22
+ function release(id, resource, signal) {
23
+ resource.releasing ??= (async () => {
24
+ await resource.stopHeartbeat?.();
25
+ if (resource.ended !== true) {
26
+ await stopDriver(resource.stateDir, resource.env, id, label, signal);
27
+ resource.ended = true;
28
+ }
29
+ await rm(resource.dir, { recursive: true, force: true });
30
+ if (id !== undefined)
31
+ held.delete(id);
32
+ })();
33
+ resource.releasing.catch(() => { resource.releasing = undefined; });
34
+ return resource.releasing;
35
+ }
36
+ return {
37
+ async acquire(request, { env, selectors, summary, prepareHome }) {
38
+ request.signal.throwIfAborted();
39
+ const dir = await mkdtemp(join(tmpdir(), `e2e-${provider}-`));
40
+ const home = join(dir, 'home');
41
+ const resource = { dir, stateDir: join(dir, 'state'), env: daemonEnv({ ...request.env, ...env }, home) };
42
+ const leaseBackend = request.platform === 'ios' ? 'ios-instance' : 'android-instance';
43
+ const allocated = { platform: request.platform, target: 'mobile', ...selectors };
44
+ let id;
45
+ try {
46
+ await prepareHome?.(home);
47
+ const grant = await startDriver({
48
+ stateDir: resource.stateDir,
49
+ allocate: {
50
+ tenant: provider,
51
+ runId: request.runId,
52
+ leaseBackend,
53
+ leaseProvider: provider,
54
+ ttlMs: LEASE_TTL_MS,
55
+ // Retain the provider lease when closeApp or cleanup closes the engine session.
56
+ // The provider releases the lease at run end.
57
+ retainOnClose: true,
58
+ ...allocated,
59
+ },
60
+ }, resource.env, label);
61
+ id = grant.leaseId;
62
+ held.set(id, resource);
63
+ if (request.signal.aborted)
64
+ throw new Error('cancelled');
65
+ if (!grant.retainOnClose)
66
+ throw new Error(`agent-device did not acknowledge retainOnClose. Closing the engine session could end the ${label} lease before run-end release`);
67
+ const scope = { tenant: grant.tenantId, runId: grant.runId, leaseId: grant.leaseId, leaseBackend, leaseProvider: provider };
68
+ resource.stopHeartbeat = await startHeartbeat(resource.stateDir, scope, request.log);
69
+ request.log(`lease ${id}: ${summary}`);
70
+ // The worker's client is created with these fields: the scope picks the lease, and the selectors match the session it holds.
71
+ return { id, client: { stateDir: resource.stateDir, ...scope, ...allocated } };
72
+ }
73
+ catch (cause) {
74
+ // The engine releases only leases `acquire` returned.
75
+ try {
76
+ await release(id, resource, AbortSignal.timeout(30_000));
77
+ }
78
+ catch (cleanup) {
79
+ throw new AggregateError([cause, cleanup], `${label} lease failed: ${messageOf(cause)}; cleanup also failed: ${messageOf(cleanup)}`, { cause: cleanup });
80
+ }
81
+ throw cause;
82
+ }
83
+ },
84
+ async release(lease, context) {
85
+ const resource = held.get(lease.id);
86
+ if (resource)
87
+ await release(lease.id, resource, context.signal);
88
+ },
89
+ };
90
+ }
91
+ /** `env` for a daemon in `home`: no daemon setting in it may select a different daemon, home, or connection profile. */
92
+ function daemonEnv(env, home) {
93
+ const result = { ...env };
94
+ for (const key of Object.keys(result)) {
95
+ // Keep the user's security policy on both the daemon and its clients.
96
+ if (key === 'AGENT_DEVICE_DAEMON_POLICY')
97
+ continue;
98
+ if (key.startsWith('AGENT_DEVICE_'))
99
+ delete result[key];
100
+ }
101
+ result.AGENT_DEVICE_HOME = home;
102
+ return result;
103
+ }
104
+ function messageOf(cause) {
105
+ return cause instanceof Error ? cause.message : String(cause);
106
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2e-dev/mobile",
3
- "version": "0.12.5-nightly-20261030030232",
3
+ "version": "0.12.5",
4
4
  "description": "Mobile engine (iOS and Android) for e2e agentic end-to-end testing, built on agent-device",
5
5
  "keywords": [
6
6
  "e2e",
@@ -44,6 +44,10 @@
44
44
  "./tools": {
45
45
  "types": "./dist/tools.d.ts",
46
46
  "default": "./dist/tools.js"
47
+ },
48
+ "./lease": {
49
+ "types": "./dist/lease/index.d.ts",
50
+ "default": "./dist/lease/index.js"
47
51
  }
48
52
  },
49
53
  "files": [
@@ -51,13 +55,13 @@
51
55
  "NOTICE"
52
56
  ],
53
57
  "dependencies": {
54
- "agent-device": "0.21.33",
58
+ "agent-device": "0.21.35",
55
59
  "pngjs": "7.0.0",
56
60
  "zod": "4.6.7"
57
61
  },
58
62
  "peerDependencies": {
59
63
  "ai": "^7.0.0",
60
- "e2e": "0.22.0-nightly-20261030030232"
64
+ "e2e": ">=0.15.0 <1"
61
65
  },
62
66
  "peerDependenciesMeta": {
63
67
  "ai": {
@@ -68,7 +72,7 @@
68
72
  "@types/node": "26.6.5",
69
73
  "@types/pngjs": "6.0.5",
70
74
  "ai": "7.0.153",
71
- "e2e": "0.22.0-nightly-20261030030232",
75
+ "e2e": "0.22.0",
72
76
  "typescript": "7.0.2",
73
77
  "vitest": "5.0.5"
74
78
  },